From 9f2ca4150bc95a6821ed3e887c03fe10b5bcd216 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Wed, 16 Sep 2026 22:12:13 +1200 Subject: [PATCH 01/41] fall back to ptx, follow kernel pointers, stop hoarding the fatbin --- CHANGELOG.md | 80 + Makefile | 6 +- docs/usage.md | 13 + lang/en.txt | 6 +- runtime/include/cooperative_groups.h | 54 + runtime/include/cooperative_groups/reduce.h | 24 + runtime/include/cublas_v2.h | 240 +++ runtime/include/cuda.h | 229 +++ runtime/include/cuda_bf16.h | 93 + runtime/include/cuda_fp16.h | 144 ++ runtime/include/cuda_runtime.h | 379 ++++ src/amdgpu/amd_be.c | 2 +- src/amdgpu/isel.c | 14 +- src/backend/backend.h | 1 + src/exec/verbs.c | 129 +- src/fe/ast.h | 1 + src/fe/bc_err.c | 9 +- src/fe/bc_err.h | 6 + src/fe/parser.c | 54 +- src/fe/preproc.c | 22 +- src/fe/preproc.h | 3 + src/fe/sema.c | 1 + src/host/hgen.c | 1164 ++++++++++++ src/host/hgen.h | 25 + src/ir/bir.c | 39 +- src/ir/bir.h | 7 +- src/ir/bir_inline.c | 197 ++- src/ir/bir_inline.h | 2 +- src/ir/bir_lower.c | 644 ++++++- src/ir/bir_lower.h | 4 + src/main.c | 55 +- src/metal/emit.c | 5 +- src/nvidia/emit_sass.c | 1768 ++++++++++++++++--- src/nvidia/isel.c | 580 +++++- src/nvidia/lt_nv.c | 493 +++++- src/nvidia/lt_nv.h | 55 +- src/nvidia/lt_nvcf.c | 32 +- src/nvidia/lt_nvi.c | 61 + src/nvidia/nv_be.c | 3 +- src/nvidia/nvidia.h | 11 +- src/tensix/isel.c | 2 +- tests/hdecl.cu | 50 + tests/hfnb.cu | 52 + tests/hfnc.cu | 57 + tests/hfnd.cu | 63 + tests/hmac.cu | 59 + tests/hmulti.cu | 73 + tests/hpack.cu | 41 + tests/hqual.cu | 23 + tests/htfn.cu | 61 + tests/htid.cu | 60 + tests/hvadd.cu | 49 + tests/tbackend.c | 2 +- tests/tcpp.c | 10 +- tests/tharns.h | 2 +- tests/thost.c | 413 +++++ tests/tinline.c | 21 +- tests/tmain.c | 1 + tests/trpi.c | 111 +- tests/ttpl.c | 52 + 60 files changed, 7313 insertions(+), 544 deletions(-) create mode 100644 runtime/include/cooperative_groups.h create mode 100644 runtime/include/cooperative_groups/reduce.h create mode 100644 runtime/include/cublas_v2.h create mode 100644 runtime/include/cuda.h create mode 100644 runtime/include/cuda_bf16.h create mode 100644 runtime/include/cuda_fp16.h create mode 100644 runtime/include/cuda_runtime.h create mode 100644 src/host/hgen.c create mode 100644 src/host/hgen.h create mode 100644 tests/hdecl.cu create mode 100644 tests/hfnb.cu create mode 100644 tests/hfnc.cu create mode 100644 tests/hfnd.cu create mode 100644 tests/hmac.cu create mode 100644 tests/hmulti.cu create mode 100644 tests/hpack.cu create mode 100644 tests/hqual.cu create mode 100644 tests/htfn.cu create mode 100644 tests/htid.cu create mode 100644 tests/hvadd.cu create mode 100644 tests/thost.c diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b59489..d3c303b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,86 @@ Booth — Changelog ================= +## Unreleased + +### Backends + +- `--nvidia-cubin` puts every kernel of a module into the one cubin, so + ggml-cuda files with several kernels no longer stop at E600 + (Zane Hambly, 2026-09-15) + +- `--nvidia-cubin` lowers local loads and stores, half and bfloat16 + conversions, rounding, votes, membar, nanosleep, 16-bit parameters and + constant divisors, and sizes each kernel's registers from its own counts + (Zane Hambly, 2026-09-15) + +- `--nvidia-cubin` holds a register only where its value is live, places join + barriers by the blocks a region covers, and lowers wmma load, store and mma + to scalar SASS, so topk-moe and lightning-indexer build (Zane Hambly, + 2026-09-16) + +- `--nvidia-cubin` lowers cvta.local and cvta.global, so cumsum and quantize + get as far as their vprintf call (Zane Hambly, 2026-09-16) + +- `--nvidia-cubin` spills values to the local frame when a kernel needs more + registers than SASS has, so mmvq gets past E603 (Zane Hambly, 2026-09-16) + +- `--cuda-host` and `--cuda-exe` emit the host half of a CUDA compile, so kath + builds a whole program the way nvcc does: the source back out with the device + definitions removed, each launch through `__cudaPushCallConfiguration` and a + stub calling `cudaLaunchKernel`, the kernels registered from a constructor out + of a fatbin carrying both the cubin and the PTX, and the system C++ compiler + driven to link it. Clean-room `cuda.h`, `cuda_runtime.h`, `cuda_fp16.h`, + `cuda_bf16.h` and `cublas_v2.h` under `runtime/include` (Zane Hambly, + 2026-09-16) + +- `--cuda-host` writes each kernel's stub where the kernel stood and keys a + launch on the instantiation rather than its position, so a kernel launched + from inside a host template or through a macro reaches the right one, and it + spells enum, struct, vector and function template arguments, so ggml-cuda + files get through the host pass (Zane Hambly, 2026-09-16) + +- `--cuda-host` writes out a variadic template argument pack, spells a function + template-id argument rather than the symbol it lowered to, keeps a launch + whose callee ends in `>>`, registers up to 4096 kernels and refuses with E622 + above that instead of falling silent, and `kath cuda` finds Booth's own + `runtime/include` from the binary rather than the working directory, so + binbcast and cpy get through (Zane Hambly, 2026-09-16) +- `--cuda-host` carries const on the BIR type itself, so a kernel taking + `const float *` registers the instantiation its launch actually names + rather than one spelled without the qualifier (Zane Hambly, 2026-09-16) + +- `kath cuda -c` compiles one `.cu` to one relocatable object rather than a + whole program, with `-fPIC` for a shared library, each object carrying its + own fatbin and registration constructor the way nvcc does, so many + translation units link into one library (Zane Hambly, 2026-09-16) + +- `kath cuda` takes `-Idir` written up against the flag as well as `-I dir`, + rather than dropping it and compiling with the include path missing +- `--cuda-host` leaves a declaration where it deleted a device function, so + host code naming one as a template argument still resolves, expands an + argument pack in the stub body, keeps default arguments, tells a commented + out parameter name from a type, and the clean-room headers gain + `cudaFuncSetAttribute`, the host-mapped allocation flags, occupancy without + the flags suffix, `cudaDataType_t`, the cuBLAS side, fill, diag, compute and + algo enums with `cublasStrsmBatched` and the `GemmEx` family, and a minimal + `cooperative_groups.h`, so 63 of the 67 ggml-cuda files compile to objects + (Zane Hambly, 2026-09-16) + +### Frontend + +- Explicit template instantiation, `template void f(params);` with + `extern template` as its declaration form, deduces and instantiates down the + same path as an implicit one, and a launch through a function-pointer local + resolves to the kernel it holds, so ggml-cuda's template-instance files get + through the device and host passes (Zane Hambly, 2026-09-16) + +- `--cuda-host` strips `__device__`, `__global__`, `__host__` and + `__forceinline__` wherever they survive into host output, and leaves an angle + include a directive rather than inlining Booth's own headers over the one g++ + will read, while `kath cuda` now hands every `-I` to every stage instead of + only the last, so the emitted C++ compiles (Zane Hambly, 2026-09-16) + ## Booth 0.6.0 ### Runtime diff --git a/Makefile b/Makefile index 627ab0f..17e0e3d 100644 --- a/Makefile +++ b/Makefile @@ -23,7 +23,7 @@ CFLAGS = -std=c99 -MMD -MP -Wall -Wextra -pedantic -O2 \ -Wdouble-promotion -Wswitch-enum -Wwrite-strings \ -D_FORTIFY_SOURCE=2 -fstack-protector-strong -fPIE $(CF_PROT) \ $(GCC_ONLY) \ - -Isrc -Isrc/fe -Isrc/ir -Isrc/tdf -Isrc/backend -Isrc/amdgpu -Isrc/tensix -Isrc/nvidia -Isrc/metal -Isrc/intel -Isrc/triton -Isrc/cpu -Isrc/build -Isrc/exec -Iruntime/include \ + -Isrc -Isrc/fe -Isrc/ir -Isrc/tdf -Isrc/backend -Isrc/amdgpu -Isrc/tensix -Isrc/nvidia -Isrc/metal -Isrc/intel -Isrc/triton -Isrc/cpu -Isrc/build -Isrc/exec -Isrc/host -Iruntime/include \ $(COVFLAGS) LDFLAGS = -pie LIBS = -lm @@ -78,6 +78,7 @@ SOURCES = src/main.c src/kauri_impl.c \ src/triton/lex.c src/triton/parse.c src/triton/sema.c src/triton/lower.c \ src/mlir/mlir_fe.c src/mlir/lower.c \ src/exec/execs.c src/exec/cpu_exec.c src/exec/booth_run.c src/exec/verbs.c \ + src/host/hgen.c \ runtime/host/cuda/nv_rt.c runtime/host/cuda/nv_exec.c # Certik's pure-C MLIR reader, vendored under src/mlir/vendor. It carries his @@ -179,7 +180,7 @@ TSRC = tests/tmain.c tests/tsmoke.c tests/tcomp.c tests/tenc.c \ tests/ttpl.c \ tests/tvec.c \ tests/tref.c tests/ttyc.c tests/tcpp.c \ - tests/tmof.c tests/tasm.c + tests/tmof.c tests/tasm.c tests/thost.c TOBJS = $(TSRC:%.c=$(OBJDIR)/%.o) COBJS = $(OBJDIR)/src/kauri_impl.o $(OBJDIR)/src/ir/bir.o $(OBJDIR)/src/ir/bir_print.o $(OBJDIR)/src/ir/bir_lower.o $(OBJDIR)/src/ir/bir_mem2reg.o $(OBJDIR)/src/ir/bir_cfold.o $(OBJDIR)/src/ir/bir_dce.o $(OBJDIR)/src/ir/bir_struct.o $(OBJDIR)/src/ir/bir_insert.o $(OBJDIR)/src/ir/bir_sroa.o $(OBJDIR)/src/ir/bir_inline.o \ @@ -190,6 +191,7 @@ COBJS = $(OBJDIR)/src/kauri_impl.o $(OBJDIR)/src/ir/bir.o $(OBJDIR)/src/ir/bir $(OBJDIR)/src/fe/bc_err.o $(OBJDIR)/src/fe/lexer.o $(OBJDIR)/src/fe/parser.o $(OBJDIR)/src/fe/preproc.o $(OBJDIR)/src/fe/sema.o \ $(OBJDIR)/runtime/host/bc_abend.o $(HOSTRT) \ $(OBJDIR)/src/backend/backends.o \ + $(OBJDIR)/src/host/hgen.o \ $(OBJDIR)/src/amdgpu/amd_be.o $(OBJDIR)/src/nvidia/nv_be.o \ $(OBJDIR)/src/tensix/tensix_be.o $(OBJDIR)/src/cpu/cpu_be.o \ $(OBJDIR)/src/metal/metal_be.o $(OBJDIR)/src/intel/intel_be.o \ diff --git a/docs/usage.md b/docs/usage.md index 213ee34..168b63a 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -32,6 +32,19 @@ The compiled binary is `kath` (after Kathleen Booth); the project is Booth. They ./kath build -o out.o # compile only ./kath doctor # report devices and toolchain, then self-test +# Compile a .cu the way nvcc would: device code into a fatbin, host code +# through your C++ compiler, one object out +./kath cuda -c -fPIC kernel.cu -o kernel.o + +# When the cubin backend refuses a kernel, that unit's fatbin carries PTX +# alone and the fallback says so on stderr. On by default, and Latimer runs +# PTX where it finds no SASS. +./kath cuda -c kernel.cu -o kernel.o --ptx-fallback + +# Turn it off and a refused unit is a hard failure again. That is how you +# enumerate every gap in the SASS backend across a whole build. +./kath cuda -c kernel.cu -o kernel.o --no-ptx-fallback + # Compile to AMD GPU binary (RDNA 3, default) ./kath --amdgpu-bin kernel.cu -o kernel.hsaco diff --git a/lang/en.txt b/lang/en.txt index cb4bb5c..8b08f46 100644 --- a/lang/en.txt +++ b/lang/en.txt @@ -185,7 +185,7 @@ E581=%s: a call names function %u, which is not in the module E582=%s: a call argument of type %s needs a register pair or a reference, which Booth does not lay down E583=%s: a call returning %s needs a register pair or a reference, which Booth does not lay down E584=%s: a call carries an operand list the emitter cannot read -E600=%s: a cubin holds one kernel and this module has %u +E600=%s: a cubin holds at most %u kernels and this module has %u E601=%s: %s has no SASS form the backend can encode E602=%s: %s needs %u basic blocks and the SASS control-flow pass holds %u E603=%s: %s needs more than the %u registers the SASS backend allocates @@ -197,6 +197,10 @@ E608=%s: the cubin for %s did not assemble E609=%s: %s takes an operand the SASS backend has no form for E610=%s: special register %u has no SASS form E611=%s: %s has an address or width the SASS backend has no form for +E620=%s: '%s' is launched here and no kernel of that name reached the cubin +E621=%s: '%s' takes a parameter the host stub cannot carry, so no launch for it can be written +E622=%s: the host registration table holds at most %u kernels and this module has more +E623=%s: the host compiler refused the emitted source (exit %d) E640='%s' needs a PTX form no Booth backend emits E660='%s' has more initialisers than it has elements E661=Booth cannot lay this initialiser down: %s diff --git a/runtime/include/cooperative_groups.h b/runtime/include/cooperative_groups.h new file mode 100644 index 0000000..31dd03b --- /dev/null +++ b/runtime/include/cooperative_groups.h @@ -0,0 +1,54 @@ +#ifndef COOPERATIVE_GROUPS_H +#define COOPERATIVE_GROUPS_H + +#include + +#if defined(__cplusplus) + +namespace cooperative_groups { + +class thread_group { +public: + void sync() const; + unsigned long long size() const; + unsigned long long num_threads() const; + unsigned long long thread_rank() const; + bool is_valid() const; +}; + +class grid_group : public thread_group { +public: + dim3 group_dim() const; + dim3 group_index() const; + dim3 thread_index() const; + unsigned long long num_blocks() const; + unsigned long long block_rank() const; +}; + +class thread_block : public thread_group { +public: + dim3 group_index() const; + dim3 thread_index() const; + dim3 dim_threads() const; +}; + +class coalesced_group : public thread_group { +public: + unsigned int ballot(int pred) const; + int any(int pred) const; + int all(int pred) const; + unsigned int match_any(int val) const; + unsigned int match_all(int val, int &pred) const; +}; + +grid_group this_grid(); +thread_block this_thread_block(); +coalesced_group coalesced_threads(); + +void sync(const thread_group &g); + +} + +#endif + +#endif diff --git a/runtime/include/cooperative_groups/reduce.h b/runtime/include/cooperative_groups/reduce.h new file mode 100644 index 0000000..d23552d --- /dev/null +++ b/runtime/include/cooperative_groups/reduce.h @@ -0,0 +1,24 @@ +#ifndef COOPERATIVE_GROUPS_REDUCE_H +#define COOPERATIVE_GROUPS_REDUCE_H + +#include + +#if defined(__cplusplus) + +namespace cooperative_groups { + +template struct plus { T operator()(T a, T b) const; }; +template struct less { T operator()(T a, T b) const; }; +template struct greater { T operator()(T a, T b) const; }; +template struct bit_and { T operator()(T a, T b) const; }; +template struct bit_or { T operator()(T a, T b) const; }; +template struct bit_xor { T operator()(T a, T b) const; }; + +template +T reduce(const G &g, T val, Op op); + +} + +#endif + +#endif diff --git a/runtime/include/cublas_v2.h b/runtime/include/cublas_v2.h new file mode 100644 index 0000000..cd21e37 --- /dev/null +++ b/runtime/include/cublas_v2.h @@ -0,0 +1,240 @@ +#ifndef CUBLAS_V2_H +#define CUBLAS_V2_H + +#include +#include "cuda_runtime.h" + +#if defined(__cplusplus) +#define CUBLAS_C extern "C" +#else +#define CUBLAS_C extern +#endif + +typedef enum { + CUBLAS_STATUS_SUCCESS = 0, + CUBLAS_STATUS_NOT_INITIALIZED = 1, + CUBLAS_STATUS_ALLOC_FAILED = 3, + CUBLAS_STATUS_INVALID_VALUE = 7, + CUBLAS_STATUS_ARCH_MISMATCH = 8, + CUBLAS_STATUS_MAPPING_ERROR = 11, + CUBLAS_STATUS_EXECUTION_FAILED = 13, + CUBLAS_STATUS_INTERNAL_ERROR = 14, + CUBLAS_STATUS_NOT_SUPPORTED = 15 +} cublasStatus_t; + +typedef enum { + CUBLAS_POINTER_MODE_HOST = 0, + CUBLAS_POINTER_MODE_DEVICE = 1 +} cublasPointerMode_t; + +typedef enum { + CUBLAS_DEFAULT_MATH = 0, + CUBLAS_TENSOR_OP_MATH = 1, + CUBLAS_PEDANTIC_MATH = 2, + CUBLAS_TF32_TENSOR_OP_MATH = 3, + CUBLAS_MATH_DISALLOW_REDUCED_PRECISION_REDUCTION = 16 +} cublasMath_t; + +typedef enum { + MAJOR_VERSION = 0, + MINOR_VERSION = 1, + PATCH_LEVEL = 2 +} libraryPropertyType; + +typedef enum { + CUBLAS_OP_N = 0, + CUBLAS_OP_T = 1, + CUBLAS_OP_C = 2 +} cublasOperation_t; + +typedef enum { + CUBLAS_SIDE_LEFT = 0, + CUBLAS_SIDE_RIGHT = 1 +} cublasSideMode_t; + +typedef enum { + CUBLAS_FILL_MODE_LOWER = 0, + CUBLAS_FILL_MODE_UPPER = 1, + CUBLAS_FILL_MODE_FULL = 2 +} cublasFillMode_t; + +typedef enum { + CUBLAS_DIAG_NON_UNIT = 0, + CUBLAS_DIAG_UNIT = 1 +} cublasDiagType_t; + +typedef enum { + CUBLAS_COMPUTE_16F = 64, + CUBLAS_COMPUTE_32F = 68, + CUBLAS_COMPUTE_64F = 70, + CUBLAS_COMPUTE_32I = 72, + CUBLAS_COMPUTE_32F_FAST_16F = 74, + CUBLAS_COMPUTE_32F_FAST_16BF = 75, + CUBLAS_COMPUTE_32F_FAST_TF32 = 77 +} cublasComputeType_t; + +typedef enum { + CUBLAS_GEMM_DEFAULT = -1, + CUBLAS_GEMM_DEFAULT_TENSOR_OP = 99 +} cublasGemmAlgo_t; + +typedef void *cublasHandle_t; + +CUBLAS_C cublasStatus_t cublasCreate_v2(cublasHandle_t *handle); +CUBLAS_C cublasStatus_t cublasDestroy_v2(cublasHandle_t handle); +CUBLAS_C cublasStatus_t cublasSetStream_v2(cublasHandle_t handle, + cudaStream_t sid); +CUBLAS_C cublasStatus_t cublasGetStream_v2(cublasHandle_t handle, + cudaStream_t *sid); +CUBLAS_C cublasStatus_t cublasSetWorkspace_v2(cublasHandle_t handle, + void *wksp, size_t wsz); +CUBLAS_C cublasStatus_t cublasSetMathMode(cublasHandle_t handle, + cublasMath_t mode); +CUBLAS_C cublasStatus_t cublasGetMathMode(cublasHandle_t handle, + cublasMath_t *mode); +CUBLAS_C cublasStatus_t cublasGetVersion_v2(cublasHandle_t handle, + int *version); +CUBLAS_C cublasStatus_t cublasGetProperty(libraryPropertyType type, + int *value); +CUBLAS_C cublasStatus_t cublasSetPointerMode_v2(cublasHandle_t handle, + cublasPointerMode_t mode); +CUBLAS_C cublasStatus_t cublasGetPointerMode_v2(cublasHandle_t handle, + cublasPointerMode_t *mode); + +CUBLAS_C cublasStatus_t cublasSaxpy_v2(cublasHandle_t handle, int n, + const float *alpha, const float *x, + int incx, float *y, int incy); +CUBLAS_C cublasStatus_t cublasSscal_v2(cublasHandle_t handle, int n, + const float *alpha, float *x, + int incx); +CUBLAS_C cublasStatus_t cublasScopy_v2(cublasHandle_t handle, int n, + const float *x, int incx, float *y, + int incy); +CUBLAS_C cublasStatus_t cublasSswap_v2(cublasHandle_t handle, int n, + float *x, int incx, float *y, + int incy); +CUBLAS_C cublasStatus_t cublasSrot_v2(cublasHandle_t handle, int n, + float *x, int incx, float *y, int incy, + const float *c, const float *s); +CUBLAS_C cublasStatus_t cublasSdot_v2(cublasHandle_t handle, int n, + const float *x, int incx, + const float *y, int incy, + float *result); +CUBLAS_C cublasStatus_t cublasSasum_v2(cublasHandle_t handle, int n, + const float *x, int incx, + float *result); +CUBLAS_C cublasStatus_t cublasSnrm2_v2(cublasHandle_t handle, int n, + const float *x, int incx, + float *result); +CUBLAS_C cublasStatus_t cublasIsamax_v2(cublasHandle_t handle, int n, + const float *x, int incx, + int *result); + +CUBLAS_C cublasStatus_t cublasSgemm_v2(cublasHandle_t handle, + cublasOperation_t transa, + cublasOperation_t transb, + int m, int n, int k, + const float *alpha, const float *A, + int lda, const float *B, int ldb, + const float *beta, float *C, int ldc); +CUBLAS_C cublasStatus_t cublasSgemmStridedBatched(cublasHandle_t handle, + cublasOperation_t transa, + cublasOperation_t transb, + int m, int n, int k, + const float *alpha, + const float *A, int lda, + long long strideA, + const float *B, int ldb, + long long strideB, + const float *beta, + float *C, int ldc, + long long strideC, + int batchCount); +CUBLAS_C cublasStatus_t cublasSgemmBatched(cublasHandle_t handle, + cublasOperation_t transa, + cublasOperation_t transb, + int m, int n, int k, + const float *alpha, + const float *const Aarray[], + int lda, + const float *const Barray[], + int ldb, const float *beta, + float *const Carray[], int ldc, + int batchCount); + +CUBLAS_C cublasStatus_t cublasStrsm_v2(cublasHandle_t handle, + cublasSideMode_t side, + cublasFillMode_t uplo, + cublasOperation_t trans, + cublasDiagType_t diag, int m, int n, + const float *alpha, const float *A, + int lda, float *B, int ldb); +CUBLAS_C cublasStatus_t cublasStrsmBatched(cublasHandle_t handle, + cublasSideMode_t side, + cublasFillMode_t uplo, + cublasOperation_t trans, + cublasDiagType_t diag, + int m, int n, const float *alpha, + const float *const A[], int lda, + float *const B[], int ldb, + int batchCount); + +CUBLAS_C cublasStatus_t cublasGemmEx(cublasHandle_t handle, + cublasOperation_t transa, + cublasOperation_t transb, + int m, int n, int k, const void *alpha, + const void *A, cudaDataType_t Atype, + int lda, const void *B, + cudaDataType_t Btype, int ldb, + const void *beta, void *C, + cudaDataType_t Ctype, int ldc, + cublasComputeType_t computeType, + cublasGemmAlgo_t algo); +CUBLAS_C cublasStatus_t cublasGemmStridedBatchedEx(cublasHandle_t handle, + cublasOperation_t transa, + cublasOperation_t transb, + int m, int n, int k, const void *alpha, + const void *A, cudaDataType_t Atype, + int lda, long long strideA, + const void *B, cudaDataType_t Btype, + int ldb, long long strideB, + const void *beta, void *C, + cudaDataType_t Ctype, int ldc, + long long strideC, int batchCount, + cublasComputeType_t computeType, + cublasGemmAlgo_t algo); +CUBLAS_C cublasStatus_t cublasGemmBatchedEx(cublasHandle_t handle, + cublasOperation_t transa, + cublasOperation_t transb, + int m, int n, int k, const void *alpha, + const void *const Aarray[], + cudaDataType_t Atype, int lda, + const void *const Barray[], + cudaDataType_t Btype, int ldb, + const void *beta, void *const Carray[], + cudaDataType_t Ctype, int ldc, + int batchCount, + cublasComputeType_t computeType, + cublasGemmAlgo_t algo); + +#define cublasStrsm cublasStrsm_v2 +#define cublasCreate cublasCreate_v2 +#define cublasDestroy cublasDestroy_v2 +#define cublasSetStream cublasSetStream_v2 +#define cublasGetStream cublasGetStream_v2 +#define cublasSetWorkspace cublasSetWorkspace_v2 +#define cublasGetVersion cublasGetVersion_v2 +#define cublasSetPointerMode cublasSetPointerMode_v2 +#define cublasGetPointerMode cublasGetPointerMode_v2 +#define cublasSaxpy cublasSaxpy_v2 +#define cublasSscal cublasSscal_v2 +#define cublasScopy cublasScopy_v2 +#define cublasSswap cublasSswap_v2 +#define cublasSrot cublasSrot_v2 +#define cublasSdot cublasSdot_v2 +#define cublasSasum cublasSasum_v2 +#define cublasSnrm2 cublasSnrm2_v2 +#define cublasIsamax cublasIsamax_v2 +#define cublasSgemm cublasSgemm_v2 + +#endif diff --git a/runtime/include/cuda.h b/runtime/include/cuda.h new file mode 100644 index 0000000..ef4c0ec --- /dev/null +++ b/runtime/include/cuda.h @@ -0,0 +1,229 @@ +#ifndef CUDA_H +#define CUDA_H + +#include + +#if defined(__cplusplus) +#define CUDRV_C extern "C" +#else +#define CUDRV_C extern +#endif + +typedef int CUresult; +typedef int CUdevice; +typedef void *CUcontext; +typedef void *CUmodule; +typedef void *CUfunction; +typedef void *CUstream; +typedef void *CUevent; +typedef unsigned long long CUdeviceptr; + +typedef struct CUuuid { char bytes[16]; } CUuuid; + +typedef unsigned long long CUmemGenericAllocationHandle; + +typedef enum CUmemAllocationType { + CU_MEM_ALLOCATION_TYPE_INVALID = 0, + CU_MEM_ALLOCATION_TYPE_PINNED = 1, + CU_MEM_ALLOCATION_TYPE_MAX = 2 +} CUmemAllocationType; + +typedef enum CUmemLocationType { + CU_MEM_LOCATION_TYPE_INVALID = 0, + CU_MEM_LOCATION_TYPE_DEVICE = 1, + CU_MEM_LOCATION_TYPE_HOST = 2, + CU_MEM_LOCATION_TYPE_HOST_NUMA = 3, + CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT = 4, + CU_MEM_LOCATION_TYPE_MAX = 5 +} CUmemLocationType; + +typedef enum CUmemAllocationHandleType { + CU_MEM_HANDLE_TYPE_NONE = 0, + CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR = 1, + CU_MEM_HANDLE_TYPE_WIN32 = 2, + CU_MEM_HANDLE_TYPE_WIN32_KMT = 4, + CU_MEM_HANDLE_TYPE_FABRIC = 8 +} CUmemAllocationHandleType; + +typedef enum CUmemAccess_flags { + CU_MEM_ACCESS_FLAGS_PROT_NONE = 0, + CU_MEM_ACCESS_FLAGS_PROT_READ = 1, + CU_MEM_ACCESS_FLAGS_PROT_READWRITE = 3, + CU_MEM_ACCESS_FLAGS_PROT_MAX = 4 +} CUmemAccess_flags; + +typedef enum CUmemAllocationGranularity_flags { + CU_MEM_ALLOC_GRANULARITY_MINIMUM = 0, + CU_MEM_ALLOC_GRANULARITY_RECOMMENDED = 1 +} CUmemAllocationGranularity_flags; + +typedef struct CUmemLocation { + CUmemLocationType type; + int id; +} CUmemLocation; + +typedef struct CUmemAllocationProp { + CUmemAllocationType type; + CUmemAllocationHandleType requestedHandleTypes; + CUmemLocation location; + void *win32HandleMetaData; + struct { + unsigned char compressionType; + unsigned char gpuDirectRDMACapable; + unsigned short usage; + unsigned char reserved[4]; + } allocFlags; +} CUmemAllocationProp; + +typedef struct CUmemAccessDesc { + CUmemLocation location; + CUmemAccess_flags flags; +} CUmemAccessDesc; + +enum { + CUDA_SUCCESS = 0, + CUDA_ERROR_INVALID_VALUE = 1, + CUDA_ERROR_OUT_OF_MEMORY = 2, + CUDA_ERROR_NOT_INITIALIZED = 3, + CUDA_ERROR_DEINITIALIZED = 4, + CUDA_ERROR_NO_DEVICE = 100, + CUDA_ERROR_INVALID_DEVICE = 101, + CUDA_ERROR_INVALID_IMAGE = 200, + CUDA_ERROR_INVALID_CONTEXT = 201, + CUDA_ERROR_INVALID_HANDLE = 400, + CUDA_ERROR_NOT_FOUND = 500, + CUDA_ERROR_NOT_READY = 600, + CUDA_ERROR_LAUNCH_FAILED = 719, + CUDA_ERROR_NOT_SUPPORTED = 801, + CUDA_ERROR_UNKNOWN = 999 +}; + +enum { + CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK = 1, + CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X = 2, + CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y = 3, + CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z = 4, + CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X = 5, + CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y = 6, + CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z = 7, + CU_DEVICE_ATTRIBUTE_WARP_SIZE = 10, + CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT = 16, + CU_DEVICE_ATTRIBUTE_PCI_BUS_ID = 33, + CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID = 34, + CU_DEVICE_ATTRIBUTE_PCI_DOMAIN_ID = 50, + CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR = 75, + CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR = 76, + CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH = 95, + CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED = 102 +}; + +enum { + CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK = 0, + CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES = 1, + CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES = 2, + CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES = 3, + CU_FUNC_ATTRIBUTE_NUM_REGS = 4 +}; + +enum { + CU_CTX_SCHED_AUTO = 0, + CU_STREAM_DEFAULT = 0, + CU_STREAM_NON_BLOCKING = 1, + CU_EVENT_DEFAULT = 0 +}; + +CUDRV_C CUresult cuInit(unsigned flags); +CUDRV_C CUresult cuDriverGetVersion(int *v); +CUDRV_C CUresult cuGetErrorName(CUresult r, const char **s); +CUDRV_C CUresult cuGetErrorString(CUresult r, const char **s); + +CUDRV_C CUresult cuDeviceGet(CUdevice *d, int ordinal); +CUDRV_C CUresult cuDeviceGetCount(int *n); +CUDRV_C CUresult cuDeviceGetName(char *buf, int len, CUdevice d); +CUDRV_C CUresult cuDeviceGetUuid(CUuuid *u, CUdevice d); +CUDRV_C CUresult cuDeviceGetAttribute(int *out, int attr, CUdevice d); +CUDRV_C CUresult cuDeviceTotalMem_v2(size_t *n, CUdevice d); +CUDRV_C CUresult cuDeviceComputeCapability(int *maj, int *min, CUdevice d); + +CUDRV_C CUresult cuCtxCreate_v2(CUcontext *c, unsigned flags, CUdevice d); +CUDRV_C CUresult cuCtxDestroy_v2(CUcontext c); +CUDRV_C CUresult cuCtxSetCurrent(CUcontext c); +CUDRV_C CUresult cuCtxGetCurrent(CUcontext *c); +CUDRV_C CUresult cuCtxGetDevice(CUdevice *d); +CUDRV_C CUresult cuCtxSynchronize(void); +CUDRV_C CUresult cuDevicePrimaryCtxRetain(CUcontext *c, CUdevice d); +CUDRV_C CUresult cuDevicePrimaryCtxRelease_v2(CUdevice d); + +CUDRV_C CUresult cuModuleLoadData(CUmodule *m, const void *image); +CUDRV_C CUresult cuModuleLoadDataEx(CUmodule *m, const void *image, + unsigned n, int *opts, void **vals); +CUDRV_C CUresult cuModuleUnload(CUmodule m); +CUDRV_C CUresult cuModuleGetFunction(CUfunction *f, CUmodule m, + const char *name); +CUDRV_C CUresult cuFuncGetAttribute(int *out, int attr, CUfunction f); + +CUDRV_C CUresult cuMemAlloc_v2(CUdeviceptr *p, size_t n); +CUDRV_C CUresult cuMemFree_v2(CUdeviceptr p); +CUDRV_C CUresult cuMemHostAlloc(void **p, size_t n, unsigned flags); +CUDRV_C CUresult cuMemFreeHost(void *p); +CUDRV_C CUresult cuMemHostGetDevicePointer_v2(CUdeviceptr *d, void *p, + unsigned flags); +CUDRV_C CUresult cuMemGetInfo_v2(size_t *freeb, size_t *total); + +CUDRV_C CUresult cuMemAddressReserve(CUdeviceptr *ptr, size_t size, + size_t alignment, CUdeviceptr addr, + unsigned long long flags); +CUDRV_C CUresult cuMemAddressFree(CUdeviceptr ptr, size_t size); +CUDRV_C CUresult cuMemCreate(CUmemGenericAllocationHandle *handle, size_t size, + const CUmemAllocationProp *prop, + unsigned long long flags); +CUDRV_C CUresult cuMemRelease(CUmemGenericAllocationHandle handle); +CUDRV_C CUresult cuMemMap(CUdeviceptr ptr, size_t size, size_t offset, + CUmemGenericAllocationHandle handle, + unsigned long long flags); +CUDRV_C CUresult cuMemUnmap(CUdeviceptr ptr, size_t size); +CUDRV_C CUresult cuMemSetAccess(CUdeviceptr ptr, size_t size, + const CUmemAccessDesc *desc, size_t count); +CUDRV_C CUresult cuMemGetAccess(unsigned long long *flags, + const CUmemLocation *location, CUdeviceptr ptr); +CUDRV_C CUresult cuMemGetAllocationGranularity( + size_t *granularity, const CUmemAllocationProp *prop, + CUmemAllocationGranularity_flags option); + +CUDRV_C CUresult cuMemcpy(CUdeviceptr dst, CUdeviceptr src, size_t n); +CUDRV_C CUresult cuMemcpyAsync(CUdeviceptr dst, CUdeviceptr src, size_t n, + CUstream s); +CUDRV_C CUresult cuMemcpyHtoD_v2(CUdeviceptr dst, const void *src, size_t n); +CUDRV_C CUresult cuMemcpyDtoH_v2(void *dst, CUdeviceptr src, size_t n); +CUDRV_C CUresult cuMemcpyDtoD_v2(CUdeviceptr dst, CUdeviceptr src, size_t n); +CUDRV_C CUresult cuMemcpyHtoDAsync_v2(CUdeviceptr dst, const void *src, + size_t n, CUstream s); +CUDRV_C CUresult cuMemcpyDtoHAsync_v2(void *dst, CUdeviceptr src, size_t n, + CUstream s); +CUDRV_C CUresult cuMemcpyDtoDAsync_v2(CUdeviceptr dst, CUdeviceptr src, + size_t n, CUstream s); +CUDRV_C CUresult cuMemsetD8_v2(CUdeviceptr p, unsigned char v, size_t n); +CUDRV_C CUresult cuMemsetD8Async(CUdeviceptr p, unsigned char v, size_t n, + CUstream s); +CUDRV_C CUresult cuMemsetD32_v2(CUdeviceptr p, unsigned v, size_t n); +CUDRV_C CUresult cuMemsetD32Async(CUdeviceptr p, unsigned v, size_t n, + CUstream s); + +CUDRV_C CUresult cuLaunchKernel(CUfunction f, unsigned gx, unsigned gy, + unsigned gz, unsigned bx, unsigned by, + unsigned bz, unsigned sh, CUstream s, + void **args, void **extra); + +CUDRV_C CUresult cuStreamCreate(CUstream *s, unsigned flags); +CUDRV_C CUresult cuStreamDestroy_v2(CUstream s); +CUDRV_C CUresult cuStreamSynchronize(CUstream s); +CUDRV_C CUresult cuStreamQuery(CUstream s); + +CUDRV_C CUresult cuEventCreate(CUevent *e, unsigned flags); +CUDRV_C CUresult cuEventDestroy_v2(CUevent e); +CUDRV_C CUresult cuEventRecord(CUevent e, CUstream s); +CUDRV_C CUresult cuEventSynchronize(CUevent e); +CUDRV_C CUresult cuEventQuery(CUevent e); +CUDRV_C CUresult cuEventElapsedTime(float *ms, CUevent a, CUevent b); + +#endif diff --git a/runtime/include/cuda_bf16.h b/runtime/include/cuda_bf16.h new file mode 100644 index 0000000..4776979 --- /dev/null +++ b/runtime/include/cuda_bf16.h @@ -0,0 +1,93 @@ +#ifndef CUDA_BF16_H +#define CUDA_BF16_H + +#if !defined(__CUDACC__) + +#include + +typedef struct __nv_bfloat16 { unsigned short __x; } __nv_bfloat16; +typedef struct __nv_bfloat162 { __nv_bfloat16 x, y; } __nv_bfloat162; + +typedef __nv_bfloat16 nv_bfloat16; +typedef __nv_bfloat162 nv_bfloat162; + +static unsigned __bbits(float f) +{ + unsigned u; + + memcpy(&u, &f, sizeof u); + return u; +} + +static float __bfrombits(unsigned u) +{ + float f; + + memcpy(&f, &u, sizeof f); + return f; +} + +static __nv_bfloat16 __float2bfloat16(float f) +{ + unsigned u = __bbits(f); + __nv_bfloat16 b; + + if (((u >> 23) & 0xFFu) == 0xFFu) { + b.__x = (unsigned short)(u >> 16); + return b; + } + b.__x = (unsigned short)((u + 0x7FFFu + ((u >> 16) & 1u)) >> 16); + return b; +} + +static float __bfloat162float(__nv_bfloat16 b) +{ + return __bfrombits((unsigned)b.__x << 16); +} + +static __nv_bfloat162 __halves2bfloat162(__nv_bfloat16 a, __nv_bfloat16 b) +{ + __nv_bfloat162 r; + + r.x = a; + r.y = b; + return r; +} + +static __nv_bfloat162 __float2bfloat162_rn(float f) +{ + return __halves2bfloat162(__float2bfloat16(f), __float2bfloat16(f)); +} + +static __nv_bfloat16 __low2bfloat16(__nv_bfloat162 a) { return a.x; } +static __nv_bfloat16 __high2bfloat16(__nv_bfloat162 a) { return a.y; } + +#if defined(__cplusplus) + +static inline __nv_bfloat16 operator+(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __float2bfloat16(__bfloat162float(a) + __bfloat162float(b)); } +static inline __nv_bfloat16 operator-(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __float2bfloat16(__bfloat162float(a) - __bfloat162float(b)); } +static inline __nv_bfloat16 operator*(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __float2bfloat16(__bfloat162float(a) * __bfloat162float(b)); } +static inline __nv_bfloat16 operator/(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __float2bfloat16(__bfloat162float(a) / __bfloat162float(b)); } + +static inline bool operator==(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __bfloat162float(a) == __bfloat162float(b); } +static inline bool operator!=(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __bfloat162float(a) != __bfloat162float(b); } +static inline bool operator<(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __bfloat162float(a) < __bfloat162float(b); } +static inline bool operator>(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __bfloat162float(a) > __bfloat162float(b); } +static inline bool operator<=(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __bfloat162float(a) <= __bfloat162float(b); } +static inline bool operator>=(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __bfloat162float(a) >= __bfloat162float(b); } + +#endif + +#endif + +#endif diff --git a/runtime/include/cuda_fp16.h b/runtime/include/cuda_fp16.h new file mode 100644 index 0000000..ed28865 --- /dev/null +++ b/runtime/include/cuda_fp16.h @@ -0,0 +1,144 @@ +#ifndef CUDA_FP16_H +#define CUDA_FP16_H + +#if !defined(__CUDACC__) + +#include + +typedef struct __half { + unsigned short __x; +#if defined(__cplusplus) + __half() = default; + __half(float f); +#endif +} __half; +typedef struct __half2 { __half x, y; } __half2; + +typedef __half half; +typedef __half2 half2; + +static unsigned __hbits(float f) +{ + unsigned u; + + memcpy(&u, &f, sizeof u); + return u; +} + +static float __hfrombits(unsigned u) +{ + float f; + + memcpy(&f, &u, sizeof f); + return f; +} + +static __half __float2half(float f) +{ + unsigned u = __hbits(f); + unsigned s = (u >> 16) & 0x8000u; + int e = (int)((u >> 23) & 0xFFu) - 112; + unsigned m = u & 0x7FFFFFu; + __half h; + + if (((u >> 23) & 0xFFu) == 0xFFu) { + h.__x = (unsigned short)(s | 0x7C00u | (m != 0u ? 0x200u : 0u)); + return h; + } + if (e >= 0x1F) { h.__x = (unsigned short)(s | 0x7C00u); return h; } + if (e <= 0) { + if (e < -10) { h.__x = (unsigned short)s; return h; } + m |= 0x800000u; + { + unsigned sh = (unsigned)(14 - e); + unsigned r = m & ((1u << sh) - 1u); + unsigned v = m >> sh; + + if (r > (1u << (sh - 1u)) + || (r == (1u << (sh - 1u)) && (v & 1u) != 0u)) v++; + h.__x = (unsigned short)(s | v); + } + return h; + } + { + unsigned v = ((unsigned)e << 10) | (m >> 13); + unsigned r = m & 0x1FFFu; + + if (r > 0x1000u || (r == 0x1000u && (v & 1u) != 0u)) v++; + h.__x = (unsigned short)(s | v); + } + return h; +} + +static float __half2float(__half h) +{ + unsigned s = (unsigned)(h.__x & 0x8000u) << 16; + unsigned e = (unsigned)(h.__x >> 10) & 0x1Fu; + unsigned m = (unsigned)h.__x & 0x3FFu; + + if (e == 0u) { + if (m == 0u) return __hfrombits(s); + while ((m & 0x400u) == 0u) { m <<= 1; e--; } + e++; + m &= 0x3FFu; + } else if (e == 0x1Fu) { + return __hfrombits(s | 0x7F800000u | (m << 13)); + } + return __hfrombits(s | ((e + 112u) << 23) | (m << 13)); +} + +#if defined(__cplusplus) +inline __half::__half(float f) { __x = __float2half(f).__x; } +#endif + +static __half2 __halves2half2(__half a, __half b) +{ + __half2 r; + + r.x = a; + r.y = b; + return r; +} + +static __half2 make_half2(__half a, __half b) +{ + return __halves2half2(a, b); +} + +static __half2 __float2half2_rn(float f) +{ + return __halves2half2(__float2half(f), __float2half(f)); +} + +static __half __low2half(__half2 a) { return a.x; } +static __half __high2half(__half2 a) { return a.y; } + +#if defined(__cplusplus) + +static inline __half operator+(__half a, __half b) +{ return __float2half(__half2float(a) + __half2float(b)); } +static inline __half operator-(__half a, __half b) +{ return __float2half(__half2float(a) - __half2float(b)); } +static inline __half operator*(__half a, __half b) +{ return __float2half(__half2float(a) * __half2float(b)); } +static inline __half operator/(__half a, __half b) +{ return __float2half(__half2float(a) / __half2float(b)); } + +static inline bool operator==(__half a, __half b) +{ return __half2float(a) == __half2float(b); } +static inline bool operator!=(__half a, __half b) +{ return __half2float(a) != __half2float(b); } +static inline bool operator<(__half a, __half b) +{ return __half2float(a) < __half2float(b); } +static inline bool operator>(__half a, __half b) +{ return __half2float(a) > __half2float(b); } +static inline bool operator<=(__half a, __half b) +{ return __half2float(a) <= __half2float(b); } +static inline bool operator>=(__half a, __half b) +{ return __half2float(a) >= __half2float(b); } + +#endif + +#endif + +#endif diff --git a/runtime/include/cuda_runtime.h b/runtime/include/cuda_runtime.h new file mode 100644 index 0000000..aea2c33 --- /dev/null +++ b/runtime/include/cuda_runtime.h @@ -0,0 +1,379 @@ +#ifndef CUDA_RUNTIME_H +#define CUDA_RUNTIME_H + +#include + +#define CUDART_VERSION 11020 + +#if defined(__cplusplus) +#define CUDART_C extern "C" +#else +#define CUDART_C extern +#endif + +typedef int cudaError_t; +typedef void *cudaStream_t; +typedef void *cudaEvent_t; + +enum { + cudaSuccess = 0, + cudaErrorInvalidValue = 1, + cudaErrorMemoryAllocation = 2, + cudaErrorInitializationError = 3, + cudaErrorInvalidConfiguration = 9, + cudaErrorInvalidSymbol = 13, + cudaErrorInvalidDeviceFunction = 98, + cudaErrorNoDevice = 100, + cudaErrorInvalidDevice = 101, + cudaErrorNoKernelImageForDevice = 209, + cudaErrorInvalidPtx = 218, + cudaErrorInvalidResourceHandle = 400, + cudaErrorNotReady = 600, + cudaErrorIllegalAddress = 700, + cudaErrorLaunchFailure = 719, + cudaErrorNotSupported = 801, + cudaErrorUnknown = 999 +}; + +enum { + cudaMemcpyHostToHost = 0, + cudaMemcpyHostToDevice = 1, + cudaMemcpyDeviceToHost = 2, + cudaMemcpyDeviceToDevice = 3, + cudaMemcpyDefault = 4 +}; + +enum { + cudaStreamDefault = 0, + cudaStreamNonBlocking = 1 +}; + +#define cudaStreamLegacy ((cudaStream_t)0x1) +#define cudaStreamPerThread ((cudaStream_t)0x2) + +typedef enum cudaStreamCaptureMode { + cudaStreamCaptureModeGlobal = 0, + cudaStreamCaptureModeThreadLocal = 1, + cudaStreamCaptureModeRelaxed = 2 +} cudaStreamCaptureMode; + +enum { + cudaDeviceScheduleAuto = 0x00, + cudaDeviceScheduleSpin = 0x01, + cudaDeviceScheduleYield = 0x02, + cudaDeviceScheduleBlockingSync = 0x04, + cudaDeviceMapHost = 0x08, + cudaDeviceLmemResizeToMax = 0x10 +}; + +enum { + cudaHostRegisterDefault = 0x00, + cudaHostRegisterPortable = 0x01, + cudaHostRegisterMapped = 0x02, + cudaHostRegisterIoMemory = 0x04, + cudaHostRegisterReadOnly = 0x08 +}; + +enum { + cudaDevAttrMaxThreadsPerBlock = 1, + cudaDevAttrWarpSize = 10, + cudaDevAttrMultiProcessorCount = 16, + cudaDevAttrComputeCapabilityMajor = 75, + cudaDevAttrComputeCapabilityMinor = 76, + cudaDevAttrCooperativeLaunch = 95 +}; + +enum { + cudaEventDefault = 0, + cudaEventBlockingSync = 1, + cudaEventDisableTiming = 2 +}; + +enum { + cudaStreamCaptureStatusNone = 0 +}; + +enum { + cudaHostAllocDefault = 0x00, + cudaHostAllocPortable = 0x01, + cudaHostAllocMapped = 0x02, + cudaHostAllocWriteCombined = 0x04 +}; + +enum { + cudaMemAttachGlobal = 0x01, + cudaMemAttachHost = 0x02, + cudaMemAttachSingle = 0x04 +}; + +enum { + cudaFuncAttributeMaxDynamicSharedMemorySize = 8, + cudaFuncAttributePreferredSharedMemoryCarveout = 9 +}; + +typedef enum { + CUDA_R_32F = 0, + CUDA_R_64F = 1, + CUDA_R_16F = 2, + CUDA_R_8I = 3, + CUDA_C_32F = 4, + CUDA_C_64F = 5, + CUDA_C_16F = 6, + CUDA_C_8I = 7, + CUDA_R_8U = 8, + CUDA_C_8U = 9, + CUDA_R_32I = 10, + CUDA_C_32I = 11, + CUDA_R_32U = 12, + CUDA_C_32U = 13, + CUDA_R_16BF = 14, + CUDA_C_16BF = 15 +} cudaDataType_t; + +typedef cudaDataType_t cudaDataType; + +typedef struct char2 { signed char x, y; } char2; +typedef struct char4 { signed char x, y, z, w; } char4; +typedef struct uchar2 { unsigned char x, y; } uchar2; +typedef struct uchar4 { unsigned char x, y, z, w; } uchar4; +typedef struct short2 { short x, y; } short2; +typedef struct ushort2 { unsigned short x, y; } ushort2; +typedef struct int2 { int x, y; } int2; +typedef struct int4 { int x, y, z, w; } int4; +typedef struct uint2 { unsigned x, y; } uint2; +typedef struct uint3 { unsigned x, y, z; } uint3; +typedef struct uint4 { unsigned x, y, z, w; } uint4; +typedef struct float2 { float x, y; } float2; +typedef struct float4 { float x, y, z, w; } float4; +typedef struct double2 { double x, y; } double2; + +#define BC_MKV2(T, E) \ + static T make_##T(E x, E y) { T r; r.x = x; r.y = y; return r; } +#define BC_MKV3(T, E) \ + static T make_##T(E x, E y, E z) { T r; r.x = x; r.y = y; r.z = z; \ + return r; } +#define BC_MKV4(T, E) \ + static T make_##T(E x, E y, E z, E w) { T r; r.x = x; r.y = y; r.z = z; \ + r.w = w; return r; } + +BC_MKV2(char2, signed char) +BC_MKV4(char4, signed char) +BC_MKV2(uchar2, unsigned char) +BC_MKV4(uchar4, unsigned char) +BC_MKV2(short2, short) +BC_MKV2(ushort2, unsigned short) +BC_MKV2(int2, int) +BC_MKV4(int4, int) +BC_MKV2(uint2, unsigned) +BC_MKV3(uint3, unsigned) +BC_MKV4(uint4, unsigned) +BC_MKV2(float2, float) +BC_MKV4(float4, float) +BC_MKV2(double2, double) + +typedef struct dim3 { + unsigned int x, y, z; +#if defined(__cplusplus) + dim3(unsigned int a = 1u, unsigned int b = 1u, unsigned int c = 1u) + : x(a), y(b), z(c) {} +#endif +} dim3; + +typedef struct cudaUUID_t { char bytes[16]; } cudaUUID_t; + +typedef struct cudaDeviceProp { + char name[256]; + cudaUUID_t uuid; + char luid[8]; + unsigned luidDeviceNodeMask; + unsigned bcrsv0; + size_t totalGlobalMem; + size_t sharedMemPerBlock; + int regsPerBlock; + int warpSize; + size_t memPitch; + int maxThreadsPerBlock; + int maxThreadsDim[3]; + int maxGridSize[3]; + int clockRate; + size_t totalConstMem; + int major; + int minor; + size_t textureAlignment; + size_t texturePitchAlignment; + int deviceOverlap; + int multiProcessorCount; + int kernelExecTimeoutEnabled; + int integrated; + char bcrsv1[208]; + int memoryClockRate; + int memoryBusWidth; + int l2CacheSize; + char bcrsv2[4]; + int maxThreadsPerMultiProcessor; + char bcrsv3[12]; + size_t sharedMemPerMultiprocessor; + char bcrsv4[48]; + size_t sharedMemPerBlockOptin; + char bcrsv5[8]; + size_t reservedSharedMemPerBlock; + char bcrsv6[64]; +} cudaDeviceProp; + +CUDART_C const char *cudaGetErrorString(cudaError_t e); +CUDART_C cudaError_t cudaGetLastError(void); +CUDART_C cudaError_t cudaPeekAtLastError(void); + +CUDART_C void **__cudaRegisterFatBinary(void *wrap); +CUDART_C void __cudaRegisterFatBinaryEnd(void **h); +CUDART_C void __cudaUnregisterFatBinary(void **h); +CUDART_C void __cudaRegisterFunction(void **h, const char *stub, char *dfn, + const char *name, int lim, void *tid, + void *bid, void *bdim, void *gdim, + int *wsz); +CUDART_C void __cudaRegisterVar(void **h, char *host, char *dev, + const char *name, int ext, size_t size, + int cons, int global); + +CUDART_C unsigned __cudaPushCallConfiguration(dim3 g, dim3 b, size_t sh, + void *stream); +CUDART_C cudaError_t __cudaPopCallConfiguration(dim3 *g, dim3 *b, size_t *sh, + void *stream); +CUDART_C cudaError_t cudaLaunchKernel(const void *fn, dim3 g, dim3 b, + void **args, size_t sh, cudaStream_t s); + +CUDART_C cudaError_t cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( + int *out, const void *fn, int bsz, size_t sh, + unsigned flags); + +CUDART_C cudaError_t cudaFuncSetAttribute(const void *fn, int attr, int val); +CUDART_C cudaError_t cudaLaunchCooperativeKernel(const void *fn, dim3 g, + dim3 b, void **args, + size_t sh, cudaStream_t s); + +CUDART_C cudaError_t cudaMalloc(void **out, size_t n); +CUDART_C cudaError_t cudaFree(void *p); +CUDART_C cudaError_t cudaMallocHost(void **out, size_t n); +CUDART_C cudaError_t cudaFreeHost(void *p); +CUDART_C cudaError_t cudaHostAlloc(void **out, size_t n, unsigned flags); +CUDART_C cudaError_t cudaMallocManaged(void **out, size_t n, unsigned flags); +CUDART_C cudaError_t cudaHostRegister(void *p, size_t n, unsigned flags); +CUDART_C cudaError_t cudaHostUnregister(void *p); +CUDART_C cudaError_t cudaHostGetDevicePointer(void **out, void *p, + unsigned flags); +CUDART_C cudaError_t cudaMemGetInfo(size_t *freeb, size_t *total); + +CUDART_C cudaError_t cudaMemcpyAsync(void *dst, const void *src, size_t n, + int kind, cudaStream_t s); +CUDART_C cudaError_t cudaMemcpy2DAsync(void *dst, size_t dp, const void *src, + size_t sp, size_t w, size_t h, + int kind, cudaStream_t s); +CUDART_C cudaError_t cudaMemcpyPeerAsync(void *dst, int dd, const void *src, + int sd, size_t n, cudaStream_t s); +CUDART_C cudaError_t cudaMemset(void *p, int v, size_t n); +CUDART_C cudaError_t cudaMemsetAsync(void *p, int v, size_t n, cudaStream_t s); + +CUDART_C cudaError_t cudaStreamCreateWithFlags(cudaStream_t *out, + unsigned flags); +CUDART_C cudaError_t cudaStreamDestroy(cudaStream_t s); +CUDART_C cudaError_t cudaStreamSynchronize(cudaStream_t s); +CUDART_C cudaError_t cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, + unsigned flags); +CUDART_C cudaError_t cudaStreamIsCapturing(cudaStream_t s, int *out); +CUDART_C cudaError_t cudaStreamBeginCapture(cudaStream_t s, + cudaStreamCaptureMode mode); +CUDART_C cudaError_t cudaStreamEndCapture(cudaStream_t s, void **graph); + +CUDART_C cudaError_t cudaEventCreateWithFlags(cudaEvent_t *out, + unsigned flags); +CUDART_C cudaError_t cudaEventDestroy(cudaEvent_t e); +CUDART_C cudaError_t cudaEventRecord(cudaEvent_t e, cudaStream_t s); +CUDART_C cudaError_t cudaEventSynchronize(cudaEvent_t e); + +CUDART_C cudaError_t cudaGetDevice(int *out); +CUDART_C cudaError_t cudaSetDevice(int dev); +CUDART_C cudaError_t cudaGetDeviceCount(int *out); +CUDART_C cudaError_t cudaDeviceGetAttribute(int *out, int attr, int dev); +CUDART_C cudaError_t cudaGetDeviceProperties_v2(cudaDeviceProp *prop, int dev); +CUDART_C cudaError_t cudaDeviceGetPCIBusId(char *buf, int len, int dev); +CUDART_C cudaError_t cudaDeviceSynchronize(void); +CUDART_C cudaError_t cudaSetDeviceFlags(unsigned flags); +CUDART_C cudaError_t cudaDeviceCanAccessPeer(int *out, int dev, int peer); +CUDART_C cudaError_t cudaDeviceEnablePeerAccess(int peer, unsigned flags); + +#if !defined(__CUDACC__) + +extern const uint3 threadIdx; +extern const uint3 blockIdx; +extern const dim3 blockDim; +extern const dim3 gridDim; +extern const int warpSize; + +static cudaError_t cudaMemcpy(void *dst, const void *src, size_t n, int kind) +{ + cudaError_t e = cudaMemcpyAsync(dst, src, n, kind, (cudaStream_t)0); + + if (e != cudaSuccess) return e; + return cudaStreamSynchronize((cudaStream_t)0); +} + +static cudaError_t cudaMemcpy2D(void *dst, size_t dp, const void *src, + size_t sp, size_t w, size_t h, int kind) +{ + cudaError_t e = cudaMemcpy2DAsync(dst, dp, src, sp, w, h, kind, + (cudaStream_t)0); + + if (e != cudaSuccess) return e; + return cudaStreamSynchronize((cudaStream_t)0); +} + +static cudaError_t cudaMemcpyPeer(void *dst, int dd, const void *src, int sd, + size_t n) +{ + cudaError_t e = cudaMemcpyPeerAsync(dst, dd, src, sd, n, (cudaStream_t)0); + + if (e != cudaSuccess) return e; + return cudaStreamSynchronize((cudaStream_t)0); +} + +static cudaError_t cudaStreamCreate(cudaStream_t *out) +{ + return cudaStreamCreateWithFlags(out, (unsigned)cudaStreamDefault); +} + +static cudaError_t cudaEventCreate(cudaEvent_t *out) +{ + return cudaEventCreateWithFlags(out, (unsigned)cudaEventDefault); +} + +static cudaError_t cudaGetDeviceProperties(cudaDeviceProp *prop, int dev) +{ + return cudaGetDeviceProperties_v2(prop, dev); +} + +#if defined(__cplusplus) + +extern "C" cudaError_t cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, + unsigned flags = 0u); +extern "C" cudaError_t cudaMallocManaged(void **out, size_t n, + unsigned flags = cudaMemAttachGlobal); + +template +static cudaError_t cudaFuncSetAttribute(T *fn, int attr, int val) +{ + return cudaFuncSetAttribute((const void *)fn, attr, val); +} + +template +static cudaError_t cudaOccupancyMaxActiveBlocksPerMultiprocessor( + int *out, T fn, int bsz, size_t sh) +{ + return cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( + out, (const void *)fn, bsz, sh, 0u); +} + +#endif + +#endif + +#endif diff --git a/src/amdgpu/amd_be.c b/src/amdgpu/amd_be.c index f680309..83e157c 100644 --- a/src/amdgpu/amd_be.c +++ b/src/amdgpu/amd_be.c @@ -180,7 +180,7 @@ const be_desc_t be_amd = { .feats = BE_F_SIMT | BE_F_ATOMIC | BE_F_SHARED | BE_F_WARP | BE_F_BARRIER | BE_F_DIV | BE_F_SCRATCH | BE_F_TRANSC | BE_F_F16 | BE_F_F64 | BE_F_MFMA | BE_F_NOCALL - | BE_F_BYTES, + | BE_F_BYTES | BE_F_REACH, .opts_size = sizeof(amd_opts_t), .flags = amd_flags, .parse = amd_parse, diff --git a/src/amdgpu/isel.c b/src/amdgpu/isel.c index 89bd2e4..e75f81b 100644 --- a/src/amdgpu/isel.c +++ b/src/amdgpu/isel.c @@ -2081,10 +2081,10 @@ static void isel_thread_model(uint32_t idx, const bir_inst_t *I) } } -static void isel_barrier(void) +static void isel_barrier(const bir_inst_t *I) { emit_wait_all(); - emit0_0(AMD_S_BARRIER, 0); + if (!I->subop) emit0_0(AMD_S_BARRIER, 0); } static void isel_fence(void) @@ -2826,7 +2826,7 @@ static void isel_function(uint32_t fi) /* Barriers */ case BIR_BARRIER: case BIR_BARRIER_GROUP: - isel_barrier(); + isel_barrier(I); break; case BIR_FENCE: isel_fence(); @@ -2981,13 +2981,13 @@ int amdgpu_compile(const bir_module_t *bir, amd_module_t *amd) amd->code_len = 0; amd->asm_len = 0; memset(amd->divergent, 0, sizeof(amd->divergent)); - memset(amd->val_vreg, 0xFF, sizeof(amd->val_vreg)); - memset(amd->val_file, 0, sizeof(amd->val_file)); + memset(amd->val_vreg, 0xFF, (size_t)bir->num_insts * sizeof(amd->val_vreg[0])); + memset(amd->val_file, 0, (size_t)bir->num_insts * sizeof(amd->val_file[0])); memset(amd->reg_map, 0, sizeof(amd->reg_map)); memset(amd->reg_file, 0, sizeof(amd->reg_file)); memset(amd->vr_divg, 0, sizeof(amd->vr_divg)); - memset(amd->val_sbase, 0xFF, sizeof(amd->val_sbase)); - memset(amd->val_scroff, 0xFF, sizeof(amd->val_scroff)); /* -1 = dynamic */ + memset(amd->val_sbase, 0xFF, (size_t)bir->num_insts * sizeof(amd->val_sbase[0])); + memset(amd->val_scroff, 0xFF, (size_t)bir->num_insts * sizeof(amd->val_scroff[0])); /* -1 = dynamic */ amd->nglit = 0; amd->gdlen = 0; amd->grbase = 0; diff --git a/src/backend/backend.h b/src/backend/backend.h index 59d96c8..2799584 100644 --- a/src/backend/backend.h +++ b/src/backend/backend.h @@ -61,6 +61,7 @@ typedef enum { * calls and are left alone. */ #define BE_F_NOCALL (1u << 14) #define BE_F_BYTES (1u << 15) /* materialises byte-initialised globals */ +#define BE_F_REACH (1u << 16) /* ---- Options storage ---- * Each backend gets one fixed slot for whatever its flags set. Sized at diff --git a/src/exec/verbs.c b/src/exec/verbs.c index ae78d6a..0337237 100644 --- a/src/exec/verbs.c +++ b/src/exec/verbs.c @@ -4,6 +4,8 @@ #include "exec.h" #include "booth_run.h" #include "backend.h" +#include "bc_err.h" +#include "hgen.h" #include #include @@ -18,6 +20,7 @@ #define MAXPASS 24 #define PATHN 512 +#define MAXINC 16 static const char VADD_SRC[] = "__global__ void vadd(int *out, int *a, int *b)\n" @@ -495,9 +498,132 @@ static int verb_doctor(void) /* ---- dispatch ---- */ +static int cuda1(const char *flag, const char *file, const char *out, + const char *fat, const char *const *inc, int ninc) +{ + char *av[10 + 2 * MAXINC]; + int n = 0; + + av[n++] = (char *)"kath"; + av[n++] = (char *)flag; + if (fat != NULL) { av[n++] = (char *)"--fatbin"; av[n++] = (char *)fat; } + for (int i = 0; i < ninc; i++) { + av[n++] = (char *)"-I"; + av[n++] = (char *)inc[i]; + } + av[n++] = (char *)file; + av[n++] = (char *)"-o"; + av[n++] = (char *)out; + av[n] = NULL; + return kath_compile(n, av, NULL); +} + +static int oapp(char *b, size_t n, size_t *u, const char *s) +{ + size_t l = strlen(s); + + if (*u + l >= n) return 0; + memcpy(b + *u, s, l); + *u += l; + b[*u] = '\0'; + return 1; +} + +static int oinc(char *b, size_t n, size_t *u, const char *d) +{ + return oapp(b, n, u, " -I\"") && oapp(b, n, u, d) && oapp(b, n, u, "\""); +} + +static int cc_obj(const char *src, const char *out, const char *const *inc, + int ninc, int pic) +{ + char cmd[4096], own[512]; + const char *cc = getenv("BOOTH_CXX"); + size_t u = 0u; + int ok; + + if (cc == NULL || cc[0] == '\0') cc = "g++"; + cmd[0] = '\0'; + ok = oapp(cmd, sizeof cmd, &u, cc) + && oapp(cmd, sizeof cmd, &u, " -std=c++17 -O2"); + if (ok && pic) ok = oapp(cmd, sizeof cmd, &u, " -fPIC"); + for (int i = 0; ok && i < ninc; i++) + ok = oinc(cmd, sizeof cmd, &u, inc[i]); + if (ok && hg_binc(own, sizeof own)) + ok = oinc(cmd, sizeof cmd, &u, own); + ok = ok && oapp(cmd, sizeof cmd, &u, " -c \"") + && oapp(cmd, sizeof cmd, &u, src) + && oapp(cmd, sizeof cmd, &u, "\" -o \"") + && oapp(cmd, sizeof cmd, &u, out) + && oapp(cmd, sizeof cmd, &u, "\""); + if (!ok) return 1; + return ok_status(system(cmd)) ? 0 : 1; +} + +static int verb_cuda(int argc, char **argv) +{ + const char *file = NULL, *out = NULL; + const char *inc[MAXINC]; + char cub[PATHN], ptx[PATHN], fat[PATHN], cpp[PATHN], obuf[PATHN]; + int ninc = 0, rc, obj = 0, pic = 0, fb = 1, nocub = 0; + + for (int i = 2; i < argc; i++) { + if (streq(argv[i], "-c")) { obj = 1; continue; } + if (streq(argv[i], "-fPIC")) { pic = 1; continue; } + if (streq(argv[i], "--ptx-fallback")) { fb = 1; continue; } + if (streq(argv[i], "--no-ptx-fallback")) { fb = 0; continue; } + if (streq(argv[i], "-o") && i + 1 < argc) { out = argv[++i]; continue; } + if (streq(argv[i], "-I") && i + 1 < argc) { + if (ninc < MAXINC) inc[ninc++] = argv[++i]; + else i++; + continue; + } + if (strncmp(argv[i], "-I", 2) == 0 && argv[i][2] != '\0') { + if (ninc < MAXINC) inc[ninc++] = argv[i] + 2; + continue; + } + if (argv[i][0] != '-' && file == NULL) file = argv[i]; + } + if (file == NULL) { + fprintf(stderr, "usage: kath cuda [-c] [-fPIC] [-o out]" + " [-I dir] [--ptx-fallback|--no-ptx-fallback]\n"); + return 2; + } + if (out == NULL) { + repl_ext(obuf, sizeof obuf, file, obj ? "o" : "exe"); + out = obuf; + } + + tmppath(cub, sizeof cub, "cuda", "cubin"); + tmppath(ptx, sizeof ptx, "cuda", "ptx"); + tmppath(fat, sizeof fat, "cuda", "fatbin"); + tmppath(cpp, sizeof cpp, "cuda", "cpp"); + + rc = cuda1("--nvidia-cubin", file, cub, NULL, inc, ninc); + if (rc != 0 && fb) { nocub = 1; rc = 0; } + else if (rc != 0) + fprintf(stderr, "kath cuda: %s: SASS refused this unit and " + "--no-ptx-fallback is set, so this is a hard failure\n", file); + if (rc == 0) rc = cuda1("--nvidia-ptx", file, ptx, NULL, inc, ninc); + if (rc == 0 && nocub) + fprintf(stderr, "kath cuda: ==== PTX FALLBACK ==== %s\n" + "kath cuda: SASS refused a kernel here, see the refusals above; " + "PTX carries this unit and no SASS is in its fatbin\n", file); + if (rc == 0) rc = hg_fat(nocub ? NULL : cub, ptx, 89u, fat); + if (rc == 0) rc = cuda1("--cuda-host", file, cpp, fat, inc, ninc); + if (rc == 0) { + rc = obj ? cc_obj(cpp, out, inc, ninc, pic) : hg_cc(cpp, out, inc, ninc); + if (rc != 0) (void)be_fail(BC_E623, file, rc); + } + remove(cub); remove(ptx); remove(fat); + if (rc == 0) { remove(cpp); printf("kath cuda: wrote %s\n", out); } + return rc == 0 ? 0 : 1; +} + int booth_is_verb(const char *s) { - return streq(s, "run") || streq(s, "build") || streq(s, "doctor"); + return streq(s, "run") || streq(s, "build") || streq(s, "doctor") + || streq(s, "cuda"); } int booth_verb(int argc, char *argv[]) @@ -505,5 +631,6 @@ int booth_verb(int argc, char *argv[]) if (streq(argv[1], "run")) return verb_run(argc, argv); if (streq(argv[1], "build")) return verb_build(argc, argv); if (streq(argv[1], "doctor")) return verb_doctor(); + if (streq(argv[1], "cuda")) return verb_cuda(argc, argv); return 2; } diff --git a/src/fe/ast.h b/src/fe/ast.h index fac6670..3c88ce3 100644 --- a/src/fe/ast.h +++ b/src/fe/ast.h @@ -69,6 +69,7 @@ typedef enum { AST_NAMESPACE, AST_TEMPLATE_DECL, AST_TEMPLATE_PARAM, + AST_TEMPLATE_INST, AST_BASE, diff --git a/src/fe/bc_err.c b/src/fe/bc_err.c index b62da6b..454f24e 100644 --- a/src/fe/bc_err.c +++ b/src/fe/bc_err.c @@ -208,7 +208,7 @@ static const char *bc_dflt[BC_EID_MAX] = { /* E583 */ "%s: a call returning %s needs a register pair or a reference, which Booth does not lay down", /* E584 */ "%s: a call carries an operand list the emitter cannot read", NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, - /* E600 */ "%s: a cubin holds one kernel and this module has %u", + /* E600 */ "%s: a cubin holds at most %u kernels and this module has %u", /* E601 */ "%s: %s has no SASS form the backend can encode", /* E602 */ "%s: %s needs %u basic blocks and the SASS control-flow pass holds %u", /* E603 */ "%s: %s needs more than the %u registers the SASS backend allocates", @@ -220,7 +220,12 @@ static const char *bc_dflt[BC_EID_MAX] = { /* E609 */ "%s: %s takes an operand the SASS backend has no form for", /* E610 */ "%s: special register %u has no SASS form", /* E611 */ "%s: %s has an address or width the SASS backend has no form for", - NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + "%s: '%s' is launched here and no kernel of that name reached the cubin", + "%s: '%s' takes a parameter the host stub cannot carry, so no launch for it can be written", + "%s: the host registration table holds at most %u kernels and this module has more", + "%s: the host compiler refused the emitted source (exit %d)", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, /* E640 */ "'%s' needs a PTX form no Booth backend emits", NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, /* E660 */ "'%s' has more initialisers than it has elements", diff --git a/src/fe/bc_err.h b/src/fe/bc_err.h index a2ede58..e840288 100644 --- a/src/fe/bc_err.h +++ b/src/fe/bc_err.h @@ -232,6 +232,12 @@ typedef enum { BC_E609 = 609, /* operand kind with no SASS form */ BC_E610 = 610, /* special register with no SASS form */ BC_E611 = 611, /* access address or width with no SASS form */ + + BC_E620 = 620, /* a launch naming a kernel with no compiled symbol */ + BC_E621 = 621, /* a kernel parameter list the host stub cannot carry */ + BC_E622 = 622, /* more kernels than the host registration table holds */ + BC_E623 = 623, /* the host compiler refused the emitted source */ + BC_E640 = 640, /* CUDA intrinsic with no PTX form any backend emits */ BC_E660 = 660, diff --git a/src/fe/parser.c b/src/fe/parser.c index 517229a..f6e9be1 100644 --- a/src/fe/parser.c +++ b/src/fe/parser.c @@ -65,6 +65,7 @@ static const char *ast_names[] = { [AST_NAMESPACE] = "namespace", [AST_TEMPLATE_DECL] = "template_decl", [AST_TEMPLATE_PARAM]= "template_param", + [AST_TEMPLATE_INST] = "template_inst", [AST_BASE] = "base", [AST_PP_DIRECTIVE] = "pp_directive", [AST_TRANSLATION_UNIT] = "translation_unit", @@ -1397,6 +1398,8 @@ static uint32_t parse_type_spec(parser_t *P, uint16_t *quals, uint16_t *cuda) } else if (ct == TOK_CU_ALIGN || ct == TOK_ALIGNAS) { uint32_t e = algcl(P); if (e) alg = e; + } else if (ct == TOK_TYPENAME) { + advance(P); } else if (is_storage_class(ct) || ct == TOK_CONST || ct == TOK_VOLATILE || ct == TOK_CONSTEXPR) { *quals |= storage_flag_for(ct); @@ -1888,6 +1891,7 @@ static int starts_declaration(parser_t *P) if (t == TOK_CU_ALIGN || t == TOK_ALIGNAS) return 1; if (t == TOK_TEMPLATE) return 1; if (t == TOK_TYPEDEF) return 1; + if (t == TOK_TYPENAME) return 1; if (t == TOK_NAMESPACE) return 1; if (t == TOK_USING) return 1; /* IDENT IDENT or IDENT * IDENT: probably a declaration. Probably. */ @@ -2067,9 +2071,19 @@ static uint32_t parse_declaration(parser_t *P) k++; } if (peek_type(P, k) == TOK_TEMPLATE && peek_type(P, k + 1) != TOK_LT) { - if (!ext) parse_error(P, BC_E175); - sync_past_semi(P); - return 0; + uint32_t ti = alloc_node(P, AST_TEMPLATE_INST); + uint32_t inner; + + P->nodes[ti].qualifiers = (uint16_t)(ext ? QUAL_EXTERN : 0); + for (int j = 0; j <= k; j++) advance(P); + inner = parse_declaration(P); + if (!inner) { + parse_error(P, BC_E175); + sync_past_semi(P); + return 0; + } + add_child(P, ti, inner); + return ti; } } @@ -2349,15 +2363,24 @@ static uint32_t parse_declaration(parser_t *P) int n = snprintf(P->anon_buf + aoff, sizeof(P->anon_buf) - aoff, "__a%u", P->anon_cnt++); + uint32_t noff = BC_ANON_BASE + aoff; + uint16_t nlen = (uint16_t)n; + P->anon_len += (uint32_t)(n + 1); + if ((quals & QUAL_TYPEDEF) && cur_type(P) == TOK_IDENT + && peek_type(P, 1) == TOK_SEMI) { + noff = cur(P)->offset; + nlen = (uint16_t)cur(P)->len; + } + /* Name the nameless struct inside def's type_node */ uint32_t sn = alloc_node(P, AST_IDENT); - P->nodes[sn].d.text.offset = BC_ANON_BASE + aoff; - P->nodes[sn].d.text.len = (uint16_t)n; + P->nodes[sn].d.text.offset = noff; + P->nodes[sn].d.text.len = nlen; add_child(P, type_node, sn); - if (!reg_tname(P, BC_ANON_BASE + aoff, (uint16_t)n)) + if (!reg_tname(P, noff, nlen)) parse_error(P, BC_E137, BC_MAX_TNAMES); /* Fresh TYPE_STRUCT referencing the synthetic name. @@ -2367,8 +2390,8 @@ static uint32_t parse_declaration(parser_t *P) P->nodes[type_node].d.btype.kind = is_union ? TYPE_UNION : TYPE_STRUCT; uint32_t ref = alloc_node(P, AST_IDENT); - P->nodes[ref].d.text.offset = BC_ANON_BASE + aoff; - P->nodes[ref].d.text.len = (uint16_t)n; + P->nodes[ref].d.text.offset = noff; + P->nodes[ref].d.text.len = nlen; add_child(P, type_node, ref); /* Stash def for injection into the var_decl as @@ -2498,19 +2521,8 @@ static uint32_t parse_declaration(parser_t *P) name = scope; } - if (cur_type(P) == TOK_LT) { - advance(P); - uint32_t targs = alloc_node(P, AST_TEMPLATE_ARGS); - while (cur_type(P) != TOK_GT && cur_type(P) != TOK_EOF) { - uint16_t q2, c2; - uint32_t ta = parse_type_spec(P, &q2, &c2); - if (!ta) ta = parse_expr(P, 21); - add_child(P, targs, pexp(P, ta)); - if (!match(P, TOK_COMMA)) break; - } - expect(P, TOK_GT); - add_child(P, name, targs); - } + if (cur_type(P) == TOK_LT) + add_child(P, name, tnargs(P)); if (cur_type(P) == TOK_LPAREN && isvini(P)) { decl_node = alloc_node(P, AST_VAR_DECL); diff --git a/src/fe/preproc.c b/src/fe/preproc.c index df0f022..b46ea67 100644 --- a/src/fe/preproc.c +++ b/src/fe/preproc.c @@ -1302,6 +1302,13 @@ static void pp_dir_include(preproc_t *pp) include_name[nlen] = '\0'; pp_skip_to_eol(pp); + if (pp->keepinc && is_angle) { + pp_emit_str(pp, "#include <", 10u); + pp_emit_str(pp, include_name, nlen); + pp_emit_char(pp, '>'); + return; + } + /* Search for the file */ char fullpath[BC_MAX_PATH]; int found = 0; @@ -1324,6 +1331,12 @@ static void pp_dir_include(preproc_t *pp) if (!found) { /* Not found — skip with warning (allows test files with system includes) */ /* Don't treat as error — common for , etc. */ + if (pp->keepinc) { + pp_emit_str(pp, "#include ", 9u); + pp_emit_char(pp, is_angle ? '<' : '"'); + pp_emit_str(pp, include_name, nlen); + pp_emit_char(pp, is_angle ? '>' : '"'); + } return; } @@ -1715,8 +1728,6 @@ void pp_init(preproc_t *pp, const char *src, uint32_t len, snprintf(pp->filename, BC_MAX_PATH, "%s", filename); pp_define(pp, "__BARRACUDA__", "1"); - pp_define(pp, "__CUDA_ARCH__", "1100"); - pp_define(pp, "__CUDACC__", "1"); pp_define(pp, "__cplusplus", "201703L"); for (size_t i = 0; i < sizeof pdlim / sizeof pdlim[0]; i++) @@ -1726,6 +1737,13 @@ void pp_init(preproc_t *pp, const char *src, uint32_t len, pdfmt(pp); } +void pp_host(preproc_t *pp) +{ + pp->keepinc = 1; + for (size_t i = 0; i < sizeof pdhnd / sizeof pdhnd[0]; i++) + pp_undef_macro(pp, pdhnd[i].n, (uint32_t)strlen(pdhnd[i].n)); +} + int pp_add_include_path(preproc_t *pp, const char *path) { if (pp->num_include_paths >= PP_MAX_INCLUDE_PATHS) return BC_ERR_OVERFLOW; diff --git a/src/fe/preproc.h b/src/fe/preproc.h index 3d1e1ea..f33ed98 100644 --- a/src/fe/preproc.h +++ b/src/fe/preproc.h @@ -102,6 +102,8 @@ typedef struct { * truncated buffer is not a smaller program, it is a broken one. */ int ovflw; + int keepinc; + /* Errors */ bc_error_t errors[BC_MAX_ERRORS]; int num_errors; @@ -110,6 +112,7 @@ typedef struct { void pp_init(preproc_t *pp, const char *src, uint32_t len, char *out_buf, uint32_t out_max, const char *filename); +void pp_host(preproc_t *pp); int pp_add_include_path(preproc_t *pp, const char *path); int pp_define(preproc_t *pp, const char *name, const char *value); int pp_process(preproc_t *pp); diff --git a/src/fe/sema.c b/src/fe/sema.c index edf1c53..d19c513 100644 --- a/src/fe/sema.c +++ b/src/fe/sema.c @@ -658,6 +658,7 @@ typedef struct { static const cuda_builtin_t cuda_builtins[] = { {"__syncthreads", 0, 1, -1}, + {"__syncwarp", -1, 1, -1}, {"__threadfence", 0, 1, -1}, {"atomicAdd", 2, 0, 1}, {"atomicSub", 2, 0, 1}, diff --git a/src/host/hgen.c b/src/host/hgen.c new file mode 100644 index 0000000..a4d5967 --- /dev/null +++ b/src/host/hgen.c @@ -0,0 +1,1164 @@ +#define _POSIX_C_SOURCE 200809L /* readlink: POSIX, not ISO C99 */ +#include "hgen.h" +#include "bir_lower.h" +#include "bc_err.h" +#include "backend.h" +#include +#include +#include + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#include +#undef OUT +#undef IN +#else +#include +#endif + +#define HG_MAXK 4096u +#define HG_MAXL 4096u +#define HG_MAXD 1024u +#define HG_MAXP 128u +#define HG_MAXT 8u +#define HG_MAXV 16u +#define HG_WBUF 65536u +#define HG_RBUF 65536u +#define HG_COLS 72u +#define HG_NAME 128u +#define HG_TARG 256u + +#define HG_FWMAG 0x466243b1 +#define HG_FMAG 0xba55ed50u +#define HG_KPTX 1u +#define HG_KCUB 2u + +typedef struct { + uint32_t s0, s1; + uint32_t nmt; + uint32_t p0, p1; + uint32_t t0, t1; + int tmpl; + int stat; + int decl; +} hg_k_t; + +typedef struct { + uint32_t s0, s1; + uint32_t k0, k1; + uint32_t c0, c1; + uint32_t a0, a1; +} hg_l_t; + +typedef struct { + uint32_t s0, s1; + uint32_t sig; +} hg_d_t; + +static hg_k_t KS[HG_MAXK]; +static uint32_t NK; +static hg_l_t LS[HG_MAXL]; +static uint32_t NL; +static hg_d_t DS[HG_MAXD]; +static uint32_t ND; +static FILE *OF; +static char WB[HG_WBUF]; +static uint32_t WN; +static int OOVF; +static int OERR; +static uint8_t RB[HG_RBUF]; + + +static void wflu(void) +{ + if (WN == 0u) return; + if (OF == NULL || fwrite(WB, 1u, WN, OF) != WN) OERR = 1; + WN = 0u; +} + +static void ow(const char *s, uint32_t n) +{ + while (n != 0u && !OERR) { + uint32_t k = HG_WBUF - WN; + + if (k == 0u) { wflu(); continue; } + if (k > n) k = n; + memcpy(WB + WN, s, k); + WN += k; + s += k; + n -= k; + } +} + +static void os_(const char *s) +{ + ow(s, (uint32_t)strlen(s)); +} + +static void onum(uint32_t v) +{ + char b[16]; + int n = snprintf(b, sizeof b, "%u", (unsigned)v); + + if (n > 0) ow(b, (uint32_t)n); +} + + +static const char *ttx(const hg_in_t *in, uint32_t i) +{ + return in->src + in->toks[i].offset; +} + +static int teq(const hg_in_t *in, uint32_t i, const char *s) +{ + size_t n = strlen(s); + + if (i >= in->ntok) return 0; + return (size_t)in->toks[i].len == n + && memcmp(ttx(in, i), s, n) == 0; +} + +static void otok(const hg_in_t *in, uint32_t a, uint32_t b) +{ + uint32_t s, e; + + if (a > b || b >= in->ntok) return; + s = in->toks[a].offset; + e = in->toks[b].offset + in->toks[b].len; + ow(in->src + s, e - s); +} + +static int isdq(int t) +{ + return t == TOK_CU_GLOBAL || t == TOK_CU_DEVICE + || t == TOK_CU_CONSTANT || t == TOK_CU_SHARED + || t == TOK_CU_MANAGED; +} + +static int isfq(int t) +{ + return t == TOK_CU_GLOBAL || t == TOK_CU_DEVICE + || t == TOK_CU_HOST || t == TOK_CU_FORCEINLINE; +} + + +static uint32_t mbrace(const hg_in_t *in, uint32_t i) +{ + int d = 0; + uint32_t g = 0; + + for (; i < in->ntok && g < (uint32_t)in->ntok + 1u; i++, g++) { + if (in->toks[i].type == TOK_LBRACE) d++; + else if (in->toks[i].type == TOK_RBRACE) { + d--; + if (d == 0) return i; + } + } + return in->ntok; +} + +static uint32_t mparen(const hg_in_t *in, uint32_t i) +{ + int d = 0; + uint32_t g = 0; + + for (; i < in->ntok && g < (uint32_t)in->ntok + 1u; i++, g++) { + if (in->toks[i].type == TOK_LPAREN) d++; + else if (in->toks[i].type == TOK_RPAREN) { + d--; + if (d == 0) return i; + } + } + return in->ntok; +} + +static uint32_t mpopen(const hg_in_t *in, uint32_t i) +{ + int d = 0; + uint32_t g = 0; + + for (; g < (uint32_t)in->ntok + 1u; g++) { + if (in->toks[i].type == TOK_RPAREN) d++; + else if (in->toks[i].type == TOK_LPAREN) { + d--; + if (d == 0) return i; + } + if (i == 0u) break; + i--; + } + return in->ntok; +} + +static uint32_t thend(const hg_in_t *in, uint32_t s) +{ + int d = 0; + uint32_t g = 0; + + if (!teq(in, s, "template") || in->toks[s + 1u].type != TOK_LT) return s; + for (uint32_t i = s + 1u; i < in->ntok && g < (uint32_t)in->ntok; + i++, g++) { + int t = in->toks[i].type; + + if (t == TOK_LT) d++; + else if (t == TOK_SHR) d -= 2; + else if (t == TOK_GT) d--; + if (d <= 0) return i + 1u; + } + return s; +} + +static uint32_t dsig(const hg_in_t *in, uint32_t s, uint32_t lb) +{ + uint32_t lp, ts; + + if (lb == 0u || lb <= s || lb >= in->ntok) return 0u; + if (in->toks[lb - 1u].type != TOK_RPAREN) return 0u; + lp = mpopen(in, lb - 1u); + if (lp <= s || lp >= in->ntok) return 0u; + if (in->toks[lp - 1u].type != TOK_IDENT + && in->toks[lp - 1u].type != TOK_GT) return 0u; + ts = thend(in, s); + for (uint32_t i = ts; i < lp; i++) + if (in->toks[i].type == TOK_ASSIGN) return 0u; + return lb - 1u; +} + +static uint8_t DIRL[BC_MAX_TOKENS]; + +static void dmark(const hg_in_t *in) +{ + uint32_t i = 0; + + memset(DIRL, 0, (size_t)in->ntok); + while (i < in->ntok) { + uint32_t ln = in->toks[i].line, j = i; + int hash = in->toks[i].type == TOK_HASH + || in->toks[i].type == TOK_PP_LINE; + + while (j < in->ntok && in->toks[j].line == ln) { + if (hash) DIRL[j] = 1u; + j++; + } + i = j; + } +} + +static uint32_t dstart(const hg_in_t *in, uint32_t i) +{ + uint32_t j = i; + + while (j > 0u) { + int t = in->toks[j - 1u].type; + + if (t == TOK_SEMI || t == TOK_RBRACE || t == TOK_LBRACE) break; + if (t == TOK_PP_LINE || t == TOK_HASH) break; + if (DIRL[j - 1u]) break; + j--; + } + return j; +} + +static uint32_t tmplat(const hg_in_t *in, uint32_t s, uint32_t *t0) +{ + uint32_t j = s; + int d; + uint32_t g = 0; + + *t0 = s; + if (j == 0u || in->toks[j - 1u].type != TOK_GT) return s; + d = 0; + j--; + for (; j > 0u && g < (uint32_t)in->ntok + 1u; j--, g++) { + int t = in->toks[j].type; + + if (t == TOK_GT) d++; + else if (t == TOK_LT) { + d--; + if (d == 0) break; + } + } + if (j == 0u || !teq(in, j - 1u, "template")) return s; + *t0 = j - 1u; + return j - 1u; +} + +static uint32_t klb(const hg_in_t *in, uint32_t i) +{ + if (in->toks[i].type != TOK_CU_LAUNCH_BOUNDS) return i; + if (i + 1u >= in->ntok || in->toks[i + 1u].type != TOK_LPAREN) return i; + return mparen(in, i + 1u); +} + +static int kstat(const hg_in_t *in, uint32_t s, uint32_t q) +{ + for (uint32_t i = s; i < q; i++) + if (in->toks[i].type == TOK_STATIC) return 1; + return 0; +} + +static int kadd(const hg_in_t *in, uint32_t q) +{ + uint32_t s = dstart(in, q), nm = 0, lp, rp, e, t0; + hg_k_t *k; + + s = tmplat(in, s, &t0); + for (lp = q; lp < in->ntok; lp++) { + uint32_t b = klb(in, lp); + + if (b != lp) { lp = b; continue; } + if (in->toks[lp].type == TOK_LPAREN) break; + if (in->toks[lp].type == TOK_IDENT) nm = lp; + } + if (lp >= in->ntok || nm == 0u) return 0; + rp = mparen(in, lp); + if (rp >= in->ntok) return 0; + for (e = rp + 1u; e < in->ntok && in->toks[e].type != TOK_LBRACE + && in->toks[e].type != TOK_SEMI; e++) { } + if (e >= in->ntok) return 0; + if (NK >= HG_MAXK) return 0; + k = &KS[NK++]; + k->decl = in->toks[e].type == TOK_SEMI; + if (!k->decl) e = mbrace(in, e); + if (e >= in->ntok) { NK--; return 0; } + k->s0 = s; k->s1 = e; k->nmt = nm; + k->p0 = lp + 1u; k->p1 = rp; + k->t0 = t0; k->t1 = (t0 == s && !teq(in, t0, "template")) ? t0 : lp; + k->tmpl = teq(in, t0, "template"); + k->stat = kstat(in, s, q); + return 1; +} + +static uint32_t lcallee(const hg_in_t *in, uint32_t open) +{ + uint32_t nm, g = 0; + int d = 0; + + if (open == 0u) return in->ntok; + nm = open - 1u; + if (in->toks[nm].type != TOK_GT && in->toks[nm].type != TOK_SHR) return nm; + while (nm > 0u && g < (uint32_t)in->ntok) { + int t = in->toks[nm].type; + + if (t == TOK_GT) d++; + else if (t == TOK_SHR) d += 2; + else if (t == TOK_LT) { d--; if (d == 0) break; } + nm--; + g++; + } + if (nm == 0u || in->toks[nm].type != TOK_LT) return in->ntok; + return nm - 1u; +} + +static void dadd(uint32_t s, uint32_t e, uint32_t sig) +{ + if (ND >= HG_MAXD) return; + DS[ND].s0 = s; + DS[ND].s1 = e; + DS[ND].sig = sig; + ND++; +} + +static void scan(const hg_in_t *in) +{ + int d = 0; + uint32_t g = 0; + + NK = 0u; NL = 0u; ND = 0u; + dmark(in); + for (uint32_t i = 0; i < in->ntok && g < (uint32_t)in->ntok + 1u; i++, g++) { + int t = in->toks[i].type; + + if (t == TOK_LBRACE) { d++; continue; } + if (t == TOK_RBRACE) { if (d > 0) d--; continue; } + if (t == TOK_LAUNCH_OPEN) { + uint32_t c1 = i, lp, rp, gg = 0, nm; + hg_l_t *l; + + for (; c1 < in->ntok && in->toks[c1].type != TOK_LAUNCH_CLOSE + && gg < (uint32_t)in->ntok; c1++, gg++) { } + if (c1 >= in->ntok || i == 0u) continue; + nm = lcallee(in, i); + if (nm >= in->ntok || in->toks[nm].type != TOK_IDENT) continue; + lp = c1 + 1u; + if (lp >= in->ntok || in->toks[lp].type != TOK_LPAREN) continue; + rp = mparen(in, lp); + if (rp >= in->ntok || NL >= HG_MAXL) continue; + l = &LS[NL++]; + l->s0 = nm; l->s1 = rp; + l->k0 = nm; l->k1 = i - 1u; + l->c0 = i + 1u; l->c1 = c1; + l->a0 = lp + 1u; l->a1 = rp; + continue; + } + if (d != 0 || !isdq(t)) continue; + if (t == TOK_CU_GLOBAL) { + uint32_t n0 = NK; + + if (kadd(in, i) && NK > n0) { i = KS[NK - 1u].s1; continue; } + } + { + uint32_t s = dstart(in, i), e = s, gg = 0, lb = 0; + int hh = 0; + + for (; e < in->ntok && gg < (uint32_t)in->ntok; e++, gg++) { + if (in->toks[e].type == TOK_CU_HOST) hh = 1; + if (in->toks[e].type == TOK_CONSTEXPR) hh = 1; + if (in->toks[e].type == TOK_LBRACE) { + lb = e; + e = mbrace(in, e); + break; + } + if (in->toks[e].type == TOK_SEMI) { lb = e; break; } + } + if (e >= in->ntok) continue; + if (!hh) dadd(s, e, dsig(in, s, lb)); + i = e; + } + } +} + + +static uint32_t psplit(const hg_in_t *in, const hg_k_t *k, uint32_t *b, + uint32_t *e, uint32_t max) +{ + uint32_t n = 0, s = k->p0; + int d = 0; + + if (k->p0 >= k->p1) return 0; + if (k->p1 - k->p0 == 1u && teq(in, k->p0, "void")) return 0; + for (uint32_t i = k->p0; i < k->p1 && n < max; i++) { + int t = in->toks[i].type; + + if (t == TOK_LPAREN || t == TOK_LT || t == TOK_LBRACKET) d++; + else if (t == TOK_RPAREN || t == TOK_GT || t == TOK_RBRACKET) d--; + else if (t == TOK_COMMA && d == 0) { + b[n] = s; e[n] = i; n++; s = i + 1u; + } + } + if (n < max && s < k->p1) { b[n] = s; e[n] = k->p1; n++; } + return n; +} + +static uint32_t pend(const hg_in_t *in, uint32_t b, uint32_t e) +{ + int d = 0; + + for (uint32_t i = b; i < e; i++) { + int t = in->toks[i].type; + + if (t == TOK_LPAREN || t == TOK_LT || t == TOK_LBRACKET) d++; + else if (t == TOK_RPAREN || t == TOK_GT || t == TOK_RBRACKET) d--; + else if (t == TOK_ASSIGN && d == 0) return i; + } + return e; +} + +static int ptyp(int t) +{ + return t == TOK_CONST || t == TOK_VOLATILE || t == TOK_STRUCT + || t == TOK_CLASS || t == TOK_ENUM || t == TOK_TYPENAME; +} + +static int pnamed(const hg_in_t *in, uint32_t b, uint32_t e) +{ + if (e < b + 2u) return 0; + if (in->toks[e - 1u].type != TOK_IDENT) return 0; + return !ptyp(in->toks[e - 2u].type); +} + +static int ppack(const hg_in_t *in, uint32_t b, uint32_t e) +{ + for (uint32_t i = b; i < e; i++) + if (in->toks[i].type == TOK_ELLIPSIS) return 1; + return 0; +} + + +typedef struct { + char nm[64]; + char dc[64]; + int pk; + int ty; +} hg_tp_t; + +static uint32_t tpgt(const hg_in_t *in, const hg_k_t *k) +{ + int d = 0; + + for (uint32_t i = k->t0 + 1u; i < in->ntok; i++) { + int t = in->toks[i].type; + + if (t == TOK_LT) d++; + else if (t == TOK_GT) { d--; if (d == 0) return i; } + } + return in->ntok; +} + +static void tcpy(const hg_in_t *in, uint32_t i, char *d, size_t n) +{ + size_t l = (size_t)in->toks[i].len; + + if (l > n - 1u) l = n - 1u; + memcpy(d, ttx(in, i), l); + d[l] = 0; +} + +static void tp1(const hg_in_t *in, uint32_t a, uint32_t b, hg_tp_t *p) +{ + uint32_t e = b, nm; + + memset(p, 0, sizeof *p); + for (uint32_t i = a; i < b; i++) + if (in->toks[i].type == TOK_ASSIGN) { e = i; break; } + if (e <= a) return; + nm = e; + p->ty = in->toks[a].type == TOK_TYPENAME + || in->toks[a].type == TOK_CLASS; + for (uint32_t i = a; i < e; i++) { + if (in->toks[i].type == TOK_ELLIPSIS) p->pk = 1; + if (in->toks[i].type == TOK_STAR && nm == e && i + 1u < e + && in->toks[i + 1u].type == TOK_IDENT) nm = i + 1u; + } + if (nm == e && in->toks[e - 1u].type == TOK_IDENT) nm = e - 1u; + if (nm == e) return; + tcpy(in, nm, p->nm, sizeof p->nm); + if (!p->ty && nm == a + 1u) tcpy(in, a, p->dc, sizeof p->dc); +} + +static uint32_t tpall(const hg_in_t *in, const hg_k_t *k, hg_tp_t *tp, + uint32_t max) +{ + uint32_t n = 0, gt, s; + int d = 0; + + if (!k->tmpl || k->t0 + 2u >= in->ntok) return 0; + gt = tpgt(in, k); + if (gt >= in->ntok) return 0; + s = k->t0 + 2u; + for (uint32_t i = s; i <= gt && n < max; i++) { + int t = in->toks[i].type; + + if (t == TOK_LT || t == TOK_LPAREN) d++; + else if (t == TOK_RPAREN || (t == TOK_GT && i != gt)) d--; + else if ((t == TOK_COMMA && d == 0) || i == gt) { + if (i > s) { tp1(in, s, i, &tp[n]); n++; } + s = i + 1u; + } + } + return n; +} + +static int oksym(const hg_in_t *in, const hg_k_t *k) +{ + hg_tp_t tp[HG_MAXT]; + uint32_t nt = tpall(in, k, tp, HG_MAXT); + + otok(in, k->nmt, k->nmt); + if (!k->tmpl) return 1; + if (nt == 0u) return 0; + os_("<"); + for (uint32_t i = 0; i < nt; i++) { + if (tp[i].nm[0] == 0) return 0; + if (i != 0u) os_(", "); + os_(tp[i].nm); + if (tp[i].pk) os_("..."); + } + os_(">"); + return 1; +} + +static void ostub(const hg_in_t *in, const hg_k_t *k) +{ + uint32_t b[HG_MAXP], e[HG_MAXP], n; + char nm[HG_NAME]; + + n = psplit(in, k, b, e, HG_MAXP); + os_("\n"); + if (k->tmpl) { otok(in, k->t0, tpgt(in, k)); os_("\n"); } + if (k->stat) os_("static "); + os_("void "); + otok(in, k->nmt, k->nmt); + os_("("); + for (uint32_t i = 0; i < n; i++) { + uint32_t pe = pend(in, b[i], e[i]); + + if (i != 0u) os_(", "); + if (pe > b[i]) otok(in, b[i], pe - 1u); + if (!pnamed(in, b[i], pe)) { os_(" __p"); onum(i); } + if (pe < e[i]) { os_(" "); otok(in, pe, e[i] - 1u); } + } + os_(")"); + if (k->decl) { os_(";\n"); return; } + os_("\n{\n void *__a[] = { "); + if (n == 0u) os_("0"); + for (uint32_t i = 0; i < n; i++) { + uint32_t pe = pend(in, b[i], e[i]); + + if (i != 0u) os_(", "); + os_("(void *)&"); + if (pnamed(in, b[i], pe)) otok(in, pe - 1u, pe - 1u); + else { os_("__p"); onum(i); } + if (ppack(in, b[i], pe)) os_("..."); + } + os_(" };\n __bl((const void *)"); + if (!oksym(in, k)) { + tcpy(in, k->nmt, nm, sizeof nm); + (void)be_fail(BC_E621, in->file, nm); + OOVF = 1; + } + os_(", __a);\n}\n"); +} + + +static void p16(uint8_t *p, uint32_t o, uint16_t v) +{ + p[o] = (uint8_t)(v & 0xFFu); + p[o + 1u] = (uint8_t)(v >> 8); +} + +static void p32(uint8_t *p, uint32_t o, uint32_t v) +{ + for (uint32_t i = 0; i < 4u; i++) p[o + i] = (uint8_t)(v >> (8u * i)); +} + +static void p64(uint8_t *p, uint32_t o, uint64_t v) +{ + for (uint32_t i = 0; i < 8u; i++) p[o + i] = (uint8_t)(v >> (8u * i)); +} + +static uint32_t fsize(const char *path, FILE **fp) +{ + FILE *f = (path != NULL) ? fopen(path, "rb") : NULL; + long sz; + + *fp = NULL; + if (f == NULL) return 0u; + if (fseek(f, 0L, SEEK_END) != 0) { fclose(f); return 0u; } + sz = ftell(f); + rewind(f); + if (sz <= 0L) { fclose(f); return 0u; } + *fp = f; + return (uint32_t)sz; +} + +static int fatno(const char *path) +{ + fprintf(stderr, "kath: cannot read %s\n", path != NULL ? path : "?"); + return 1; +} + +static int fcpy(FILE *o, FILE *i, uint32_t n) +{ + while (n != 0u) { + uint32_t k = (n > HG_RBUF) ? HG_RBUF : n; + + if (fread(RB, 1u, k, i) != k) return 1; + if (fwrite(RB, 1u, k, o) != k) return 1; + n -= k; + } + return 0; +} + +static int fent(FILE *o, FILE *i, uint32_t kind, uint32_t sm, uint32_t len) +{ + uint8_t h[64]; + uint32_t pad = ((len + 7u) & ~7u) - len; + + memset(h, 0, sizeof h); + p16(h, 0u, (uint16_t)kind); + p32(h, 4u, 64u); + p64(h, 8u, (len + 7u) & ~7u); + p32(h, 16u, len); + p16(h, 26u, 1u); + p32(h, 28u, sm); + if (fwrite(h, 1u, 64u, o) != 64u) return 1; + if (fcpy(o, i, len) != 0) return 1; + return pad != 0u && fwrite(h + 8u, 1u, pad, o) != pad; +} + +static uint32_t g32(const uint8_t *p) +{ + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) + | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); +} + +static uint32_t fcar(const char *path) +{ + FILE *f; + uint8_t h[64]; + uint32_t at = 16u, m = 0u, n = fsize(path, &f); + + KA_GUARD(g, 64); + if (f == NULL) return 0u; + if (n < 16u || fread(h, 1u, 16u, f) != 16u || g32(h) != HG_FMAG) { + fclose(f); + return 0u; + } + while (at + 64u <= n && g--) { + uint32_t k, hs, z; + + if (fseek(f, (long)at, SEEK_SET) != 0) break; + if (fread(h, 1u, 64u, f) != 64u) break; + k = (uint32_t)h[0] | ((uint32_t)h[1] << 8); + hs = g32(h + 4u); + z = g32(h + 8u); + if (hs < 64u || hs > n - at) break; + if (g32(h + 12u) != 0u) break; + if (z > n - at - hs) break; + if (k == HG_KCUB) m |= 2u; + if (k == HG_KPTX) m |= 1u; + at += hs + z; + } + fclose(f); + return m; +} + +int hg_fat(const char *cubin, const char *ptx, uint32_t sm, const char *out) +{ + FILE *cf = NULL, *pf = NULL, *o; + uint32_t cn = 0u, pn, tot = 0u; + uint8_t h[16]; + int rc = 0; + + if (cubin != NULL) { + cn = fsize(cubin, &cf); + if (cn == 0u) return fatno(cubin); + } + pn = fsize(ptx, &pf); + if (cn == 0u && pn == 0u) return fatno(ptx); + if (cn != 0u) tot += 64u + ((cn + 7u) & ~7u); + if (pn != 0u) tot += 64u + ((pn + 7u) & ~7u); + memset(h, 0, sizeof h); + p32(h, 0u, HG_FMAG); + p16(h, 4u, 1u); + p16(h, 6u, 16u); + p64(h, 8u, tot); + o = fopen(out, "wb"); + if (o == NULL) rc = 1; + if (rc == 0 && fwrite(h, 1u, 16u, o) != 16u) rc = 1; + if (rc == 0 && cn != 0u) rc = fent(o, cf, HG_KCUB, sm, cn); + if (rc == 0 && pn != 0u) rc = fent(o, pf, HG_KPTX, sm, pn); + if (cf != NULL) fclose(cf); + if (pf != NULL) fclose(pf); + if (o == NULL) return 1; + if (fclose(o) != 0) rc = 1; + if (rc != 0) remove(out); + return rc; +} + + +int hg_binc(char *buf, size_t n) +{ + char exe[512]; + char *sep, *bs; + +#ifdef _WIN32 + DWORD k = GetModuleFileNameA(NULL, exe, (DWORD)sizeof exe); + + if (k == 0u || (size_t)k >= sizeof exe) return 0; +#else + ssize_t k = readlink("/proc/self/exe", exe, sizeof exe - 1u); + + if (k <= 0 || (size_t)k >= sizeof exe) return 0; + exe[k] = '\0'; +#endif + sep = strrchr(exe, '/'); + bs = strrchr(exe, '\\'); + if (bs > sep) sep = bs; + if (sep == NULL) return 0; + *sep = '\0'; + return snprintf(buf, n, "%s/runtime/include", exe) > 0; +} + +static int capp(char *b, size_t n, size_t *u, const char *s) +{ + size_t l = strlen(s); + + if (*u + l >= n) return 0; + memcpy(b + *u, s, l); + *u += l; + b[*u] = '\0'; + return 1; +} + +static int cinc(char *b, size_t n, size_t *u, const char *d) +{ + return capp(b, n, u, " -I\"") && capp(b, n, u, d) && capp(b, n, u, "\""); +} + +int hg_cc(const char *src, const char *out, const char *const *inc, int ninc) +{ + char cmd[4096], own[512]; + const char *cc = getenv("BOOTH_CXX"); + const char *rt = getenv("BOOTH_CUDART"); + size_t u = 0u; + int ok, rc; + + if (cc == NULL || cc[0] == '\0') cc = "g++"; + if (rt == NULL || rt[0] == '\0') rt = "-lcudart"; + cmd[0] = '\0'; + ok = capp(cmd, sizeof cmd, &u, cc) + && capp(cmd, sizeof cmd, &u, " -std=c++17 -O2"); + for (int i = 0; ok && i < ninc; i++) + ok = cinc(cmd, sizeof cmd, &u, inc[i]); + if (ok && hg_binc(own, sizeof own)) + ok = cinc(cmd, sizeof cmd, &u, own); + ok = ok && capp(cmd, sizeof cmd, &u, " \"") + && capp(cmd, sizeof cmd, &u, src) + && capp(cmd, sizeof cmd, &u, "\" -o \"") + && capp(cmd, sizeof cmd, &u, out) + && capp(cmd, sizeof cmd, &u, "\" ") + && capp(cmd, sizeof cmd, &u, rt); + if (!ok) return 1; + rc = system(cmd); +#ifdef _WIN32 + return rc == 0 ? 0 : rc; +#else + return rc == 0 ? 0 : 1; +#endif +} + +typedef struct { uint32_t s, e; int k; uint32_t i; } hg_e_t; + +static hg_e_t ES[HG_MAXK + HG_MAXL + HG_MAXD]; +static uint32_t NE; + +static struct { + char sym[HG_NAME]; + char base[HG_NAME]; + char targ[HG_TARG]; +} SM[HG_MAXK]; +static uint32_t NSM; + +static void eadd(uint32_t s, uint32_t e, int k, uint32_t i) +{ + if (NE >= (uint32_t)(sizeof ES / sizeof ES[0])) return; + ES[NE].s = s; ES[NE].e = e; ES[NE].k = k; ES[NE].i = i; + NE++; +} + +static void esort(void) +{ + for (uint32_t i = 1; i < NE; i++) { + hg_e_t t = ES[i]; + uint32_t j = i; + + while (j > 0u && ES[j - 1u].s > t.s) { ES[j] = ES[j - 1u]; j--; } + ES[j] = t; + } +} + +static void cpn(char *d, size_t n, const char *s) +{ + size_t k = (s != NULL) ? strlen(s) : 0u; + + if (k > n - 1u) k = n - 1u; + if (k != 0u) memcpy(d, s, k); + d[k] = 0; +} + +static uint32_t smget(const char *sym, const char *base, const char *targ) +{ + for (uint32_t i = 0; i < NSM; i++) + if (strcmp(SM[i].sym, sym) == 0) return i; + if (NSM >= HG_MAXK) return HG_MAXK; + cpn(SM[NSM].sym, HG_NAME, sym); + cpn(SM[NSM].base, HG_NAME, base); + cpn(SM[NSM].targ, HG_TARG, targ); + NSM++; + return NSM - 1u; +} + +static uint32_t tvsp(const char *targ, char v[][64], uint32_t max) +{ + uint32_t n = 0, j = 0; + int d = 0; + + if (targ == NULL || targ[0] == 0) return 0; + for (const char *p = targ; n < max; p++) { + if (*p == '<') d++; + else if (*p == '>') d--; + if ((*p == ',' && d == 0) || *p == 0) { + while (j > 0u && v[n][j - 1u] == 32) j--; + v[n][j] = 0; + n++; + j = 0; + if (*p == 0) break; + while (p[1] == 32) p++; + } else if (j < 63u) { + v[n][j++] = *p; + } + } + return n; +} + +static const hg_k_t *kfind(const hg_in_t *in, const char *nm) +{ + for (uint32_t i = 0; i < NK; i++) { + uint32_t l = in->toks[KS[i].nmt].len; + + if ((size_t)l == strlen(nm) + && memcmp(ttx(in, KS[i].nmt), nm, l) == 0) return &KS[i]; + } + return NULL; +} + +static void olnch(const hg_in_t *in, uint32_t li) +{ + const hg_l_t *l = &LS[li]; + uint32_t cb[8], ce[8], n = 0, s = l->c0; + int d = 0; + + for (uint32_t i = l->c0; i < l->c1 && n < 4u; i++) { + int t = in->toks[i].type; + + if (t == TOK_LPAREN || t == TOK_LBRACKET) d++; + else if (t == TOK_RPAREN || t == TOK_RBRACKET) d--; + else if (t == TOK_COMMA && d == 0) { + cb[n] = s; ce[n] = i; n++; s = i + 1u; + } + } + if (n < 4u && s < l->c1) { cb[n] = s; ce[n] = l->c1; n++; } + os_("(__cudaPushCallConfiguration("); + for (uint32_t i = 0; i < 4u; i++) { + if (i != 0u) os_(", "); + if (i < n && ce[i] > cb[i]) otok(in, cb[i], ce[i] - 1u); + else if (i == 3u) os_("(void *)0"); + else os_("0"); + } + os_(") ? (void)0 : "); + otok(in, l->k0, l->k1); + os_("("); + if (l->a1 > l->a0) otok(in, l->a0, l->a1 - 1u); + os_("))"); +} + +static void obase(const char *p) +{ + const char *s = p; + char c[2]; + + if (p == NULL) { os_("?"); return; } + for (const char *q = p; *q != '\0'; q++) + if (*q == '/' || *q == '\\') s = q + 1; + c[1] = '\0'; + for (uint32_t i = 0; i < HG_NAME && s[i] != '\0'; i++) { + int ok = (s[i] >= '0' && s[i] <= '9') || (s[i] >= 'A' && s[i] <= 'Z') + || (s[i] >= 'a' && s[i] <= 'z') || s[i] == '.' || s[i] == '_' + || s[i] == '-'; + + c[0] = ok ? s[i] : '_'; + ow(c, 1u); + } +} + +static uint32_t besc(uint8_t b, char *d) +{ + static const char OCT[] = "01234567"; + + d[0] = '\\'; + if (b == 0x22u || b == 0x5Cu || b == 0x3Fu) { d[1] = (char)b; return 2u; } + if (b == 0x0Au) { d[1] = 'n'; return 2u; } + if (b == 0x09u) { d[1] = 't'; return 2u; } + if (b == 0x0Du) { d[1] = 'r'; return 2u; } + if (b >= 0x20u && b <= 0x7Eu) { d[0] = (char)b; return 1u; } + d[1] = OCT[(b >> 6) & 7u]; + d[2] = OCT[(b >> 3) & 7u]; + d[3] = OCT[b & 7u]; + return 4u; +} + +static void ofat(const char *path) +{ + FILE *f = (path != NULL) ? fopen(path, "rb") : NULL; + char e[4]; + uint32_t col = 0u; + size_t n; + + os_("\""); + if (f != NULL) { + while (!OERR && (n = fread(RB, 1u, HG_RBUF, f)) != 0u) { + for (size_t i = 0; i < n; i++) { + uint32_t k = besc(RB[i], e); + + if (col + k > HG_COLS) { os_("\"\n\""); col = 0u; } + ow(e, k); + col += k; + } + } + fclose(f); + } + os_("\";\n"); +} + +static void opro(const hg_in_t *in) +{ + uint32_t c = fcar(in->fat); + + if (c == 1u) + fprintf(stderr, "kath: %s: the fatbin carries PTX only, no cubin\n", + in->file != NULL ? in->file : "?"); + os_("#include \n"); + os_("static void __bl(const void *f, void **a)\n{\n"); + os_(" dim3 g, b;\n size_t s;\n void *t;\n\n"); + os_(" if (__cudaPopCallConfiguration(&g, &b, &s, &t) != cudaSuccess)"); + os_(" return;\n"); + os_(" (void)cudaLaunchKernel(f, g, b, a, s, (cudaStream_t)t);\n}\n"); + os_("static const unsigned char __bfat[] =\n"); + ofat(in->fat); + if (c != 0u) { + os_("static const char __bcar[] __attribute__((used)) = \"booth-fat: "); + os_(c == 1u ? "ptx-only " : (c == 3u ? "cubin+ptx " : "cubin ")); + obase(in->file); + os_("\";\n"); + } + os_("struct __bfw { int m; int v; const void *d; void *f; };\n"); + os_("static struct __bfw __bw = { "); + onum((uint32_t)HG_FWMAG); + os_(", 1, __bfat, 0 };\n"); + os_("static void **__bh;\n"); +} + +static int isnum(const char *s) +{ + return s[0] == '-' || (s[0] >= '0' && s[0] <= '9'); +} + +static int oreg(const hg_in_t *in, uint32_t i) +{ + const hg_k_t *k = kfind(in, SM[i].base); + hg_tp_t tp[HG_MAXT]; + char vv[HG_MAXV][64]; + uint32_t nt, nv, fx = 0u, np = 0u, c = 0u; + + if (k == NULL) { (void)be_fail(BC_E620, in->file, SM[i].base); return 0; } + os_(SM[i].base); + if (!k->tmpl) return 1; + nt = tpall(in, k, tp, HG_MAXT); + nv = tvsp(SM[i].targ, vv, HG_MAXV); + for (uint32_t j = 0; j < nt; j++) { + if (tp[j].pk) np++; + else fx++; + } + if (nt == 0u || np > 1u || nv < fx || (np == 0u && nv != nt)) { + (void)be_fail(BC_E621, in->file, SM[i].base); + return 0; + } + os_("<"); + for (uint32_t j = 0; j < nt; j++) { + uint32_t cnt = tp[j].pk ? nv - fx : 1u; + + for (uint32_t m = 0; m < cnt && c < nv; m++, c++) { + if (c != 0u) os_(", "); + if (!tp[j].ty && tp[j].dc[0] != 0 && isnum(vv[c])) { + os_("("); + os_(tp[j].dc); + os_(")"); + } + os_(vv[c]); + } + } + os_(">"); + return 1; +} + +static void octor(const hg_in_t *in) +{ + os_("\nstatic void __bctor(void) __attribute__((constructor));\n"); + os_("static void __bctor(void)\n{\n"); + os_(" __bh = __cudaRegisterFatBinary((void *)&__bw);\n"); + for (uint32_t i = 0; i < NSM; i++) { + os_(" __cudaRegisterFunction(__bh, (const char *)"); + if (!oreg(in, i)) { OOVF = 1; return; } + os_(", (char *)\""); + os_(SM[i].sym); + os_("\", \""); + os_(SM[i].sym); + os_("\", -1, 0, 0, 0, 0, 0);\n"); + } + os_(" __cudaRegisterFatBinaryEnd(__bh);\n}\n"); +} + +static uint32_t TQ; + +static void ogap(const hg_in_t *in, uint32_t a, uint32_t b) +{ + uint32_t c = a; + + while (TQ < in->ntok && in->toks[TQ].offset < a) TQ++; + for (; TQ < in->ntok && in->toks[TQ].offset < b; TQ++) { + uint32_t s = in->toks[TQ].offset; + + if (!isfq(in->toks[TQ].type)) continue; + if (s > c) ow(in->src + c, s - c); + c = s + in->toks[TQ].len; + } + if (b > c) ow(in->src + c, b - c); +} + +static void odecl(const hg_in_t *in, uint32_t di) +{ + uint32_t sig = DS[di].sig; + + if (sig == 0u || sig >= in->ntok) return; + ogap(in, in->toks[DS[di].s0].offset, + in->toks[sig].offset + in->toks[sig].len); + os_(";\n"); +} + +static void obody(const hg_in_t *in) +{ + uint32_t cur = 0u; + + for (uint32_t i = 0; i < NE; i++) { + uint32_t s = in->toks[ES[i].s].offset; + uint32_t e = in->toks[ES[i].e].offset + in->toks[ES[i].e].len; + + if (s < cur) continue; + ogap(in, cur, s); + if (ES[i].k == 2) olnch(in, ES[i].i); + else if (ES[i].k == 1) ostub(in, &KS[ES[i].i]); + else odecl(in, ES[i].i); + cur = e; + } + if (cur < in->slen) ogap(in, cur, in->slen); +} + +static int hgmap(const hg_in_t *in) +{ + uint32_t n = bir_nlnch(); + + for (uint32_t i = 0; i < n; i++) { + const char *base = NULL, *sym = NULL, *targ = NULL; + + if (!bir_lnch(i, &base, &sym, &targ)) continue; + if (smget(sym, base, targ) >= HG_MAXK) { + (void)be_fail(BC_E622, in->file, (unsigned)HG_MAXK); + return 1; + } + } + return 0; +} + +int hg_emit(const hg_in_t *in, const char *out) +{ + WN = 0u; OOVF = 0; OERR = 0; NE = 0u; NSM = 0u; TQ = 0u; + scan(in); + if (hgmap(in) != 0) return 1; + for (uint32_t i = 0; i < NL; i++) eadd(LS[i].s0, LS[i].s1, 2, i); + for (uint32_t i = 0; i < NK; i++) eadd(KS[i].s0, KS[i].s1, 1, i); + for (uint32_t i = 0; i < ND; i++) eadd(DS[i].s0, DS[i].s1, 0, i); + esort(); + OF = fopen(out, "wb"); + if (OF == NULL) { fprintf(stderr, "kath: cannot write %s\n", out); return 1; } + opro(in); + obody(in); + if (!OOVF) octor(in); + wflu(); + if (fclose(OF) != 0) OERR = 1; + OF = NULL; + if (!OOVF && !OERR) return 0; + if (OERR) fprintf(stderr, "kath: cannot write %s\n", out); + remove(out); + return 1; +} diff --git a/src/host/hgen.h b/src/host/hgen.h new file mode 100644 index 0000000..77266c9 --- /dev/null +++ b/src/host/hgen.h @@ -0,0 +1,25 @@ +#ifndef BOOTH_HGEN_H +#define BOOTH_HGEN_H + +#include "barracuda.h" +#include "token.h" + + +typedef struct { + const char *file; + const char *src; + uint32_t slen; + const token_t *toks; + uint32_t ntok; + const char *fat; +} hg_in_t; + +int hg_emit(const hg_in_t *in, const char *out); + +int hg_fat(const char *cubin, const char *ptx, uint32_t sm, const char *out); + +int hg_binc(char *buf, size_t n); + +int hg_cc(const char *src, const char *out, const char *const *inc, int ninc); + +#endif /* BOOTH_HGEN_H */ diff --git a/src/ir/bir.c b/src/ir/bir.c index 170eb64..b002b1f 100644 --- a/src/ir/bir.c +++ b/src/ir/bir.c @@ -1,5 +1,6 @@ #include "bir.h" #include "backend.h" +#include #include #include @@ -294,7 +295,9 @@ int bir_pchk(const bir_module_t *M, const char *phase) void bir_module_init(bir_module_t *M) { - memset(M, 0, sizeof(*M)); + memset(M, 0, offsetof(bir_module_t, insts)); + memset((char *)M + offsetof(bir_module_t, inst_lines), 0, + sizeof(*M) - offsetof(bir_module_t, inst_lines)); /* Reserve type 0 as void. ptr_inner() returns types[t].inner, and callers treat 0 as "no element type". If some other type (e.g. f32) happened to land at index 0, the sentinel check @@ -312,7 +315,8 @@ static int type_eq_simple(const bir_type_t *a, const bir_type_t *b) && a->width == b->width && a->inner == b->inner && a->count == b->count - && a->num_fields == b->num_fields; + && a->num_fields == b->num_fields + && a->cst == b->cst; } static uint32_t intern_type(bir_module_t *M, const bir_type_t *t) @@ -340,7 +344,7 @@ static uint32_t intern_compound(bir_module_t *M, uint8_t kind, for (uint32_t i = 0; i < M->num_types && guard > 0; i++, guard--) { bir_type_t *t = &M->types[i]; if (t->kind != kind || t->inner != inner || t->uni != 0 - || t->num_fields != (uint16_t)nfields) + || t->cst != 0 || t->num_fields != (uint16_t)nfields) continue; int match = 1; for (int j = 0; j < nfields && match; j++) { @@ -487,6 +491,35 @@ int bir_umrk(bir_module_t *M, uint32_t ty) return 1; } +uint32_t bir_tcst(bir_module_t *M, uint32_t ty) +{ + bir_type_t t; + + if (ty >= M->num_types) return ty; + t = M->types[ty]; + if (t.cst) return ty; + t.cst = 1; + return intern_type(M, &t); +} + +uint32_t bir_tunq(const bir_module_t *M, uint32_t ty) +{ + const bir_type_t *q; + uint32_t guard = M->num_types; + + if (ty >= M->num_types || !M->types[ty].cst) return ty; + q = &M->types[ty]; + for (uint32_t i = 0; i < M->num_types && guard > 0; i++, guard--) { + const bir_type_t *c = &M->types[i]; + + if (c->cst == 0 && c->kind == q->kind && c->addrspace == q->addrspace + && c->width == q->width && c->inner == q->inner + && c->count == q->count && c->num_fields == q->num_fields) + return i; + } + return ty; +} + /* ---- Type Sizes ---- */ static uint32_t bsz_al(uint32_t sz, uint32_t psz) diff --git a/src/ir/bir.h b/src/ir/bir.h index 6ea032a..15a4ddb 100644 --- a/src/ir/bir.h +++ b/src/ir/bir.h @@ -14,7 +14,7 @@ #define BIR_MAX_TYPES (1 << 14) #define BIR_MAX_TYPE_FIELDS (1 << 16) #define BIR_MAX_CONSTS (1 << 16) -#define BIR_MAX_INSTS (1 << 22) +#define BIR_MAX_INSTS (1 << 23) #define BIR_MAX_EXTRA_OPS (1 << 19) #define BIR_MAX_BLOCKS (1 << 19) #define BIR_MAX_FUNCS (1 << 14) @@ -72,7 +72,8 @@ typedef struct { uint32_t inner; /* PTR: pointee. ARRAY/VECTOR: element. FUNC: return type */ uint32_t count; /* ARRAY: element count. STRUCT/FUNC: fields_start index */ uint16_t num_fields; /* STRUCT/FUNC: field/param count */ - uint16_t uni; /* STRUCT: 1 = union, every field at offset 0 */ + uint8_t uni; /* STRUCT: 1 = union, every field at offset 0 */ + uint8_t cst; } bir_type_t; /* 16 bytes */ /* ---- Comparison Predicates ---- */ @@ -402,6 +403,8 @@ uint32_t bir_type_float(bir_module_t *M, int width_bits); uint32_t bir_type_bfloat(bir_module_t *M); uint32_t bir_type_ptr(bir_module_t *M, uint32_t pointee, int addrspace); int bir_umrk(bir_module_t *M, uint32_t ty); +uint32_t bir_tcst(bir_module_t *M, uint32_t ty); +uint32_t bir_tunq(const bir_module_t *M, uint32_t ty); uint32_t bir_type_array(bir_module_t *M, uint32_t elem, uint32_t count); uint32_t bir_type_vector(bir_module_t *M, uint32_t elem, uint32_t count); uint32_t bir_type_struct(bir_module_t *M, const uint32_t *fields, int nfields); diff --git a/src/ir/bir_inline.c b/src/ir/bir_inline.c index fac1851..677c1f3 100644 --- a/src/ir/bir_inline.c +++ b/src/ir/bir_inline.c @@ -40,6 +40,10 @@ typedef struct { uint32_t ret_val[INL_MAX_CALLEE_BLOCKS]; /* value each callee return yielded */ uint8_t warned[BIR_MAX_FUNCS]; /* callee already warned about */ uint8_t cyc[BIR_MAX_FUNCS]; /* function sits on, or reaches, a call cycle */ + uint8_t need[BIR_MAX_FUNCS]; + uint32_t ihwm; + uint32_t bhwm; + int drop; } inl_t; /* ---- Value / block mapping ---- */ @@ -613,74 +617,143 @@ static int rebuild_func(inl_t *X, uint32_t fidx) /* ---- Driver ---- */ -static int blkcpy(inl_t *X, uint32_t ob, uint32_t ib0, uint32_t bb0) +static void pinst(inl_t *X, uint32_t n) { bir_module_t *M = X->M; - const bir_block_t *B = &M->blocks[ob]; - uint32_t n = B->num_insts, nb, j; - - if (B->first_inst >= ib0) n = 0; - else if (n > ib0 - B->first_inst) n = ib0 - B->first_inst; - - if (M->num_blocks >= BIR_MAX_BLOCKS) { - bir_pfull(M, BIR_P_BLOCKS); - return BC_ERR_OVERFLOW; - } - if (n > BIR_MAX_INSTS - M->num_insts) { - bir_pfull(M, BIR_P_INSTS); - return BC_ERR_OVERFLOW; + uint32_t i, j, g; + + for (i = 0; i < n; i++) X->spliced[i] = 0; + for (i = 0; i < n; i++) { + bir_inst_t hi; + uint32_t hl; + if (X->spliced[i]) continue; + hi = M->insts[i]; + hl = M->inst_lines[i]; + j = X->val_map[i]; + for (g = 0; j != i && j < n && g < n; g++) { + bir_inst_t ti = M->insts[j]; + uint32_t tl = M->inst_lines[j]; + M->insts[j] = hi; + M->inst_lines[j] = hl; + X->spliced[j] = 1; + hi = ti; + hl = tl; + j = X->val_map[j]; + } + M->insts[i] = hi; + M->inst_lines[i] = hl; + X->spliced[i] = 1; } +} - nb = M->num_blocks++; - X->blk_map[ob] = nb - bb0; - M->blocks[nb].name = B->name; - M->blocks[nb].first_inst = M->num_insts - ib0; - M->blocks[nb].num_insts = n; - for (j = 0; j < n; j++) { - uint32_t src = B->first_inst + j, dst = M->num_insts; - X->val_map[src] = dst - ib0; - M->insts[dst] = M->insts[src]; - M->inst_lines[dst] = M->inst_lines[src]; - M->num_insts++; +static void pblk(inl_t *X, uint32_t n) +{ + bir_module_t *M = X->M; + uint32_t i, j, g; + + for (i = 0; i < n; i++) X->cal_map[i] = 0; + for (i = 0; i < n; i++) { + bir_block_t hb; + if (X->cal_map[i]) continue; + hb = M->blocks[i]; + j = X->blk_map[i]; + for (g = 0; j != i && j < n && g < n; g++) { + bir_block_t tb = M->blocks[j]; + M->blocks[j] = hb; + X->cal_map[j] = 1; + hb = tb; + j = X->blk_map[j]; + } + M->blocks[i] = hb; + X->cal_map[i] = 1; } - return BC_OK; } -static int cmpct(inl_t *X) +static void cmpct(inl_t *X, uint8_t lvl) { bir_module_t *M = X->M; - uint32_t ib0 = M->num_insts, bb0 = M->num_blocks; - uint32_t f, b, nb, ni; + uint32_t f, b, i, n, ni = 0, nb = 0; + + for (i = 0; i < M->num_insts; i++) X->val_map[i] = BIR_VAL_NONE; + for (b = 0; b < M->num_blocks; b++) X->blk_map[b] = BIR_VAL_NONE; for (f = 0; f < M->num_funcs; f++) { bir_func_t *F = &M->funcs[f]; - uint32_t ob0 = F->first_block, cnt = 0, tot = 0; - - for (b = 0; b < F->num_blocks && ob0 + b < bb0; b++) { - uint32_t was = M->num_insts; - int rc = blkcpy(X, ob0 + b, ib0, bb0); - if (rc != BC_OK) return rc; - cnt++; - tot += M->num_insts - was; + uint32_t fb = nb; + if (X->need[f] < lvl) { + F->first_block = 0; + F->num_blocks = 0; + F->total_insts = 0; + continue; + } + if (F->num_blocks == 0) continue; + if (F->first_block >= M->num_blocks) { + F->num_blocks = 0; + F->total_insts = 0; + continue; } - if (cnt != 0) F->first_block = X->blk_map[ob0]; - F->num_blocks = (uint16_t)cnt; - F->total_insts = tot; + if (F->num_blocks > M->num_blocks - F->first_block) + F->num_blocks = (uint16_t)(M->num_blocks - F->first_block); + for (b = F->first_block; b < F->first_block + F->num_blocks; b++) { + bir_block_t *B = &M->blocks[b]; + uint32_t fi = ni; + if (B->first_inst > M->num_insts + || B->num_insts > M->num_insts - B->first_inst) + B->num_insts = 0; + X->blk_map[b] = nb++; + for (i = B->first_inst; i < B->first_inst + B->num_insts; i++) + if (X->val_map[i] == BIR_VAL_NONE) X->val_map[i] = ni++; + B->first_inst = fi; + } + F->first_block = fb; } - nb = M->num_blocks - bb0; - ni = M->num_insts - ib0; - memmove(M->blocks, &M->blocks[bb0], (size_t)nb * sizeof M->blocks[0]); - memmove(M->insts, &M->insts[ib0], (size_t)ni * sizeof M->insts[0]); - memmove(M->inst_lines, &M->inst_lines[ib0], - (size_t)ni * sizeof M->inst_lines[0]); - M->num_blocks = nb; + for (i = 0, n = ni; i < M->num_insts; i++) + if (X->val_map[i] == BIR_VAL_NONE) X->val_map[i] = n++; + for (b = 0, n = nb; b < M->num_blocks; b++) + if (X->blk_map[b] == BIR_VAL_NONE) X->blk_map[b] = n++; + pinst(X, M->num_insts); + pblk(X, M->num_blocks); + M->num_insts = ni; + M->num_blocks = nb; + for (i = 0; i < ni; i++) + remap_ops(M, i, X->val_map, 0, X->blk_map, X->blk_map, 0); +} - for (f = 0; f < ni; f++) - remap_ops(M, f, X->val_map, 0, X->blk_map, X->blk_map, 0); +static void fkeep(inl_t *X) +{ + bir_module_t *M = X->M; + uint32_t f, b, k, it; - return BC_OK; + for (f = 0; f < M->num_funcs; f++) + X->need[f] = (X->drop && is_device(M, f) + && !(M->funcs[f].cuda_flags & (CUDA_GLOBAL | CUDA_HOST))) + ? 0 : 2; + if (!X->drop) return; + + for (it = 0; it < INL_MAX_CGRND; it++) { + int grew = 0; + for (f = 0; f < M->num_funcs; f++) { + const bir_func_t *F = &M->funcs[f]; + if (X->need[f] == 0) continue; + for (b = 0; b < F->num_blocks; b++) { + const bir_block_t *B = &M->blocks[F->first_block + b]; + for (k = 0; k < B->num_insts; k++) { + const bir_inst_t *I = &M->insts[B->first_inst + k]; + uint32_t g; + uint8_t w; + if (I->op != BIR_CALL && I->op != BIR_FNREF) continue; + g = call_func_index(M, I); + if (g >= M->num_funcs) continue; + w = (I->op == BIR_CALL && is_inlinable(X, g)) ? 1 : 2; + if (X->need[g] < w) { X->need[g] = w; grew = 1; } + } + } + } + if (!grew) return; + } + memset(X->need, 2, sizeof(X->need)); } static int func_has_inlinable_call(const inl_t *X, uint32_t fidx) @@ -710,6 +783,7 @@ static void warn_uninlined(inl_t *X) uint32_t f, b, k; for (f = 0; f < M->num_funcs; f++) { const bir_func_t *F = &M->funcs[f]; + if (X->need[f] != 2) continue; for (b = 0; b < F->num_blocks; b++) { const bir_block_t *B = &M->blocks[F->first_block + b]; for (k = 0; k < B->num_insts; k++) { @@ -740,6 +814,9 @@ static int inline_run(inl_t *X) int round; cgcyc(X); + fkeep(X); + X->ihwm = (uint32_t)BIR_MAX_INSTS / 2u; + X->bhwm = (uint32_t)BIR_MAX_BLOCKS / 2u; /* Each round inlines every inlinable device call it finds, straight-line * and control-flow bodies alike. A callee that itself rings up another @@ -752,11 +829,16 @@ static int inline_run(inl_t *X) int changed = 0; uint32_t nf = M->num_funcs, f; for (f = 0; f < nf; f++) { - if (func_has_inlinable_call(X, f)) { - int rc = rebuild_func(X, f); - if (rc != BC_OK) return rc; - changed = 1; + int rc; + if (X->need[f] != 2 || !func_has_inlinable_call(X, f)) continue; + if (M->num_insts > X->ihwm || M->num_blocks > X->bhwm) { + cmpct(X, 1); + X->ihwm = M->num_insts + ((uint32_t)BIR_MAX_INSTS - M->num_insts) / 2u; + X->bhwm = M->num_blocks + ((uint32_t)BIR_MAX_BLOCKS - M->num_blocks) / 2u; } + rc = rebuild_func(X, f); + if (rc != BC_OK) return rc; + changed = 1; } if (!changed) break; } @@ -764,7 +846,7 @@ static int inline_run(inl_t *X) { uint32_t f; for (f = 0; f < M->num_funcs; f++) { - if (func_has_inlinable_call(X, f)) { + if (X->need[f] == 2 && func_has_inlinable_call(X, f)) { fprintf(stderr, "kath: device call inlining did not " "converge after %d rounds (recursive __device__ " "function '%s'?)\n", INL_MAX_ROUNDS, func_name(M, f)); @@ -777,7 +859,7 @@ static int inline_run(inl_t *X) return BC_OK; } -int bir_inline_device(bir_module_t *M) +int bir_inline_device(bir_module_t *M, int drop) { inl_t *X; int rc; @@ -787,11 +869,12 @@ int bir_inline_device(bir_module_t *M) X = (inl_t *)malloc(sizeof(inl_t)); if (!X) return BC_ERR_IO; X->M = M; + X->drop = drop; memset(X->spliced, 0, sizeof(X->spliced)); memset(X->warned, 0, sizeof(X->warned)); rc = inline_run(X); - if (rc == BC_OK) rc = cmpct(X); + if (rc == BC_OK) cmpct(X, 2); free(X); if (rc == BC_OK) rc = bir_vchk(M); diff --git a/src/ir/bir_inline.h b/src/ir/bir_inline.h index 53ab39f..9611552 100644 --- a/src/ir/bir_inline.h +++ b/src/ir/bir_inline.h @@ -22,6 +22,6 @@ * Returns BC_OK on success, or BC_ERR_VERIFY (with a message on stderr) if the * call graph will not converge, which means a __device__ function recurses. */ -int bir_inline_device(bir_module_t *M); +int bir_inline_device(bir_module_t *M, int drop); #endif /* BARRACUDA_BIR_INLINE_H */ diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index f2f5e1e..f4a3e4e 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -27,11 +27,12 @@ #define MAX_TDSN 1024 #define MAX_ALIAS 64 #define MAX_TEMPLATES 256 -#define MAX_PKELM 32 +#define MAX_PKELM 64 #define MAX_FWPK 64 #define MAX_FPACKS 4 #define MAX_INSTS 16384 -#define MAX_TPARM 8 +#define MAX_LNCH 4096 +#define MAX_TPARM 16 #define MAX_BIND 64 #define MAX_TDEP 7 #define MAX_NEST 8 @@ -52,6 +53,7 @@ #define MAX_CNST 24 #define MAX_VTPL 64 #define MAX_SDM 512 +#define MAX_MAL 512 #define MAX_BASE 4 #define SD_QUE 8 #define CI_SEP '$' @@ -74,6 +76,9 @@ #define MAX_LAMS 1024 #define MAX_TAGS 32 #define MAX_GLAM 16 +#define MAX_FNAL 32 +#define MAX_FNC 4 +#define MAX_FNT 12 #define LM_CAP 16 #define LM_PARM 8 #define LM_EXCL 64 @@ -164,6 +169,12 @@ typedef struct { uint8_t arr; } sdm_t; +typedef struct { + char cls[64]; + char nm[64]; + uint32_t type; +} mal_t; + typedef struct { char name[64]; uint32_t bir_type; @@ -249,6 +260,17 @@ typedef struct { int64_t val; } tgent_t; +typedef struct { + uint32_t ini; + tgent_t tg[MAX_FNT]; + int ntg; +} fnc_t; + +typedef struct { + int ei; + int ci; +} fnh_t; + typedef struct { char name[64]; uint32_t ast; @@ -286,6 +308,8 @@ typedef struct { int ncag; sdm_t sdms[MAX_SDM]; int nsdm; + mal_t mals[MAX_MAL]; + int nmal; char scls[64]; uint16_t sdbad; uint8_t sdarr; @@ -383,6 +407,8 @@ typedef struct { tgent_t tags[MAX_TAGS]; int ntags; + struct { char name[64]; fnc_t c[MAX_FNC]; int n; } fnal[MAX_FNAL]; + int nfnal; glent_t glms[MAX_GLAM]; int nglm; @@ -404,6 +430,16 @@ typedef struct { uint32_t srdty; } lower_t; +typedef struct { + char base[64]; + char sym[128]; + char targ[256]; +} lnch_t; + +static lnch_t LNCH[MAX_LNCH]; +static uint32_t NLNCH; +static uint32_t LPEND; + /* ---- Names ---- */ static void ncpy(char *d, size_t n, const char *s) @@ -446,6 +482,166 @@ static void get_text(const lower_t *L, uint32_t node, char *buf, int sz) buf[len] = '\0'; } +static const char *sname(const lower_t *L, uint32_t ty); + +static void lnrec(const lower_t *L, uint32_t callee) +{ + lnch_t *e; + + LPEND = 0u; + if (NLNCH >= MAX_LNCH) return; + e = &LNCH[NLNCH]; + memset(e, 0, sizeof *e); + get_text(L, callee, e->base, (int)sizeof e->base); + ncpy(e->sym, sizeof e->sym, e->base); + NLNCH++; + LPEND = NLNCH; +} + +static void lnsc(const lower_t *L, uint32_t t, char *out, size_t oz) +{ + const bir_type_t *y; + const char *s; + + out[0] = '\0'; + if (L->M == NULL || t >= L->M->num_types) return; + y = &L->M->types[t]; + if (y->kind == BIR_TYPE_INT) { + if (y->width == 1u) ncpy(out, oz, "bool"); + else if (y->width == 8u) ncpy(out, oz, "signed char"); + else if (y->width == 16u) ncpy(out, oz, "short"); + else if (y->width == 32u) ncpy(out, oz, "int"); + else if (y->width == 64u) ncpy(out, oz, "long long"); + } else if (y->kind == BIR_TYPE_FLOAT) { + if (y->width == 16u) ncpy(out, oz, "__half"); + else if (y->width == 32u) ncpy(out, oz, "float"); + else if (y->width == 64u) ncpy(out, oz, "double"); + } else if (y->kind == BIR_TYPE_BFLOAT) { + ncpy(out, oz, "__nv_bfloat16"); + } else if (y->kind == BIR_TYPE_VOID) { + ncpy(out, oz, "void"); + } else if (y->kind == BIR_TYPE_STRUCT || y->kind == BIR_TYPE_VECTOR) { + s = sname(L, t); + if (s != NULL && s[0] != '\0') ncpy(out, oz, s); + } + if (y->cst && out[0] != 0) { + char b[64]; + + ncpy(b, sizeof b, out); + if (snprintf(out, oz, "const %s", b) < 0) out[0] = 0; + } +} + +static void lnspl(const lower_t *L, uint32_t t, char *out, size_t oz) +{ + char in[64]; + uint32_t np = 0u; + + out[0] = '\0'; + if (L->M == NULL) return; + KA_GUARD(g, 4); + while (t < L->M->num_types + && L->M->types[t].kind == BIR_TYPE_PTR && g--) { + t = L->M->types[t].inner; + np++; + } + lnsc(L, t, in, sizeof in); + if (in[0] == '\0' || np > 3u) return; + if (np == 0u) { ncpy(out, oz, in); return; } + if (snprintf(out, oz, "%s %.*s", in, (int)np, "***") < 0) out[0] = '\0'; +} + +#define FSP_MAX 256 + +static struct { + char sym[64]; + char spl[192]; +} FSPL[FSP_MAX]; +static uint32_t NFSP; + +static void fsput(const char *sym, const char *spl) +{ + if (NFSP >= FSP_MAX) return; + for (uint32_t i = 0; i < NFSP; i++) + if (strcmp(FSPL[i].sym, sym) == 0) return; + ncpy(FSPL[NFSP].sym, sizeof FSPL[0].sym, sym); + ncpy(FSPL[NFSP].spl, sizeof FSPL[0].spl, spl); + NFSP++; +} + +static const char *fsget(const char *sym) +{ + for (uint32_t i = 0; i < NFSP; i++) + if (strcmp(FSPL[i].sym, sym) == 0) return FSPL[i].spl; + return NULL; +} + +static int lnone(const lower_t *L, const binding_t *b, int k, + char *one, size_t oz) +{ + const char *s; + + if (b->is_pack) { + if (b->pk_nt) + return snprintf(one, oz, "%lld", (long long)b->pk_v[k]) > 0; + lnspl(L, b->pk_t[k], one, oz); + return one[0] != '\0'; + } + if (b->is_fn) { + if (b->fnm[0] == '\0') return 0; + s = fsget(b->fnm); + if (s == NULL) s = b->fnm; + if (strchr(s, '$') != NULL) return 0; + ncpy(one, oz, s); + return 1; + } + if (b->is_type) { + if (b->guess) return 0; + lnspl(L, b->type, one, oz); + return one[0] != '\0'; + } + return snprintf(one, oz, "%lld", (long long)b->ival) > 0; +} + +static void lntarg(const lower_t *L, const binding_t *nb, int ntp, + char *out, size_t oz) +{ + size_t n = 0; + + out[0] = '\0'; + for (int i = 0; i < ntp; i++) { + int nk = nb[i].is_pack ? nb[i].npk : 1; + + for (int k = 0; k < nk; k++) { + char one[192]; + size_t l; + + if (!lnone(L, &nb[i], k, one, sizeof one)) { + out[0] = '\0'; + return; + } + l = strlen(one); + if (n + l + 3u >= oz) { out[0] = '\0'; return; } + if (n != 0u) { out[n++] = ','; out[n++] = ' '; } + memcpy(out + n, one, l); + n += l; + out[n] = '\0'; + } + } +} + +static void lnsym(const lower_t *L, const char *sym, const binding_t *nb, + int ntp) +{ + lnch_t *e; + + if (LPEND == 0u || LPEND > NLNCH) return; + e = &LNCH[LPEND - 1u]; + ncpy(e->sym, sizeof e->sym, sym); + lntarg(L, nb, ntp, e->targ, sizeof e->targ); + LPEND = 0u; +} + static int text_eq(const lower_t *L, uint32_t node, const char *s) { const ast_node_t *n = ND(L, node); @@ -627,6 +823,7 @@ static int aggr(const lower_t *L, uint32_t t) static const char *sname(const lower_t *L, uint32_t ty) { + ty = bir_tunq(L->M, ty); for (int i = 0; i < L->nstructs; i++) if (L->structs[i].bir_type == ty) return L->structs[i].name; return NULL; @@ -809,6 +1006,7 @@ static uint32_t natal(const lower_t *L, uint32_t t) && (L->M->types[e].kind == BIR_TYPE_ARRAY || L->M->types[e].kind == BIR_TYPE_VECTOR)) e = L->M->types[e].inner; + e = bir_tunq(L->M, e); for (int i = 0; i < L->nstructs; i++) if (L->structs[i].bir_type == e && L->structs[i].algn > a) a = L->structs[i].algn; @@ -1270,6 +1468,8 @@ static int tpdep(const lower_t *L, uint32_t n) } static int altry(lower_t *L, const char *nm, uint32_t ta, uint32_t *out); +static int malfnd(const lower_t *L, const char *cls, const char *nm, + uint32_t *ty); static int cgknd(const char *n) { @@ -1346,12 +1546,23 @@ static uint32_t resolve_type(lower_t *L, uint32_t node, int ptr_depth, if (ND(L, tc)->type == AST_IDENT && tc != nc) get_text(L, tc, name, sizeof(name)); if (ND(L, tc)->type == AST_TEMPLATE_ARGS) { - char mg[128]; + char mg[128], mb[64]; + uint32_t mn = ND(L, tc)->next_sibling; int si = cget(L, node, name, tc, mg, sizeof(mg)) ? cslot(L, mg) : -1; L->rtbad = 0; L->rtunk = 0; L->rtalgn = 0; + while (mn && ND(L, mn)->type != AST_IDENT) + mn = ND(L, mn)->next_sibling; + if (si >= 0 && mn) { + uint32_t mt = 0; + get_text(L, mn, mb, sizeof(mb)); + if (malfnd(L, mg, mb, &mt)) return mt; + L->rtbad = BC_E155; + ncpy(L->rtbadn, sizeof(L->rtbadn), mb); + return bir_type_int(L->M, 32); + } if (si >= 0) { L->rtalgn = L->structs[si].algn; ncpy(L->rtsnm, sizeof(L->rtsnm), mg); @@ -1460,6 +1671,9 @@ static uint32_t resolve_type(lower_t *L, uint32_t node, int ptr_depth, base = resolve_basic(L, kind); } + if (ptr_depth > 0 && (n->qualifiers & QUAL_CONST)) + base = bir_tcst(L->M, base); + for (int i = 0; i < ptr_depth; i++) { int as = BIR_AS_GLOBAL; if (cuda & CUDA_SHARED) as = BIR_AS_SHARED; @@ -1487,10 +1701,12 @@ static uint32_t ref_type(const lower_t *L, uint32_t ref) if (ref == BIR_VAL_NONE) return 0; if (BIR_VAL_IS_CONST(ref)) { uint32_t ci = BIR_VAL_INDEX(ref); - return ci < L->M->num_consts ? L->M->consts[ci].type : 0; + return ci < L->M->num_consts + ? bir_tunq(L->M, L->M->consts[ci].type) : 0; } uint32_t ii = BIR_VAL_INDEX(ref); - return ii < L->M->num_insts ? L->M->insts[ii].type : 0; + return ii < L->M->num_insts + ? bir_tunq(L->M, L->M->insts[ii].type) : 0; } static uint32_t vlane(lower_t *L, uint32_t val, int lane) @@ -1644,7 +1860,7 @@ static int is_ptr_type(const lower_t *L, uint32_t t) static uint32_t ptr_inner(const lower_t *L, uint32_t t) { - if (is_ptr_type(L, t)) return L->M->types[t].inner; + if (is_ptr_type(L, t)) return bir_tunq(L->M, L->M->types[t].inner); return 0; } @@ -2356,6 +2572,7 @@ static int tamb(const lower_t *L, uint32_t ty) { int n = 0; + ty = bir_tunq(L->M, ty); for (int i = 0; i < L->nstructs; i++) if (L->structs[i].bir_type == ty) n++; return n; @@ -4077,6 +4294,7 @@ static uint32_t bin_val(lower_t *L, uint32_t node, int op, static struct_def_t *sdbyt(lower_t *L, uint32_t t) { + t = bir_tunq(L->M, t); for (int i = 0; i < L->nstructs; i++) if (L->structs[i].bir_type == t) return &L->structs[i]; return NULL; @@ -4112,7 +4330,7 @@ static uint32_t stof(lower_t *L, uint32_t ref, uint32_t node) if (L->M->types[t].kind == BIR_TYPE_STRUCT) return t; if (L->M->types[t].kind != BIR_TYPE_PTR || !(agglv(L, node) || aggv(L, node))) return 0; - t = L->M->types[t].inner; + t = ptr_inner(L, t); return (t < L->M->num_types && L->M->types[t].kind == BIR_TYPE_STRUCT) ? t : 0; } @@ -5167,10 +5385,12 @@ static int lwalk(lower_t *L, uint32_t root, int excl, lam_t *m, if (n->type == AST_IDENT) { sym_t *s; + int64_t bv; if (excl) continue; get_text(L, nd, nm, sizeof nm); if (lhas(ex, *nex, nm)) continue; if (lhas(m->cnm, m->ncap, nm)) continue; + if (find_binding_int(L, nm, &bv)) continue; s = find_sym(L, nm); if (!s || lglob(L, s, nm)) continue; if (m->ncap >= LM_CAP) return 0; @@ -7220,6 +7440,19 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) uint32_t inst = emit(L, BIR_BARRIER, bir_type_void(L->M), 0, 0); return BIR_MAKE_VAL(inst); } + if (strcmp(cname, "__syncwarp") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + int64_t msk = 0; + + if (an && (!cival(L, an, &msk) + || (uint64_t)msk != 0xffffffffu)) { + lower_error(L, node, BC_E030, + "__syncwarp with a mask short of every lane"); + return BIR_VAL_NONE; + } + return BIR_MAKE_VAL(emit(L, BIR_BARRIER, + bir_type_void(L->M), 0, 1)); + } { static const struct { const char *n; uint8_t sc; } ftab[] = { {"__threadfence_block", 0}, @@ -8951,6 +9184,7 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) static int sfind(const lower_t *L, uint32_t st) { + st = bir_tunq(L->M, st); for (int si = 0; si < L->nstructs; si++) if (L->structs[si].bir_type == st) return si; return -1; @@ -10281,6 +10515,44 @@ static int collect_params(const lower_t *L, uint32_t func_def, static void lfbody(lower_t *L, uint32_t func_def, uint16_t cuda_flags, const char *name_override); +static int ureg(lower_t *L, uint32_t node); + +static int ustmt(int t) +{ + return t == AST_BLOCK || t == AST_IF || t == AST_FOR + || t == AST_RANGE_FOR || t == AST_WHILE || t == AST_DO_WHILE + || t == AST_SWITCH || t == AST_CASE || t == AST_DEFAULT; +} + +static void uscan(lower_t *L, uint32_t fd) +{ + uint32_t wk[UC_NEST]; + int wn = 0; + uint32_t bd = find_func_body(L, fd); + + if (!bd) return; + wk[wn++] = bd; + KA_GUARD(g, 4096); + while (wn > 0 && g--) { + uint32_t nd = wk[--wn], c; + int n0 = wn, i, j; + + for (c = ND(L, nd)->first_child; c; c = ND(L, c)->next_sibling) { + if (ND(L, c)->type == AST_USING) { + if (!ureg(L, c)) lower_error(L, c, BC_E140, MAX_TYPEDEFS); + continue; + } + if (!ustmt(ND(L, c)->type)) continue; + if (wn >= UC_NEST) break; + wk[wn++] = c; + } + for (i = n0, j = wn - 1; i < j; i++, j--) { + uint32_t t = wk[i]; + wk[i] = wk[j]; + wk[j] = t; + } + } +} static void lower_func_body(lower_t *L, uint32_t func_def, uint16_t cuda_flags, const char *name_override) @@ -10291,6 +10563,7 @@ static void lower_func_body(lower_t *L, uint32_t func_def, L->tsc = 0; L->clow = 1; L->ntdf = L->ntypedefs; + uscan(L, func_def); lfbody(L, func_def, cuda_flags, name_override); ldrain(L); L->ntdf = fsv; @@ -10653,6 +10926,48 @@ static void salgn(lower_t *L, struct_def_t *sd, uint32_t node) sd->algn = (uint16_t)want; } +static int malfnd(const lower_t *L, const char *cls, const char *nm, + uint32_t *ty) +{ + for (int i = L->nmal - 1; i >= 0; i--) + if (strcmp(L->mals[i].cls, cls) == 0 + && strcmp(L->mals[i].nm, nm) == 0) { + *ty = L->mals[i].type; + return 1; + } + return 0; +} + +static int malad(lower_t *L, uint32_t mem, struct_def_t *sd) +{ + uint32_t nn = ND(L, mem)->first_child; + uint32_t ty = nn ? ND(L, nn)->next_sibling : 0; + char an[64]; + uint32_t t; + mal_t *e = NULL; + + if (!nn || ND(L, nn)->type != AST_IDENT) return 1; + if (!ty || ND(L, ty)->type != AST_TYPE_SPEC) return 1; + if (!sd->name[0]) return 1; + t = resolve_type(L, ty, ND(L, mem)->d.oper.flags, ND(L, mem)->cuda_flags); + L->rtbad = 0; + L->rtunk = 0; + if (!t) return 1; + get_text(L, nn, an, sizeof(an)); + for (int i = 0; i < L->nmal; i++) + if (strcmp(L->mals[i].cls, sd->name) == 0 + && strcmp(L->mals[i].nm, an) == 0) { e = &L->mals[i]; break; } + if (!e) { + if (L->nmal >= MAX_MAL) return 0; + e = &L->mals[L->nmal++]; + } + memset(e, 0, sizeof(*e)); + ncpy(e->cls, sizeof(e->cls), sd->name); + ncpy(e->nm, sizeof(e->nm), an); + e->type = t; + return 1; +} + static int sdreg(lower_t *L, uint32_t mem, struct_def_t *sd) { uint32_t ft = ND(L, mem)->first_child; @@ -10749,6 +11064,12 @@ static void collect_struct(lower_t *L, uint32_t node) int over = 0; while (member) { if (sd->num_fields >= MAX_FIELDS) { over = 1; break; } + if (ND(L, member)->type == AST_USING) { + if (!malad(L, member, sd)) + lower_error(L, member, BC_E340, sd->name, MAX_MAL); + member = ND(L, member)->next_sibling; + continue; + } if (ND(L, member)->type == AST_FUNC_DEF && (ND(L, member)->qualifiers & QUAL_CONSTEXPR)) { uint32_t mid = child_at(L, member, 1); @@ -11316,7 +11637,7 @@ static uint32_t arg_type(lower_t *L, uint32_t arg) && (L->M->types[bt].kind == BIR_TYPE_ARRAY || L->M->types[bt].kind == BIR_TYPE_PTR) && L->M->types[bt].inner) - return L->M->types[bt].inner; + return bir_tunq(L->M, L->M->types[bt].inner); } if (a->type == AST_MEMBER && a->first_child && L->atdp < MAX_CDEP) { uint32_t obj = a->first_child; @@ -11349,7 +11670,7 @@ static uint32_t tpeel(const lower_t *L, uint32_t t, int dep) return 0; t = L->M->types[t].inner; } - return t; + return bir_tunq(L->M, t); } static int tfarg(lower_t *L, uint32_t a, const char *vn, @@ -11357,10 +11678,12 @@ static int tfarg(lower_t *L, uint32_t a, const char *vn, { template_def_t *tm = find_template(L, vn); binding_t *nb2; - char key[256]; + char key[256], ta[192], spl[224]; int ntp = 0, ok; uint32_t fn2 = 0; + uint32_t lp = LPEND; + if (!tm || L->xdep >= MAX_NEST) return 0; nb2 = L->xnb[L->xdep]; L->xdep++; @@ -11373,6 +11696,13 @@ static int tfarg(lower_t *L, uint32_t a, const char *vn, && tfind(L, key, out, oz); } } + if (ok) { + lntarg(L, nb2, ntp, ta, sizeof ta); + if (ta[0] != '\0' + && snprintf(spl, sizeof spl, "%s<%s>", vn, ta) > 0) + fsput(out, spl); + } + LPEND = lp; L->xdep--; return ok; } @@ -11596,9 +11926,10 @@ static int tparm(lower_t *L, uint32_t tnode, binding_t *nb) int ntp = 0; for (uint32_t tp = ND(L, tnode)->first_child; - tp && ND(L, tp)->type == AST_TEMPLATE_PARAM && ntp < MAX_TPARM; + tp && ND(L, tp)->type == AST_TEMPLATE_PARAM; tp = ND(L, tp)->next_sibling) { int fl = ND(L, tp)->d.oper.flags; + if (ntp >= MAX_TPARM) return -1; memset(&nb[ntp], 0, sizeof(nb[0])); nb[ntp].is_type = !(fl & TP_NTYP); if (fl & TP_PACK) { @@ -12229,7 +12560,8 @@ static int tdeduc(lower_t *L, uint32_t tnode, uint32_t cal, { int ntp = tparm(L, tnode, nb); int ai = 0; - *ntpo = ntp; + *ntpo = ntp < 0 ? 0 : ntp; + if (ntp < 0) return 0; uint32_t func_n = 0; for (uint32_t fc = ND(L, tnode)->first_child; fc; @@ -12333,7 +12665,10 @@ static int tinst(lower_t *L, uint32_t node, const char *cname, int nsame = 0; size_t cl = strlen(cname); for (int i = 0; i < L->ninst; i++) { - if (strcmp(L->inst[i].key, key) == 0) return 0; + if (strcmp(L->inst[i].key, key) == 0) { + lnsym(L, L->inst[i].sym, nb, ntp); + return 0; + } if (strncmp(L->inst[i].key, cname, cl) == 0 && L->inst[i].key[cl] == '|') nsame++; @@ -12346,6 +12681,7 @@ static int tinst(lower_t *L, uint32_t node, const char *cname, char mangled[128]; if (!tmang(L, cname, nsame, mangled, sizeof(mangled))) return -1; + lnsym(L, mangled, nb, ntp); if (snprintf(L->inst[L->ninst].key, sizeof(L->inst[0].key), "%s", key) < 0 || snprintf(L->inst[L->ninst].sym, sizeof(L->inst[0].sym), "%s", mangled) < 0) return -1; @@ -12681,23 +13017,64 @@ static void tscan(lower_t *L, uint32_t node) vscn(L, node); } } + if (n->type == AST_USING && !ureg(L, node)) + lower_error(L, node, BC_E140, MAX_TYPEDEFS); if (psv >= 0) L->nsyms = psv; if (tsv >= 0) L->ntypedefs = tsv; if (csv >= 0) ccomp(L, csv); } -static uint32_t fwlk(const lower_t *L, uint32_t nd) +static uint32_t fwlkn(const lower_t *L, uint32_t nd, int k, int *nc, fnh_t *h) { + if (nc) *nc = 1; + if (h) { h->ei = -1; h->ci = -1; } nd = unfw(L, nd); if (L->nfwf <= 0 || !nd || ND(L, nd)->type != AST_IDENT) return nd; - const fwfr_t *f = &L->fwf[L->nfwf - 1]; - char nm[64]; - get_text(L, nd, nm, sizeof(nm)); - for (int i = 0; i < f->nb; i++) - if (strcmp(f->b[i].name, nm) == 0) return f->b[i].arg; + for (int fi = L->nfwf - 1; fi >= 0; fi--) { + const fwfr_t *f = &L->fwf[fi]; + char nm[64]; + + if (!nd || ND(L, nd)->type != AST_IDENT) break; + get_text(L, nd, nm, sizeof(nm)); + for (int i = 0; i < f->nb; i++) + if (strcmp(f->b[i].name, nm) == 0) { + nd = unfw(L, f->b[i].arg); + break; + } + } + + KA_GUARD(g, MAX_FNAL); + while (g-- && nd && ND(L, nd)->type == AST_IDENT) { + char nm[64]; + int hit = 0; + + get_text(L, nd, nm, sizeof(nm)); + for (int i = L->nfnal - 1; i >= 0; i--) + if (strcmp(L->fnal[i].name, nm) == 0) { + int c = L->fnal[i].n, j; + + if (c <= 0) return nd; + j = k % c; + if (nc && *nc <= MAX_FNC * MAX_FNC) *nc *= c; + if (h) { h->ei = i; h->ci = j; } + nd = unfw(L, L->fnal[i].c[j].ini); + k /= c; + hit = 1; + break; + } + if (!hit) break; + } return nd; } +static int fwnc(const lower_t *L, uint32_t nd) +{ + int nc = 1; + + (void)fwlkn(L, nd, 0, &nc, NULL); + return nc > 0 ? nc : 1; +} + static int fwmen(const lower_t *L, uint32_t nd, int depth) { const fwfr_t *f = &L->fwf[L->nfwf - 1]; @@ -12756,7 +13133,12 @@ static int subav(lower_t *L, uint32_t first, uint32_t *av, int max) continue; } if (n >= max) return -1; - av[n++] = fwlk(L, c); + { + int nci = 1; + uint32_t rv = fwlkn(L, c, 0, &nci, NULL); + + av[n++] = (nci > 1) ? unfw(L, c) : rv; + } } return n; } @@ -13008,9 +13390,9 @@ static int fwpush(lower_t *L, uint32_t func_n, const uint32_t *av, int na) return 1; } -static int slnch(lower_t *L, uint32_t node) +static int slnch(lower_t *L, uint32_t node, int k) { - uint32_t callee_n = fwlk(L, ND(L, node)->first_child); + uint32_t callee_n = fwlkn(L, ND(L, node)->first_child, k, NULL, NULL); if (!callee_n || ND(L, callee_n)->type != AST_IDENT) return 0; char cname[128]; @@ -13240,6 +13622,132 @@ static void slcx(lower_t *L, uint32_t c) (n->qualifiers & QUAL_CONSTEXPR) != 0); } +static void fncap(lower_t *L, uint32_t r, fnc_t *fc) +{ + uint32_t ta = ND(L, r)->first_child; + + fc->ntg = 0; + if (!ta || ND(L, ta)->type != AST_TEMPLATE_ARGS) return; + for (uint32_t a = ND(L, ta)->first_child; a; a = ND(L, a)->next_sibling) { + cval_t v; + + if (ND(L, a)->type != AST_IDENT || fc->ntg >= MAX_FNT) continue; + if (!cfold(L, a, &v) || v.isf) continue; + get_text(L, a, fc->tg[fc->ntg].name, sizeof(fc->tg[0].name)); + fc->tg[fc->ntg].val = v.ival; + fc->ntg++; + } +} + +static void fnadd(lower_t *L, const char *nm, uint32_t rhs) +{ + int e = -1; + + for (int i = L->nfnal - 1; i >= 0; i--) + if (strcmp(L->fnal[i].name, nm) == 0) { e = i; break; } + if (e < 0) { + if (L->nfnal >= MAX_FNAL) return; + e = L->nfnal++; + ncpy(L->fnal[e].name, sizeof(L->fnal[0].name), nm); + L->fnal[e].n = 0; + } + for (int j = 0; j < L->fnal[e].n; j++) + if (L->fnal[e].c[j].ini == rhs) return; + if (L->fnal[e].n >= MAX_FNC) return; + L->fnal[e].c[L->fnal[e].n].ini = rhs; + fncap(L, rhs, &L->fnal[e].c[L->fnal[e].n]); + L->fnal[e].n++; +} + +static void fnpsh(lower_t *L, const fnc_t *fc) +{ + for (int i = 0; i < fc->ntg; i++) + (void)tgadd(L, fc->tg[i].name, fc->tg[i].val); +} + +static void fnasg(lower_t *L, uint32_t nd, int depth) +{ + const ast_node_t *n; + uint32_t l, r; + + if (!nd || depth > CE_NEST) return; + n = ND(L, nd); + l = (n->type == AST_BINARY && n->d.oper.op == TOK_ASSIGN) + ? n->first_child : 0; + r = l ? ND(L, l)->next_sibling : 0; + if (r && !ND(L, r)->next_sibling && ND(L, l)->type == AST_IDENT + && ND(L, r)->type == AST_IDENT) { + char nm[64], rn[128]; + + get_text(L, r, rn, sizeof(rn)); + if (find_template(L, rn)) { + get_text(L, l, nm, sizeof(nm)); + fnadd(L, nm, r); + } + } + for (uint32_t c = n->first_child; c; c = ND(L, c)->next_sibling) + fnasg(L, c, depth + 1); +} + +static void fnreg(lower_t *L, uint32_t c) +{ + const ast_node_t *n = ND(L, c); + uint32_t nm_n, in_n; + char nm[64]; + + if (n->type != AST_VAR_DECL || (n->qualifiers & QUAL_TYPEDEF)) return; + nm_n = child_at(L, c, 1); + if (!nm_n || ND(L, nm_n)->type != AST_IDENT) return; + in_n = ND(L, nm_n)->next_sibling; + if (in_n && ND(L, in_n)->type == AST_STRUCT_DEF) + in_n = ND(L, in_n)->next_sibling; + if (!in_n || ND(L, in_n)->type != AST_IDENT) return; + get_text(L, nm_n, nm, sizeof(nm)); + fnadd(L, nm, in_n); +} + +static void fnfil(lower_t *L, uint32_t nd) +{ + const ast_node_t *n = ND(L, nd); + uint32_t l = n->first_child; + uint32_t r = l ? ND(L, l)->next_sibling : 0; + char nm[64]; + + if (!r || ND(L, r)->next_sibling) return; + if (ND(L, l)->type != AST_IDENT || ND(L, r)->type != AST_IDENT) return; + get_text(L, l, nm, sizeof(nm)); + for (int i = L->nfnal - 1; i >= 0; i--) + if (strcmp(L->fnal[i].name, nm) == 0) { + for (int j = 0; j < L->fnal[i].n; j++) + if (L->fnal[i].c[j].ini == r) + fncap(L, r, &L->fnal[i].c[j]); + return; + } +} + +static int slnal(lower_t *L, uint32_t node) +{ + uint32_t cal = ND(L, node)->first_child; + int nc = fwnc(L, cal), hit = 0; + + if (nc > MAX_FNC * MAX_FNC) { + lower_error(L, node, BC_E030, + "more kernels behind one launch pointer than Booth tracks"); + return 1; + } + for (int k = 0; k < nc; k++) { + fnh_t h; + uint32_t c = fwlkn(L, cal, k, NULL, &h); + int tsv = L->ntags; + + if (h.ei >= 0) fnpsh(L, &L->fnal[h.ei].c[h.ci]); + if (c && ND(L, c)->type == AST_IDENT) lnrec(L, c); + if (slnch(L, node, k)) hit = 1; + L->ntags = tsv; + } + return hit; +} + static void scan_launches(lower_t *L, uint32_t node) { if (!node) return; @@ -13247,16 +13755,19 @@ static void scan_launches(lower_t *L, uint32_t node) if (n->type == AST_LAMBDA && lgen(L, node)) return; if (n->type == AST_FOLD && sfld(L, node)) return; - if (n->type == AST_LAUNCH && slnch(L, node)) return; + if (n->type == AST_BINARY && n->d.oper.op == TOK_ASSIGN) fnfil(L, node); + if (n->type == AST_LAUNCH && slnal(L, node)) return; if (n->type == AST_CALL && sglc(L, node)) return; if (n->type == AST_CALL && swrap(L, node)) return; if (n->type == AST_BLOCK) { - int gsv = L->nglm; + int gsv = L->nglm, fsv = L->nfnal; push_scope(L); for (uint32_t c = n->first_child; c; c = ND(L, c)->next_sibling) { uint32_t lm = lvlam(L, c); slcx(L, c); + fnreg(L, c); + fnasg(L, c, 0); if (lm && lgen(L, lm) && L->nglm < MAX_GLAM) { get_text(L, child_at(L, c, 1), L->glms[L->nglm].name, (int)sizeof(L->glms[0].name)); @@ -13269,6 +13780,7 @@ static void scan_launches(lower_t *L, uint32_t node) } pop_scope(L); L->nglm = gsv; + L->nfnal = fsv; return; } @@ -13276,6 +13788,72 @@ static void scan_launches(lower_t *L, uint32_t node) scan_launches(L, c); } +static uint32_t tixnm(const lower_t *L, uint32_t node, uint32_t *ta, + uint32_t *fdn) +{ + uint32_t fd = ND(L, node)->first_child, nm, c; + + *ta = 0; + *fdn = 0; + if (!fd) return 0; + if (ND(L, fd)->type != AST_FUNC_DECL && ND(L, fd)->type != AST_FUNC_DEF) + return 0; + nm = child_at(L, fd, 1); + if (!nm || ND(L, nm)->type != AST_IDENT) return 0; + for (c = ND(L, nm)->first_child; c; c = ND(L, c)->next_sibling) + if (ND(L, c)->type == AST_TEMPLATE_ARGS) { *ta = c; break; } + if (!*ta) return 0; + *fdn = fd; + return nm; +} + +static void tixp(lower_t *L, uint32_t node) +{ + uint32_t ta, nm, fd, func_n, body, pv[MAX_PARM]; + binding_t *nb = L->tnb; + template_def_t *tm; + char cname[128]; + int ntp, np, onb, obs; + + if (ND(L, node)->qualifiers & QUAL_EXTERN) return; + nm = tixnm(L, node, &ta, &fd); + if (!nm) { lower_error(L, node, BC_E175); return; } + get_text(L, nm, cname, sizeof(cname)); + + np = collect_params(L, fd, pv, MAX_PARM); + tm = ftmpl(L, cname, np); + if (!tm) { lower_error(L, node, BC_E175); return; } + func_n = tfunc(L, tm); + if (!func_n) { lower_error(L, node, BC_E175); return; } + + ntp = tparm(L, tm->ast, nb); + if (!texpl(L, nm, nb, ntp) || !tdflt(L, nb, ntp)) { + lower_error(L, node, BC_E175); + return; + } + + if (ND(L, func_n)->cuda_flags & (CUDA_GLOBAL | CUDA_DEVICE)) { + tinst(L, node, cname, nb, ntp, func_n); + return; + } + + body = find_func_body(L, func_n); + if (!body) return; + + onb = L->nbindings; + obs = L->nbbase; + if (ntp > MAX_BIND - onb) { + lower_error(L, node, BC_E157, cname); + return; + } + for (int i = 0; i < ntp; i++) + L->bindings[L->nbindings++] = nb[i]; + L->nbbase = onb; + scan_launches(L, body); + L->nbbase = obs; + L->nbindings = onb; +} + static void cscan(lower_t *L, uint32_t root) { uint32_t wk[CE_NEST]; @@ -13389,6 +13967,21 @@ static int tlcol(lower_t *L, uint32_t root) /* ---- Top-Level Entry Point ---- */ +uint32_t bir_nlnch(void) +{ + return NLNCH; +} + +int bir_lnch(uint32_t i, const char **base, const char **sym, + const char **targ) +{ + if (i >= NLNCH) return 0; + if (base) *base = LNCH[i].base; + if (sym) *sym = LNCH[i].sym; + if (targ) *targ = LNCH[i].targ; + return 1; +} + int bir_lower(const parser_t *P, uint32_t ast_root, bir_module_t *M, const sema_ctx_t *sema, bc_error_t *out_errs, int *out_nerrs) @@ -13411,6 +14004,8 @@ int bir_ltu(const parser_t *P, uint32_t ast_root, bir_module_t *M, L->tu = tu; L->tsc = 1; L->srdst = BIR_VAL_NONE; + NLNCH = 0u; + LPEND = 0u; if (!cfcol(L, ast_root)) lower_error(L, 0, BC_E030, "too many constexpr functions"); @@ -13489,6 +14084,7 @@ int bir_ltu(const parser_t *P, uint32_t ast_root, bir_module_t *M, uint32_t body = find_func_body(L, c); if (body) scan_launches(L, body); } + if (n->type == AST_TEMPLATE_INST) tixp(L, c); } if (M->pool_full) { diff --git a/src/ir/bir_lower.h b/src/ir/bir_lower.h index 0f5b9e9..7cf1d68 100644 --- a/src/ir/bir_lower.h +++ b/src/ir/bir_lower.h @@ -22,4 +22,8 @@ int bir_ltu(const struct parser_s *P, uint32_t ast_root, bir_module_t *M, const struct sema_ctx_s *sema, uint16_t tu, bc_error_t *out_errs, int *out_nerrs); +uint32_t bir_nlnch(void); +int bir_lnch(uint32_t i, const char **base, const char **sym, + const char **targ); + #endif /* BARRACUDA_BIR_LOWER_H */ diff --git a/src/main.c b/src/main.c index 3d1bd47..6815b2f 100644 --- a/src/main.c +++ b/src/main.c @@ -29,6 +29,7 @@ #include "backend.h" #include "backend_cfg.h" #include "exec/front.h" +#include "hgen.h" #include static char source_buf[BC_MAX_SOURCE]; @@ -36,6 +37,8 @@ static char pp_out_buf[BC_MAX_SOURCE]; /* preprocessor output */ static token_t token_buf[BC_MAX_TOKENS]; static ast_node_t node_buf[BC_MAX_NODES]; static bir_module_t *bir_module; /* heap-allocated (~11 MB) */ +static uint32_t g_ntok; +static uint32_t g_slen; /* kath run wants a kernel name, and only the built module knows one */ static kath_out_t *g_kout; @@ -129,7 +132,7 @@ static int run_bir_backends(bir_module_t *bir, const backend_cfg_t *cfg) { const be_desc_t *b = be_active(); if (b != NULL && (b->feats & BE_F_NOCALL)) { - int irc = bir_inline_device(bir); + int irc = bir_inline_device(bir, (b->feats & BE_F_REACH) != 0); if (irc != BC_OK) { (void)bir_pchk(bir, "device inlining"); return irc; } } } @@ -240,6 +243,7 @@ static void dump_tokens(const lexer_t *L) typedef struct { int mode_pp, mode_lex, mode_parse, mode_sema, mode_hip, no_pp; + int hostp; int want_ast, want_sema, want_bir; const char *const *incs; int nincs; const char *const *defs; int ndefs; @@ -266,6 +270,14 @@ static int comp_tu(const char *file, const tuc_t *c) } pp_init(pp, source_buf, src_len, pp_out_buf, BC_MAX_SOURCE, file); + if (c->hostp) { + pp_host(pp); + } else { + pp_define(pp, "__CUDA_ARCH__", "1100"); + pp_define(pp, "__CUDACC__", "1"); + } + pp_define(pp, "CUDART_VERSION", "11020"); + if (c->mode_hip) { pp_define(pp, "__HIPCC__", "1"); pp_define(pp, "__HIP_DEVICE_COMPILE__", "1"); @@ -324,6 +336,9 @@ static int comp_tu(const char *file, const tuc_t *c) bc_diag(file, lex_src, L.errors, L.num_errors); + g_ntok = L.num_tokens; + g_slen = lex_len; + if (c->mode_lex) { dump_tokens(&L); printf("\n%u tokens, %d error(s)\n", L.num_tokens, L.num_errors); @@ -415,6 +430,10 @@ static void usage(const char *prog) " --sema Run semantic analysis and dump types\n" " --pp Preprocess only and print result\n" " --no-pp Skip preprocessor\n" + " --cuda-host Write the host half of the program back out: device\n" + " definitions removed, each <<< >>> through the CUDA\n" + " registration ABI. Pair with --fatbin.\n" + " --fatbin The fatbin --cuda-host registers from a constructor\n" " -I Add include search path\n" " -D Define a preprocessor macro\n" " --amdgpu Compile to AMDGCN assembly (default: gfx1100)\n" @@ -436,6 +455,10 @@ static void usage(const char *prog) " --nvidia-ptx Compile to NVIDIA PTX (sm_89), for the driver to JIT\n" " --nvidia-sass Compile to a SASS listing (sm_89), no NVIDIA tool involved\n" " --nvidia-cubin Compile to a loadable cubin (sm_89), no NVIDIA tool involved\n" + " --ptx-fallback kath cuda: when the cubin backend refuses a unit, let\n" + " its fatbin carry PTX alone and say so. On by default\n" + " --no-ptx-fallback kath cuda: turn that off, so a refused unit is a\n" + " hard failure again and a build lists every gap\n" " --hip HIP frontend mode (predefines __HIPCC__ and platform macros;\n" " auto-on for .hip files; combine with --amdgpu-bin or --nvidia-ptx)\n" " --mlir Read MLIR text. Core dialects only, anything else is refused\n" @@ -480,6 +503,8 @@ int kath_compile(int argc, char *argv[], kath_out_t *out) int mode_triton = 0; /* Triton frontend: see TRITON NOTES below */ int mode_mlir = 0; /* MLIR frontend: see MLIR NOTES below */ int mode_bir_in = 0; /* BIR text in: see BIR NOTES below */ + int mode_chost = 0; + const char *fat_file = NULL; int no_mem2reg = 0; int no_cfold = 0; int no_dce = 0; @@ -519,6 +544,10 @@ int kath_compile(int argc, char *argv[], kath_out_t *out) mode_pp = 1; else if (strcmp(argv[i], "--no-pp") == 0) no_pp = 1; + else if (strcmp(argv[i], "--cuda-host") == 0) + mode_chost = 1; + else if (strcmp(argv[i], "--fatbin") == 0 && i + 1 < argc) + fat_file = argv[++i]; /* CDNA 2 (GFX9) */ /* CDNA 3 (GFX9.4.2) */ /* RDNA 2 (GFX10.3) */ @@ -615,7 +644,7 @@ int kath_compile(int argc, char *argv[], kath_out_t *out) * --tdf reached some gates and not others. Triton keeps its own list below; * it gates a different frontend and does not accept --rv-elf. */ int want_bir = mode_ir || mode_tdf || mode_tdf_fission || - be_num_on() > 0u; + mode_chost || be_num_on() > 0u; int want_sema = mode_sema || want_bir; if (!mode_pp && !mode_lex && !mode_parse && !want_sema) @@ -843,6 +872,7 @@ int kath_compile(int argc, char *argv[], kath_out_t *out) tc.mode_sema = mode_sema; tc.mode_hip = mode_hip; tc.no_pp = no_pp; + tc.hostp = 0; tc.want_ast = want_ast; tc.want_sema = want_sema; tc.want_bir = want_bir; @@ -887,6 +917,27 @@ int kath_compile(int argc, char *argv[], kath_out_t *out) if (bir_module) free(bir_module); + if (rc == BC_OK && mode_chost) { + hg_in_t hin; + + tc.hostp = 1; + tc.want_ast = 0; + tc.want_sema = 0; + tc.want_bir = 0; + tc.M = NULL; + rc = comp_tu(file, &tc); + if (rc != BC_OK) return 1; + + memset(&hin, 0, sizeof hin); + hin.file = file; + hin.src = pp_out_buf; + hin.slen = g_slen; + hin.toks = token_buf; + hin.ntok = g_ntok; + hin.fat = fat_file; + return hg_emit(&hin, output_file ? output_file : "a_host.cpp"); + } + return rc != BC_OK ? 1 : 0; } diff --git a/src/metal/emit.c b/src/metal/emit.c index d4e23a3..53d0861 100644 --- a/src/metal/emit.c +++ b/src/metal/emit.c @@ -733,8 +733,9 @@ static int mt_stmt(metal_module_t *mm, uint32_t gi) case BIR_BARRIER: case BIR_BARRIER_GROUP: if (!mt_ind(mm)) return 0; - return mt_wstr(mm, - "threadgroup_barrier(mem_flags::mem_threadgroup);\n"); + return mt_wstr(mm, I->subop + ? "simdgroup_barrier(mem_flags::mem_threadgroup);\n" + : "threadgroup_barrier(mem_flags::mem_threadgroup);\n"); case BIR_SHARED_ALLOC: case BIR_ALLOCA: { diff --git a/src/nvidia/emit_sass.c b/src/nvidia/emit_sass.c index 81d454a..170c593 100644 --- a/src/nvidia/emit_sass.c +++ b/src/nvidia/emit_sass.c @@ -16,6 +16,11 @@ #define SA_TMP2 10u #define SA_NPR 6u #define SA_NOIX 0xFFFFu +#define SA_STK 0x028u +#define SA_NVW (SA_NV / 64u) +#define SA_NIW 1024u +#define SA_NSEG 262144u +#define SA_NOSG 0xFFFFFFFFu typedef struct { lt_ncf_t cf; @@ -32,14 +37,28 @@ typedef struct { uint16_t bmap[SA_NBB + 1u]; uint32_t ist[SA_NBB + 1u]; uint16_t rmap[SA_NV]; - uint16_t vlo[SA_NV]; - uint16_t vhi[SA_NV]; - uint16_t vbk[SA_NV]; - uint8_t vlc[SA_NV]; uint8_t vwd[SA_NV]; uint8_t vpr[SA_NV]; - uint16_t ru[LT_MAX_NVREG]; - uint16_t pu[SA_NPR]; + uint32_t vseg[SA_NV]; + uint16_t sopn[SA_NV]; + uint16_t sslot[SA_NV]; + uint16_t vuse[SA_NV]; + uint64_t sbit[SA_NIW]; + uint32_t nspl; + uint32_t rlo; + uint32_t fbas; + uint32_t ktop; + uint32_t nmop; + uint32_t vbad; + uint16_t sglo[SA_NSEG]; + uint16_t sghi[SA_NSEG]; + uint32_t sgnx[SA_NSEG]; + uint32_t nseg; + uint32_t lchg; + uint64_t lcur[SA_NVW]; + uint64_t lvin[SA_NBB][SA_NVW]; + uint64_t rocc[LT_MAX_NVREG][SA_NIW]; + uint64_t pocc[SA_NPR][SA_NIW]; uint32_t rbas[NV_RF_COUNT]; uint32_t nvr; uint32_t nreg; @@ -48,18 +67,30 @@ typedef struct { uint32_t fn; uint32_t nerr; uint32_t nbad; - uint16_t lpt[LT_MAX_NVLP]; - uint16_t lpi[LT_MAX_NVLP]; - uint32_t nlp; - uint8_t lpof; char name[LT_MAX_NVNAME]; const nv_module_t *M; const nv_mfunc_t *F; uint32_t pofs[NV_MAX_PARAMS]; uint8_t img[LT_MAX_NVIMG]; uint32_t ilen; + uint8_t pool[LT_MAX_NVIMG]; + uint32_t plen; + lt_nvk_t kt[LT_MAX_NVKRN]; + uint32_t nk; uint16_t cop; uint16_t src[LT_MAX_NVCODE / 16u]; + lt_nvrl_t rlp[LT_MAX_NVREL]; + uint32_t rltot; + uint32_t rlbase; + uint32_t nrl; + uint32_t fmap[NV_MAX_MFUNC]; + uint16_t fofm[BIR_MAX_FUNCS]; + uint8_t kcall; + uint8_t isfn; + lt_nvg_t gtab[LT_MAX_NVGLB]; + uint32_t ng; + uint8_t gby[LT_MAX_NVGBY]; + uint32_t gtot; } sass_t; static sass_t sast; @@ -332,6 +363,40 @@ static int sasucc(void) return 0; } +static const nv_call_t *sacof(const nv_minst_t *I) +{ + if (I->op != (uint16_t)NV_CALL) return NULL; + return &sast.M->calls[I->flags % NV_MAX_CALL]; +} + +static uint32_t sanop(const nv_minst_t *I) +{ + const nv_call_t *C = sacof(I); + + if (C == NULL) return (uint32_t)I->num_defs + (uint32_t)I->num_uses; + return (uint32_t)C->hasret + (uint32_t)C->nargs; +} + +static uint32_t sandf(const nv_minst_t *I) +{ + const nv_call_t *C = sacof(I); + + if (C == NULL) return (uint32_t)I->num_defs; + return (uint32_t)C->hasret; +} + +static const nv_opnd_t *saopd(const nv_minst_t *I, uint32_t k) +{ + const nv_call_t *C = sacof(I); + + if (C == NULL) return (k < NV_MAX_OPS) ? &I->ops[k] : NULL; + if (C->hasret != 0u) { + if (k == 0u) return &C->ret; + k--; + } + return (k < C->nargs && k < NV_MAX_CARG) ? &C->args[k] : NULL; +} + static uint32_t savw(uint8_t rf) { return (rf == (uint8_t)NV_RF_U64 || rf == (uint8_t)NV_RF_F64) ? 2u : 1u; @@ -352,163 +417,297 @@ static int sabase(void) for (uint32_t f = 0; f < (uint32_t)NV_RF_COUNT; f++) { sast.rbas[f] = t; - t += (uint32_t)sast.M->rc[f] + 1u; + t += (uint32_t)sast.F->rc[f] + 1u; if (t > SA_NV) return 1; } sast.nvr = t; return 0; } -static void saedge(uint32_t i, const nv_minst_t *I) +static int sascan(void) { - uint32_t n = (uint32_t)I->num_defs + (uint32_t)I->num_uses; - uint32_t t; + for (uint32_t i = 0; i < sast.fn; i++) { + const nv_minst_t *I = &sast.M->minsts[sast.f0 + i]; + uint32_t n = sanop(I); + uint32_t m = 0u; - for (uint32_t k = 0; k < n && k < NV_MAX_OPS; k++) { - if (I->ops[k].kind != (uint8_t)NV_MOP_LABEL) continue; - t = satgt(&I->ops[k]); - if (t == SA_NOIX || sast.ist[t] > i) continue; - if (sast.nlp >= LT_MAX_NVLP) { sast.lpof = 1u; return; } - sast.lpt[sast.nlp] = (uint16_t)sast.ist[t]; - sast.lpi[sast.nlp] = (uint16_t)i; - sast.nlp++; + for (uint32_t k = 0; k < n; k++) { + const nv_opnd_t *o = saopd(I, k); + uint32_t v; + + if (o == NULL || o->kind != (uint8_t)NV_MOP_REG) continue; + v = savx(o); + if (v == SA_NOIX) return 1; + sast.vwd[v] = (uint8_t)savw(o->rfile); + sast.vpr[v] = (o->rfile == (uint8_t)NV_RF_PRED) ? 1u : 0u; + if (I->op != (uint16_t)NV_CALL) m++; + if (saterm(I) != TFALL) sast.vuse[v] = 0xFFFFu; + else if (sast.vuse[v] < 0xFFFEu) sast.vuse[v]++; + } + if (m > sast.nmop) sast.nmop = m; } + return 0; +} + +static void sabset(uint64_t *s, uint32_t v) +{ + s[v >> 6] |= 1ull << (v & 63u); } -static int sardt(const nv_minst_t *I, const nv_opnd_t *d, uint32_t n) +static void sabclr(uint64_t *s, uint32_t v) { - for (uint32_t k = 1; k < n && k < NV_MAX_OPS; k++) - if (I->ops[k].kind == (uint8_t)NV_MOP_REG - && I->ops[k].rfile == d->rfile - && I->ops[k].reg_num == d->reg_num) return 1; + s[v >> 6] &= ~(1ull << (v & 63u)); +} + +static int sabhas(const uint64_t *s, uint32_t v) +{ + return (int)((s[v >> 6] >> (v & 63u)) & 1ull); +} + +static int saseg(uint32_t v, uint32_t lo, uint32_t hi) +{ + uint32_t h = sast.vseg[v]; + + if (h != SA_NOSG && hi + 1u >= sast.sglo[h]) { + if (lo < sast.sglo[h]) sast.sglo[h] = (uint16_t)lo; + return 0; + } + if (sast.nseg >= SA_NSEG) { + if (h == SA_NOSG) return 1; + sast.sglo[h] = (uint16_t)lo; + return 0; + } + sast.sglo[sast.nseg] = (uint16_t)lo; + sast.sghi[sast.nseg] = (uint16_t)hi; + sast.sgnx[sast.nseg] = h; + sast.vseg[v] = sast.nseg++; return 0; } -static int sascan(void) +static int saends(uint32_t at, int open) { - uint32_t cb = 0u; + uint32_t nw = (sast.nvr + 63u) / 64u; - for (uint32_t i = 0; i < sast.fn; i++) { - const nv_minst_t *I = &sast.M->minsts[sast.f0 + i]; - uint32_t n = (uint32_t)I->num_defs + (uint32_t)I->num_uses; + for (uint32_t q = 0; q < nw; q++) { + uint64_t m = sast.lcur[q]; - while (cb + 1u < sast.cf.nbb && sast.ist[cb + 1u] <= i) cb++; - saedge(i, I); - for (uint32_t k = 0; k < n && k < NV_MAX_OPS; k++) { - const nv_opnd_t *o = &I->ops[k]; + for (uint32_t g = 0; g < 64u && m != 0ull; g++) { + uint32_t b = 0u; uint32_t v; - if (o->kind != (uint8_t)NV_MOP_REG) continue; - v = savx(o); - if (v == SA_NOIX) return 1; - sast.vwd[v] = (uint8_t)savw(o->rfile); - sast.vpr[v] = (o->rfile == (uint8_t)NV_RF_PRED) ? 1u : 0u; - if (sast.vlo[v] != (uint16_t)SA_NOIX) { - if (sast.vbk[v] != (uint16_t)cb) sast.vlc[v] = 0u; - } else { - sast.vlo[v] = (uint16_t)i; - sast.vbk[v] = (uint16_t)cb; - sast.vlc[v] = (k == 0u && I->num_defs == 1u - && sardt(I, o, n) == 0) ? 1u : 0u; - } - sast.vhi[v] = (uint16_t)i; + while (b < 63u && ((m >> b) & 1ull) == 0ull) b++; + m &= m - 1ull; + v = q * 64u + b; + if (open != 0) sast.sopn[v] = (uint16_t)at; + else if (saseg(v, at, sast.sopn[v]) != 0) return 1; } } return 0; } -static void samrg(void) +static int sawalk(uint32_t k, int gen) { - for (uint32_t r = 0; r <= sast.nlp; r++) { - uint32_t ch = 0u; + const lt_ncf_t *c = &sast.cf; + uint32_t nw = (sast.nvr + 63u) / 64u; + uint32_t lo = sast.ist[k], hi = sast.ist[k + 1u]; + + memset(sast.lcur, 0, (size_t)nw * 8u); + for (uint32_t e = 0; e < 2u; e++) { + uint32_t s = (e == 0u) ? c->s0[k] : c->s1[k]; - for (uint32_t a = 0; a < sast.nlp; a++) - for (uint32_t c = 0; c < sast.nlp; c++) { - uint16_t t = sast.lpt[c], e = sast.lpi[c]; + if (s >= c->nbb) continue; + for (uint32_t q = 0; q < nw; q++) sast.lcur[q] |= sast.lvin[s][q]; + } + gen = gen && lo < hi; + if (gen && saends(hi - 1u, 1) != 0) return 1; + for (uint32_t i = hi; i > lo; i--) { + const nv_minst_t *I = &sast.M->minsts[sast.f0 + i - 1u]; + uint32_t n = sanop(I); + + for (uint32_t d = 0; d < n; d++) { + const nv_opnd_t *o = saopd(I, d); + uint32_t v; - if (a == c || sast.lpt[a] > e || sast.lpi[a] < t) continue; - if (t < sast.lpt[a]) { sast.lpt[a] = t; ch = 1u; } - if (e > sast.lpi[a]) { sast.lpi[a] = e; ch = 1u; } + if (o == NULL || o->kind != (uint8_t)NV_MOP_REG) continue; + v = savx(o); + if (v == SA_NOIX) return 1; + if (d < sandf(I)) { + if (gen && saseg(v, i - 1u, sabhas(sast.lcur, v) + ? sast.sopn[v] : i - 1u) != 0) return 1; + sabclr(sast.lcur, v); + } else if (sabhas(sast.lcur, v) == 0) { + sabset(sast.lcur, v); + sast.sopn[v] = (uint16_t)(i - 1u); } - if (ch == 0u) break; + } } + if (gen && saends(lo, 0) != 0) return 1; + if (memcmp(sast.lcur, sast.lvin[k], (size_t)nw * 8u) != 0) { + memcpy(sast.lvin[k], sast.lcur, (size_t)nw * 8u); + sast.lchg = 1u; + } + return 0; } -static void sastr(void) +static int salvin(void) { - if (sast.lpof != 0u) { - sast.lpt[0] = 0u; - sast.lpi[0] = (uint16_t)(sast.fn > 0u ? sast.fn - 1u : 0u); - sast.nlp = 1u; - } else { - samrg(); + uint32_t nw = (sast.nvr + 63u) / 64u; + uint32_t nb = sast.cf.nbb; + + for (uint32_t k = 0; k < nb; k++) + memset(sast.lvin[k], 0, (size_t)nw * 8u); + for (uint32_t g = 0; g < 4u * nb + 8u; g++) { + sast.lchg = 0u; + for (uint32_t k = nb; k > 0u; k--) + if (sawalk(k - 1u, 0) != 0) return 1; + if (sast.lchg != 0u) continue; + for (uint32_t k = nb; k > 0u; k--) + if (sawalk(k - 1u, 1) != 0) return 1; + return 0; } - for (uint32_t v = 0; v < sast.nvr; v++) { - if (sast.vlo[v] == (uint16_t)SA_NOIX || sast.vlc[v] != 0u) continue; - for (uint32_t a = 0; a < sast.nlp; a++) { - if (sast.vhi[v] < sast.lpt[a] || sast.vlo[v] > sast.lpi[a]) - continue; - if (sast.lpt[a] < sast.vlo[v]) sast.vlo[v] = sast.lpt[a]; - if (sast.lpi[a] > sast.vhi[v]) sast.vhi[v] = sast.lpi[a]; + return 1; +} + +static int saocc(uint64_t *o, uint32_t v, int pin) +{ + uint32_t s = sast.vseg[v]; + + for (uint32_t g = 0; g < SA_NSEG && s != SA_NOSG; g++) { + uint32_t a = sast.sglo[s], b = sast.sghi[s]; + + for (uint32_t q = a >> 6; q <= b >> 6 && q < SA_NIW; q++) { + uint64_t m = ~0ull; + + if (q == a >> 6) m &= ~0ull << (a & 63u); + if (q == b >> 6) m &= ~0ull >> (63u - (b & 63u)); + if (pin != 0) o[q] |= m; + else if ((o[q] & m) != 0ull) return 1; } + s = sast.sgnx[s]; } + return 0; } -static uint32_t sapick(uint32_t w, uint32_t lo) +static int sarsv(uint32_t r, uint32_t w) { - for (uint32_t r = SA_RBAS; r + w <= LT_MAX_NVREG; r += w) { - if (sast.ru[r] != (uint16_t)SA_NOIX && sast.ru[r] >= lo) continue; - if (w == 2u && sast.ru[r + 1u] != (uint16_t)SA_NOIX - && sast.ru[r + 1u] >= lo) continue; + if (sast.kcall == 0u) return 0; + return (r <= LT_NV_R21 && r + w > LT_NV_R20); +} + +static uint32_t sapick(uint32_t w, uint32_t v) +{ + for (uint32_t r = sast.rlo; r + w <= LT_MAX_NVREG; r += w) { + if (sarsv(r, w)) continue; + if (saocc(sast.rocc[r], v, 0) != 0) continue; + if (w == 2u && saocc(sast.rocc[r + 1u], v, 0) != 0) continue; return r; } return LT_MAX_NVREG; } -static uint32_t sappik(uint32_t lo) +static uint32_t sappik(uint32_t v) { - for (uint32_t r = 1u; r < SA_NPR; r++) { - if (sast.pu[r] != (uint16_t)SA_NOIX && sast.pu[r] >= lo) continue; - return r; - } + for (uint32_t r = 1u; r < SA_NPR; r++) + if (saocc(sast.pocc[r], v, 0) == 0) return r; return SA_NPR; } static int saall(void) { - uint32_t top = SA_RBAS; + uint32_t top = sast.rlo; for (uint32_t i = 0; i < sast.fn; i++) { const nv_minst_t *I = &sast.M->minsts[sast.f0 + i]; - uint32_t n = (uint32_t)I->num_defs + (uint32_t)I->num_uses; + uint32_t n = sanop(I); - for (uint32_t k = 0; k < n && k < NV_MAX_OPS; k++) { + for (uint32_t k = 0; k < n; k++) { + const nv_opnd_t *o = saopd(I, k); uint32_t v, w, r; - if (I->ops[k].kind != (uint8_t)NV_MOP_REG) continue; - v = savx(&I->ops[k]); + if (o == NULL || o->kind != (uint8_t)NV_MOP_REG) continue; + v = savx(o); if (v == SA_NOIX) return 1; if (sast.rmap[v] != (uint16_t)SA_NOIX) continue; + if (sast.sslot[v] != (uint16_t)SA_NOIX) continue; if (sast.vpr[v] != 0u) { - r = sappik(sast.vlo[v]); + r = sappik(v); if (r >= SA_NPR) { sast.npr = 1u; return 1; } sast.rmap[v] = (uint16_t)r; - sast.pu[r] = sast.vhi[v]; + (void)saocc(sast.pocc[r], v, 1); continue; } w = sast.vwd[v]; - r = sapick(w, sast.vlo[v]); + r = sapick(w, v); + sast.vbad = v; if (r >= LT_MAX_NVREG) return 1; sast.rmap[v] = (uint16_t)r; - sast.ru[r] = sast.vhi[v]; - if (w == 2u) sast.ru[r + 1u] = sast.vhi[v]; + (void)saocc(sast.rocc[r], v, 1); + if (w == 2u) (void)saocc(sast.rocc[r + 1u], v, 1); if (r + w > top) top = r + w; } } + if (sast.kcall != 0u && top < LT_NV_R21 + 1u) top = LT_NV_R21 + 1u; sast.nreg = top; return 0; } +static uint32_t salen(uint32_t v) +{ + uint32_t s = sast.vseg[v], n = 0u; + + for (uint32_t g = 0; g < SA_NSEG && s != SA_NOSG; g++) { + n += (uint32_t)sast.sghi[s] - (uint32_t)sast.sglo[s] + 1u; + s = sast.sgnx[s]; + } + return n; +} + +static uint32_t savict(void) +{ + uint32_t best = SA_NOIX; + uint64_t bl = 0u, bu = 1u; + + memset(sast.sbit, 0, sizeof sast.sbit); + (void)saocc(sast.sbit, sast.vbad, 1); + for (uint32_t u = 0; u < sast.nvr; u++) { + uint64_t l, n = sast.vuse[u]; + + if (n == 0u || n == 0xFFFFu || sast.vpr[u] != 0u) continue; + if (sast.sslot[u] != (uint16_t)SA_NOIX) continue; + if (saocc(sast.sbit, u, 0) == 0) continue; + l = salen(u); + if (best != SA_NOIX && l * bu <= bl * n) continue; + best = u; + bl = l; + bu = n; + } + return best; +} + +static int saspil(void) +{ + uint32_t nw = (sast.fn >> 6) + 1u; + + for (uint32_t g = 0; g <= sast.nvr; g++) { + uint32_t u; + + for (uint32_t r = 0; r < LT_MAX_NVREG; r++) + memset(sast.rocc[r], 0, (size_t)nw * 8u); + for (uint32_t r = 0; r < SA_NPR; r++) + memset(sast.pocc[r], 0, (size_t)nw * 8u); + memset(sast.rmap, 0xFF, sizeof sast.rmap); + if (saall() == 0) return 0; + if (sast.npr != 0u) return 1; + u = savict(); + if (u == SA_NOIX + || sast.F->lcl_bytes + 8u * (sast.nspl + 1u) > NV_MAX_FRAME) + return 1; + sast.sslot[u] = (uint16_t)sast.nspl++; + sast.rlo = sast.fbas + 2u + 2u * sast.nmop; + } + return 1; +} + static void sacfp(uint64_t *w) { lt_nrw_t x; @@ -1320,14 +1519,17 @@ static void safdivs(const lt_nrw_t *x, uint32_t d, uint32_t aa, uint32_t bb) safire(w, x, 0u); } -static void safdiv32(const lt_nrw_t *x, uint32_t d, uint32_t a, uint32_t b) +static void safdiv32(const lt_nrw_t *x, uint32_t d, const nv_opnd_t *oa, + const nv_opnd_t *ob) { uint32_t aa = SCD(5u), bb = SCD(5u) + 1u; uint64_t w[2]; - lt_nvmov(w, aa, a); + if (oa->kind == (uint8_t)NV_MOP_REG) lt_nvmov(w, aa, sarg(oa)); + else lt_nvmovi(w, aa, (uint32_t)oa->imm); safire(w, x, 0u); - lt_nvmov(w, bb, b); + if (ob->kind == (uint8_t)NV_MOP_REG) lt_nvmov(w, bb, sarg(ob)); + else lt_nvmovi(w, bb, (uint32_t)ob->imm); safire(w, x, 0u); lt_nvf2f(w, SCD(0u), aa, 3u, 2u, 0u); safire(w, x, SA_DW); @@ -1391,16 +1593,25 @@ static void saudiv32(const lt_nrw_t *x, uint32_t xr, uint32_t yr) saudivc(x, xr, yr); } -static void sasgnf(const lt_nrw_t *x, uint32_t d, uint32_t r, uint32_t sx, - uint32_t sy) +static void samask(const lt_nrw_t *x, uint32_t d, const nv_opnd_t *o) { uint64_t w[2]; - lt_nvshi(w, SCT(0u), LT_NV_RZ, 31u, sx, 2u, 1u, 1u); + if (o->kind == (uint8_t)NV_MOP_REG) + lt_nvshi(w, d, LT_NV_RZ, 31u, sarg(o), 2u, 1u, 1u); + else + lt_nvmovi(w, d, (o->imm < 0) ? 0xFFFFFFFFu : 0u); safire(w, x, 0u); - if (sy != LT_NV_RZ) { - lt_nvshi(w, SCD(0u), LT_NV_RZ, 31u, sy, 2u, 1u, 1u); - safire(w, x, 0u); +} + +static void sasgnf(const lt_nrw_t *x, uint32_t d, uint32_t r, + const nv_opnd_t *sx, const nv_opnd_t *sy) +{ + uint64_t w[2]; + + samask(x, SCT(0u), sx); + if (sy != NULL) { + samask(x, SCD(0u), sy); lt_nvlop(w, SCT(0u), SCT(0u), SCD(0u), LT_NV_RZ, 0x3Cu); safire(w, x, 0u); } @@ -1410,41 +1621,52 @@ static void sasgnf(const lt_nrw_t *x, uint32_t d, uint32_t r, uint32_t sx, safire(w, x, 0u); } +static void sadld(const lt_nrw_t *x, uint32_t d, const nv_opnd_t *o, int sg) +{ + uint64_t w[2]; + int64_t v = o->imm; + + if (o->kind == (uint8_t)NV_MOP_REG && sg != 0) { + sasgnf(x, d, sarg(o), o, NULL); + return; + } + if (o->kind == (uint8_t)NV_MOP_REG) lt_nvmov(w, d, sarg(o)); + else lt_nvmovi(w, d, (uint32_t)((sg != 0 && v < 0) ? -v : v)); + safire(w, x, 0u); +} + +static int saiop(const nv_opnd_t *o) +{ + return o->kind == (uint8_t)NV_MOP_REG || o->kind == (uint8_t)NV_MOP_IMM; +} + static void sadiv32(const nv_minst_t *I, int sg, int rem) { lt_nrw_t y; uint64_t w[2]; - uint32_t d, sx, sy, xr = SCD(5u), yr = SCD(5u) + 1u; + const nv_opnd_t *ox = &I->ops[1], *oy = &I->ops[2]; + uint32_t d, xr = SCD(5u), yr = SCD(5u) + 1u; - if (I->ops[1].kind != (uint8_t)NV_MOP_REG - || I->ops[2].kind != (uint8_t)NV_MOP_REG) { + if (!saiop(ox) || !saiop(oy)) { sabad(I->op, BC_E609); return; } - d = sarg(&I->ops[0]); - sx = sarg(&I->ops[1]); - sy = sarg(&I->ops[2]); + d = sarg(&I->ops[0]); memset(&y, 0, sizeof y); samsr(&y.rd, 0u, LT_NV_NSCR); samsr(&y.wr, 0u, LT_NV_NSCR); - samsr(&y.rd, sx, 1u); - samsr(&y.rd, sy, 1u); + if (ox->kind == (uint8_t)NV_MOP_REG) samsr(&y.rd, sarg(ox), 1u); + if (oy->kind == (uint8_t)NV_MOP_REG) samsr(&y.rd, sarg(oy), 1u); samsr(&y.wr, d, 1u); - if (sg != 0) { - sasgnf(&y, xr, sx, sx, LT_NV_RZ); - sasgnf(&y, yr, sy, sy, LT_NV_RZ); - } else { - lt_nvmov(w, xr, sx); - safire(w, &y, 0u); - lt_nvmov(w, yr, sy); - safire(w, &y, 0u); - } + sadld(&y, xr, ox, sg); + sadld(&y, yr, oy, sg); saudiv32(&y, xr, yr); lt_nvmov(w, SCT(3u), rem ? SCT(2u) : SCT(1u)); safire(w, &y, 0u); if (sg != 0) - sasgnf(&y, SCT(3u), SCT(3u), sx, rem ? LT_NV_RZ : sy); - lt_nvstp(w, LT_NV_P0, sy, LT_NV_RZ, 2u, 0u); + sasgnf(&y, SCT(3u), SCT(3u), ox, rem ? NULL : oy); + lt_nvstp(w, LT_NV_P0, oy->kind == (uint8_t)NV_MOP_REG ? sarg(oy) : yr, + LT_NV_RZ, 2u, 0u); safire(w, &y, 0u); lt_nvsei(w, d, SCT(3u), 0u, LT_NV_P0, 1u); safire(w, &y, 0u); @@ -1453,23 +1675,22 @@ static void sadiv32(const nv_minst_t *I, int sg, int rem) static void safdiv(const nv_minst_t *I) { lt_nrw_t y; - uint32_t d, a, b; + uint32_t d; - if (I->ops[1].kind != (uint8_t)NV_MOP_REG - || I->ops[2].kind != (uint8_t)NV_MOP_REG) { + if (!saiop(&I->ops[1]) || !saiop(&I->ops[2])) { sabad(I->op, BC_E609); return; } d = sarg(&I->ops[0]); - a = sarg(&I->ops[1]); - b = sarg(&I->ops[2]); memset(&y, 0, sizeof y); samsr(&y.rd, 0u, LT_NV_NSCR); samsr(&y.wr, 0u, LT_NV_NSCR); - samsr(&y.rd, a, 1u); - samsr(&y.rd, b, 1u); + if (I->ops[1].kind == (uint8_t)NV_MOP_REG) + samsr(&y.rd, sarg(&I->ops[1]), 1u); + if (I->ops[2].kind == (uint8_t)NV_MOP_REG) + samsr(&y.rd, sarg(&I->ops[2]), 1u); samsr(&y.wr, d, 1u); - safdiv32(&y, d, a, b); + safdiv32(&y, d, &I->ops[1], &I->ops[2]); } static void sadpick(const lt_nrw_t *x, uint32_t d, uint32_t a, uint32_t b, @@ -1584,23 +1805,34 @@ static void saq64sgn(const lt_nrw_t *x, uint32_t d, uint32_t s, uint32_t sa, safire(w, x, 0u); } +static uint32_t saq64in(const lt_nrw_t *x, const nv_opnd_t *o, uint32_t r) +{ + uint64_t w[2]; + + if (o->kind == (uint8_t)NV_MOP_REG) return sarg(o); + lt_nvmovi(w, r, (uint32_t)o->imm); + safire(w, x, 0u); + lt_nvmovi(w, r + 1u, (o->imm < 0) ? 0xFFFFFFFFu : 0u); + safire(w, x, 0u); + return r; +} + static void sadiv64(const nv_minst_t *I, int sg, int rem) { lt_nrw_t y; uint64_t w[2]; uint32_t d, a0, a1, b0, b1; - if (I->ops[1].kind != (uint8_t)NV_MOP_REG - || I->ops[2].kind != (uint8_t)NV_MOP_REG) { + if (!saiop(&I->ops[1]) || !saiop(&I->ops[2])) { sabad(I->op, BC_E609); return; } d = sarg(&I->ops[0]); - a0 = sarg(&I->ops[1]); a1 = a0 + 1u; - b0 = sarg(&I->ops[2]); b1 = b0 + 1u; memset(&y, 0, sizeof y); samsr(&y.rd, 0u, LT_NV_NSCR); samsr(&y.wr, 0u, LT_NV_NSCR); + a0 = saq64in(&y, &I->ops[1], SCD(3u)); a1 = a0 + 1u; + b0 = saq64in(&y, &I->ops[2], SCD(4u)); b1 = b0 + 1u; samsr(&y.rd, a0, 2u); samsr(&y.rd, b0, 2u); samsr(&y.wr, d, 2u); @@ -1635,120 +1867,808 @@ static void sadiv64(const nv_minst_t *I, int sg, int rem) sadpick(&y, d, SCD(2u), LT_NV_RZ, LT_NV_P0, 0u); } -static void samnx(const nv_minst_t *I, int mx) +static void sadexp(const lt_nrw_t *x, uint32_t d, uint32_t hi) { - lt_nrw_t x; uint64_t w[2]; - uint32_t d, a, b; - memset(&x, 0, sizeof x); - if (sawchk(I, 1u) != 0) { sabad(I->op, BC_E611); return; } - d = sadef(I, &x); - a = sasrc(I->op, &I->ops[1], SA_IMM0, 1u, &x); - b = sasrc(I->op, &I->ops[2], SA_IMM1, 1u, &x); - lt_nvftp(w, LT_NV_P0, a, b, mx ? 4u : 1u); - safire(w, &x, 0u); - lt_nvsel(w, d, a, b, LT_NV_P0, 0u); - safire(w, &x, 0u); - lt_nvftp(w, LT_NV_P0, a, b, 8u); - safire(w, &x, 0u); - lt_nvsei(w, d, d, 0x7FC00000u, LT_NV_P0, 1u); - safire(w, &x, 0u); + lt_nvshi(w, d, LT_NV_RZ, 20u, hi, 3u, 1u, 1u); + safire(w, x, 0u); + lt_nvlpi(w, d, d, 0x7FFu, 0xC0u); + safire(w, x, 0u); } -static uint32_t sats(uint16_t op) +static void sadnrm(const lt_nrw_t *x, uint32_t d, uint32_t s, uint32_t e) { - switch (op) { - case NV_LD_GLB_U8: case NV_ST_GLB_U8: - case NV_LD_SHR_U8: case NV_ST_SHR_U8: return 0u; - case NV_LD_GLB_U16: case NV_ST_GLB_U16: - case NV_LD_GLB_B16: case NV_ST_GLB_B16: - case NV_LD_SHR_U16: case NV_ST_SHR_U16: - case NV_LD_SHR_B16: case NV_ST_SHR_B16: return 2u; - case NV_LD_GLB_U64: case NV_ST_GLB_U64: - case NV_LD_GLB_F64: case NV_ST_GLB_F64: return 5u; - default: return 4u; - } + uint64_t w[2]; + + sadexp(x, SCT(0u), s + 1u); + lt_nvstp(w, LT_NV_P0, SCT(0u), LT_NV_RZ, 2u, 0u); + safire(w, x, 0u); + lt_nvdmu(w, d, s, SCD(4u)); + safire(w, x, SA_DW); + sadpick(x, d, d, s, LT_NV_P0, 0u); + lt_nvsei(w, SCT(1u), LT_NV_RZ, 54u, LT_NV_P0, 1u); + safire(w, x, 0u); + sadexp(x, SCT(0u), d + 1u); + lt_nvadi(w, e, SCT(0u), 0xFFFFFC01u, 0u); + safire(w, x, 0u); + lt_nvadd(w, e, e, SCT(1u), 1u); + safire(w, x, 0u); + lt_nvlpi(w, d + 1u, d + 1u, 0x000FFFFFu, 0xC0u); + safire(w, x, 0u); + lt_nvlpi(w, d + 1u, d + 1u, 0x3FF00000u, 0xFCu); + safire(w, x, 0u); } -static void samem(const nv_minst_t *I, int shr, int st) +static void sadfst(const lt_nrw_t *x) { - lt_nrw_t x; uint64_t w[2]; - uint32_t t = sats(I->op); - const nv_opnd_t *ao = st ? &I->ops[0] : &I->ops[1]; - const nv_opnd_t *vo = st ? &I->ops[1] : &I->ops[0]; - uint32_t ra, rv; - memset(&x, 0, sizeof x); - if (ao->kind != (uint8_t)NV_MOP_REG || vo->kind != (uint8_t)NV_MOP_REG) { - sabad(I->op, BC_E609); - return; - } - if (!shr && ao->rfile != (uint8_t)NV_RF_U64) { - sabad(I->op, BC_E611); - return; - } - if (shr && ao->rfile != (uint8_t)NV_RF_U64 - && ao->rfile != (uint8_t)NV_RF_U32) { - sabad(I->op, BC_E611); - return; - } - if ((t == 5u) != (savw(vo->rfile) == 2u)) { - sabad(I->op, BC_E611); - return; - } - ra = sarg(ao); - rv = sarg(vo); - samsr(&x.rd, ra, savw(ao->rfile)); - if (st) samsr(&x.rd, rv, savw(vo->rfile)); - else samsr(&x.wr, rv, savw(vo->rfile)); - if (shr && st) lt_nvsts(w, ra, rv, 0u, t); - else if (shr) lt_nvlds(w, rv, ra, 0u, t); - else if (st) lt_nvstg(w, ra, rv, 0u, t, 0u); - else lt_nvldg(w, rv, ra, 0u, t, 0u); - safire(w, &x, st ? 2u : 3u); + lt_nvmovi(w, SCD(2u), 1u); + safire(w, x, 0u); + lt_nvmuf(w, SCD(2u) + 1u, SCD(1u) + 1u, 6u); + safire(w, x, SA_DW); + sadcon(x, SCD(3u), 0x3FF00000u); + lt_nvdfm(w, SCD(4u), SCD(1u), SCD(2u), SCD(3u), 1u); + safire(w, x, SA_DW); + lt_nvdfm(w, SCD(4u), SCD(4u), SCD(4u), SCD(4u), 0u); + safire(w, x, SA_DW); + lt_nvdfm(w, SCD(2u), SCD(2u), SCD(4u), SCD(2u), 0u); + safire(w, x, SA_DW); + lt_nvdfm(w, SCD(4u), SCD(1u), SCD(2u), SCD(3u), 1u); + safire(w, x, SA_DW); + lt_nvdfm(w, SCD(2u), SCD(2u), SCD(4u), SCD(2u), 0u); + safire(w, x, SA_DW); + lt_nvdmu(w, SCD(4u), SCD(0u), SCD(2u)); + safire(w, x, SA_DW); + lt_nvdfm(w, SCD(5u), SCD(1u), SCD(4u), SCD(0u), 1u); + safire(w, x, SA_DW); + lt_nvdfm(w, SCD(3u), SCD(2u), SCD(5u), SCD(4u), 0u); + safire(w, x, SA_DW); + lt_nvdfm(w, SCD(5u), SCD(1u), SCD(3u), SCD(0u), 1u); + safire(w, x, SA_DW); } -static void sapld(const nv_minst_t *I) +static void sadtrn(const lt_nrw_t *x) { - lt_nrw_t x; uint64_t w[2]; - uint32_t d, o, n; - memset(&x, 0, sizeof x); - n = sadw(I); - if ((I->op == (uint16_t)NV_LD_PARAM_U64 - || I->op == (uint16_t)NV_LD_PARAM_F64) != (n == 2u)) { - sabad(I->op, BC_E611); - return; - } - d = sadef(I, &x); - if (I->ops[1].kind != (uint8_t)NV_MOP_IMM || I->ops[1].imm < 0 - || (uint32_t)I->ops[1].imm >= sast.k.np) { - sabad(I->op, BC_E609); - return; - } - o = LT_NV_PBASE + sast.pofs[I->ops[1].imm]; - lt_nvmovc(w, d, 0u, o); - safire(w, &x, 0u); - if (n != 2u) return; - lt_nvmovc(w, d + 1u, 0u, o + 4u); - safire(w, &x, 0u); + lt_nvmovi(w, SCT(0u), 1u); + safire(w, x, 0u); + lt_nvmovi(w, SCT(1u), 0xFFFFFFFFu); + safire(w, x, 0u); + lt_nvadc(w, SCD(1u), SCD(3u), SCT(0u), 1u); + safire(w, x, 0u); + lt_nvadx(w, SCD(1u) + 1u, SCD(3u) + 1u, SCT(1u), 0u); + safire(w, x, 0u); + lt_nvstp(w, LT_NV_P1, SCD(5u) + 1u, LT_NV_RZ, 1u, 1u); + safire(w, x, 0u); + sadpick(x, SCD(2u), SCD(1u), SCD(3u), LT_NV_P1, 0u); + lt_nvlpi(w, SCT(2u), SCD(5u) + 1u, 0x7FFFFFFFu, 0xC0u); + safire(w, x, 0u); + lt_nvlop(w, SCT(2u), SCT(2u), SCD(5u), LT_NV_RZ, 0xFCu); + safire(w, x, 0u); + lt_nvlpi(w, SCD(2u) + 1u, SCD(2u) + 1u, 0x000FFFFFu, 0xC0u); + safire(w, x, 0u); + lt_nvlpi(w, SCD(2u) + 1u, SCD(2u) + 1u, 0x00100000u, 0xFCu); + safire(w, x, 0u); } -static void sactl(const nv_minst_t *I) +static void sadsub(const lt_nrw_t *x, uint32_t eb) { - lt_nrw_t x; uint64_t w[2]; - uint32_t p = LT_NV_PT; - int32_t lb; - memset(&x, 0, sizeof x); - if (I->op == (uint16_t)NV_BRA_PRED) p = saprd(&I->ops[0]); - lb = (int32_t)satgt(I->op == (uint16_t)NV_BRA_PRED ? &I->ops[1] - : &I->ops[0]); - sast.gate = (uint8_t)LT_NV_PT; + sadtrn(x); + lt_nvadi(w, SCT(3u), eb, 1u, 1u); + safire(w, x, 0u); + lt_nvsti(w, LT_NV_P0, SCT(3u), 54u, 4u, 1u); + safire(w, x, 0u); + lt_nvsei(w, SCT(3u), SCT(3u), 54u, LT_NV_P0, 1u); + safire(w, x, 0u); + lt_nvshf(w, SCD(0u), SCD(2u), SCT(3u), SCD(2u) + 1u, 1u, 1u, 0u); + safire(w, x, 0u); + lt_nvshf(w, SCD(0u) + 1u, SCD(2u), SCT(3u), SCD(2u) + 1u, 1u, 1u, 1u); + safire(w, x, 0u); + lt_nvadi(w, SCT(0u), SCT(3u), 64u, 1u); + safire(w, x, 0u); + lt_nvshf(w, SCD(1u), SCD(2u), SCT(0u), SCD(2u) + 1u, 1u, 0u, 0u); + safire(w, x, 0u); + lt_nvshf(w, SCD(1u) + 1u, SCD(2u), SCT(0u), SCD(2u) + 1u, 1u, 0u, 1u); + safire(w, x, 0u); + lt_nvlpi(w, SCT(1u), SCD(1u) + 1u, 0x7FFFFFFFu, 0xC0u); + safire(w, x, 0u); + lt_nvlop(w, SCT(1u), SCT(1u), SCD(1u), SCT(2u), 0xFEu); + safire(w, x, 0u); + lt_nvlpi(w, SCT(0u), SCD(0u), 1u, 0xC0u); + safire(w, x, 0u); + lt_nvlop(w, SCT(1u), SCT(1u), SCT(0u), LT_NV_RZ, 0xFCu); + safire(w, x, 0u); + lt_nvstp(w, LT_NV_P0, SCT(1u), LT_NV_RZ, 5u, 0u); + safire(w, x, 0u); + lt_nvsei(w, SCT(1u), LT_NV_RZ, 1u, LT_NV_P0, 1u); + safire(w, x, 0u); + lt_nvshi(w, SCT(0u), LT_NV_RZ, 31u, SCD(1u) + 1u, 3u, 1u, 1u); + safire(w, x, 0u); + lt_nvlop(w, SCT(1u), SCT(1u), SCT(0u), LT_NV_RZ, 0xC0u); + safire(w, x, 0u); + lt_nvadc(w, SCD(0u), SCD(0u), SCT(1u), 0u); + safire(w, x, 0u); + lt_nvadx(w, SCD(0u) + 1u, SCD(0u) + 1u, LT_NV_RZ, 0u); + safire(w, x, 0u); +} + +static void sadscl(const lt_nrw_t *x, uint32_t d) +{ + uint64_t w[2]; + + sadexp(x, SCT(0u), SCD(3u) + 1u); + lt_nvadd(w, d, SCT(0u), SCT(2u), 0u); + safire(w, x, 0u); + lt_nvshi(w, SCT(3u), SCT(2u), 20u, LT_NV_RZ, 3u, 0u, 0u); + safire(w, x, 0u); + lt_nvmov(w, SCD(4u), SCD(3u)); + safire(w, x, 0u); + lt_nvadd(w, SCD(4u) + 1u, SCD(3u) + 1u, SCT(3u), 0u); + safire(w, x, 0u); + sadsub(x, d); + lt_nvstp(w, LT_NV_P0, d, LT_NV_RZ, 3u, 1u); + safire(w, x, 0u); + sadpick(x, SCD(4u), SCD(0u), SCD(4u), LT_NV_P0, 0u); + lt_nvsti(w, LT_NV_P0, d, 2046u, 4u, 1u); + safire(w, x, 0u); + sadcon(x, SCD(5u), 0x7FF00000u); + sadpick(x, SCD(4u), SCD(5u), SCD(4u), LT_NV_P0, 0u); +} + +static void sadflg(const lt_nrw_t *x, uint32_t s, uint32_t z, uint32_t i, + uint32_t n) +{ + uint64_t w[2]; + + lt_nvlpi(w, SCT(0u), s + 1u, 0x7FFFFFFFu, 0xC0u); + safire(w, x, 0u); + lt_nvlop(w, SCT(1u), SCT(0u), s, LT_NV_RZ, 0xFCu); + safire(w, x, 0u); + lt_nvstp(w, LT_NV_P0, SCT(1u), LT_NV_RZ, 2u, 0u); + safire(w, x, 0u); + lt_nvsei(w, z, LT_NV_RZ, 1u, LT_NV_P0, 1u); + safire(w, x, 0u); + lt_nvlpi(w, SCT(1u), SCT(0u), 0x7FF00000u, 0x3Cu); + safire(w, x, 0u); + lt_nvlop(w, SCT(1u), SCT(1u), s, LT_NV_RZ, 0xFCu); + safire(w, x, 0u); + lt_nvstp(w, LT_NV_P0, SCT(1u), LT_NV_RZ, 2u, 0u); + safire(w, x, 0u); + lt_nvsei(w, i, LT_NV_RZ, 1u, LT_NV_P0, 1u); + safire(w, x, 0u); + lt_nvmovi(w, SCT(1u), 0x7FF00000u); + safire(w, x, 0u); + lt_nvstp(w, LT_NV_P1, s, LT_NV_RZ, 4u, 0u); + safire(w, x, 0u); + lt_nvstx(w, LT_NV_P0, SCT(0u), SCT(1u), 4u, 0u, LT_NV_P1); + safire(w, x, 0u); + lt_nvsei(w, SCT(0u), LT_NV_RZ, 1u, LT_NV_P0, 1u); + safire(w, x, 0u); + lt_nvlop(w, n, n, SCT(0u), LT_NV_RZ, 0xFCu); + safire(w, x, 0u); +} + +static void sadspc(const lt_nrw_t *x, uint32_t d, uint32_t a, uint32_t b) +{ + uint64_t w[2]; + + lt_nvmovi(w, SCD(2u), 0u); + safire(w, x, 0u); + sadflg(x, a, SCD(0u), SCD(0u) + 1u, SCD(2u)); + lt_nvlop(w, SCD(2u) + 1u, a + 1u, b + 1u, LT_NV_RZ, 0x3Cu); + safire(w, x, 0u); + lt_nvlpi(w, SCD(2u) + 1u, SCD(2u) + 1u, 0x80000000u, 0xC0u); + safire(w, x, 0u); + sadflg(x, b, SCD(1u), SCD(1u) + 1u, SCD(2u)); + lt_nvlop(w, SCT(0u), SCD(0u), SCD(1u), LT_NV_RZ, 0x30u); + safire(w, x, 0u); + lt_nvlop(w, SCT(1u), SCD(1u) + 1u, SCD(0u) + 1u, LT_NV_RZ, 0x30u); + safire(w, x, 0u); + lt_nvlop(w, SCT(0u), SCT(0u), SCT(1u), LT_NV_RZ, 0xFCu); + safire(w, x, 0u); + lt_nvstp(w, LT_NV_P0, SCT(0u), LT_NV_RZ, 5u, 0u); + safire(w, x, 0u); + sadpick(x, SCD(4u), LT_NV_RZ, SCD(4u), LT_NV_P0, 0u); + lt_nvlop(w, SCT(0u), SCD(1u), SCD(0u), LT_NV_RZ, 0x30u); + safire(w, x, 0u); + lt_nvlop(w, SCT(1u), SCD(0u) + 1u, SCD(1u) + 1u, LT_NV_RZ, 0x30u); + safire(w, x, 0u); + lt_nvlop(w, SCT(0u), SCT(0u), SCT(1u), LT_NV_RZ, 0xFCu); + safire(w, x, 0u); + lt_nvstp(w, LT_NV_P0, SCT(0u), LT_NV_RZ, 5u, 0u); + safire(w, x, 0u); + sadcon(x, SCD(5u), 0x7FF00000u); + sadpick(x, SCD(4u), SCD(5u), SCD(4u), LT_NV_P0, 0u); + lt_nvlop(w, SCD(4u) + 1u, SCD(4u) + 1u, SCD(2u) + 1u, LT_NV_RZ, 0xFCu); + safire(w, x, 0u); + lt_nvlop(w, SCT(0u), SCD(0u), SCD(1u), LT_NV_RZ, 0xC0u); + safire(w, x, 0u); + lt_nvlop(w, SCT(1u), SCD(0u) + 1u, SCD(1u) + 1u, LT_NV_RZ, 0xC0u); + safire(w, x, 0u); + lt_nvlop(w, SCT(0u), SCT(0u), SCT(1u), SCD(2u), 0xFEu); + safire(w, x, 0u); + lt_nvstp(w, LT_NV_P0, SCT(0u), LT_NV_RZ, 5u, 0u); + safire(w, x, 0u); + sadcon(x, SCD(5u), 0x7FF80000u); + sadpick(x, d, SCD(5u), SCD(4u), LT_NV_P0, 0u); +} + +static void safd64(const nv_minst_t *I) +{ + lt_nrw_t y; + uint64_t w[2]; + uint32_t d, a, b; + + if (I->ops[1].kind != (uint8_t)NV_MOP_REG + || I->ops[2].kind != (uint8_t)NV_MOP_REG) { + sabad(I->op, BC_E609); + return; + } + if (sawchk(I, 2u) != 0) { sabad(I->op, BC_E611); return; } + d = sarg(&I->ops[0]); + a = sarg(&I->ops[1]); + b = sarg(&I->ops[2]); + memset(&y, 0, sizeof y); + samsr(&y.rd, 0u, LT_NV_NSCR); + samsr(&y.wr, 0u, LT_NV_NSCR); + samsr(&y.rd, a, 2u); + samsr(&y.rd, b, 2u); + samsr(&y.rd, d, 2u); + samsr(&y.wr, d, 2u); + sadcon(&y, SCD(4u), 0x43500000u); + sadnrm(&y, SCD(0u), a, SCT(2u)); + sadnrm(&y, SCD(1u), b, SCT(3u)); + lt_nvadd(w, SCT(2u), SCT(2u), SCT(3u), 1u); + safire(w, &y, 0u); + sadfst(&y); + sadscl(&y, d); + sadspc(&y, d, a, b); +} + +static uint32_t sasmd(uint16_t op) +{ + switch (op) { + case NV_SHFL_UP: return 1u; + case NV_SHFL_DOWN: return 2u; + case NV_SHFL_XOR: return 3u; + default: return 0u; + } +} + +static void sashf(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, a, l; + + memset(&x, 0, sizeof x); + if (sawchk(I, 1u) != 0) { sabad(I->op, BC_E611); return; } + d = sadef(I, &x); + a = sasrc(I->op, &I->ops[1], SA_IMM0, 1u, &x); + l = sasrc(I->op, &I->ops[2], SA_IMM1, 1u, &x); + lt_nvsfl(w, d, LT_NV_PT, a, l, 0x1Fu, sasmd(I->op)); + safire(w, &x, 1u); +} + +static void salea(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, f = sast.F->lcl_bytes; + + memset(&x, 0, sizeof x); + if (sadw(I) != 2u) { sabad(I->op, BC_E611); return; } + if (I->ops[1].kind != (uint8_t)NV_MOP_IMM || I->ops[1].imm < 0 + || (uint32_t)I->ops[1].imm > f) { + sabad(I->op, BC_E609); + return; + } + d = sadef(I, &x); + lt_nvmovc(w, d, 0u, SA_STK); + safire(w, &x, 0u); + lt_nvadi(w, d, d, (uint32_t)I->ops[1].imm - f, 0u); + safire(w, &x, 0u); + lt_nvmovi(w, d + 1u, 0u); + safire(w, &x, 0u); +} + +static void sacvl(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, s; + + memset(&x, 0, sizeof x); + if (sadw(I) != 2u || sawchk(I, 2u) != 0) { + sabad(I->op, BC_E611); + return; + } + d = sadef(I, &x); + s = sasrc(I->op, &I->ops[1], SA_IMM0, 2u, &x); + samsr(&x.wr, SA_TMP0, 2u); + samsr(&x.rd, SA_TMP0, 2u); + lt_nvmovc(w, SA_TMP0, 0u, 0x020u); + safire(w, &x, 0u); + lt_nvmovc(w, SA_TMP0 + 1u, 0u, 0x024u); + safire(w, &x, 0u); + saad64(d, s, SA_TMP0, &x); +} + +static void samnx(const nv_minst_t *I, int mx) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, a, b; + + memset(&x, 0, sizeof x); + if (sawchk(I, 1u) != 0) { sabad(I->op, BC_E611); return; } + d = sadef(I, &x); + a = sasrc(I->op, &I->ops[1], SA_IMM0, 1u, &x); + b = sasrc(I->op, &I->ops[2], SA_IMM1, 1u, &x); + lt_nvftp(w, LT_NV_P0, a, b, mx ? 4u : 1u); + safire(w, &x, 0u); + lt_nvsel(w, d, a, b, LT_NV_P0, 0u); + safire(w, &x, 0u); + lt_nvftp(w, LT_NV_P0, a, b, 8u); + safire(w, &x, 0u); + lt_nvsei(w, d, d, 0x7FC00000u, LT_NV_P0, 1u); + safire(w, &x, 0u); +} + +static void savote(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + + memset(&x, 0, sizeof x); + if (I->ops[0].kind != (uint8_t)NV_MOP_REG + || I->ops[0].rfile != (uint8_t)NV_RF_PRED + || I->ops[1].kind != (uint8_t)NV_MOP_REG + || I->ops[1].rfile != (uint8_t)NV_RF_PRED) { + sabad(I->op, BC_E611); + return; + } + lt_nvvot(w, LT_NV_RZ, sapd(I), saprd(&I->ops[1]), 0u, + I->op == (uint16_t)NV_VOTE_ANY ? 1u : 0u); + safire(w, &x, 0u); +} + +static void satrap(void) +{ + lt_nrw_t x; + uint64_t w[2]; + + memset(&x, 0, sizeof x); + lt_nvbpt(w); + safire(w, &x, 0u); +} + +static void sadsh(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, base; + + memset(&x, 0, sizeof x); + if (sadw(I) != 2u) { sabad(I->op, BC_E611); return; } + d = sadef(I, &x); + base = (sast.F->lds_bytes + 15u) & ~15u; + lt_nvmovi(w, d, base); + safire(w, &x, 0u); + lt_nvmovi(w, d + 1u, 0u); + safire(w, &x, 0u); +} + +static uint32_t saaop(uint16_t op) +{ + switch (op) { + case NV_ATOM_ADD_U32: return 0u; + case NV_ATOM_AND_B32: return 5u; + case NV_ATOM_OR_B32: return 6u; + case NV_ATOM_XOR_B32: return 7u; + case NV_ATOM_XCHG_B32: return 8u; + default: return 0xFFu; + } +} + +static void saatom(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, ra, rv, aop = saaop(I->op); + + memset(&x, 0, sizeof x); + if (aop == 0xFFu) { sabad(I->op, BC_E601); return; } + if (I->ops[1].kind != (uint8_t)NV_MOP_REG + || I->ops[1].rfile != (uint8_t)NV_RF_U64 + || I->ops[2].kind != (uint8_t)NV_MOP_REG) { + sabad(I->op, BC_E611); + return; + } + d = sadef(I, &x); + ra = sasrc(I->op, &I->ops[1], SA_IMM0, 2u, &x); + rv = sasrc(I->op, &I->ops[2], SA_IMM1, 1u, &x); + lt_nvatg(w, d, ra, rv, 0u, aop, 0u, 0x7u); + safire(w, &x, 3u); +} + +static void sarelc(uint32_t at, uint32_t gi, uint32_t kind, uint8_t hi, + uint32_t add) +{ + if (sast.rltot >= LT_MAX_NVREL) { sast.nbad++; return; } + sast.rlp[sast.rltot].at = at; + sast.rlp[sast.rltot].gi = gi; + sast.rlp[sast.rltot].add = add; + sast.rlp[sast.rltot].hi = hi; + sast.rlp[sast.rltot].kind = (uint8_t)kind; + sast.rltot++; + sast.nrl++; +} + +static void sarel(uint32_t at, uint32_t gi, uint8_t hi) +{ + sarelc(at, gi, LT_NV_RGLB, hi, 0u); +} + +static void saglb(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, gi; + + memset(&x, 0, sizeof x); + if (sadw(I) != 2u || I->ops[1].kind != (uint8_t)NV_MOP_IMM + || I->ops[1].imm < 0) { sabad(I->op, BC_E611); return; } + gi = (uint32_t)I->ops[1].imm; + if (gi >= sast.ng || sast.rltot + 2u > LT_MAX_NVREL) { + sabad(I->op, BC_E609); + return; + } + d = sadef(I, &x); + sarel(sast.clen, gi, 0u); + lt_nvmovi(w, d, 0u); + safire(w, &x, 0u); + sarel(sast.clen, gi, 1u); + lt_nvmovi(w, d + 1u, 0u); + safire(w, &x, 0u); +} + +static uint32_t saslot(uint8_t rf) +{ + return (rf == (uint8_t)NV_RF_U64 || rf == (uint8_t)NV_RF_F64) ? 2u : 1u; +} + +static uint32_t saaoff(const nv_call_t *C, uint32_t k) +{ + uint32_t o = 0u; + + for (uint32_t i = 0; i <= k; i++) { + uint32_t n = saslot(C->args[i].rfile); + + o = (o + n - 1u) & ~(n - 1u); + if (i < k) o += n; + } + return o; +} + +static void samove(uint32_t r, const nv_opnd_t *o, uint32_t n, lt_nrw_t *x) +{ + uint64_t w[2]; + + samsr(&x->wr, r, n); + if (o->kind == (uint8_t)NV_MOP_REG) { + uint32_t s = sarg(o); + + samsr(&x->rd, s, n); + lt_nvmov(w, r, s); + safire(w, x, 0u); + if (n == 2u) { lt_nvmov(w, r + 1u, s + 1u); safire(w, x, 0u); } + return; + } + lt_nvmovi(w, r, (uint32_t)o->imm); + safire(w, x, 0u); + if (n == 2u) { + lt_nvmovi(w, r + 1u, (o->imm < 0) ? 0xFFFFFFFFu : 0u); + safire(w, x, 0u); + } +} + +static int saargs(const nv_call_t *C, lt_nrw_t *x) +{ + for (uint32_t k = 0; k < C->nargs && k < NV_MAX_CARG; k++) { + uint32_t n = saslot(C->args[k].rfile); + uint32_t o = saaoff(C, k); + + if (o + n > LT_NV_NARG) { + (void)be_fail(BC_E545, "nvptx", "device call argument registers", + (unsigned)(LT_NV_NARG * 4u)); + sast.nbad++; + return 1; + } + if (C->args[k].kind != (uint8_t)NV_MOP_REG + && C->args[k].kind != (uint8_t)NV_MOP_IMM) { + sabad((uint16_t)NV_CALL, BC_E609); + return 1; + } + samove(LT_NV_ARG0 + o, &C->args[k], n, x); + } + return 0; +} + +static void sacret(const nv_call_t *C) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, n; + + if (C->hasret == 0u || C->ret.kind != (uint8_t)NV_MOP_REG) return; + memset(&x, 0, sizeof x); + d = sarg(&C->ret); + n = saslot(C->ret.rfile); + samsr(&x.rd, LT_NV_ARG0, n); + samsr(&x.wr, d, n); + lt_nvmov(w, d, LT_NV_ARG0); + safire(w, &x, 0u); + if (n == 2u) { lt_nvmov(w, d + 1u, LT_NV_ARG0 + 1u); safire(w, &x, 0u); } +} + +static void sacall(const nv_minst_t *I) +{ + const nv_call_t *C = &sast.M->calls[I->flags % NV_MAX_CALL]; + lt_nrw_t x; + uint64_t w[2]; + uint32_t g, ci, at; + + memset(&x, 0, sizeof x); + if (C->vprt != 0u || C->fn >= BIR_MAX_FUNCS) { + sabad(I->op, BC_E601); + return; + } + if (sast.isfn != 0u) { + (void)be_fail(BC_E541, "nvptx", + "a device function that itself calls, whose return " + "address has nowhere to spill"); + sast.nbad++; + return; + } + g = sast.fofm[C->fn]; + if (g >= sast.M->num_mfunc) { sabad(I->op, BC_E609); return; } + ci = sast.fmap[g]; + if (ci == SA_NOIX || sast.rltot + 3u > LT_MAX_NVREL) { + sabad(I->op, BC_E609); + return; + } + if (saargs(C, &x) != 0) return; + + sast.gate = (uint8_t)LT_NV_PT; + sadrn(); + at = sast.clen + 48u; + samsr(&x.wr, LT_NV_R20, 2u); + sarelc(sast.clen, ci, LT_NV_RRET, 0u, at); + lt_nvmovi(w, LT_NV_R20, 0u); + safire(w, &x, 0u); + sarelc(sast.clen, ci, LT_NV_RRET, 1u, at); + lt_nvmovi(w, LT_NV_R21, 0u); + safire(w, &x, 0u); + sarelc(sast.clen, ci, LT_NV_RTGT, 0u, 0u); + lt_nvcall(w); + sacfp(w); + sacret(C); +} + +static void saretp(const nv_minst_t *I) +{ + lt_nrw_t x; + uint32_t n; + + memset(&x, 0, sizeof x); + if (I->ops[0].kind != (uint8_t)NV_MOP_REG + && I->ops[0].kind != (uint8_t)NV_MOP_IMM) { + sabad(I->op, BC_E609); + return; + } + n = savw(I->ops[0].rfile); + samove(LT_NV_ARG0, &I->ops[0], n, &x); +} + +static uint32_t sarm(uint16_t op) +{ + switch (op) { + case NV_FLOOR_F32: return 1u; + case NV_CEIL_F32: return 2u; + case NV_TRUNC_F32: return 3u; + default: return 0u; + } +} + +static void sarnd(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, a; + + memset(&x, 0, sizeof x); + if (sawchk(I, 1u) != 0) { sabad(I->op, BC_E611); return; } + d = sadef(I, &x); + a = sasrc(I->op, &I->ops[1], SA_IMM0, 1u, &x); + lt_nvfrn(w, d, a, sarm(I->op)); + safire(w, &x, 1u); + lt_nvftp(w, LT_NV_P0, d, d, 8u); + safire(w, &x, 0u); + lt_nvsei(w, d, d, 0x7FC00000u, LT_NV_P0, 1u); + safire(w, &x, 0u); +} + +static void sahalf(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, s; + + memset(&x, 0, sizeof x); + if (I->ops[1].kind != (uint8_t)NV_MOP_REG + || savw(I->ops[1].rfile) != 1u + || sadw(I) != (I->op == (uint16_t)NV_CVT_F64_F16 ? 2u : 1u)) { + sabad(I->op, BC_E611); + return; + } + d = sadef(I, &x); + s = sasrc(I->op, &I->ops[1], SA_IMM0, 1u, &x); + switch (I->op) { + case NV_CVT_F32_F16: lt_nvh2f(w, d, s); break; + case NV_CVT_F16_F32: lt_nvf2h(w, d, s, 0u); break; + case NV_CVT_BF16_F32: lt_nvf2h(w, d, s, 1u); break; + case NV_CVT_F32_BF16: lt_nvshi(w, d, s, 16u, LT_NV_RZ, 3u, 0u, 0u); break; + default: + samsr(&x.rd, SA_TMP0, 1u); + samsr(&x.wr, SA_TMP0, 1u); + lt_nvh2f(w, SA_TMP0, s); + safire(w, &x, 0u); + lt_nvf2f(w, d, SA_TMP0, 3u, 2u, 0u); + safire(w, &x, 1u); + return; + } + safire(w, &x, 0u); +} + +static void sacv16(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, a; + + memset(&x, 0, sizeof x); + if (sawchk(I, 1u) != 0) { sabad(I->op, BC_E611); return; } + d = sadef(I, &x); + a = sasrc(I->op, &I->ops[1], SA_IMM0, 1u, &x); + if (I->op != (uint16_t)NV_CVT_S32_S16) { + lt_nvlpi(w, d, a, 0xFFFFu, 0xC0u); + safire(w, &x, 0u); + return; + } + lt_nvshi(w, d, a, 16u, LT_NV_RZ, 3u, 0u, 0u); + safire(w, &x, 0u); + lt_nvshi(w, d, LT_NV_RZ, 16u, d, 2u, 1u, 1u); + safire(w, &x, 0u); +} + +static uint32_t sats(uint16_t op) +{ + switch (op) { + case NV_LD_GLB_U8: case NV_ST_GLB_U8: + case NV_LD_SHR_U8: case NV_ST_SHR_U8: + case NV_LD_LOC_U8: case NV_ST_LOC_U8: return 0u; + case NV_LD_GLB_U16: case NV_ST_GLB_U16: + case NV_LD_GLB_B16: case NV_ST_GLB_B16: + case NV_LD_SHR_U16: case NV_ST_SHR_U16: + case NV_LD_SHR_B16: case NV_ST_SHR_B16: + case NV_LD_LOC_U16: case NV_ST_LOC_U16: + case NV_LD_LOC_B16: case NV_ST_LOC_B16: return 2u; + case NV_LD_GLB_U64: case NV_ST_GLB_U64: + case NV_LD_GLB_F64: case NV_ST_GLB_F64: + case NV_LD_LOC_U64: case NV_ST_LOC_U64: + case NV_LD_LOC_F64: case NV_ST_LOC_F64: return 5u; + default: return 4u; + } +} + +static void samem(const nv_minst_t *I, int sp, int st) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t t = sats(I->op); + const nv_opnd_t *ao = st ? &I->ops[0] : &I->ops[1]; + const nv_opnd_t *vo = st ? &I->ops[1] : &I->ops[0]; + uint32_t ra, rv; + + memset(&x, 0, sizeof x); + if (ao->kind != (uint8_t)NV_MOP_REG || vo->kind != (uint8_t)NV_MOP_REG) { + sabad(I->op, BC_E609); + return; + } + if (sp == 0 && ao->rfile != (uint8_t)NV_RF_U64) { + sabad(I->op, BC_E611); + return; + } + if (sp != 0 && ao->rfile != (uint8_t)NV_RF_U64 + && ao->rfile != (uint8_t)NV_RF_U32) { + sabad(I->op, BC_E611); + return; + } + if ((t == 5u) != (savw(vo->rfile) == 2u)) { + sabad(I->op, BC_E611); + return; + } + ra = sarg(ao); + rv = sarg(vo); + samsr(&x.rd, ra, savw(ao->rfile)); + if (st) samsr(&x.rd, rv, savw(vo->rfile)); + else samsr(&x.wr, rv, savw(vo->rfile)); + if (sp == 1 && st) lt_nvsts(w, ra, rv, 0u, t); + else if (sp == 1) lt_nvlds(w, rv, ra, 0u, t); + else if (sp == 2 && st) lt_nvstl(w, ra, rv, 0u, t); + else if (sp == 2) lt_nvldl(w, rv, ra, 0u, t); + else if (st) lt_nvstg(w, ra, rv, 0u, t, 0u); + else lt_nvldg(w, rv, ra, 0u, t, 0u); + safire(w, &x, st ? 2u : 3u); +} + +static void sapld(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, o, n; + + memset(&x, 0, sizeof x); + n = sadw(I); + if ((I->op == (uint16_t)NV_LD_PARAM_U64 + || I->op == (uint16_t)NV_LD_PARAM_F64) != (n == 2u)) { + sabad(I->op, BC_E611); + return; + } + d = sadef(I, &x); + if (I->ops[1].kind != (uint8_t)NV_MOP_IMM || I->ops[1].imm < 0 + || (uint32_t)I->ops[1].imm >= sast.k.np) { + sabad(I->op, BC_E609); + return; + } + if (sast.isfn != 0u) { + uint32_t s = LT_NV_ARG0 + sast.pofs[I->ops[1].imm] / 4u; + + lt_nvmov(w, d, s); + safire(w, &x, 0u); + if (n == 2u) { lt_nvmov(w, d + 1u, s + 1u); safire(w, &x, 0u); } + return; + } + o = LT_NV_PBASE + sast.pofs[I->ops[1].imm]; + lt_nvmovc(w, d, 0u, o); + safire(w, &x, 0u); + if (I->op == (uint16_t)NV_LD_PARAM_B16) { + lt_nvlpi(w, d, d, 0xFFFFu, 0xC0u); + safire(w, &x, 0u); + } + if (n != 2u) return; + lt_nvmovc(w, d + 1u, 0u, o + 4u); + safire(w, &x, 0u); +} + +static void sactl(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t p = LT_NV_PT; + int32_t lb; + + memset(&x, 0, sizeof x); + if (I->op == (uint16_t)NV_BRA_PRED) p = saprd(&I->ops[0]); + lb = (int32_t)satgt(I->op == (uint16_t)NV_BRA_PRED ? &I->ops[1] + : &I->ops[0]); + sast.gate = (uint8_t)LT_NV_PT; sabrk(sast.cf.cur, 1u, p); sadrn(); sajmp(lb); @@ -1773,7 +2693,41 @@ static void saquit(void) uint64_t w[2]; memset(&x, 0, sizeof x); - lt_nvexit(w); + if (sast.isfn != 0u) { + samsr(&x.rd, LT_NV_R20, 2u); + lt_nvret(w, LT_NV_R20); + } else { + lt_nvexit(w); + } + safire(w, &x, 0u); +} + +static void samb(const nv_minst_t *I) +{ + static const uint8_t sc[3] = { 0u, 2u, 3u }; + lt_nrw_t x; + uint64_t w[2]; + uint8_t g = sast.gate; + + memset(&x, 0, sizeof x); + sast.gate = (uint8_t)LT_NV_PT; + lt_nvmbr(w, sc[I->flags % 3u]); + sadrn(); + safire(w, &x, 0u); + sast.gate = g; +} + +static void sansl(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t s; + + memset(&x, 0, sizeof x); + if (sawchk(I, 1u) != 0) { sabad(I->op, BC_E611); return; } + s = sasrc(I->op, &I->ops[0], SA_IMM0, 1u, &x); + lt_nvnsl(w, s); + sadrn(); safire(w, &x, 0u); } @@ -1794,11 +2748,35 @@ static void samemc(const nv_minst_t *I) case NV_ST_SHR_U32: case NV_ST_SHR_F32: case NV_ST_SHR_U8: case NV_ST_SHR_U16: case NV_ST_SHR_B16: samem(I, 1, 1); return; + case NV_LD_LOC_U32: case NV_LD_LOC_U64: + case NV_LD_LOC_F32: case NV_LD_LOC_F64: + case NV_LD_LOC_U8: case NV_LD_LOC_U16: + case NV_LD_LOC_B16: samem(I, 2, 0); return; + case NV_ST_LOC_U32: case NV_ST_LOC_U64: + case NV_ST_LOC_F32: case NV_ST_LOC_F64: + case NV_ST_LOC_U8: case NV_ST_LOC_U16: + case NV_ST_LOC_B16: samem(I, 2, 1); return; case NV_LD_PARAM_U32: case NV_LD_PARAM_U64: - case NV_LD_PARAM_F32: case NV_LD_PARAM_F64: sapld(I); return; + case NV_LD_PARAM_F32: case NV_LD_PARAM_F64: + case NV_LD_PARAM_B16: sapld(I); return; + case NV_VOTE_ANY: case NV_VOTE_ALL: savote(I); return; case NV_BRA: case NV_BRA_PRED: sactl(I); return; case NV_BAR_SYNC: sabar(); return; + case NV_MEMBAR: samb(I); return; + case NV_NANOSLP: sansl(I); return; case NV_RET: case NV_EXIT: saquit(); return; + case NV_CALL: sacall(I); return; + case NV_ST_RETP: saretp(I); return; + case NV_SHFL_IDX: case NV_SHFL_UP: + case NV_SHFL_DOWN: case NV_SHFL_XOR: sashf(I); return; + case NV_LEA_LOCAL: salea(I); return; + case NV_LEA_GLB: saglb(I); return; + case NV_LEA_DSH: sadsh(I); return; + case NV_CVTA_GLB: samov(I); return; + case NV_CVTA_LOC: sacvl(I); return; + case NV_TRAP: satrap(); return; + case NV_ATOM_ADD_U32: case NV_ATOM_AND_B32: case NV_ATOM_OR_B32: + case NV_ATOM_XOR_B32: case NV_ATOM_XCHG_B32: saatom(I); return; default: sabad(I->op, BC_E601); return; } } @@ -1827,8 +2805,16 @@ static void saext(const nv_minst_t *I) case NV_REM_U64: sadiv64(I, 0, 1); return; case NV_REM_S64: sadiv64(I, 1, 1); return; case NV_DIV_F32: safdiv(I); return; + case NV_DIV_F64: safd64(I); return; case NV_MAX_F32: samnx(I, 1); return; case NV_MIN_F32: samnx(I, 0); return; + case NV_FLOOR_F32: case NV_CEIL_F32: + case NV_TRUNC_F32: case NV_ROUND_F32: sarnd(I); return; + case NV_CVT_F32_F16: case NV_CVT_F16_F32: + case NV_CVT_F32_BF16: case NV_CVT_BF16_F32: + case NV_CVT_F64_F16: sahalf(I); return; + case NV_CVT_U16_U32: case NV_CVT_U32_U16: + case NV_CVT_S32_S16: sacv16(I); return; default: samemc(I); return; } } @@ -1886,6 +2872,68 @@ static void sastep(const nv_minst_t *I) } } +static void saxfer(uint32_t v, int st) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t a = sast.fbas, h = sast.rmap[v], n = sast.vwd[v]; + uint32_t t = (n == 2u) ? 5u : 4u; + uint32_t f = sast.F->lcl_bytes + 8u * sast.nspl; + + memset(&x, 0, sizeof x); + samsr(&x.wr, a, 2u); + lt_nvmovc(w, a, 0u, SA_STK); + safire(w, &x, 0u); + lt_nvadi(w, a, a, 8u * (uint32_t)sast.sslot[v] - f, 0u); + safire(w, &x, 0u); + lt_nvmovi(w, a + 1u, 0u); + safire(w, &x, 0u); + memset(&x, 0, sizeof x); + samsr(&x.rd, a, 2u); + if (st) samsr(&x.rd, h, n); + else samsr(&x.wr, h, n); + if (st) lt_nvstl(w, a, h, 0u, t); + else lt_nvldl(w, h, a, 0u, t); + safire(w, &x, st ? 2u : 3u); +} + +static uint32_t saspv(const nv_minst_t *I, uint32_t k) +{ + const nv_opnd_t *o = saopd(I, k); + uint32_t v; + + if (o == NULL || o->kind != (uint8_t)NV_MOP_REG) return SA_NOIX; + v = savx(o); + if (v == SA_NOIX || sast.sslot[v] == (uint16_t)SA_NOIX) return SA_NOIX; + return v; +} + +static void saspst(const nv_minst_t *I) +{ + uint32_t n = sanop(I); + uint32_t h = sast.fbas + 2u, v; + + if (sast.nspl == 0u) { sastep(I); return; } + sast.cop = I->op; + for (uint32_t k = 0; k < n; k++) { + v = saspv(I, k); + if (v == SA_NOIX || sast.rmap[v] != (uint16_t)SA_NOIX) continue; + sast.rmap[v] = (uint16_t)h; + h += 2u; + for (uint32_t j = sandf(I); j < n; j++) + if (saspv(I, j) == v) { saxfer(v, 0); break; } + } + sastep(I); + for (uint32_t k = 0; k < sandf(I); k++) { + v = saspv(I, k); + if (v == SA_NOIX || sast.rmap[v] == (uint16_t)SA_NOIX) continue; + saxfer(v, 1); + sast.rmap[v] = (uint16_t)SA_NOIX; + } + for (uint32_t k = 0; k < n; k++) + if ((v = saspv(I, k)) != SA_NOIX) sast.rmap[v] = (uint16_t)SA_NOIX; +} + static uint32_t sapsz(uint8_t rf) { if (rf == (uint8_t)NV_RF_U64 || rf == (uint8_t)NV_RF_F64) return 8u; @@ -1901,6 +2949,7 @@ static void sapar(void) for (uint32_t i = 0; i < sast.k.np && i < LT_MAX_NVPRM; i++) { uint32_t z = sapsz(sast.F->params[i].rfile); + if (sast.isfn != 0u && z < 4u) z = 4u; o = (o + z - 1u) & ~(z - 1u); sast.pofs[i] = o; sast.k.psz[i] = (uint8_t)z; @@ -1915,22 +2964,26 @@ static void sazero(void) memset(sast.bkd, 0, sizeof sast.bkd); memset(sast.brs, 0, sizeof sast.brs); memset(sast.rmap, 0xFF, sizeof sast.rmap); - memset(sast.vlo, 0xFF, sizeof sast.vlo); - memset(sast.vhi, 0, sizeof sast.vhi); - memset(sast.vbk, 0, sizeof sast.vbk); - memset(sast.vlc, 0, sizeof sast.vlc); memset(sast.vwd, 0, sizeof sast.vwd); memset(sast.vpr, 0, sizeof sast.vpr); - memset(sast.ru, 0xFF, sizeof sast.ru); - memset(sast.pu, 0xFF, sizeof sast.pu); + memset(sast.vseg, 0xFF, sizeof sast.vseg); + memset(sast.sslot, 0xFF, sizeof sast.sslot); + memset(sast.vuse, 0, sizeof sast.vuse); + sast.nspl = 0u; + sast.fbas = SA_RBAS; + sast.rlo = SA_RBAS; + sast.nmop = 0u; sast.clen = 0u; sast.nfx = 0u; + sast.rlbase = sast.rltot; + sast.nrl = 0u; sast.pend = 0u; - sast.nlp = 0u; - sast.lpof = 0u; + sast.nseg = 0u; sast.nerr = 0u; sast.nbad = 0u; sast.npr = 0u; + sast.kcall = 0u; + sast.isfn = 0u; sast.gate = (uint8_t)LT_NV_PT; sast.cop = 0xFFFEu; } @@ -1947,11 +3000,11 @@ static void sarun(void) sadrn(); sahead(k); for (uint32_t i = sast.ist[k]; i < sast.ist[k + 1u]; i++) - sastep(&sast.M->minsts[sast.f0 + i]); + saspst(&sast.M->minsts[sast.f0 + i]); } sast.cop = 0xFFFEu; sast.lat[sast.cf.nbb] = sast.clen; - lt_nvexit(w); + if (sast.isfn != 0u) lt_nvret(w, LT_NV_R20); else lt_nvexit(w); saput(w); lt_nvbra(w, -4); saput(w); @@ -1960,17 +3013,12 @@ static void sarun(void) sapat(); } -static int sakern(const nv_module_t *M, uint32_t *fi) +static int sakern(const nv_module_t *M) { - uint32_t n = 0u; + uint32_t n = M->num_mfunc; - for (uint32_t i = 0; i < M->num_mfunc; i++) { - if (M->mfuncs[i].is_kern == 0u) continue; - *fi = i; - n++; - } - if (n == 1u) return 0; - (void)be_fail(BC_E600, "nvptx", (unsigned)n); + if (n <= LT_MAX_NVKRN) return 0; + (void)be_fail(BC_E600, "nvptx", (unsigned)LT_MAX_NVKRN, (unsigned)n); return 1; } @@ -1995,17 +3043,27 @@ static int sabld(const nv_module_t *M, uint32_t fi) sazero(); sast.M = M; sast.F = F; + sast.isfn = (uint8_t)(F->is_kern == 0u); + sast.kcall = sast.isfn; + sast.fbas = (sast.isfn != 0u && sast.ktop > SA_RBAS) ? sast.ktop + : SA_RBAS; + sast.rlo = sast.fbas; if (F->num_blks == 0u || F->num_params > LT_MAX_NVPRM) { - (void)be_fail(BC_E600, "nvptx", 0u); + (void)be_fail(BC_E600, "nvptx", (unsigned)LT_MAX_NVKRN, 0u); return 1; } last = F->first_blk + F->num_blks - 1u; sast.f0 = M->mblks[F->first_blk].first_inst; sast.fn = M->mblks[last].first_inst + M->mblks[last].num_insts - sast.f0; if (saname() != 0) { - (void)be_fail(BC_E600, "nvptx", 1u); + (void)be_fail(BC_E600, "nvptx", (unsigned)LT_MAX_NVKRN, 1u); return 1; } + for (uint32_t i = 0; i < sast.fn; i++) + if (M->minsts[sast.f0 + i].op == (uint16_t)NV_CALL) { + sast.kcall = 1u; + break; + } if (sast.fn >= 0xFFFFu || F->num_blks >= SA_NBB) { (void)be_fail(BC_E602, "nvptx", sast.name, (unsigned)F->num_blks, (unsigned)SA_NBB); @@ -2030,12 +3088,13 @@ static int sabld(const nv_module_t *M, uint32_t fi) static int sarega(void) { - if (sascan() != 0) { + uint32_t nw = (sast.fn >> 6) + 1u; + + if (nw > SA_NIW || sascan() != 0 || salvin() != 0) { (void)be_fail(BC_E606, "nvptx", sast.name, (unsigned)SA_NV); return 1; } - sastr(); - if (saall() != 0) { + if (saspil() != 0) { if (sast.npr != 0u) (void)be_fail(BC_E604, "nvptx", sast.name, (unsigned)SA_NPR - 1u); else @@ -2046,12 +3105,64 @@ static int sarega(void) return 0; } -static int sacomp(nv_module_t *nv) +static uint32_t satxt(char *out, uint32_t max); + +static int sagbuild(const nv_module_t *nv) +{ + const bir_module_t *M = nv->bir; + uint32_t n = (M != NULL) ? M->num_globals : 0u; + uint32_t off = 0u; + + sast.ng = 0u; + sast.gtot = 0u; + if (n == 0u && nv->gbar == 0u) return 0; + if (n + (nv->gbar != 0u ? 1u : 0u) > LT_MAX_NVGLB) return 1; + for (uint32_t gi = 0; gi < n; gi++) { + uint32_t sz = bir_bsz(M, M->globals[gi].type, 8); + uint32_t no = M->globals[gi].name; + uint32_t ini = M->globals[gi].initializer; + + if (sz == 0u) sz = 1u; + off = (off + 7u) & ~7u; + if (off > LT_MAX_NVGBY - sz) return 1; + memset(sast.gby + off, 0, sz); + if (ini != BIR_VAL_NONE && BIR_VAL_IS_CONST(ini)) { + uint32_t ci = BIR_VAL_INDEX(ini); + + if (ci < M->num_consts && M->consts[ci].kind == BIR_CONST_BYTES) { + uint32_t bo = M->consts[ci].d.bytes.off; + uint32_t bl = M->consts[ci].d.bytes.len; + + if (bo < M->string_len && bl <= M->string_len - bo) + memcpy(sast.gby + off, &M->strings[bo], + (bl < sz) ? bl : sz); + } + } + sast.gtab[gi].name = (no < M->string_len) ? &M->strings[no] : "g"; + sast.gtab[gi].off = off; + sast.gtab[gi].size = sz; + off += sz; + } + if (nv->gbar != 0u) { + off = (off + 7u) & ~7u; + if (off > LT_MAX_NVGBY - 8u) return 1; + memset(sast.gby + off, 0, 8u); + sast.gtab[n].name = "$bgbar"; + sast.gtab[n].off = off; + sast.gtab[n].size = 8u; + off += 8u; + n++; + } + sast.ng = n; + sast.gtot = off; + return 0; +} + +static int saone(nv_module_t *nv, uint32_t fi, int text) { - uint32_t fi = 0u; + lt_nvk_t *K; lt_res_t rc; - if (sakern(nv, &fi) != 0) return 1; if (sabld(nv, fi) != 0) return 1; if (sarega() != 0) return 1; @@ -2065,14 +3176,136 @@ static int sacomp(nv_module_t *nv) sarun(); if (sast.nbad != 0u) return 1; sast.k.nreg = sast.nreg + 2u; + sast.k.isfn = sast.isfn; + if (sast.isfn == 0u && sast.k.nreg > sast.ktop) sast.ktop = sast.k.nreg; sast.k.smem = sast.F->lds_bytes; - sast.k.lmem = sast.F->lcl_bytes; + sast.k.lmem = sast.F->lcl_bytes + 8u * sast.nspl; if (sast.clen == 0u || sast.clen > LT_MAX_NVCODE) { - (void)be_fail(BC_E607, "nvptx", sast.name, (unsigned)LT_MAX_NVCODE); + (void)be_fail(BC_E607, "nvptx", sast.name, + (unsigned)LT_MAX_NVCODE); + return 1; + } + if (sast.nk >= LT_MAX_NVKRN || sast.clen > LT_MAX_NVIMG - sast.plen) { + (void)be_fail(BC_E608, "nvptx", sast.name); + return 1; + } + if (text != 0) + sast.ilen += satxt((char *)sast.img + sast.ilen, + LT_MAX_NVIMG - sast.ilen); + K = &sast.kt[sast.nk++]; + *K = sast.k; + K->name = &nv->bir->strings[sast.F->name]; + K->code = sast.pool + sast.plen; + K->clen = sast.clen; + K->rel = &sast.rlp[sast.rlbase]; + K->nrel = sast.nrl; + memcpy(sast.pool + sast.plen, sast.code, sast.clen); + sast.plen += sast.clen; + return 0; +} + +static int sahasc(const nv_module_t *nv, uint32_t f, const uint8_t *out) +{ + const nv_mfunc_t *F = &nv->mfuncs[f]; + + for (uint32_t b = 0; b < F->num_blks; b++) { + const nv_mblk_t *B = &nv->mblks[F->first_blk + b]; + + for (uint32_t i = 0; i < B->num_insts; i++) { + const nv_minst_t *I = &nv->minsts[B->first_inst + i]; + uint32_t cf, g; + + if (I->op != (uint16_t)NV_CALL) continue; + if (nv->calls[I->flags % NV_MAX_CALL].vprt != 0u) continue; + cf = nv->calls[I->flags % NV_MAX_CALL].fn; + if (cf >= BIR_MAX_FUNCS) continue; + g = sast.fofm[cf]; + if (g < nv->num_mfunc && out[g] == 0u) return 1; + } + } + return 0; +} + +static int sacyc(const nv_module_t *nv) +{ + static uint8_t out[NV_MAX_MFUNC]; + uint32_t n = nv->num_mfunc; + + memset(out, 0, sizeof out); + for (uint32_t pass = 0; pass <= n; pass++) { + int drop = 0; + + for (uint32_t f = 0; f < n; f++) { + if (out[f] != 0u || sahasc(nv, f, out) != 0) continue; + out[f] = 1u; + drop = 1; + } + if (drop == 0) break; + } + for (uint32_t f = 0; f < n; f++) + if (out[f] == 0u) { + (void)be_fail(BC_E541, "nvptx", + "a recursive device call, which has no second " + "return address to hold"); + return 1; + } + return 0; +} + +static int saplan(const nv_module_t *nv) +{ + uint32_t n = 0u; + + memset(sast.fofm, 0xFF, sizeof sast.fofm); + for (uint32_t fi = 0; fi < nv->num_mfunc; fi++) { + sast.fmap[fi] = SA_NOIX; + if (nv->mfuncs[fi].bir_func < BIR_MAX_FUNCS) + sast.fofm[nv->mfuncs[fi].bir_func] = (uint16_t)fi; + } + for (uint32_t fi = 0; fi < nv->num_mfunc; fi++) + if (nv->mfuncs[fi].is_kern != 0u) sast.fmap[fi] = n++; + for (uint32_t fi = 0; fi < nv->num_mfunc; fi++) + if (nv->mfuncs[fi].is_kern == 0u) sast.fmap[fi] = n++; + return sacyc(nv); +} + +static void sanreg(void) +{ + uint32_t g = 0u; + + for (uint32_t i = 0; i < sast.nk; i++) + if (sast.kt[i].nreg > g) g = sast.kt[i].nreg; + for (uint32_t i = 0; i < sast.nk; i++) + if (sast.kt[i].isfn == 0u) sast.kt[i].nreg = g; +} + +static int sacomp(nv_module_t *nv, int text) +{ + lt_nvgd_t gd; + + sast.nk = 0u; + sast.plen = 0u; + sast.ilen = 0u; + sast.rltot = 0u; + sast.ktop = 0u; + if (sakern(nv) != 0) return 1; + if (sagbuild(nv) != 0) { + (void)be_fail(BC_E608, "nvptx", "globals"); return 1; } - if (lt_nvcub(sast.img, LT_MAX_NVIMG, &sast.ilen, &sast.k, - sast.code, sast.clen) != LT_OK) { + if (saplan(nv) != 0) return 1; + for (uint32_t fi = 0; fi < nv->num_mfunc; fi++) + if (nv->mfuncs[fi].is_kern != 0u && saone(nv, fi, text) != 0) return 1; + for (uint32_t fi = 0; fi < nv->num_mfunc; fi++) + if (nv->mfuncs[fi].is_kern == 0u && saone(nv, fi, text) != 0) return 1; + sanreg(); + if (text != 0) return 0; + gd.g = sast.gtab; + gd.ng = sast.ng; + gd.bytes = sast.gby; + gd.gtot = sast.gtot; + if (lt_nvcub(sast.img, LT_MAX_NVIMG, &sast.ilen, sast.kt, + sast.nk, sast.ng ? &gd : NULL) != LT_OK) { (void)be_fail(BC_E608, "nvptx", sast.name); return 1; } @@ -2121,16 +3354,11 @@ static uint32_t satxt(char *out, uint32_t max) int nv_sass(nv_module_t *nv, const char *path, int text) { - if (sacomp(nv) != 0) return BC_ERR_NVIDIA; - if (text == 0) { - if (sawrit(path, sast.img, sast.ilen) != 0) return BC_ERR_IO; - printf("wrote %s (%u bytes cubin, 1 kernel, %u instructions)\n", - path, (unsigned)sast.ilen, (unsigned)(sast.clen / 16u)); - return BC_OK; - } - sast.ilen = satxt((char *)sast.img, LT_MAX_NVIMG); + if (sacomp(nv, text) != 0) return BC_ERR_NVIDIA; if (sawrit(path, sast.img, sast.ilen) != 0) return BC_ERR_IO; - printf("wrote %s (%u bytes, 1 kernel, %u instructions)\n", - path, (unsigned)sast.ilen, (unsigned)(sast.clen / 16u)); + printf("wrote %s (%u bytes%s, %u kernel%s, %u instructions)\n", + path, (unsigned)sast.ilen, text != 0 ? "" : " cubin", + (unsigned)sast.nk, sast.nk == 1u ? "" : "s", + (unsigned)(sast.plen / 16u)); return BC_OK; } diff --git a/src/nvidia/isel.c b/src/nvidia/isel.c index 0afb063..38392dc 100644 --- a/src/nvidia/isel.c +++ b/src/nvidia/isel.c @@ -11,6 +11,8 @@ static struct { nv_module_t *nv; const bir_module_t *bir; uint32_t block_map[BIR_MAX_BLOCKS]; + uint32_t blk_lst[BIR_MAX_BLOCKS]; + uint32_t cmb; uint32_t lcl_off; /* local (alloca) byte offset */ uint32_t shr_off; /* shared memory byte offset */ uint32_t lcl_alg; @@ -1298,6 +1300,13 @@ static int mblk(uint32_t bir_bi, uint32_t *out) return 0; } +static int mblkl(uint32_t bir_bi, uint32_t *out) +{ + if (mblk(bir_bi, out) != 0) return 1; + *out = S.blk_lst[bir_bi]; + return 0; +} + static void is_br(const bir_inst_t *I) { uint32_t m_tgt; @@ -1425,7 +1434,7 @@ static void is_phi(uint32_t idx, const bir_inst_t *I, if (val == BIR_VAL_NONE) continue; uint32_t m_pred; - if (mblk(pred_bir, &m_pred) != 0) return; + if (mblkl(pred_bir, &m_pred) != 0) return; if (m_pred >= NV_MAX_MBLK) continue; nv_opnd_t src = rslv_p(val); @@ -1451,9 +1460,159 @@ static void is_phi(uint32_t idx, const bir_inst_t *I, /* ---- Barriers ---- */ -static void is_barrier(void) +static void is_barrier(const bir_inst_t *I) +{ + em0(I->subop ? NV_BARWARP : NV_BAR_SYNC); +} + +#define GB_NBLK 4u + +static uint32_t gbcnt(uint32_t bir_bi) { + const bir_block_t *B; + uint32_t n = 0; + + if (bir_bi >= S.bir->num_blocks) return 0; + B = &S.bir->blocks[bir_bi]; + for (uint32_t ii = 0; ii < B->num_insts && ii < 65536u; ii++) + if (S.bir->insts[B->first_inst + ii].op == BIR_GRIDBAR) n++; + return n; +} + +static uint32_t bcut(uint32_t bir_bi) +{ + nv_mblk_t *MB; + + if (S.cmb + 1u >= NV_MAX_MBLK) { + nv_cap("machine blocks", (unsigned)NV_MAX_MBLK); + return 0; + } + MB = &S.nv->mblks[S.cmb]; + MB->num_insts = S.nv->num_minst - MB->first_inst; + S.cmb++; + MB = &S.nv->mblks[S.cmb]; + MB->first_inst = S.nv->num_minst; + MB->num_insts = 0; + MB->bir_block = bir_bi; + if (S.nv->num_mblk <= S.cmb) S.nv->num_mblk = S.cmb + 1u; + return S.cmb; +} + +static void gbbr(nv_opnd_t p, uint32_t t, uint32_t f) +{ + nv_opnd_t ops[2] = { p, mop_lbl(t) }; + nv_opnd_t fops[1] = { mop_lbl(f) }; + + emit(NV_BRA_PRED, 0, 2, ops, 0); + emit(NV_BRA, 0, 1, fops, 0); +} + +static nv_opnd_t gbfold(uint16_t op, int32_t a, int32_t b, int32_t c) +{ + nv_opnd_t r = mop_reg(NV_RF_U32, new_vreg(NV_RF_U32)); + nv_opnd_t t = mop_reg(NV_RF_U32, new_vreg(NV_RF_U32)); + + em1u(NV_MOV_U32, r, mop_spec(a)); + em1u(NV_MOV_U32, t, mop_spec(b)); + em1(op, r, r, t); + em1u(NV_MOV_U32, t, mop_spec(c)); + em1(op, r, r, t); + return r; +} + +static void gbfen(void) +{ + nv_opnd_t ops[1] = { mop_none() }; + emit(NV_MEMBAR, 0, 0, ops, NV_SCOPE_GPU); +} + +static nv_opnd_t gbadd(nv_opnd_t a) +{ + nv_opnd_t d = mop_reg(NV_RF_U32, new_vreg(NV_RF_U32)); + nv_opnd_t v = mop_reg(NV_RF_U32, new_vreg(NV_RF_U32)); + nv_opnd_t ops[3]; + + em1u(NV_MOV_U32, v, mop_imm(1)); + ops[0] = d; ops[1] = a; ops[2] = v; + emit(NV_ATOM_ADD_U32, 1, 2, ops, NV_ASP_GLB); + return d; +} + +static void gbhd(nv_opnd_t p, uint32_t w, uint32_t l1) +{ + nv_opnd_t n; + + em0(NV_BAR_SYNC); + n = gbfold(NV_OR_B32, NV_SPEC_TID_X, NV_SPEC_TID_Y, NV_SPEC_TID_Z); + em1(NV_SETP_NE_U32, p, n, mop_imm(0)); + gbbr(p, w, l1); +} + +static void gbarr(nv_opnd_t p, nv_opnd_t rd, nv_opnd_t rg, nv_opnd_t gen, + uint32_t sp, uint32_t l2) +{ + nv_opnd_t n, a; + + em1u(NV_LEA_GLB, rd, mop_imm((int32_t)S.bir->num_globals)); + em1(NV_ADD_U64, rg, rd, mop_imm(4)); + gbfen(); + em1u(NV_LD_GLB_U32, gen, rg); + n = gbfold(NV_MUL_LO_U32, NV_SPEC_NCTAID_X, NV_SPEC_NCTAID_Y, + NV_SPEC_NCTAID_Z); + em1(NV_SUB_U32, n, n, mop_imm(1)); + a = gbadd(rd); + em1(NV_SETP_NE_U32, p, a, n); + gbbr(p, sp, l2); +} + +static void gbrel(nv_opnd_t rd, nv_opnd_t rg, uint32_t w) +{ + nv_opnd_t z = mop_reg(NV_RF_U32, new_vreg(NV_RF_U32)); + nv_opnd_t ops[2]; + nv_opnd_t bops[1] = { mop_lbl(w) }; + + em1u(NV_MOV_U32, z, mop_imm(0)); + ops[0] = rd; ops[1] = z; + emit(NV_ST_GLB_U32, 0, 2, ops, 0); + gbfen(); + (void)gbadd(rg); + emit(NV_BRA, 0, 1, bops, 0); +} + +static void gbspn(nv_opnd_t p, nv_opnd_t rg, nv_opnd_t gen, uint32_t sp, + uint32_t w) +{ + nv_opnd_t c = mop_reg(NV_RF_U32, new_vreg(NV_RF_U32)); + + em1u(NV_LD_GLB_U32, c, rg); + em1(NV_SETP_EQ_U32, p, c, gen); + gbbr(p, sp, w); +} + +static void is_gbar(uint32_t bir_bi) +{ + uint32_t b, l1, l2, sp, w; + nv_opnd_t p, rd, rg, gen; + + S.nv->gbar = 1; + if (S.nv->sass == 0) { em0(NV_GBAR); return; } + + b = S.cmb; l1 = b + 1u; l2 = b + 2u; sp = b + 3u; w = b + 4u; + p = mop_reg(NV_RF_PRED, new_vreg(NV_RF_PRED)); + rd = mop_reg(NV_RF_U64, new_vreg(NV_RF_U64)); + rg = mop_reg(NV_RF_U64, new_vreg(NV_RF_U64)); + gen = mop_reg(NV_RF_U32, new_vreg(NV_RF_U32)); + + gbhd(p, w, l1); + if (bcut(bir_bi) != l1) return; + gbarr(p, rd, rg, gen, sp, l2); + if (bcut(bir_bi) != l2) return; + gbrel(rd, rg, w); + if (bcut(bir_bi) != sp) return; + gbspn(p, rg, gen, sp, w); + if (bcut(bir_bi) != w) return; em0(NV_BAR_SYNC); + gbfen(); } static void is_fence(const bir_inst_t *I) @@ -2141,8 +2300,394 @@ static void wm_in(uint32_t fp, uint16_t tb, uint8_t rf, uint8_t n) wm_ea(base, (int32_t)k * w)); } +typedef struct { + uint32_t lm, ln, lk; + uint32_t ab, cb; + uint32_t kind; +} wsh_t; + +static int wslog(uint32_t v) +{ + for (int i = 0; i < 16; i++) + if (v == (1u << i)) return i; + return -1; +} + +static uint32_t wsnum(const char *s, char tag, uint32_t *at) +{ + uint32_t v = 0u, i = *at; + + if (s[i] != tag) return 0u; + i++; + for (uint32_t g = 0; g < 4u && s[i] >= '0' && s[i] <= '9'; g++) + v = v * 10u + (uint32_t)(s[i++] - '0'); + *at = i; + return v; +} + +static int wsdim(uint32_t row, wsh_t *h) +{ + const bir_wmma_t *W = &bir_wmma[row % BIR_WM_NROW]; + uint32_t at = 0u; + int lm = wslog(wsnum(W->shp, 'm', &at)); + int ln = wslog(wsnum(W->shp, 'n', &at)); + int lk = wslog(wsnum(W->shp, 'k', &at)); + + if (lm < 0 || ln < 0 || lk < 0 || W->shp[at] != 0) { + nv_refuse("a wmma shape the SASS lowering cannot read"); + return 0; + } + h->lm = (uint32_t)lm; + h->ln = (uint32_t)ln; + h->lk = (uint32_t)lk; + if (strcmp(W->abt, "f16") == 0) { h->kind = 0u; h->ab = 16u; } + else if (strcmp(W->abt, "bf16") == 0) { h->kind = 1u; h->ab = 16u; } + else if (strcmp(W->abt, "s8") == 0) { h->kind = 2u; h->ab = 8u; } + else if (strcmp(W->abt, "u8") == 0) { h->kind = 3u; h->ab = 8u; } + else { + nv_refuse("a wmma fragment of tf32, f64, four-bit or single-bit elements on the SASS backend"); + return 0; + } + h->cb = (strcmp(W->act, "f16") == 0) ? 16u : 32u; + if ((h->kind < 2u) == (strcmp(W->act, "s32") == 0)) { + nv_refuse("a wmma accumulator whose type does not match its multiplicands"); + return 0; + } + return 1; +} + +static int wsfit(const wsh_t *h, unsigned role, uint32_t n, uint32_t epr, + uint32_t *lc) +{ + int l = wslog(n * epr); + int ok = l >= 0; + + if (ok) *lc = (uint32_t)l; + if (ok && role == NV_WM_ROLE_A) + ok = h->lm + h->lk <= 5u + *lc && *lc <= h->lk; + else if (ok && role == NV_WM_ROLE_B) + ok = h->lk + h->ln <= 5u + *lc && *lc <= h->lk; + else if (ok) + ok = h->lm + h->ln == 5u + *lc && *lc <= h->ln; + if (!ok) + nv_refuse("a wmma shape the SASS lowering cannot distribute across one warp"); + return ok; +} + +static nv_opnd_t wsu(void) +{ + return mop_reg(NV_RF_U32, new_vreg(NV_RF_U32)); +} + +static nv_opnd_t wsop(uint16_t op, nv_opnd_t a, nv_opnd_t b) +{ + nv_opnd_t d = wsu(); + em1(op, d, a, b); + return d; +} + +static nv_opnd_t wsfop(uint16_t op, nv_opnd_t a, nv_opnd_t b) +{ + nv_opnd_t d = mop_reg(NV_RF_F32, new_vreg(NV_RF_F32)); + em1(op, d, a, b); + return d; +} + +static nv_opnd_t wsbit(nv_opnd_t r, uint8_t rf) +{ + nv_opnd_t d = mop_reg(rf, new_vreg(rf)); + em1u(NV_MOV_B32, d, r); + return d; +} + +static nv_opnd_t wslane(uint32_t sh) +{ + nv_opnd_t l = wsu(); + em1u(NV_MOV_U32, l, mop_spec(NV_SPEC_LANEID)); + return (sh != 0u) ? wsop(NV_SHL_B32, l, mop_imm((int32_t)sh)) : l; +} + +static nv_opnd_t wsshf(nv_opnd_t v, nv_opnd_t lane) +{ + nv_opnd_t ops[3] = { wsu(), v, lane }; + emit(NV_SHFL_IDX, 1, 2, ops, 0); + return ops[0]; +} + +static void wsmap(const wsh_t *h, unsigned role, nv_opnd_t tl, uint32_t e, + nv_opnd_t *i, nv_opnd_t *j) +{ + nv_opnd_t t = wsop(NV_ADD_U32, tl, mop_imm((int32_t)e)); + int32_t km = (int32_t)((1u << h->lk) - 1u); + + if (role == NV_WM_ROLE_A) { + t = wsop(NV_AND_B32, t, mop_imm((int32_t)((1u << (h->lm + h->lk)) - 1u))); + *i = wsop(NV_SHR_U32, t, mop_imm((int32_t)h->lk)); + *j = wsop(NV_AND_B32, t, mop_imm(km)); + } else if (role == NV_WM_ROLE_B) { + t = wsop(NV_AND_B32, t, mop_imm((int32_t)((1u << (h->lk + h->ln)) - 1u))); + *i = wsop(NV_AND_B32, t, mop_imm(km)); + *j = wsop(NV_SHR_U32, t, mop_imm((int32_t)h->lk)); + } else { + *i = wsop(NV_SHR_U32, t, mop_imm((int32_t)h->ln)); + *j = wsop(NV_AND_B32, t, mop_imm((int32_t)((1u << h->ln) - 1u))); + } +} + +static nv_opnd_t wsadr(nv_opnd_t base, nv_opnd_t std, unsigned lay, + nv_opnd_t i, nv_opnd_t j, uint32_t bits) +{ + int32_t esz = (int32_t)(bits / 8u); + return (lay != 0u) ? mma_adr(base, std, j, i, esz) + : mma_adr(base, std, i, j, esz); +} + +static nv_opnd_t wsget(int as, nv_opnd_t a, uint32_t bits) +{ + nv_opnd_t d = wsu(); + + if (bits == 16u) { + nv_opnd_t h = mop_reg(NV_RF_U16, new_vreg(NV_RF_U16)); + em1u(ldop(as, NV_RF_U16, 2u), h, a); + em1u(NV_CVT_U32_U16, d, h); + return d; + } + em1u(ldop(as, NV_RF_U32, bits / 8u), d, a); + return d; +} + +static void wsput(int as, nv_opnd_t a, nv_opnd_t v, uint32_t bits) +{ + nv_opnd_t ops[2] = { a, v }; + + if (bits == 16u) { + ops[1] = mop_reg(NV_RF_U16, new_vreg(NV_RF_U16)); + em1u(NV_CVT_U16_U32, ops[1], v); + } + emit(stop(as, bits == 16u ? NV_RF_U16 : NV_RF_U32, bits / 8u), 0, 2, ops, 0); +} + +static nv_opnd_t wswide(uint32_t kind, nv_opnd_t r, uint32_t off) +{ + nv_opnd_t h, f, g; + + if (kind == 2u) { + nv_opnd_t t = wsop(NV_SHL_B32, r, mop_imm((int32_t)(24u - off))); + return wsop(NV_SHR_S32, t, mop_imm(24)); + } + if (off != 0u) r = wsop(NV_SHR_U32, r, mop_imm((int32_t)off)); + if (kind == 3u) return wsop(NV_AND_B32, r, mop_imm(0xFF)); + h = mop_reg(NV_RF_U16, new_vreg(NV_RF_U16)); + em1u(NV_CVT_U16_U32, h, r); + f = mop_reg(NV_RF_F32, new_vreg(NV_RF_F32)); + if (kind == 1u) { + em1u(NV_CVT_F32_BF16, f, h); + return f; + } + g = mop_reg(NV_RF_F16, new_vreg(NV_RF_F16)); + em1u(NV_MOV_B16, g, h); + em1u(NV_CVT_F32_F16, f, g); + return f; +} + +static nv_opnd_t wsacc(const wsh_t *h, nv_opnd_t r, uint32_t off) +{ + if (h->cb == 16u) return wswide(0u, r, off); + if (h->kind < 2u) return wsbit(r, NV_RF_F32); + return r; +} + +static nv_opnd_t wsnar(const wsh_t *h, nv_opnd_t v) +{ + nv_opnd_t g, u, z; + + if (h->kind >= 2u) return v; + if (h->cb == 32u) return wsbit(v, NV_RF_U32); + g = mop_reg(NV_RF_F16, new_vreg(NV_RF_F16)); + em1u(NV_CVT_F16_F32, g, v); + u = mop_reg(NV_RF_U16, new_vreg(NV_RF_U16)); + em1u(NV_MOV_B16, u, g); + z = wsu(); + em1u(NV_CVT_U32_U16, z, u); + return z; +} + +static void wsld(const bir_inst_t *I) +{ + uint32_t row = (uint32_t)(I->subop & 31u); + unsigned role = ((unsigned)I->subop >> 6) & 3u; + unsigned lay = ((unsigned)I->subop >> 5) & 1u; + uint8_t rf = nv_wmrf(row); + uint8_t n = bir_wmn(row, role); + uint32_t bits, epr, lc = 0u; + wsh_t h; + + if (!wsdim(row, &h)) return; + bits = (role == NV_WM_ROLE_C) ? h.cb : h.ab; + epr = 32u / bits; + if (!wsfit(&h, role, n, epr, &lc)) return; + + int as = pas(I->operands[1]); + nv_opnd_t base = mat_const(I->operands[1], NV_RF_U64); + nv_opnd_t std = mat_const(I->operands[2], NV_RF_U32); + uint16_t tb = mma_frag(rf, n); + + em0(NV_BAR_SYNC); + nv_opnd_t tl = wslane(lc); + for (uint32_t r = 0; r < n; r++) { + nv_opnd_t acc = mop_none(); + + for (uint32_t x = 0; x < epr; x++) { + nv_opnd_t i, j, v; + + wsmap(&h, role, tl, r * epr + x, &i, &j); + v = wsget(as, wsadr(base, std, lay, i, j, bits), bits); + if (x == 0u) { acc = v; continue; } + v = wsop(NV_SHL_B32, v, mop_imm((int32_t)(x * bits))); + acc = wsop(NV_OR_B32, acc, v); + } + em1u(NV_MOV_B32, mop_reg(rf, (uint16_t)(tb + r)), acc); + } + wm_out(I->operands[0], tb, rf, n); +} + +static void wsst(const bir_inst_t *I) +{ + uint32_t row = (uint32_t)(I->subop & 31u); + unsigned lay = ((unsigned)I->subop >> 5) & 1u; + uint8_t rf = nv_wmrf(row); + uint8_t n = bir_wmn(row, NV_WM_ROLE_D); + uint32_t epr, lc = 0u; + wsh_t h; + + if (!wsdim(row, &h)) return; + epr = 32u / h.cb; + if (!wsfit(&h, NV_WM_ROLE_D, n, epr, &lc)) return; + + uint16_t tb = mma_frag(rf, n); + wm_in(I->operands[1], tb, rf, n); + int as = pas(I->operands[0]); + nv_opnd_t base = mat_const(I->operands[0], NV_RF_U64); + nv_opnd_t std = mat_const(I->operands[2], NV_RF_U32); + + em0(NV_BAR_SYNC); + nv_opnd_t tl = wslane(lc); + for (uint32_t r = 0; r < n; r++) { + nv_opnd_t g = wsbit(mop_reg(rf, (uint16_t)(tb + r)), NV_RF_U32); + + for (uint32_t x = 0; x < epr; x++) { + nv_opnd_t i, j; + nv_opnd_t v = (x != 0u) + ? wsop(NV_SHR_U32, g, mop_imm((int32_t)(x * h.cb))) : g; + + wsmap(&h, NV_WM_ROLE_D, tl, r * epr + x, &i, &j); + wsput(as, wsadr(base, std, lay, i, j, h.cb), v, h.cb); + } + } +} + +static nv_opnd_t wsar[16][8], wsbr[16][8], wscr[8], wsdv[16]; + +static void wsbrow(uint8_t rf, uint16_t bbas, uint8_t nb, uint32_t sh, + uint32_t qb, nv_opnd_t c) +{ + nv_opnd_t cl = wsop(NV_SHL_B32, c, mop_imm((int32_t)sh)); + + for (uint32_t q = 0; q < qb; q++) { + nv_opnd_t ln = wsop(NV_ADD_U32, cl, mop_imm((int32_t)q)); + + for (uint32_t j = 0; j < nb; j++) + wsbr[q][j] = wsshf(mop_reg(rf, (uint16_t)(bbas + j)), ln); + } +} + +static nv_opnd_t wsdot(const wsh_t *h, uint32_t la, uint32_t lb, uint32_t e) +{ + uint32_t ea = 32u / h->ab, ed = 32u / h->cb; + nv_opnd_t acc = wsacc(h, wscr[e / ed], (e % ed) * h->cb); + + for (uint32_t k = 0; k < (1u << h->lk); k++) { + uint32_t ka = k & ((1u << la) - 1u); + uint32_t kb = k & ((1u << lb) - 1u); + nv_opnd_t a = wswide(h->kind, wsar[k >> la][ka / ea], (ka % ea) * h->ab); + nv_opnd_t b = wswide(h->kind, wsbr[k >> lb][kb / ea], (kb % ea) * h->ab); + + if (h->kind < 2u) + acc = wsfop(NV_ADD_F32, acc, wsfop(NV_MUL_F32, a, b)); + else + acc = wsop(NV_ADD_S32, acc, wsop(NV_MUL_LO_S32, a, b)); + } + return wsnar(h, acc); +} + +static void wspack(const wsh_t *h, uint8_t rf, uint16_t dbas, uint8_t nc) +{ + uint32_t ed = 32u / h->cb; + + for (uint32_t j = 0; j < nc; j++) { + nv_opnd_t v = wsdv[j * ed]; + + for (uint32_t x = 1; x < ed; x++) + v = wsop(NV_OR_B32, v, wsop(NV_SHL_B32, wsdv[j * ed + x], + mop_imm((int32_t)(x * h->cb)))); + em1u(NV_MOV_B32, mop_reg(rf, (uint16_t)(dbas + j)), v); + } +} + +static void wsmm(const bir_inst_t *I) +{ + uint32_t row = (uint32_t)(I->subop & 31u); + uint8_t rf = nv_wmrf(row); + uint8_t na = bir_wmn(row, NV_WM_ROLE_A); + uint8_t nb = bir_wmn(row, NV_WM_ROLE_B); + uint8_t nc = bir_wmn(row, NV_WM_ROLE_C); + uint32_t la = 0u, lb = 0u, ld = 0u; + wsh_t h; + + if (!wsdim(row, &h)) return; + if (!wsfit(&h, NV_WM_ROLE_A, na, 32u / h.ab, &la) + || !wsfit(&h, NV_WM_ROLE_B, nb, 32u / h.ab, &lb) + || !wsfit(&h, NV_WM_ROLE_C, nc, 32u / h.cb, &ld)) return; + if (h.lk - la > 4u || h.lk - lb > 4u || na > 8u || nb > 8u || nc > 8u + || ld > 4u) { + nv_refuse("a wmma shape the SASS lowering cannot distribute across one warp"); + return; + } + + uint16_t abas = mma_frag(rf, na); + wm_in(I->operands[1], abas, rf, na); + uint16_t bbas = mma_frag(rf, nb); + wm_in(I->operands[2], bbas, rf, nb); + uint16_t cbas = mma_frag(rf, nc); + wm_in(I->operands[3], cbas, rf, nc); + uint16_t dbas = mma_frag(rf, nc); + + em0(NV_BAR_SYNC); + nv_opnd_t tl = wslane(ld); + nv_opnd_t cs = wsop(NV_AND_B32, tl, mop_imm((int32_t)((1u << h.ln) - 1u))); + nv_opnd_t rr = wsop(NV_SHR_U32, tl, mop_imm((int32_t)h.ln)); + nv_opnd_t rl = wsop(NV_SHL_B32, rr, mop_imm((int32_t)(h.lk - la))); + + for (uint32_t q = 0; q < (1u << (h.lk - la)); q++) { + nv_opnd_t ln = wsop(NV_ADD_U32, rl, mop_imm((int32_t)q)); + + for (uint32_t j = 0; j < na; j++) + wsar[q][j] = wsshf(mop_reg(rf, (uint16_t)(abas + j)), ln); + } + for (uint32_t j = 0; j < nc; j++) + wscr[j] = wsbit(mop_reg(rf, (uint16_t)(cbas + j)), NV_RF_U32); + for (uint32_t e = 0; e < (1u << ld); e++) { + wsbrow(rf, bbas, nb, h.lk - lb, 1u << (h.lk - lb), + wsop(NV_ADD_U32, cs, mop_imm((int32_t)e))); + wsdv[e] = wsdot(&h, la, lb, e); + } + wspack(&h, rf, dbas, nc); + wm_out(I->operands[0], dbas, rf, nc); +} + static void is_wld(const bir_inst_t *I) { + if (S.nv->sass != 0u) { wsld(I); return; } uint32_t row = (uint32_t)(I->subop & 31u); unsigned role = ((unsigned)I->subop >> 6) & 3u; unsigned lay = ((unsigned)I->subop >> 5) & 1u; @@ -2159,6 +2704,7 @@ static void is_wld(const bir_inst_t *I) static void is_wst(const bir_inst_t *I) { + if (S.nv->sass != 0u) { wsst(I); return; } uint32_t row = (uint32_t)(I->subop & 31u); unsigned lay = ((unsigned)I->subop >> 5) & 1u; uint8_t rf = nv_wmrf(row); @@ -2174,6 +2720,7 @@ static void is_wst(const bir_inst_t *I) static void is_wmma(const bir_inst_t *I) { + if (S.nv->sass != 0u) { wsmm(I); return; } uint32_t row = (uint32_t)(I->subop & 31u); unsigned al = ((unsigned)I->subop >> 5) & 1u; unsigned bl = ((unsigned)I->subop >> 6) & 1u; @@ -2292,7 +2839,7 @@ static void isel_blk(uint32_t bir_bi) /* ---- Barriers ---- */ case BIR_BARRIER: case BIR_BARRIER_GROUP: - is_barrier(); break; + is_barrier(I); break; case BIR_FENCE: is_fence(I); break; case BIR_NANOSLP: @@ -2300,8 +2847,7 @@ static void isel_blk(uint32_t bir_bi) case BIR_BARRED: is_barred(idx, I); break; case BIR_GRIDBAR: - S.nv->gbar = 1; - em0(NV_GBAR); break; + is_gbar(bir_bi); break; /* ---- Atomics ---- */ case BIR_ATOMIC_ADD: case BIR_ATOMIC_SUB: @@ -2813,28 +3359,36 @@ static int isel_func(uint32_t fi) } /* Pre-create block map */ - for (uint32_t bi = 0; bi < F->num_blocks; bi++) { - uint32_t bir_bi = F->first_block + bi; - S.block_map[bir_bi] = S.nv->num_mblk + bi; + { + uint32_t ex = 0; + for (uint32_t bi = 0; bi < F->num_blocks; bi++) { + uint32_t bir_bi = F->first_block + bi; + + S.block_map[bir_bi] = S.nv->num_mblk + bi + ex; + if (S.nv->sass) ex += GB_NBLK * gbcnt(bir_bi); + S.blk_lst[bir_bi] = S.nv->num_mblk + bi + ex; + } } /* Select instructions per block */ for (uint32_t bi = 0; bi < F->num_blocks; bi++) { uint32_t bir_bi = F->first_block + bi; + nv_mblk_t *MB; if (S.nv->num_mblk >= NV_MAX_MBLK) { nv_cap("machine blocks", (unsigned)NV_MAX_MBLK); break; } - uint32_t mbi = S.nv->num_mblk; - nv_mblk_t *MB = &S.nv->mblks[mbi]; + S.cmb = S.nv->num_mblk; + MB = &S.nv->mblks[S.cmb]; MB->first_inst = S.nv->num_minst; MB->bir_block = bir_bi; isel_blk(bir_bi); + MB = &S.nv->mblks[S.cmb]; MB->num_insts = S.nv->num_minst - MB->first_inst; - S.nv->num_mblk++; + S.nv->num_mblk = S.cmb + 1u; } /* Insert deferred PHI copies into predecessor blocks. @@ -2877,8 +3431,8 @@ int nv_compile(const bir_module_t *bir, nv_module_t *nv) nv->out_len = 0; memset(nv->rc, 0, sizeof(nv->rc)); - memset(nv->val_vreg, 0, sizeof(nv->val_vreg)); - memset(nv->val_rfile, 0, sizeof(nv->val_rfile)); + memset(nv->val_vreg, 0, (size_t)bir->num_insts * sizeof(nv->val_vreg[0])); + memset(nv->val_rfile, 0, (size_t)bir->num_insts * sizeof(nv->val_rfile[0])); fmark(); diff --git a/src/nvidia/lt_nv.c b/src/nvidia/lt_nv.c index 2aee3c9..758d6f1 100644 --- a/src/nvidia/lt_nv.c +++ b/src/nvidia/lt_nv.c @@ -11,13 +11,17 @@ #define NV_ABIVER 8u #define NV_FLAGS 0x06005904u -#define NV_NSYM 4u +#define NV_NSYM 3u #define SH_PROG 1u #define SH_SYMTAB 2u #define SH_STRTAB 3u +#define SH_RELA 4u +#define SH_REL 9u #define SH_NOBITS 8u #define SH_NVINFO 0x70000000u +#define SH_NVCG 0x70000001u +#define SH_NVPRO 0x70000002u #define NV_FRAME 0x11u #define NV_STACK 0x12u @@ -25,6 +29,15 @@ #define EHDR_SZ 64u #define SHDR_SZ 64u #define SYM_SZ 24u +#define RELA_SZ 24u +#define REL_SZ 16u +#define CG_SZ 8u + +static const uint8_t FNINF[20] = { + 0x03u, 0x5Fu, 0x00u, 0x00u, + 0x04u, 0x37u, 0x04u, 0x00u, 0x86u, 0x00u, 0x00u, 0x00u, + 0x04u, 0x66u, 0x04u, 0x00u, 0x03u, 0x00u, 0x00u, 0x00u +}; /* ---- Little-endian writes ---- */ @@ -56,7 +69,7 @@ static uint32_t align(uint32_t v, uint32_t a) /* ---- String tables ---- */ typedef struct { - char s[1024]; + char s[LT_MAX_NVSTR]; uint32_t n; } str_t; @@ -71,7 +84,7 @@ static uint32_t sadd(str_t *t, const char *a, const char *b) if (at + la + lb + 2u > sizeof t->s) return 0u; memcpy(t->s + at, a, la); if (b != NULL) memcpy(t->s + at + la, b, lb); - t->s[at + la + lb] = '\0'; + t->s[at + la + lb] = 0; t->n = at + (uint32_t)(la + lb) + 1u; return at; } @@ -130,6 +143,11 @@ static uint32_t nvinfo(uint8_t *p, const lt_nvk_t *k, uint32_t symi) assert(p != NULL && k != NULL); + if (k->isfn != 0u) { + memcpy(p, FNINF, sizeof FNINF); + return (uint32_t)sizeof FNINF; + } + for (uint32_t i = 0; i < k->np; i++) { uint32_t w = k->psz[i]; @@ -153,95 +171,237 @@ static uint32_t nvinfo(uint8_t *p, const lt_nvk_t *k, uint32_t symi) return n; } -static uint32_t ginfo(uint8_t *p, const lt_nvk_t *k, uint32_t symi) +/* ---- Layout ---- */ + +typedef struct { + uint32_t text, con, ikr, kern, shr; + uint32_t otext, ocon, oikr, zcon, zikr, ishr; + uint32_t itext, icon, iikr, fsym; + uint32_t nrl, nrla, irel, irla, orel, orla, rnm, anm; + uint8_t isfn; +} lkrn_t; + +typedef struct { + uint32_t nm[8]; + uint32_t off[8]; + lkrn_t k[LT_MAX_NVKRN]; + uint32_t inf, sym, str, ssh, cgnm, prnm; + uint32_t oinf, osym, ostr, ossh, osh, nsym; + uint32_t zinf, total, iinf, isym, istr, issh, nsect; + uint32_t ng, ig, gsyi, og, gtot, gnm; + uint32_t icg, ocg, zcg, ipro, opro, zpro, nedge, nfn; + uint32_t gsym[LT_MAX_NVGLB]; +} lay_t; + +static uint32_t ginfo(uint8_t *p, const lay_t *L, const lt_nvk_t *k, + uint32_t nk) { uint32_t n = 0; - assert(p != NULL && k != NULL); - - p[n++] = 0x04u; p[n++] = NV_FRAME; w16(p + n, 8u); n += 2u; - w32(p + n, symi); n += 4u; - w32(p + n, k->lmem); n += 4u; + assert(p != NULL && (k != NULL || nk == 0u)); - p[n++] = 0x04u; p[n++] = NV_STACK; w16(p + n, 8u); n += 2u; - w32(p + n, symi); n += 4u; - w32(p + n, k->lmem); n += 4u; + for (uint32_t i = 0; i < nk; i++) { + p[n++] = 0x04u; p[n++] = NV_FRAME; w16(p + n, 8u); n += 2u; + w32(p + n, L->k[i].fsym); n += 4u; + w32(p + n, k[i].lmem); n += 4u; + } + for (uint32_t i = 0; i < nk; i++) { + if (k[i].isfn != 0u) continue; + p[n++] = 0x04u; p[n++] = NV_STACK; w16(p + n, 8u); n += 2u; + w32(p + n, L->k[i].fsym); n += 4u; + w32(p + n, k[i].lmem); n += 4u; + } return n; } -/* ---- Layout ---- */ +static void plrel(lay_t *L, const lt_nvk_t *k, uint32_t nk) +{ + for (uint32_t i = 0; i < nk; i++) { + lkrn_t *K = &L->k[i]; + + K->nrl = 0u; + K->nrla = 0u; + if (K->isfn != 0u) L->nfn++; + for (uint32_t j = 0; j < k[i].nrel; j++) { + if (k[i].rel[j].kind == (uint8_t)LT_NV_RRET) K->nrla++; + else K->nrl++; + if (k[i].rel[j].kind == (uint8_t)LT_NV_RTGT) L->nedge++; + } + } +} -typedef struct { - uint32_t nm[8]; - uint32_t off[8]; - uint32_t text, con, ikr, inf, sym, str, ssh, kern, shr; - uint32_t otext, ocon, oikr, oinf, osym, ostr, ossh, osh; - uint32_t zcon, zikr, zinf, total, isym, istr, issh, ishr, nsect; -} lay_t; +static lt_res_t plkrn(lay_t *L, str_t *sst, str_t *st, const lt_nvk_t *k, + uint32_t nk, uint32_t *op) +{ + uint32_t o = *op, ns = 0u, sx = 1u, yx = 1u; + + assert(L != NULL && (k != NULL || nk == 0u)); + + for (uint32_t i = 0; i < nk; i++) { + lkrn_t *K = &L->k[i]; + + K->isfn = k[i].isfn; + K->text = sadd(sst, ".text.", k[i].name); + K->ikr = sadd(sst, ".nv.info.", k[i].name); + K->kern = sadd(st, k[i].name, NULL); + K->itext = sx++; + if (K->isfn == 0u) { + K->con = sadd(sst, ".nv.constant0.", k[i].name); + K->icon = sx++; + if (K->con == 0u) return LT_EFULL; + } + K->iikr = sx++; + if (K->text == 0u || K->ikr == 0u || K->kern == 0u) return LT_EFULL; + K->zcon = LT_NV_PBASE + pblock(&k[i]); + K->zikr = (K->isfn != 0u) ? (uint32_t)sizeof FNINF + : k[i].np * 16u + 16u; + K->otext = align(o, 128u); + K->ocon = align(K->otext + k[i].clen, 4u); + K->oikr = align(K->ocon + (K->isfn != 0u ? 0u : K->zcon), 4u); + o = K->oikr + K->zikr; + yx++; + if (K->isfn == 0u) yx++; + K->fsym = yx++; + } + L->iinf = sx; + L->nsym = yx; + for (uint32_t i = 0; i < nk; i++) + if (k[i].smem != 0u) L->k[i].ishr = L->iinf + 1u + lt_nv_noten + ns++; + L->isym = L->iinf + 1u + lt_nv_noten + ns; + L->istr = L->isym + 1u; + L->issh = L->istr + 1u; + *op = o; + return LT_OK; +} + +static lt_res_t plglb(lay_t *L, str_t *sst, str_t *st, const lt_nvgd_t *gd, + uint32_t *next) +{ + if (L->ng == 0u) return LT_OK; + L->ig = (*next)++; + L->gnm = sadd(sst, ".nv.global.init", NULL); + L->gsyi = L->nsym; + L->nsym += L->ng; + L->gtot = gd->gtot; + for (uint32_t i = 0; i < L->ng; i++) { + L->gsym[i] = sadd(st, gd->g[i].name, NULL); + if (L->gsym[i] == 0u) return LT_EFULL; + } + return LT_OK; +} + +static lt_res_t plsec(lay_t *L, str_t *sst, str_t *st, const lt_nvk_t *k, + uint32_t nk, const lt_nvgd_t *gd) +{ + uint32_t next = L->issh + 1u; + lt_res_t rc; + + assert(L != NULL && (k != NULL || nk == 0u)); + + rc = plglb(L, sst, st, gd, &next); + if (rc != LT_OK) return rc; + for (uint32_t i = 0; i < nk; i++) { + if (L->k[i].nrl != 0u) { + L->k[i].irel = next++; + L->k[i].rnm = sadd(sst, ".rel.text.", k[i].name); + if (L->k[i].rnm == 0u) return LT_EFULL; + } + if (L->k[i].nrla != 0u) { + L->k[i].irla = next++; + L->k[i].anm = sadd(sst, ".rela.text.", k[i].name); + if (L->k[i].anm == 0u) return LT_EFULL; + } + } + if (L->nedge != 0u) { + L->icg = next++; + L->cgnm = sadd(sst, ".nv.callgraph", NULL); + L->zcg = CG_SZ * (L->nedge + 4u); + if (L->cgnm == 0u) return LT_EFULL; + } + if (L->nfn != 0u) { + L->ipro = next++; + L->prnm = sadd(sst, ".nv.prototype", NULL); + L->zpro = CG_SZ * L->nfn; + if (L->prnm == 0u) return LT_EFULL; + } + L->nsect = next; + return LT_OK; +} + +static void plofs(lay_t *L, const str_t *sst, const str_t *st, + const lt_nvk_t *k, uint32_t nk, uint32_t o) +{ + uint32_t p, nen = 0u; + + assert(L != NULL && (k != NULL || nk == 0u)); + + o = align(o, 4u); + for (uint32_t i = 0; i < lt_nv_noten; i++) { + L->off[i] = align(o, lt_nv_note[i].align); + o = L->off[i] + lt_nv_note[i].len; + } + for (uint32_t i = 0; i < nk; i++) if (k[i].isfn == 0u) nen++; + L->zinf = 12u * nk + 12u * nen; + L->oinf = o; + L->osym = align(L->oinf + L->zinf, 8u); + L->ostr = L->osym + L->nsym * SYM_SZ; + L->ossh = L->ostr + st->n; + p = align(L->ossh + sst->n, 8u); + if (L->ng > 0u) { L->og = p; p = align(L->og + L->gtot, 8u); } + for (uint32_t i = 0; i < nk; i++) { + if (L->k[i].nrl != 0u) { + L->k[i].orel = p; + p = align(p + L->k[i].nrl * REL_SZ, 8u); + } + if (L->k[i].nrla != 0u) { + L->k[i].orla = p; + p = align(p + L->k[i].nrla * RELA_SZ, 8u); + } + } + if (L->nedge != 0u) { L->ocg = p; p = align(p + L->zcg, 8u); } + if (L->nfn != 0u) { L->opro = p; p = align(p + L->zpro, 8u); } + L->osh = p; + L->total = L->osh + L->nsect * SHDR_SZ; +} static lt_res_t plan(lay_t *L, str_t *sst, str_t *st, const lt_nvk_t *k, - uint32_t clen) + uint32_t nk, const lt_nvgd_t *gd) { - assert(L != NULL && k != NULL); - assert(sst != NULL && st != NULL); + uint32_t o = EHDR_SZ; + lt_res_t rc; - if (lt_nv_noten > 8u) return LT_EFULL; + assert(L != NULL && (k != NULL || nk == 0u)); + assert(sst != NULL && st != NULL); + if (lt_nv_noten > 8u || nk > LT_MAX_NVKRN) return LT_EFULL; memset(L, 0, sizeof *L); + L->ng = (gd != NULL) ? gd->ng : 0u; + if (L->ng > LT_MAX_NVGLB) return LT_EFULL; sst->n = 1u; st->n = 1u; - - L->text = sadd(sst, ".text.", k->name); - L->con = sadd(sst, ".nv.constant0.", k->name); - L->ikr = sadd(sst, ".nv.info.", k->name); L->inf = sadd(sst, ".nv.info", NULL); L->sym = sadd(sst, ".symtab", NULL); L->str = sadd(sst, ".strtab", NULL); L->ssh = sadd(sst, ".shstrtab", NULL); - L->kern = sadd(st, k->name, NULL); for (uint32_t i = 0; i < lt_nv_noten; i++) L->nm[i] = sadd(sst, lt_nv_note[i].name, NULL); - if (k->smem != 0u) L->shr = sadd(sst, ".nv.shared.", k->name); - L->ishr = (k->smem != 0u) ? 5u + lt_nv_noten : 0u; - L->nsect = 8u + lt_nv_noten + ((k->smem != 0u) ? 1u : 0u); - L->isym = 5u + lt_nv_noten + ((k->smem != 0u) ? 1u : 0u); - L->istr = L->isym + 1u; - L->issh = L->istr + 1u; - - L->zcon = LT_NV_PBASE + pblock(k); - L->zikr = k->np * 16u + 16u; - L->zinf = 24u; - - L->otext = align(EHDR_SZ, 128u); - L->ocon = align(L->otext + clen, 4u); - L->oikr = align(L->ocon + L->zcon, 4u); - L->osym = align(L->oikr + L->zikr, 4u); - - for (uint32_t i = 0; i < lt_nv_noten; i++) { - L->off[i] = align(L->osym, lt_nv_note[i].align); - L->osym = L->off[i] + lt_nv_note[i].len; - } - L->oinf = L->osym; - L->osym = align(L->oinf + L->zinf, 8u); - L->ostr = L->osym + NV_NSYM * SYM_SZ; - L->ossh = L->ostr + st->n; - L->osh = align(L->ossh + sst->n, 8u); - L->total = L->osh + L->nsect * SHDR_SZ; + rc = plkrn(L, sst, st, k, nk, &o); + if (rc != LT_OK) return rc; + plrel(L, k, nk); + rc = plsec(L, sst, st, k, nk, gd); + if (rc != LT_OK) return rc; + plofs(L, sst, st, k, nk, o); return LT_OK; } /* ---- Headers ---- */ -static void heads(uint8_t *out, const lay_t *L, const lt_nvk_t *k, - uint32_t clen, uint32_t zst, uint32_t zss) +static void nvehdr(uint8_t *out, const lay_t *L) { - uint8_t *sh = out + L->osh; - assert(out != NULL && L != NULL); - assert(k != NULL); - out[0] = 0x7Fu; out[1] = 'E'; out[2] = 'L'; out[3] = 'F'; + out[0] = 0x7Fu; out[1] = 0x45u; out[2] = 0x4Cu; out[3] = 0x46u; out[4] = 2u; out[5] = 1u; out[6] = 1u; out[7] = NV_OSABI; out[8] = NV_ABIVER; @@ -254,75 +414,224 @@ static void heads(uint8_t *out, const lay_t *L, const lt_nvk_t *k, w16(out + 58, SHDR_SZ); w16(out + 60, L->nsect); w16(out + 62, L->issh); +} + +static void hxtra(uint8_t *sh, const lay_t *L, uint32_t nk) +{ + for (uint32_t i = 0; i < nk; i++) { + const lkrn_t *K = &L->k[i]; + + if (K->nrl != 0u) + shdr(sh + K->irel * SHDR_SZ, K->rnm, SH_REL, 0x40u, + K->orel, K->nrl * REL_SZ, L->isym, K->itext, 8u, REL_SZ); + if (K->nrla != 0u) + shdr(sh + K->irla * SHDR_SZ, K->anm, SH_RELA, 0x40u, + K->orla, K->nrla * RELA_SZ, L->isym, K->itext, 8u, RELA_SZ); + } + if (L->nedge != 0u) + shdr(sh + L->icg * SHDR_SZ, L->cgnm, SH_NVCG, 0u, L->ocg, L->zcg, + L->isym, 0u, 4u, CG_SZ); + if (L->nfn != 0u) + shdr(sh + L->ipro * SHDR_SZ, L->prnm, SH_NVPRO, 0u, L->opro, L->zpro, + L->isym, 0u, 4u, CG_SZ); + if (L->ng > 0u) + shdr(sh + L->ig * SHDR_SZ, L->gnm, SH_PROG, 0x3u, L->og, L->gtot, + 0u, 0u, 8u, 0u); +} + +static void heads(uint8_t *out, const lay_t *L, const lt_nvk_t *k, + uint32_t nk, uint32_t zst, uint32_t zss) +{ + uint8_t *sh = out + L->osh; + + assert(out != NULL && L != NULL); + assert(k != NULL || nk == 0u); + nvehdr(out, L); shdr(sh, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u); - shdr(sh + SHDR_SZ, L->text, SH_PROG, 6u, L->otext, clen, L->isym, - (k->nreg << 24) | 3u, 128u, 0u); - shdr(sh + 2u * SHDR_SZ, L->con, SH_PROG, 0x42u, L->ocon, L->zcon, 0u, - 1u, 4u, 0u); - shdr(sh + 3u * SHDR_SZ, L->ikr, SH_NVINFO, 0x40u, L->oikr, L->zikr, - L->isym, 1u, 4u, 0u); - shdr(sh + 4u * SHDR_SZ, L->inf, SH_NVINFO, 0u, L->oinf, L->zinf, L->isym, - 0u, 4u, 0u); + for (uint32_t i = 0; i < nk; i++) { + const lkrn_t *K = &L->k[i]; + + shdr(sh + K->itext * SHDR_SZ, K->text, SH_PROG, 6u, K->otext, + k[i].clen, L->isym, (k[i].nreg << 24) | K->fsym, 128u, 0u); + if (K->isfn == 0u) + shdr(sh + K->icon * SHDR_SZ, K->con, SH_PROG, 0x42u, K->ocon, + K->zcon, 0u, K->itext, 4u, 0u); + shdr(sh + K->iikr * SHDR_SZ, K->ikr, SH_NVINFO, 0x40u, K->oikr, + K->zikr, L->isym, K->itext, 4u, 0u); + } + shdr(sh + L->iinf * SHDR_SZ, L->inf, SH_NVINFO, 0u, L->oinf, L->zinf, + L->isym, 0u, 4u, 0u); for (uint32_t i = 0; i < lt_nv_noten; i++) { const lt_nvn_t *v = <_nv_note[i]; - shdr(sh + (5u + i) * SHDR_SZ, L->nm[i], v->type, v->flags, L->off[i], - v->len, i == 1u ? 5u : 0u, v->info, v->align, 0u); + shdr(sh + (L->iinf + 1u + i) * SHDR_SZ, L->nm[i], v->type, v->flags, + L->off[i], v->len, i == 1u ? L->iinf + 1u : 0u, v->info, + v->align, 0u); } /* per probe obj/corpus/test_shared2d.cubin */ - if (L->ishr != 0u) - shdr(sh + L->ishr * SHDR_SZ, L->shr, SH_NOBITS, 0x43u, L->osym, - k->smem, 0u, 1u, 4u, 0u); + for (uint32_t i = 0; i < nk; i++) + if (L->k[i].ishr != 0u) + shdr(sh + L->k[i].ishr * SHDR_SZ, L->k[i].shr, SH_NOBITS, 0x43u, + L->osym, k[i].smem, 0u, L->k[i].itext, 4u, 0u); shdr(sh + L->isym * SHDR_SZ, L->sym, SH_SYMTAB, 0u, L->osym, - NV_NSYM * SYM_SZ, L->istr, 3u, 8u, SYM_SZ); + L->nsym * SYM_SZ, L->istr, L->nsym, 8u, SYM_SZ); shdr(sh + L->istr * SHDR_SZ, L->str, SH_STRTAB, 0u, L->ostr, zst, 0u, 0u, 1u, 0u); shdr(sh + L->issh * SHDR_SZ, L->ssh, SH_STRTAB, 0u, L->ossh, zss, 0u, 0u, 1u, 0u); + hxtra(sh, L, nk); } /* ---- Writing ---- */ +static uint32_t rsymof(const lay_t *L, const lt_nvk_t *k, uint32_t i, + uint32_t j) +{ + const lt_nvrl_t *r = &k[i].rel[j]; + + if (r->kind == (uint8_t)LT_NV_RTGT) + return (r->gi < LT_MAX_NVKRN) ? L->k[r->gi].fsym : 0u; + if (r->kind == (uint8_t)LT_NV_RRET) return L->k[i].fsym; + return L->gsyi + r->gi; +} + +static void grel(uint8_t *out, const lay_t *L, const lt_nvk_t *k, uint32_t nk) +{ + assert(out != NULL && L != NULL); + assert(k != NULL || nk == 0u); + + for (uint32_t i = 0; i < nk; i++) { + uint8_t *r = out + L->k[i].orel; + uint8_t *a = out + L->k[i].orla; + uint32_t nr = 0u, na = 0u; + + for (uint32_t j = 0; j < k[i].nrel; j++) { + const lt_nvrl_t *e = &k[i].rel[j]; + uint32_t s = rsymof(L, k, i, j); + uint32_t ty; + + if (e->kind == (uint8_t)LT_NV_RRET) { + ty = (e->hi != 0u) ? 0x39u : 0x38u; + w64(a + na * RELA_SZ, e->at); + w64(a + na * RELA_SZ + 8u, ((uint64_t)s << 32) | ty); + w64(a + na * RELA_SZ + 16u, e->add); + na++; + continue; + } + ty = (e->kind == (uint8_t)LT_NV_RTGT) + ? 0x3Au : ((e->hi != 0u) ? 0x39u : 0x38u); + w64(r + nr * REL_SZ, e->at); + w64(r + nr * REL_SZ + 8u, ((uint64_t)s << 32) | ty); + nr++; + } + } +} + +static void gcgph(uint8_t *out, const lay_t *L, const lt_nvk_t *k, uint32_t nk) +{ + uint8_t *p = out + L->ocg; + uint32_t n = 1u; + + if (L->nedge == 0u) return; + w32(p + 0, 0u); + w32(p + 4, 0xFFFFFFFFu); + for (uint32_t i = 0; i < nk; i++) + for (uint32_t j = 0; j < k[i].nrel; j++) { + if (k[i].rel[j].kind != (uint8_t)LT_NV_RTGT) continue; + w32(p + n * CG_SZ, L->k[i].fsym); + w32(p + n * CG_SZ + 4u, rsymof(L, k, i, j)); + n++; + } + w32(p + n * CG_SZ, 0u); w32(p + n * CG_SZ + 4u, 0xFFFFFFFEu); n++; + w32(p + n * CG_SZ, 0u); w32(p + n * CG_SZ + 4u, 0xFFFFFFFDu); n++; + w32(p + n * CG_SZ, 0u); w32(p + n * CG_SZ + 4u, 0xFFFFFFFCu); +} + +static void gproto(uint8_t *out, const lay_t *L, const lt_nvk_t *k, + uint32_t nk) +{ + uint8_t *p = out + L->opro; + uint32_t n = 0u; + + if (L->nfn == 0u) return; + for (uint32_t i = 0; i < nk; i++) { + if (k[i].isfn == 0u) continue; + w32(p + n * CG_SZ, L->k[i].fsym); + w32(p + n * CG_SZ + 4u, 1u); + n++; + } +} + +/* per probe obj/corpus */ +static void gsyms(uint8_t *out, const lay_t *L, const lt_nvk_t *k, + uint32_t nk) +{ + for (uint32_t i = 0; i < nk; i++) { + const lkrn_t *K = &L->k[i]; + uint32_t t = K->fsym - (K->isfn != 0u ? 1u : 2u); + + sym(out + L->osym + t * SYM_SZ, 0u, 0x03u, 0u, + (uint16_t)K->itext, 0u, 0u); + if (K->isfn == 0u) + sym(out + L->osym + (t + 1u) * SYM_SZ, 0u, 0x03u, 0u, + (uint16_t)K->icon, 0u, 0u); + sym(out + L->osym + K->fsym * SYM_SZ, K->kern, 0x02u, + (uint8_t)(K->isfn != 0u ? 0x00u : 0x10u), + (uint16_t)K->itext, 0u, k[i].clen); + } +} + lt_res_t lt_nvcub(uint8_t *out, uint32_t max, uint32_t *len, const lt_nvk_t *k, - const uint8_t *code, uint32_t clen) + uint32_t nk, const lt_nvgd_t *gd) { static str_t sst, st; static lay_t L; assert(out != NULL && len != NULL); - assert(k != NULL && k->name != NULL); - - if (clen == 0u || (clen & 15u) != 0u) return LT_EBAD; - if (strlen(k->name) + 1u > LT_MAX_NVNAME) return LT_EBAD; - if (k->nreg > 255u || k->np > LT_MAX_NVPRM) return LT_EBAD; + assert(k != NULL || nk == 0u); + + if (nk > LT_MAX_NVKRN) return LT_EFULL; + for (uint32_t i = 0; i < nk; i++) { + if (k[i].name == NULL || k[i].code == NULL) return LT_EBAD; + if (k[i].clen == 0u || (k[i].clen & 15u) != 0u) return LT_EBAD; + if (strlen(k[i].name) + 1u > LT_MAX_NVNAME) return LT_EBAD; + if (k[i].nreg > 255u || k[i].np > LT_MAX_NVPRM) return LT_EBAD; + } - memset(&sst, 0, sizeof sst); - memset(&st, 0, sizeof st); - if (plan(&L, &sst, &st, k, clen) != LT_OK) return LT_EFULL; + if (plan(&L, &sst, &st, k, nk, gd) != LT_OK) return LT_EFULL; if (L.total > max || L.total > LT_MAX_NVIMG) return LT_EFULL; memset(out, 0, L.total); - memcpy(out + L.otext, code, clen); - (void)nvinfo(out + L.oikr, k, 3u); - (void)ginfo(out + L.oinf, k, 3u); + for (uint32_t i = 0; i < nk; i++) { + memcpy(out + L.k[i].otext, k[i].code, k[i].clen); + (void)nvinfo(out + L.k[i].oikr, &k[i], L.k[i].fsym - 1u); + } + (void)ginfo(out + L.oinf, &L, k, nk); for (uint32_t i = 0; i < lt_nv_noten; i++) memcpy(out + L.off[i], lt_nv_note[i].data, lt_nv_note[i].len); - sym(out + L.osym + 1u * SYM_SZ, 0u, 0x03u, 0u, 1u, 0u, 0u); - sym(out + L.osym + 2u * SYM_SZ, 0u, 0x03u, 0u, 2u, 0u, 0u); - /* per probe obj/corpus */ - sym(out + L.osym + 3u * SYM_SZ, L.kern, 0x02u, 0x10u, 1u, 0u, clen); + gsyms(out, &L, k, nk); + + if (L.ng > 0u) { + memcpy(out + L.og, gd->bytes, L.gtot); + for (uint32_t i = 0; i < L.ng; i++) + sym(out + L.osym + (L.gsyi + i) * SYM_SZ, L.gsym[i], 0x01u, 0u, + (uint16_t)L.ig, gd->g[i].off, gd->g[i].size); + } + grel(out, &L, k, nk); + gcgph(out, &L, k, nk); + gproto(out, &L, k, nk); memcpy(out + L.ostr, st.s, st.n); memcpy(out + L.ossh, sst.s, sst.n); - heads(out, &L, k, clen, st.n, sst.n); + heads(out, &L, k, nk, st.n, sst.n); *len = L.total; return LT_OK; } diff --git a/src/nvidia/lt_nv.h b/src/nvidia/lt_nv.h index 86c4ddc..e21af49 100644 --- a/src/nvidia/lt_nv.h +++ b/src/nvidia/lt_nv.h @@ -18,10 +18,12 @@ typedef enum { /* ---- Ceilings ---- */ -#define LT_MAX_NVIMG (1024u * 1024u) +#define LT_MAX_NVIMG (64u * 1024u * 1024u) +#define LT_MAX_NVKRN 4096u +#define LT_MAX_NVSTR (LT_MAX_NVKRN * 512u) #define LT_MAX_NVNAME 96u #define LT_NV_PBASE 0x160u -#define LT_MAX_NVPRM 32u +#define LT_MAX_NVPRM 64u #define LT_MAX_NVCODE (256u * 1024u) #define LT_MAX_NVREG 253u #define LT_MAX_NVFIX 4096u @@ -58,6 +60,11 @@ typedef enum { #define LT_NV_PE 6u #define LT_MAX_NVXD 4u +#define LT_NV_R20 20u +#define LT_NV_R21 21u +#define LT_NV_ARG0 4u +#define LT_NV_NARG 12u + #define LT_NV_PT 7u #define LT_NV_URZ 63u #define LT_NV_RZ 255u @@ -96,6 +103,36 @@ extern const lt_nvn_t lt_nv_note[]; extern const uint32_t lt_nv_noten; extern const char *const lt_nv_nsrc; + +#define LT_MAX_NVGLB 1024u +#define LT_MAX_NVGBY (1024u * 1024u) +#define LT_MAX_NVREL 65536u + +#define LT_NV_RGLB 0u +#define LT_NV_RRET 1u +#define LT_NV_RTGT 2u + +typedef struct { + uint32_t at; + uint32_t gi; + uint32_t add; + uint8_t hi; + uint8_t kind; +} lt_nvrl_t; + +typedef struct { + const char *name; + uint32_t off; + uint32_t size; +} lt_nvg_t; + +typedef struct { + const lt_nvg_t *g; + uint32_t ng; + const uint8_t *bytes; + uint32_t gtot; +} lt_nvgd_t; + /* ---- What a kernel needs around it ---- */ typedef struct { @@ -107,6 +144,11 @@ typedef struct { uint32_t np; uint32_t wave; uint32_t mthr; + const uint8_t *code; + uint32_t clen; + const lt_nvrl_t *rel; + uint32_t nrel; + uint8_t isfn; } lt_nvk_t; /* ---- Scoreboards and branch targets ---- */ @@ -192,6 +234,8 @@ typedef struct { uint32_t nst; lt_nbs_t body; lt_nbs_t tmp; + lt_nbs_t ext[LT_MAX_NVRG]; + lt_nbs_t sl[LT_NV_NJB]; } lt_ncf_t; /* ---- Terminator kinds ---- */ @@ -267,6 +311,8 @@ void lt_nvsrm(uint64_t *w, uint32_t rnd); void lt_nvf2f(uint64_t *w, uint32_t d, uint32_t s, uint32_t dsz, uint32_t ssz, uint32_t rnd); void lt_nvhfm(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t c); +void lt_nvh2f(uint64_t *w, uint32_t d, uint32_t s); +void lt_nvf2h(uint64_t *w, uint32_t d, uint32_t s, uint32_t bf); void lt_nvi2f(uint64_t *w, uint32_t d, uint32_t s, uint32_t sgn, uint32_t dsz, uint32_t ssz); void lt_nvf2i(uint64_t *w, uint32_t d, uint32_t s, uint32_t sgn, uint32_t dsz, @@ -294,7 +340,10 @@ void lt_nvbar(uint64_t *w, uint32_t idx); void lt_nvrb(uint64_t *w, uint32_t idx); void lt_nvwait(uint64_t *w, uint32_t mask); void lt_nvsyn(uint64_t *w); +void lt_nvnsl(uint64_t *w, uint32_t s); void lt_nvexit(uint64_t *w); +void lt_nvcall(uint64_t *w); +void lt_nvret(uint64_t *w, uint32_t ra); void lt_nvbra(uint64_t *w, int32_t rel); void lt_nvbrp(uint64_t *w, int32_t rel, uint32_t p, uint32_t nt); void lt_nvnop(uint64_t *w); @@ -305,6 +354,6 @@ void lt_nvbrk(uint64_t *w, uint32_t bar, uint32_t p, uint32_t nt); void lt_nvbrs(uint64_t *w, uint32_t rb, uint32_t cnt); lt_res_t lt_nvcub(uint8_t *out, uint32_t max, uint32_t *len, - const lt_nvk_t *k, const uint8_t *code, uint32_t clen); + const lt_nvk_t *k, uint32_t nk, const lt_nvgd_t *gd); #endif /* LT_NV_H */ diff --git a/src/nvidia/lt_nvcf.c b/src/nvidia/lt_nvcf.c index 56a984b..c1a601b 100644 --- a/src/nvidia/lt_nvcf.c +++ b/src/nvidia/lt_nvcf.c @@ -419,6 +419,9 @@ static lt_res_t leaves(lt_ncf_t *c, uint32_t r) assert(c != NULL); assert(r < c->nrg); + c->ext[r] = c->body; + bsadd(&c->ext[r], g->at); + if (g->j < c->nbb) bsadd(&c->ext[r], g->j); for (uint32_t x = 0; x < c->nbb; x++) { if (!bshas(&c->body, x)) continue; if (x < c->rg[r].lo) c->rg[r].lo = (uint16_t)x; @@ -652,15 +655,28 @@ static lt_res_t iregn(lt_ncf_t *c, uint32_t bb) /* ---- Barrier slots ---- */ -static lt_res_t slots(lt_ncf_t *c) +static int bsmeet(const lt_nbs_t *a, const lt_nbs_t *b) { - uint32_t end[LT_NV_NJB]; - uint32_t used[LT_NV_NJB]; + assert(a != NULL && b != NULL); + for (uint32_t i = 0; i < LT_NV_NBW; i++) + if ((a->w[i] & b->w[i]) != 0ull) return 1; + return 0; +} + +static void bsor(lt_nbs_t *d, const lt_nbs_t *s) +{ + assert(d != NULL && s != NULL); + + for (uint32_t i = 0; i < LT_NV_NBW; i++) d->w[i] |= s->w[i]; +} + +static lt_res_t slots(lt_ncf_t *c) +{ assert(c != NULL); assert(c->nrg <= LT_MAX_NVRG); - memset(used, 0, sizeof used); + for (uint32_t s = 0; s < LT_NV_NJB; s++) bsclr(&c->sl[s]); for (uint32_t r = 0; r < c->nrg; r++) { uint32_t i; @@ -669,17 +685,17 @@ static lt_res_t slots(lt_ncf_t *c) c->rord[i] = (uint16_t)r; } for (uint32_t i = 0; i < c->nrg; i++) { - lt_nrg_t *g = &c->rg[c->rord[i]]; + uint32_t r = c->rord[i]; + lt_nrg_t *g = &c->rg[r]; uint32_t s; for (s = 0; s < LT_NV_NJB; s++) - if (used[s] == 0u || end[s] <= g->lo) break; + if (!bsmeet(&c->sl[s], &c->ext[r])) break; if (s >= LT_NV_NJB) return LT_WHY(LT_W_TOOJOIN, LT_EHOLE, NULL, c->bs[g->at], LT_NV_NJB + 1u, LT_NV_NJB); g->slot = (uint8_t)s; - used[s] = 1u; - end[s] = g->hi; + bsor(&c->sl[s], &c->ext[r]); } return LT_OK; } diff --git a/src/nvidia/lt_nvi.c b/src/nvidia/lt_nvi.c index dd8b984..75da347 100644 --- a/src/nvidia/lt_nvi.c +++ b/src/nvidia/lt_nvi.c @@ -627,6 +627,18 @@ lt_nvsyn(uint64_t *w) lt_nvput(w, 109u, 109u, 1u); } +void +lt_nvnsl(uint64_t *w, uint32_t s) +{ + assert(w != NULL); + assert(s < 256u); + + head(w, 0x15Du, 1u); + lt_nvput(w, 39u, 32u, s); + lt_nvput(w, 89u, 87u, LT_NV_PT); + lt_nvput(w, 109u, 109u, 1u); +} + void lt_nvbrs(uint64_t *w, uint32_t rb, uint32_t cnt) { @@ -690,6 +702,28 @@ lt_nvnop(uint64_t *w) head(w, 0x918u, 0u); } +void +lt_nvcall(uint64_t *w) +{ + assert(w != NULL); + + head(w, 0x143u, 4u); + lt_nvput(w, 86u, 86u, 1u); + lt_nvput(w, 89u, 87u, LT_NV_PT); +} + +void +lt_nvret(uint64_t *w, uint32_t ra) +{ + assert(w != NULL); + assert(ra < 256u); + + head(w, 0x150u, 4u); + lt_nvput(w, 31u, 24u, ra); + lt_nvput(w, 86u, 85u, 3u); + lt_nvput(w, 89u, 87u, LT_NV_PT); +} + /* ---- Convergence ---- */ void @@ -898,6 +932,33 @@ lt_nvf2f(uint64_t *w, uint32_t d, uint32_t s, uint32_t dsz, uint32_t ssz, lt_nvput(w, 85u, 84u, ssz); } +void +lt_nvh2f(uint64_t *w, uint32_t d, uint32_t s) +{ + assert(d < 256u && s < 256u); + + head(w, 0x030u, 1u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 31u, 24u, LT_NV_RZ); + lt_nvput(w, 39u, 32u, s); + lt_nvput(w, 61u, 60u, 2u); + lt_nvput(w, 72u, 72u, 1u); + lt_nvput(w, 78u, 78u, 1u); +} + +void +lt_nvf2h(uint64_t *w, uint32_t d, uint32_t s, uint32_t bf) +{ + assert(d < 256u && s < 256u && bf < 2u); + + head(w, 0x03Eu, 1u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 31u, 24u, LT_NV_RZ); + lt_nvput(w, 39u, 32u, s); + lt_nvput(w, 71u, 64u, LT_NV_RZ); + lt_nvput(w, 76u, 76u, bf); +} + void lt_nvhfm(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t c) { diff --git a/src/nvidia/nv_be.c b/src/nvidia/nv_be.c index 67f9cb7..92bd076 100644 --- a/src/nvidia/nv_be.c +++ b/src/nvidia/nv_be.c @@ -48,6 +48,7 @@ static int nv_isel(const struct bir_module *M, const be_cfg_t *cfg, (void)cfg; nv_module_t *nvm = calloc(1, sizeof(*nvm)); if (nvm == NULL) return BE_ENOMEM; + nvm->sass = (uint8_t)(p->sass | p->cubin); if (nv_compile((const bir_module_t *)M, nvm) != BC_OK || nv_vchk(nvm) != BC_OK) { free(nvm); @@ -79,7 +80,7 @@ const be_desc_t be_ptx = { .feats = BE_F_SIMT | BE_F_ATOMIC | BE_F_SHARED | BE_F_WARP | BE_F_BARRIER | BE_F_DIV | BE_F_SCRATCH | BE_F_TRANSC | BE_F_F16 | BE_F_F64 | BE_F_BF16 | BE_F_NOCALL - | BE_F_BYTES, + | BE_F_BYTES | BE_F_REACH, .opts_size = sizeof(nv_opts_t), .flags = nv_flags, .parse = nv_parse, diff --git a/src/nvidia/nvidia.h b/src/nvidia/nvidia.h index 64d823d..a61c3b6 100644 --- a/src/nvidia/nvidia.h +++ b/src/nvidia/nvidia.h @@ -280,7 +280,7 @@ typedef struct { /* ---- Machine Instruction ---- */ #define NV_MAX_FRAME (512u * 1024u) -#define NV_MAX_ASM 4096 +#define NV_MAX_ASM (1 << 15) #define NV_MAX_ASMOP BIR_ASM_MAXOP #define NV_MAX_OPS 6 @@ -294,7 +294,7 @@ typedef struct { uint16_t pad; } nv_minst_t; -#define NV_MAX_CALL 4096 +#define NV_MAX_CALL (1 << 15) #define NV_MAX_CARG 24 typedef struct { @@ -352,8 +352,8 @@ typedef struct { /* ---- Module ---- */ -#define NV_MAX_MINST (1 << 21) /* 2097152 */ -#define NV_MAX_MBLK (1 << 18) /* 262144 */ +#define NV_MAX_MINST (1 << 22) /* 4194304 */ +#define NV_MAX_MBLK (1 << 19) /* 524288 */ #define NV_MAX_MFUNC (1 << 12) /* 4096 */ #define NV_MAX_OUT (2 * 1024 * 1024) /* 2 MB output buffer */ @@ -383,7 +383,8 @@ typedef struct { uint32_t num_call; uint32_t cur_emf; uint8_t vprt; - uint8_t vp_pad[3]; + uint8_t sass; + uint8_t vp_pad[2]; /* Block-hit instrumentation (diagnostic) */ uint8_t bkhit; /* emit atom.add at each block label */ diff --git a/src/tensix/isel.c b/src/tensix/isel.c index e99aaba..5e7730d 100644 --- a/src/tensix/isel.c +++ b/src/tensix/isel.c @@ -1002,7 +1002,7 @@ int tensix_compile(const bir_module_t *bir, tt_module_t *tt) tt->vreg_count = 1; /* vreg 0 reserved as sentinel */ tt->out_len = 0; - memset(tt->val_vreg, 0, sizeof(tt->val_vreg)); + memset(tt->val_vreg, 0, (size_t)bir->num_insts * sizeof(tt->val_vreg[0])); memset(tt->reg_map, 0, sizeof(tt->reg_map)); int guard = 8192; diff --git a/tests/hdecl.cu b/tests/hdecl.cu new file mode 100644 index 0000000..eacf2c4 --- /dev/null +++ b/tests/hdecl.cu @@ -0,0 +1,50 @@ +#include +#include +#include + +__device__ float dbl(float x) +{ + return x + x; +} + +__global__ void vset(float *o, int64_t /*stride*/, int n, float v = 0.5f) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + + if (i < n) o[i] = v; +} + +__global__ void vdbl(float *o, int n) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + + if (i < n) o[i] = dbl(o[i]); +} + +int main(void) +{ + enum { N = 64 }; + float hf[N]; + float *d; + int bad = 0; + + cudaMalloc((void **)&d, N * sizeof(float)); + + vset<<<(N + 63) / 64, 64>>>(d, (int64_t)1, N, 1.25f); + vdbl<<<(N + 63) / 64, 64>>>(d, N); + + cudaDeviceSynchronize(); + cudaMemcpy(hf, d, N * sizeof(float), cudaMemcpyDeviceToHost); + + for (int i = 0; i < N; i++) + if (hf[i] != 2.5f) bad++; + + cudaFree(d); + + if (bad != 0) { + printf("hdecl: %d of %d lanes disagree\n", bad, (int)N); + return 1; + } + printf("hdecl: %d lanes, o[0]=%g, all agree\n", (int)N, (double)hf[0]); + return 0; +} diff --git a/tests/hfnb.cu b/tests/hfnb.cu new file mode 100644 index 0000000..754244f --- /dev/null +++ b/tests/hfnb.cu @@ -0,0 +1,52 @@ +#include +#include + +typedef void (*kfn_t)(float *, int); + +template +__global__ void scale(float *o, int n) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + + if (i >= n) return; + o[i] = B ? (float)(S * 2) : (float)S; +} + +template +static void fire(float *o, int n, kfn_t k) +{ + k<<<(n + 63) / 64, 64>>>(o, n); +} + +template +static void run(float *o, int n, int dbl) +{ + kfn_t k; + + if (dbl) k = scale; + else k = scale; + fire(o, n, k); +} + +int main(void) +{ + enum { N = 64 }; + float h[N]; + float *d; + int bad = 0; + + cudaMalloc((void **)&d, N * sizeof(float)); + run<3>(d, N, 1); + cudaDeviceSynchronize(); + cudaMemcpy(h, d, N * sizeof(float), cudaMemcpyDeviceToHost); + for (int i = 0; i < N; i++) + if (h[i] != 6.0f) bad++; + cudaFree(d); + + if (bad != 0) { + printf("hfnb: %d disagreements over %d lanes\n", bad, (int)N); + return 1; + } + printf("hfnb: %d lanes, v=%g, all agree\n", (int)N, (double)h[0]); + return 0; +} diff --git a/tests/hfnc.cu b/tests/hfnc.cu new file mode 100644 index 0000000..386ce57 --- /dev/null +++ b/tests/hfnc.cu @@ -0,0 +1,57 @@ +#include +#include + +typedef void (*kfn_t)(float *, int); + +template +__global__ void scale(float *o, int n) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + + if (i >= n) return; + o[i] = B ? (float)(S * 2) : (float)S; +} + +template +static void fire(K k, int g, int b, A... a) +{ + k<<>>(a...); +} + +template +static void run(float *o, int n, int dbl) +{ + kfn_t k; + + if (dbl) { + constexpr bool B = true; + k = scale; + } else { + constexpr bool B = false; + k = scale; + } + fire(k, (n + 63) / 64, 64, o, n); +} + +int main(void) +{ + enum { N = 64 }; + float h[N]; + float *d; + int bad = 0; + + cudaMalloc((void **)&d, N * sizeof(float)); + run<3>(d, N, 1); + cudaDeviceSynchronize(); + cudaMemcpy(h, d, N * sizeof(float), cudaMemcpyDeviceToHost); + for (int i = 0; i < N; i++) + if (h[i] != 6.0f) bad++; + cudaFree(d); + + if (bad != 0) { + printf("hfnc: %d disagreements over %d lanes\n", bad, (int)N); + return 1; + } + printf("hfnc: %d lanes, v=%g, all agree\n", (int)N, (double)h[0]); + return 0; +} diff --git a/tests/hfnd.cu b/tests/hfnd.cu new file mode 100644 index 0000000..11f942c --- /dev/null +++ b/tests/hfnd.cu @@ -0,0 +1,63 @@ +#include +#include + +typedef void (*kfn_t)(float *, int); + +template +__global__ void scale(float *o, int n) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + + if (i >= n) return; + o[i] = B ? (float)(S * 2) : (float)S; +} + +template +static void fire(K k, int g, int b, A &&... a) +{ + k<<>>(std::forward(a)...); +} + +template +static void mid(float *o, int n, kfn_t k) +{ + fire(k, (n + 63) / 64, 64, o, n); +} + +template +static void run(float *o, int n, int dbl) +{ + kfn_t k; + + if (dbl) { + constexpr bool B = true; + k = scale; + } else { + constexpr bool B = false; + k = scale; + } + mid(o, n, k); +} + +int main(void) +{ + enum { N = 64 }; + float h[N]; + float *d; + int bad = 0; + + cudaMalloc((void **)&d, N * sizeof(float)); + run<3>(d, N, 1); + cudaDeviceSynchronize(); + cudaMemcpy(h, d, N * sizeof(float), cudaMemcpyDeviceToHost); + for (int i = 0; i < N; i++) + if (h[i] != 6.0f) bad++; + cudaFree(d); + + if (bad != 0) { + printf("hfnd: %d disagreements over %d lanes\n", bad, (int)N); + return 1; + } + printf("hfnd: %d lanes, v=%g, all agree\n", (int)N, (double)h[0]); + return 0; +} diff --git a/tests/hmac.cu b/tests/hmac.cu new file mode 100644 index 0000000..ff3bb7f --- /dev/null +++ b/tests/hmac.cu @@ -0,0 +1,59 @@ +#include +#include + +#define LAUNCH(k, n, o, v) k<<<((n) + 63) / 64, 64>>>(o, v, n) + +struct vec2 { float a; float b; }; + +template +__global__ void fill2(T *o, T v, int n) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + + if (i < n) o[i] = v; +} + +template +static void fwd(K k, T *o, T v, int n) +{ + k<<<(n + 63) / 64, 64>>>(o, v, n); +} + +int main(void) +{ + enum { N = 64 }; + vec2 hp[N]; + float hf[N]; + vec2 *dp; + float *df; + vec2 one; + int bad = 0; + + one.a = 1.0f; + one.b = 2.0f; + cudaMalloc((void **)&dp, N * sizeof(vec2)); + cudaMalloc((void **)&df, N * sizeof(float)); + + LAUNCH(fill2, N, dp, one); + fwd(fill2, df, 0.5f, N); + + cudaDeviceSynchronize(); + cudaMemcpy(hp, dp, N * sizeof(vec2), cudaMemcpyDeviceToHost); + cudaMemcpy(hf, df, N * sizeof(float), cudaMemcpyDeviceToHost); + + for (int i = 0; i < N; i++) { + if (hp[i].a != 1.0f || hp[i].b != 2.0f) bad++; + if (hf[i] != 0.5f) bad++; + } + + cudaFree(dp); + cudaFree(df); + + if (bad != 0) { + printf("hmac: %d disagreements over %d lanes\n", bad, (int)N); + return 1; + } + printf("hmac: %d lanes, p=(%g,%g) f=%g, all agree\n", + (int)N, (double)hp[0].a, (double)hp[0].b, (double)hf[0]); + return 0; +} diff --git a/tests/hmulti.cu b/tests/hmulti.cu new file mode 100644 index 0000000..d8e54d3 --- /dev/null +++ b/tests/hmulti.cu @@ -0,0 +1,73 @@ +#include +#include + +__device__ float twice(float x) +{ + return x + x; +} + +__global__ void vadd(const float *a, const float *b, float *c, int n) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + + if (i < n) c[i] = a[i] + b[i]; +} + +__global__ void vdbl(float *c, int n) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + + if (i < n) c[i] = twice(c[i]); +} + +template +__global__ void vfill(T *o, T v, int n) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + + if (i < n) o[i] = v; +} + +int main(void) +{ + enum { N = 128 }; + float hf[N]; + int hi[N]; + float *da, *db, *dc; + int *di; + int bad = 0; + + cudaMalloc((void **)&da, N * sizeof(float)); + cudaMalloc((void **)&db, N * sizeof(float)); + cudaMalloc((void **)&dc, N * sizeof(float)); + cudaMalloc((void **)&di, N * sizeof(int)); + + vfill<<<(N + 63) / 64, 64>>>(da, 1.5f, N); + vfill<<<(N + 63) / 64, 64>>>(db, 2.25f, N); + vfill<<<(N + 63) / 64, 64>>>(di, 7, N); + + vadd<<<(N + 63) / 64, 64>>>(da, db, dc, N); + vdbl<<<(N + 63) / 64, 64>>>(dc, N); + + cudaDeviceSynchronize(); + cudaMemcpy(hf, dc, N * sizeof(float), cudaMemcpyDeviceToHost); + cudaMemcpy(hi, di, N * sizeof(int), cudaMemcpyDeviceToHost); + + for (int i = 0; i < N; i++) { + if (hf[i] != 7.5f) bad++; + if (hi[i] != 7) bad++; + } + + cudaFree(da); + cudaFree(db); + cudaFree(dc); + cudaFree(di); + + if (bad != 0) { + printf("hmulti: %d disagreements over %d lanes\n", bad, (int)N); + return 1; + } + printf("hmulti: %d lanes, f=%g i=%d, all agree\n", + (int)N, (double)hf[0], hi[0]); + return 0; +} diff --git a/tests/hpack.cu b/tests/hpack.cu new file mode 100644 index 0000000..5dbdb94 --- /dev/null +++ b/tests/hpack.cu @@ -0,0 +1,41 @@ +#include +#include + +template +__global__ void vfan(T *o, int n, Ps... ps) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + + if (i < n) o[i] = (T)sizeof...(Ps); +} + +int main(void) +{ + enum { N = 64 }; + float hf[N]; + float *da, *db, *dc; + int bad = 0; + + cudaMalloc((void **)&da, N * sizeof(float)); + cudaMalloc((void **)&db, N * sizeof(float)); + cudaMalloc((void **)&dc, N * sizeof(float)); + + vfan<<<(N + 63) / 64, 64>>>(dc, N, da, db); + + cudaDeviceSynchronize(); + cudaMemcpy(hf, dc, N * sizeof(float), cudaMemcpyDeviceToHost); + + for (int i = 0; i < N; i++) + if (hf[i] != 2.0f) bad++; + + cudaFree(da); + cudaFree(db); + cudaFree(dc); + + if (bad != 0) { + printf("hpack: %d of %d lanes disagree\n", bad, (int)N); + return 1; + } + printf("hpack: %d lanes, o[0]=%g, all agree\n", (int)N, (double)hf[0]); + return 0; +} diff --git a/tests/hqual.cu b/tests/hqual.cu new file mode 100644 index 0000000..ac0c073 --- /dev/null +++ b/tests/hqual.cu @@ -0,0 +1,23 @@ +#include + +struct qop { + int v; + + __device__ qop(int a) : v(a) {} + __device__ int operator()(int x) const { return x + v; } + static __device__ int dbl(int x) { return 2 * x; } + __device__ __forceinline__ int trip(int x) const { return 3 * x; } + __host__ __device__ int keep(int x) const { return x; } +}; + +__global__ void qk(int *o, int n) +{ + int i = threadIdx.x; + + if (i < n) o[i] = i; +} + +void qgo(int *o, int n) +{ + qk<<<1, 64>>>(o, n); +} diff --git a/tests/htfn.cu b/tests/htfn.cu new file mode 100644 index 0000000..7c3bd17 --- /dev/null +++ b/tests/htfn.cu @@ -0,0 +1,61 @@ +#include +#include + +enum mode { M_ADD = 0, M_MUL = 1 }; + +struct vec2 { float a; float b; }; + +template +__global__ void apply(T *o, vec2 p, int n) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + + if (i >= n) return; + o[i] = (M == M_MUL) ? (T)(p.a * p.b) : (T)(p.a + p.b); +} + +template +static void run(T *o, vec2 p, int n, int mul) +{ + if (mul) apply<<<(n + 63) / 64, 64>>>(o, p, n); + else apply<<<(n + 63) / 64, 64>>>(o, p, n); +} + +int main(void) +{ + enum { N = 64 }; + float hf[N]; + int hi[N]; + float *df; + int *di; + vec2 p; + int bad = 0; + + p.a = 3.0f; + p.b = 4.0f; + cudaMalloc((void **)&df, N * sizeof(float)); + cudaMalloc((void **)&di, N * sizeof(int)); + + run(df, p, N, 1); + run(di, p, N, 0); + + cudaDeviceSynchronize(); + cudaMemcpy(hf, df, N * sizeof(float), cudaMemcpyDeviceToHost); + cudaMemcpy(hi, di, N * sizeof(int), cudaMemcpyDeviceToHost); + + for (int i = 0; i < N; i++) { + if (hf[i] != 12.0f) bad++; + if (hi[i] != 7) bad++; + } + + cudaFree(df); + cudaFree(di); + + if (bad != 0) { + printf("htfn: %d disagreements over %d lanes\n", bad, (int)N); + return 1; + } + printf("htfn: %d lanes, f=%g i=%d, all agree\n", + (int)N, (double)hf[0], hi[0]); + return 0; +} diff --git a/tests/htid.cu b/tests/htid.cu new file mode 100644 index 0000000..f86c856 --- /dev/null +++ b/tests/htid.cu @@ -0,0 +1,60 @@ +#include +#include + +typedef void (*cpy_kernel_t)(const char *cx, char *cdst); + +template +static __device__ void cpy1(const char *cxi, char *cdsti) +{ + *(dst_t *)cdsti = (dst_t)(*(const src_t *)cxi); +} + +template +__global__ void cpyk(const char *cx, char *cdst, int n) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + + if (i < n) cpy_1(cx + i * 4, cdst + i * 4); +} + +template +static void run(const char *cx, char *cdst, int n) +{ + cpyk><<<(n + 63) / 64, 64>>>(cx, cdst, n); +} + +int main(void) +{ + enum { N = 64 }; + float hs[N], hd[N]; + char *ds, *dd; + int bad = 0; + + for (int i = 0; i < N; i++) { + hs[i] = 1.5f * (float)i; + hd[i] = 0.0f; + } + + cudaMalloc((void **)&ds, N * sizeof(float)); + cudaMalloc((void **)&dd, N * sizeof(float)); + cudaMemcpy(ds, hs, N * sizeof(float), cudaMemcpyHostToDevice); + + run(ds, dd, N); + + cudaDeviceSynchronize(); + cudaMemcpy(hd, dd, N * sizeof(float), cudaMemcpyDeviceToHost); + + for (int i = 0; i < N; i++) + if (hd[i] != hs[i]) bad++; + + cudaFree(ds); + cudaFree(dd); + + if (bad != 0) { + printf("htid: %d of %d lanes disagree\n", bad, (int)N); + return 1; + } + printf("htid: %d lanes, d[1]=%g d[63]=%g, all agree\n", + (int)N, (double)hd[1], (double)hd[63]); + return 0; +} diff --git a/tests/hvadd.cu b/tests/hvadd.cu new file mode 100644 index 0000000..cbadda7 --- /dev/null +++ b/tests/hvadd.cu @@ -0,0 +1,49 @@ +#include +#include + +__global__ void vadd(const float *a, const float *b, float *c, int n) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + + if (i < n) c[i] = a[i] + b[i]; +} + +int main(void) +{ + enum { N = 256 }; + float ha[N], hb[N], hc[N]; + float *da, *db, *dc; + int bad = 0; + + for (int i = 0; i < N; i++) { + ha[i] = (float)i; + hb[i] = 0.25f * (float)i; + hc[i] = 0.0f; + } + + cudaMalloc((void **)&da, N * sizeof(float)); + cudaMalloc((void **)&db, N * sizeof(float)); + cudaMalloc((void **)&dc, N * sizeof(float)); + cudaMemcpy(da, ha, N * sizeof(float), cudaMemcpyHostToDevice); + cudaMemcpy(db, hb, N * sizeof(float), cudaMemcpyHostToDevice); + + vadd<<<(N + 63) / 64, 64>>>(da, db, dc, N); + + cudaDeviceSynchronize(); + cudaMemcpy(hc, dc, N * sizeof(float), cudaMemcpyDeviceToHost); + + for (int i = 0; i < N; i++) + if (hc[i] != ha[i] + hb[i]) bad++; + + cudaFree(da); + cudaFree(db); + cudaFree(dc); + + if (bad != 0) { + printf("hvadd: %d of %d lanes disagree\n", bad, (int)N); + return 1; + } + printf("hvadd: %d lanes, c[1]=%g c[255]=%g, all agree\n", + (int)N, (double)hc[1], (double)hc[255]); + return 0; +} diff --git a/tests/tbackend.c b/tests/tbackend.c index 6454d04..8fbf80b 100644 --- a/tests/tbackend.c +++ b/tests/tbackend.c @@ -51,7 +51,7 @@ static void bkd04(void) BE_F_SIMT | BE_F_SCALAR | BE_F_ATOMIC | BE_F_SHARED | BE_F_WARP | BE_F_MFMA | BE_F_BARRIER | BE_F_DIV | BE_F_SCRATCH | BE_F_TRANSC | BE_F_F16 | BE_F_F64 | - BE_F_BF16 | BE_F_MULTIOUT | BE_F_NOCALL | BE_F_BYTES; + BE_F_BF16 | BE_F_MULTIOUT | BE_F_NOCALL | BE_F_BYTES | BE_F_REACH; for (uint32_t i = 0; be_list[i] != NULL && i < 64; i++) { CHEQ(be_list[i]->feats & ~all, 0u); } diff --git a/tests/tcpp.c b/tests/tcpp.c index ccae609..973ea10 100644 --- a/tests/tcpp.c +++ b/tests/tcpp.c @@ -286,14 +286,14 @@ TH_REG("cpp", 20, "a macro definition too wide to hold says so", cpp20) static void cpp15(void) { - CHNE(cprun("template __device__ T id(T v){ return v; }\n" + CHEQ(cprun("template __device__ T id(T v){ return v; }\n" "template __device__ float id(float v);\n", - "--parse"), 0); - CHNE(strstr(obuf, "E175"), NULL); - CHEQ(strstr(obuf, "E020"), NULL); + "--ir"), 0); + CHNE(strstr(obuf, "@id"), NULL); + CHEQ(strstr(obuf, "E175"), NULL); PASS(); } -TH_REG("cpp", 15, "an explicit instantiation is refused by name", cpp15) +TH_REG("cpp", 15, "an explicit instantiation emits the function", cpp15) static void cpp16(void) { diff --git a/tests/tharns.h b/tests/tharns.h index 62c03a9..bcb20c8 100644 --- a/tests/tharns.h +++ b/tests/tharns.h @@ -21,7 +21,7 @@ typedef struct { tfunc_t func; } tcase_t; -#define TH_MAXTS 1024 +#define TH_MAXTS 1280 #define TH_BUFSZ 4096 /* Column widths for the result line. TH_DESCW is a budget, not a hint. A diff --git a/tests/thost.c b/tests/thost.c new file mode 100644 index 0000000..6910046 --- /dev/null +++ b/tests/thost.c @@ -0,0 +1,413 @@ +#include "tharns.h" + +static char obuf[TH_BUFSZ]; +static char hbuf[65536]; + +static int slurp(const char *path) +{ + FILE *f = fopen(path, "rb"); + size_t n; + + hbuf[0] = '\0'; + if (f == NULL) return 0; + n = fread(hbuf, 1u, sizeof hbuf - 1u, f); + fclose(f); + hbuf[n] = '\0'; + return n != 0u; +} + +static int emit(const char *cu, const char *out) +{ + char cmd[512]; + + snprintf(cmd, sizeof cmd, + BC_BIN " --cuda-host -Iruntime/include %s -o %s", cu, out); + if (th_run(cmd, obuf, TH_BUFSZ) != 0) return 0; + return slurp(out); +} + +static void hst01(void) +{ + CHECK(emit("tests/hvadd.cu", "tests/hst01.cpp")); + CHECK(strstr(hbuf, "__global__") == NULL); + CHECK(strstr(hbuf, "void vadd(") != NULL); + remove("tests/hst01.cpp"); + PASS(); +} +TH_REG("hst", 1, "the device definition leaves and a stub stays", hst01) + +static void hst02(void) +{ + CHECK(emit("tests/hvadd.cu", "tests/hst02.cpp")); + CHECK(strstr(hbuf, "__cudaRegisterFatBinary") != NULL); + CHECK(strstr(hbuf, "__cudaRegisterFunction") != NULL); + CHECK(strstr(hbuf, "\"vadd\"") != NULL); + CHECK(strstr(hbuf, "__cudaRegisterFatBinaryEnd") != NULL); + remove("tests/hst02.cpp"); + PASS(); +} +TH_REG("hst", 2, "a constructor registers fatbin and kernel", hst02) + +static void hst03(void) +{ + CHECK(emit("tests/hvadd.cu", "tests/hst03.cpp")); + CHECK(strstr(hbuf, "__cudaPushCallConfiguration") != NULL); + CHECK(strstr(hbuf, "cudaLaunchKernel") != NULL); + CHECK(strstr(hbuf, "<<<") == NULL); + remove("tests/hst03.cpp"); + PASS(); +} +TH_REG("hst", 3, "a launch goes through the registration ABI", hst03) + +static void hst04(void) +{ + CHECK(emit("tests/hmulti.cu", "tests/hst04.cpp")); + CHECK(strstr(hbuf, "\"vfill\"") != NULL); + CHECK(strstr(hbuf, "\"vfill$1\"") != NULL); + CHECK(strstr(hbuf, "\"vadd\"") != NULL); + CHECK(strstr(hbuf, "\"vdbl\"") != NULL); + remove("tests/hst04.cpp"); + PASS(); +} +TH_REG("hst", 4, "both template instantiations reach the table", hst04) + +static void hst05(void) +{ + CHECK(emit("tests/hvadd.cu", "tests/hst05.cpp")); + CHECK(strstr(hbuf, "#include ") != NULL); + remove("tests/hst05.cpp"); + PASS(); +} +TH_REG("hst", 5, "an include Booth cannot read stays a directive", hst05) + +static void hst06(void) +{ + CHECK(emit("tests/hmulti.cu", "tests/hst06.cpp")); + CHECK(strstr(hbuf, "__device__") == NULL); + CHECK(strstr(hbuf, "float twice(float x);") != NULL); + CHECK(strstr(hbuf, "x + x") == NULL); + remove("tests/hst06.cpp"); + PASS(); +} +TH_REG("hst", 6, "a __device__ helper leaves a declaration", hst06) + +static void hst07(void) +{ + CHECK(emit("tests/htfn.cu", "tests/hst07.cpp")); + CHECK(strstr(hbuf, "template ") != NULL); + CHECK(strstr(hbuf, "apply(o, p, n)") != NULL); + CHECK(strstr(hbuf, "apply(o, p, n)") != NULL); + remove("tests/hst07.cpp"); + PASS(); +} +TH_REG("hst", 7, "a launch inside a host template stays generic", hst07) + +static void hst08(void) +{ + CHECK(emit("tests/htfn.cu", "tests/hst08.cpp")); + CHECK(strstr(hbuf, "(const char *)apply") != NULL); + CHECK(strstr(hbuf, "(const char *)apply") != NULL); + CHECK(strstr(hbuf, "(const char *)apply") != NULL); + CHECK(strstr(hbuf, "(const char *)apply") != NULL); + remove("tests/hst08.cpp"); + PASS(); +} +TH_REG("hst", 8, "one source launch reaches four instantiations", hst08) + +static void hst09(void) +{ + CHECK(emit("tests/hmac.cu", "tests/hst09.cpp")); + CHECK(strstr(hbuf, "(const char *)fill2") != NULL); + CHECK(strstr(hbuf, "(const char *)fill2") != NULL); + remove("tests/hst09.cpp"); + PASS(); +} +TH_REG("hst", 9, "a struct template argument is spelled out", hst09) + +static void hst10(void) +{ + CHECK(emit("tests/hmac.cu", "tests/hst10.cpp")); + CHECK(strstr(hbuf, ": fill2(dp,") != NULL); + CHECK(strstr(hbuf, ": k(o, v, n)") != NULL); + remove("tests/hst10.cpp"); + PASS(); +} +TH_REG("hst", 10, "a macro launch and a callee argument", hst10) + +static void hst11(void) +{ + CHECK(emit("tests/hpack.cu", "tests/hst11.cpp")); + CHECK(strstr(hbuf, "(const char *)vfan") != NULL); + remove("tests/hst11.cpp"); + PASS(); +} +TH_REG("hst", 11, "a template argument pack is written out", hst11) + +static void hst12(void) +{ + CHECK(emit("tests/htid.cu", "tests/hst12.cpp")); + CHECK(strstr(hbuf, "(const char *)cpyk>") != NULL); + CHECK(strstr(hbuf, "<<<") == NULL); + remove("tests/hst12.cpp"); + PASS(); +} +TH_REG("hst", 12, "a function template-id argument is spelled", hst12) + +static void hst13(void) +{ + CHECK(emit("tests/hqual.cu", "tests/hst13.cpp")); + CHECK(strstr(hbuf, "__device__") == NULL); + CHECK(strstr(hbuf, "__forceinline__") == NULL); + CHECK(strstr(hbuf, "__host__") == NULL); + CHECK(strstr(hbuf, "__global__") == NULL); + remove("tests/hst13.cpp"); + PASS(); +} +TH_REG("hst", 13, "no device qualifier survives on a member", hst13) + +static void hst14(void) +{ + CHECK(emit("tests/hqual.cu", "tests/hst14.cpp")); + CHECK(strstr(hbuf, "operator()(int x) const") != NULL); + CHECK(strstr(hbuf, "int dbl(int x)") != NULL); + CHECK(strstr(hbuf, "int trip(int x) const") != NULL); + CHECK(strstr(hbuf, "qop(int a) : v(a)") != NULL); + remove("tests/hst14.cpp"); + PASS(); +} +TH_REG("hst", 14, "the member itself stays behind", hst14) + +static void hst16(void) +{ + CHECK(emit("tests/hpack.cu", "tests/hst16.cpp")); + CHECK(strstr(hbuf, "(void *)&ps...") != NULL); + remove("tests/hst16.cpp"); + PASS(); +} +TH_REG("hst", 16, "a stub body expands its argument pack", hst16) + +static void hst17(void) +{ + CHECK(emit("tests/hdecl.cu", "tests/hst17.cpp")); + CHECK(strstr(hbuf, "int64_t __p1") != NULL); + CHECK(strstr(hbuf, "(void *)&__p1") != NULL); + CHECK(strstr(hbuf, "(void *)&int64_t") == NULL); + remove("tests/hst17.cpp"); + PASS(); +} +TH_REG("hst", 17, "a commented out parameter name is not a type", hst17) + +static void hst18(void) +{ + CHECK(emit("tests/hdecl.cu", "tests/hst18.cpp")); + CHECK(strstr(hbuf, "float v = 0.5f") != NULL); + CHECK(strstr(hbuf, "(void *)&v") != NULL); + CHECK(strstr(hbuf, "float dbl(float x);") != NULL); + remove("tests/hst18.cpp"); + PASS(); +} +TH_REG("hst", 18, "a default argument reaches the stub", hst18) + +static void hst15(void) +{ + CHECK(emit("tests/hqual.cu", "tests/hst15.cpp")); + CHECK(strstr(hbuf, "#include ") != NULL); + CHECK(strstr(hbuf, "cudaError_t") == NULL); + remove("tests/hst15.cpp"); + PASS(); +} +TH_REG("hst", 15, "an angle include stays a directive", hst15) + +static unsigned char fbuf[512]; + +static unsigned fent1(unsigned char *p, unsigned kind, const char *s) +{ + unsigned len = (unsigned)strlen(s); + unsigned pad = (len + 7u) & ~7u; + + memset(p, 0, 64u + pad); + p[0] = (unsigned char)kind; + p[4] = 64u; + p[8] = (unsigned char)pad; + p[16] = (unsigned char)len; + p[26] = 1u; + p[28] = 89u; + memcpy(p + 64u, s, len); + return 64u + pad; +} + +static int mkfat(const char *path, int cub, int ptx) +{ + unsigned at = 16u; + FILE *f; + + memset(fbuf, 0, sizeof fbuf); + fbuf[0] = 0x50u; fbuf[1] = 0xEDu; fbuf[2] = 0x55u; fbuf[3] = 0xBAu; + fbuf[4] = 1u; + fbuf[6] = 16u; + if (cub) at += fent1(fbuf + at, 2u, "notreallyacubin"); + if (ptx) at += fent1(fbuf + at, 1u, ".version 8.0\n"); + fbuf[8] = (unsigned char)(at - 16u); + f = fopen(path, "wb"); + if (f == NULL) return 0; + if (fwrite(fbuf, 1u, at, f) != at) { fclose(f); return 0; } + return fclose(f) == 0; +} + +static int emitf(const char *cu, const char *fat, const char *out) +{ + char cmd[512]; + + snprintf(cmd, sizeof cmd, + BC_BIN " --cuda-host --fatbin %s -Iruntime/include %s -o %s", + fat, cu, out); + if (th_run(cmd, obuf, TH_BUFSZ) != 0) return 0; + return slurp(out); +} + +static void hst19(void) +{ + CHECK(mkfat("tests/hst19.fatbin", 0, 1)); + CHECK(emitf("tests/hvadd.cu", "tests/hst19.fatbin", "tests/hst19.cpp")); + CHECK(strstr(hbuf, "booth-fat: ptx-only hvadd.cu") != NULL); + remove("tests/hst19.cpp"); + remove("tests/hst19.fatbin"); + PASS(); +} +TH_REG("hst", 19, "a PTX-only fatbin says so in the host unit", hst19) + +static void hst20(void) +{ + CHECK(mkfat("tests/hst20.fatbin", 1, 1)); + CHECK(emitf("tests/hvadd.cu", "tests/hst20.fatbin", "tests/hst20.cpp")); + CHECK(strstr(hbuf, "booth-fat: cubin+ptx hvadd.cu") != NULL); + CHECK(strstr(hbuf, "ptx-only") == NULL); + remove("tests/hst20.cpp"); + remove("tests/hst20.fatbin"); + PASS(); +} +TH_REG("hst", 20, "a fatbin with both names both", hst20) + +static void hst21(void) +{ + CHECK(mkfat("tests/hst21.fatbin", 1, 0)); + CHECK(emitf("tests/hvadd.cu", "tests/hst21.fatbin", "tests/hst21.cpp")); + CHECK(strstr(hbuf, "booth-fat: cubin hvadd.cu") != NULL); + CHECK(strstr(hbuf, "ptx") == NULL); + remove("tests/hst21.cpp"); + remove("tests/hst21.fatbin"); + PASS(); +} +TH_REG("hst", 21, "a fatbin with only a cubin names only that", hst21) + +static void hst22(void) +{ + CHECK(emit("tests/hfnb.cu", "tests/hst22.cpp")); + CHECK(strstr(hbuf, "(const char *)scale<(int)3, (bool)1>") != NULL); + CHECK(strstr(hbuf, "(const char *)scale<(int)3, (bool)0>") != NULL); + remove("tests/hst22.cpp"); + PASS(); +} +TH_REG("hst", 22, "both branch assignments reach the table", hst22) + +static void hst23(void) +{ + CHECK(emit("tests/hfnc.cu", "tests/hst23.cpp")); + CHECK(strstr(hbuf, "(const char *)scale<(int)3, (bool)1>") != NULL); + CHECK(strstr(hbuf, "(const char *)scale<(int)3, (bool)0>") != NULL); + remove("tests/hst23.cpp"); + PASS(); +} +TH_REG("hst", 23, "a block scoped constexpr reaches the launch", hst23) + +static void hst24(void) +{ + CHECK(emit("tests/hfnd.cu", "tests/hst24.cpp")); + CHECK(strstr(hbuf, "(const char *)scale<(int)3, (bool)1>") != NULL); + CHECK(strstr(hbuf, "(const char *)scale<(int)3, (bool)0>") != NULL); + remove("tests/hst24.cpp"); + PASS(); +} +TH_REG("hst", 24, "a kernel pointer crosses two call frames", hst24) + +static unsigned char f2[512]; +static unsigned char dbuf[1024]; + +static int mkfat2(const char *path, const unsigned char *img, unsigned len) +{ + unsigned pad = (len + 7u) & ~7u; + unsigned at = 80u + pad; + FILE *f; + + memset(f2, 0, sizeof f2); + f2[0] = 0x50u; f2[1] = 0xEDu; f2[2] = 0x55u; f2[3] = 0xBAu; + f2[4] = 1u; + f2[6] = 16u; + f2[8] = (unsigned char)(at - 16u); + f2[9] = (unsigned char)((at - 16u) >> 8); + f2[16] = 1u; + f2[20] = 64u; + f2[24] = (unsigned char)pad; + f2[25] = (unsigned char)(pad >> 8); + f2[32] = (unsigned char)len; + f2[33] = (unsigned char)(len >> 8); + f2[42] = 1u; + f2[44] = 89u; + memcpy(f2 + 80u, img, len); + f = fopen(path, "wb"); + if (f == NULL) return 0; + if (fwrite(f2, 1u, at, f) != at) { fclose(f); return 0; } + return fclose(f) == 0; +} + +static unsigned bdec(const char *p, unsigned char *d, unsigned max) +{ + unsigned n = 0; + int in = 0; + + for (; *p != '\0' && n < max; p++) { + if (!in) { + if (*p == '"') in = 1; + else if (*p == ';') break; + continue; + } + if (*p == '"') { in = 0; continue; } + if (*p != '\\') { d[n++] = (unsigned char)*p; continue; } + p++; + if (*p == 'n') d[n++] = 10u; + else if (*p == 't') d[n++] = 9u; + else if (*p == 'r') d[n++] = 13u; + else if (*p >= '0' && *p <= '7') { + unsigned v = 0, k = 0; + + while (k < 3u && *p >= '0' && *p <= '7') { + v = v * 8u + (unsigned)(*p - '0'); + p++; + k++; + } + p--; + d[n++] = (unsigned char)v; + } else d[n++] = (unsigned char)*p; + } + return n; +} + +static void hst25(void) +{ + unsigned char img[256]; + const char *at; + unsigned n; + + for (unsigned i = 0; i < 256u; i++) img[i] = (unsigned char)i; + CHECK(mkfat2("tests/hst25.fatbin", img, 256u)); + CHECK(emitf("tests/hvadd.cu", "tests/hst25.fatbin", "tests/hst25.cpp")); + at = strstr(hbuf, "__bfat[] ="); + CHECK(at != NULL); + n = bdec(at + 10, dbuf, sizeof dbuf); + CHECK(n == 336u); + CHECK(memcmp(dbuf + 80u, img, 256u) == 0); + remove("tests/hst25.cpp"); + remove("tests/hst25.fatbin"); + PASS(); +} +TH_REG("hst", 25, "every byte value survives the fatbin literal", hst25) diff --git a/tests/tinline.c b/tests/tinline.c index af5f5e8..b5ecb61 100644 --- a/tests/tinline.c +++ b/tests/tinline.c @@ -189,7 +189,7 @@ static void inl05(void) CHECK(M != NULL); (void)bmod(M, 0); - { int rc = bir_inline_device(M); printf("RC=%d\n", rc); } + { int rc = bir_inline_device(M, 0); printf("RC=%d\n", rc); } CHECK(bir_vchk(M) == BC_OK); CHECK(ncall(M, 1) == 0); free(M); @@ -203,7 +203,7 @@ static void inl06(void) CHECK(M != NULL); (void)bmod(M, 0); - CHECK(bir_inline_device(M) == BC_OK); + CHECK(bir_inline_device(M, 0) == BC_OK); for (f = 0; f < M->num_funcs; f++) live += M->funcs[f].num_blocks; CHECK(live == M->num_blocks); CHECK(M->funcs[0].first_block == 0); @@ -219,13 +219,27 @@ static void inl07(void) CHECK(M != NULL); (void)bmod(M, 1); - CHECK(bir_inline_device(M) == BC_OK); + CHECK(bir_inline_device(M, 0) == BC_OK); CHECK(bir_vchk(M) == BC_OK); CHECK(ncall(M, 0) == 1); free(M); PASS(); } +static void inl08(void) +{ + bir_module_t *M = malloc(sizeof(*M)); + CHECK(M != NULL); + (void)bmod(M, 0); + + CHECK(bir_inline_device(M, 1) == BC_OK); + CHECK(bir_vchk(M) == BC_OK); + CHECK(M->funcs[0].num_blocks == 0); + CHECK(ncall(M, 1) == 0); + free(M); + PASS(); +} + TH_REG("inl", 1, "a GPU kernel ends up with no calls", inl01); TH_REG("inl", 2, "a GPU binary inlines", inl02); TH_REG("inl", 3, "other GPU targets inline too", inl03); @@ -233,3 +247,4 @@ TH_REG("inl", 4, "CPU keeps its calls", inl04); TH_REG("inl", 5, "a phi survives a split predecessor", inl05); TH_REG("inl", 6, "the arenas come back packed and in order", inl06); TH_REG("inl", 7, "a recursive device body stays a call", inl07); +TH_REG("inl", 8, "a helper with no callers left is dropped", inl08); diff --git a/tests/tmain.c b/tests/tmain.c index 2feca9d..c8c1986 100644 --- a/tests/tmain.c +++ b/tests/tmain.c @@ -126,6 +126,7 @@ static const tfam_t fam_order[] = { { "bkd", "tbackend.c", "backend registry", 2 }, { "cmp", "tcomp.c", "compile matrix", 2 }, { "wsz", "twarpsize.c", "warp size", 2 }, + { "hst", "thost.c", "host side", 2 }, { "ord", "tordr.c", "harness ordering", 2 }, { "ocm", "tocm.c", "OCaml frontend", 2 }, diff --git a/tests/trpi.c b/tests/trpi.c index 3972f51..fd75b0d 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -2175,36 +2175,40 @@ TH_REG("rpi", 81, "a divergent if gets its bssy and bsync", rpi81) static void rpi82(void) { - const char *path = scratch("rpi82.cu", + const char *p = rpi_sass( "__global__ void k(const double *a, double *o, int n){\n" - " int i = threadIdx.x; if (i < n) o[i] = a[i] / a[0]; }\n"); - char cmd[512]; + " int i = threadIdx.x; if (i < n) o[i] = a[i] / a[0]; }\n", "rpi82"); - CHNE(path, NULL); - snprintf(cmd, sizeof cmd, "%s --nvidia-cubin %s -o build/rpi82.cubin", - BC_BIN, path); - CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); - CHNE(strstr(obuf, "E601"), NULL); - CHNE(strstr(obuf, "NV_DIV_F64"), NULL); + CHNE(p, NULL); + CHNE(strstr(p, "NV_DIV_F64"), NULL); PASS(); } -TH_REG("rpi", 82, "a double divide names its SASS refusal", rpi82) +TH_REG("rpi", 82, "a double divide lowers to SASS", rpi82) static void rpi83(void) { const char *path = scratch("rpi83.cu", "__global__ void k1(int *o){ o[0] = 1; }\n" "__global__ void k2(int *o){ o[1] = 2; }\n"); + unsigned char hdr[64]; char cmd[512]; + FILE *f; CHNE(path, NULL); + remove("build/rpi83.cubin"); snprintf(cmd, sizeof cmd, "%s --nvidia-cubin %s -o build/rpi83.cubin", BC_BIN, path); - CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); - CHNE(strstr(obuf, "E600"), NULL); + CHEQ(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "2 kernels"), NULL); + f = fopen("build/rpi83.cubin", "rb"); + CHNE(f, NULL); + if (!f) return; + CHEQ(fread(hdr, 1, sizeof hdr, f), sizeof hdr); + fclose(f); + CHEQ(hdr[60] | (hdr[61] << 8), 14); PASS(); } -TH_REG("rpi", 83, "a cubin holds one kernel, not two", rpi83) +TH_REG("rpi", 83, "a cubin holds every kernel in the module", rpi83) static void rpi84(void) { @@ -5953,3 +5957,84 @@ static void rpi299(void) PASS(); } TH_REG("rpi", 299, "a bfloat widen shifts, not movrelsd", rpi299) + +static void rpi300(void) +{ + const char *p = rpi_sass( + "__global__ void k(const float *a, float *o, int n){\n" + " int i = threadIdx.x; float t[8];\n" + " for (int j = 0; j < 8; j++) t[j] = a[i] * (float)j;\n" + " if (i < n) o[i] = t[i % 8]; }\n", "rpi300"); + + CHNE(p, NULL); + if (p) { + CHNE(strstr(p, "NV_ST_LOC_F32"), NULL); + CHNE(strstr(p, "7387 "), NULL); + } + PASS(); +} +TH_REG("rpi", 300, "a local array store reaches stl", rpi300) + +static void rpi301(void) +{ + const char *p = rpi_sass( + "__global__ void k(const float *a, const half *h, half *o, float *g){\n" + " int i = threadIdx.x;\n" + " o[i] = __float2half(a[i]); g[i] = __half2float(h[i]); }\n", + "rpi301"); + + CHNE(p, NULL); + if (p) { + CHNE(strstr(p, "723e "), NULL); + CHNE(strstr(p, "7230 "), NULL); + } + PASS(); +} +TH_REG("rpi", 301, "half conversions take f2fp and hadd2", rpi301) + +static void rpi302(void) +{ + const char *p = rpi_sass( + "__global__ void k(const long long *a, long long *o, int n){\n" + " int i = threadIdx.x; if (i < n) o[i] = a[i] / 3; }\n", "rpi302"); + + CHNE(p, NULL); + if (p) CHNE(strstr(p, "NV_DIV_S64"), NULL); + PASS(); +} +TH_REG("rpi", 302, "a 64-bit divide by a constant lowers", rpi302) + +static void rpi303(void) +{ + const char *p = rpi_sass( + "__global__ void k1(const long long *a, long long *o, int n){\n" + " int i = threadIdx.x; long long s = a[0];\n" + " if (i < n && a[i] > s) o[i] = a[i] * s + (a[i] >> 3); }\n" + "__global__ void k2(int *o){ o[threadIdx.x] = 1; }\n", "rpi303"); + + CHNE(p, NULL); + PASS(); +} +TH_REG("rpi", 303, "each kernel sizes its own registers", rpi303) + +static void rpi304(void) +{ + const char *p = rpi_sass( + "namespace cooperative_groups { }\n" + "namespace cg = cooperative_groups;\n" + "__global__ void k(int *d, int n){\n" + " cg::grid_group g = cg::this_grid();\n" + " int i = threadIdx.x; d[i] = i;\n" + " g.sync();\n" + " if (i < n) d[i] = d[0] + 1; }\n", "rpi304"); + + CHNE(p, NULL); + if (p) { + CHEQ(strstr(p, "NV_GBAR"), NULL); + CHNE(strstr(p, "NV_ATOM_ADD_U32"), NULL); + CHNE(strstr(p, "NV_BAR_SYNC"), NULL); + CHNE(strstr(p, "NV_MEMBAR"), NULL); + } + PASS(); +} +TH_REG("rpi", 304, "a grid barrier lowers to blocks, not one op", rpi304) diff --git a/tests/ttpl.c b/tests/ttpl.c index 652851b..e7962b0 100644 --- a/tests/ttpl.c +++ b/tests/ttpl.c @@ -446,3 +446,55 @@ static void tpl27(void) PASS(); } TH_REG("tpl", 27, "a launch names what it could not deduce", tpl27) + +static void tpl33(void) +{ + CHEQ(tpptx("template struct ts {\n" + " using M = int; static const int ne = 1; };\n" + "template struct ts {\n" + " using M = float; static const int ne = 2; };\n" + "template\n" + "__global__ void k(float *o){\n" + " using M = typename ts::M;\n" + " M a = (M)3;\n" + " o[0] = (float)a + (float)ts::ne; }\n" + "void go(float *o){ k<64,8><<<1,1>>>(o);" + " k<64,16><<<1,1>>>(o); }\n"), 0); + CHNE(strstr(tpx, "0f40A00000"), NULL); + CHNE(strstr(tpx, "0f40800000"), NULL); + PASS(); +} +TH_REG("tpl", 33, "a member type alias follows the chosen partial", tpl33) + +static void tpl34(void) +{ + CHNE(tprun("template struct ts { using M = int; };\n" + "__global__ void k(int *o){\n" + " using Q = typename ts<64, 16>::Nope;\n" + " Q a = (Q)1;\n" + " o[0] = (int)a; }\n", "--ir"), 0); + CHNE(strstr(obuf, "E155"), NULL); + CHNE(strstr(obuf, "Nope"), NULL); + PASS(); +} +TH_REG("tpl", 34, "a missing member type refuses by name", tpl34) + +static void tpl35(void) +{ + CHEQ(tpptx("template struct tile {\n" + " static const int ne = I*J/32; };\n" + "template struct mts {" + " using C = tile<32,16>; };\n" + "template struct mts {" + " using C = tile<16,16>; };\n" + "template\n" + "__global__ void k(int *o){\n" + " using C = typename mts::C;\n" + " o[0] = C::ne; }\n" + "void go(int *o){ k<64,8><<<1,1>>>(o);" + " k<64,16><<<1,1>>>(o); }\n"), 0); + CHNE(strstr(tpx, "mov.u32 %r1, 8;"), NULL); + CHNE(strstr(tpx, "mov.u32 %r1, 16;"), NULL); + PASS(); +} +TH_REG("tpl", 35, "a local alias reaches the code under it", tpl35) From 0656d992c7983fcbc9e372579f6b1920ced76f8a Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Thu, 17 Sep 2026 19:41:44 +1200 Subject: [PATCH 02/41] an object that calls, an extent that counts, and a namespace that picks its own --- src/fe/ast.h | 3 + src/fe/parser.c | 13 ++ src/ir/bir_lower.c | 405 ++++++++++++++++++++++++++++++++++++++------- tests/tcpp.c | 114 ++++++++++++- tests/tcxp.c | 50 ++++++ tests/ttpl.c | 26 +++ 6 files changed, 553 insertions(+), 58 deletions(-) diff --git a/src/fe/ast.h b/src/fe/ast.h index 3c88ce3..43e7ce0 100644 --- a/src/fe/ast.h +++ b/src/fe/ast.h @@ -113,6 +113,8 @@ typedef enum { #define QUAL_PTR1 0x4000 #define QUAL_PTR2 0x8000 +#define TS_AUNS 0xFFFFFFFFu + typedef enum { TYPE_VOID, TYPE_BOOL, TYPE_CHAR, TYPE_SHORT, TYPE_INT, TYPE_LONG, TYPE_LLONG, TYPE_FLOAT, TYPE_DOUBLE, TYPE_LDOUBLE, @@ -135,6 +137,7 @@ typedef struct { uint32_t launch_bounds_max; /* 0 = not set. Outside union to avoid the oper.flags conflict. */ uint32_t launch_bounds_min; /* 0 = not set */ uint32_t algn; + uint32_t arrx; union { int64_t ival; double fval; diff --git a/src/fe/parser.c b/src/fe/parser.c index f6e9be1..8c4e2bb 100644 --- a/src/fe/parser.c +++ b/src/fe/parser.c @@ -1592,6 +1592,16 @@ static uint32_t tnargs(parser_t *P) (((pd & 1) ? QUAL_PTR1 : 0) | ((pd & 2) ? QUAL_PTR2 : 0)); else if (ta && pd > 3) P->nodes[ta].qualifiers |= QUAL_DECOR; + if (ta && cur_type(P) == TOK_LBRACKET) { + advance(P); + if (cur_type(P) == TOK_RBRACKET) { + P->nodes[ta].arrx = TS_AUNS; + } else { + uint32_t ex = parse_expr(P, 0); + P->nodes[ta].arrx = ex ? ex : TS_AUNS; + } + if (!match(P, TOK_RBRACKET)) P->nodes[ta].arrx = TS_AUNS; + } if (!ta || !(at_gt(P) || cur_type(P) == TOK_COMMA || cur_type(P) == TOK_ELLIPSIS)) { P->pos = sp; @@ -2567,6 +2577,9 @@ static uint32_t parse_declaration(parser_t *P) while (cur_type(P) == TOK_CONST || cur_type(P) == TOK_NOEXCEPT || cur_type(P) == TOK_OVERRIDE || cur_type(P) == TOK_FINAL) { + if (cur_type(P) == TOK_CONST) + P->nodes[func].qualifiers = + (uint16_t)(P->nodes[func].qualifiers | QUAL_CONST); advance(P); } diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index f4a3e4e..e39879c 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -45,6 +45,8 @@ #define MAX_CEXPS 512 #define MAX_CFNS 128 #define MAX_TLV 8192 +#define MAX_TNS 64 +#define TQ_SEG 8 #define MAX_CDEP 12 #define CF_DEEP 24 #define MAX_CLST 64 @@ -94,6 +96,7 @@ typedef struct { int is_alloca; int lam; int wfrg; + int cst; } sym_t; typedef struct { @@ -186,6 +189,7 @@ typedef struct { typedef struct { uint32_t ast; /* AST_TEMPLATE_DECL node index */ char name[64]; /* function name inside */ + char ns[64]; } template_def_t; typedef struct { @@ -321,6 +325,11 @@ typedef struct { struct { char name[64]; uint32_t ast; } cfns[MAX_CFNS]; int ncfn; uint32_t tlv[MAX_TLV]; + uint8_t tlni[MAX_TLV]; + char tnsp[MAX_TNS][64]; + int ntnsp; + char cns[64]; + char tqns[64]; int ntlv; int cdep; int sdep; @@ -362,6 +371,7 @@ typedef struct { int tsc; struct { char key[256]; char sym[128]; } inst[MAX_INSTS]; int ninst; + uint8_t cmth[BIR_MAX_FUNCS / 8]; int tdep; char pnms[MAX_PARM][64]; @@ -413,6 +423,7 @@ typedef struct { int nglm; int wpend; + int cpend; uint16_t rtbad; int pkbad; int rtunk; @@ -771,6 +782,8 @@ static void add_sym(lower_t *L, const char *name, uint32_t ref, s->lam = 0; s->wfrg = L->wpend; L->wpend = 0; + s->cst = L->cpend; + L->cpend = 0; } static sym_t *find_sym(lower_t *L, const char *name) @@ -917,10 +930,79 @@ static void pk_rw(const lower_t *L, char *name, size_t n) } } +static int tmnsq(const char *ns, const char *q) +{ + size_t nl, ql; + + if (!q[0]) return 1; + if (strcmp(ns, q) == 0) return 1; + nl = strlen(ns); + ql = strlen(q); + return nl > ql + 2 && ns[nl - ql - 1] == ':' && ns[nl - ql - 2] == ':' + && strcmp(ns + nl - ql, q) == 0; +} + +static int tmhit(const lower_t *L, const template_def_t *t, const char *nm) +{ + if (strcmp(t->name, nm) != 0) return 0; + return tmnsq(t->ns, L->tqns); +} + +static int tqany(const lower_t *L, const char *nm, const char *q) +{ + for (int i = 0; i < L->ntemplates; i++) + if (strcmp(L->templates[i].name, nm) == 0 + && tmnsq(L->templates[i].ns, q)) return 1; + return 0; +} + +static void tqset(lower_t *L, const char *nm, const char *q) +{ + L->tqns[0] = 0; + if (q && q[0] && tqany(L, nm, q)) ncpy(L->tqns, sizeof(L->tqns), q); +} + +static uint32_t tqcal(lower_t *L, uint32_t cal, char *nm, size_t nz, + char *q, size_t qz) +{ + uint32_t id[TQ_SEG]; + int n = 0; + + nm[0] = 0; + q[0] = 0; + if (!cal) return 0; + if (ND(L, cal)->type == AST_IDENT) { + get_text(L, cal, nm, (int)nz); + return cal; + } + if (ND(L, cal)->type != AST_SCOPE_RES) return 0; + for (uint32_t c = ND(L, cal)->first_child; c; c = ND(L, c)->next_sibling) { + if (ND(L, c)->type != AST_IDENT || n >= TQ_SEG) return 0; + id[n++] = c; + } + if (n < 2) return 0; + get_text(L, id[n - 1], nm, (int)nz); + for (int i = 0; i < n - 1; i++) { + char part[64]; + size_t u = strlen(q), pl; + + get_text(L, id[i], part, sizeof(part)); + pl = strlen(part); + if (u && u + 2 < qz) { + q[u++] = ':'; + q[u++] = ':'; + q[u] = 0; + } + if (u + pl >= qz) return 0; + memcpy(q + u, part, pl + 1); + } + return id[n - 1]; +} + static template_def_t *find_template(lower_t *L, const char *name) { for (int i = 0; i < L->ntemplates; i++) - if (strcmp(L->templates[i].name, name) == 0) + if (tmhit(L, &L->templates[i], name)) return &L->templates[i]; return NULL; } @@ -2040,6 +2122,18 @@ static void tkeyb(const binding_t *nb, int ntp, const char *cname, static int tfind(const lower_t *L, const char *key, char *sym, size_t symz); static template_def_t *tmpick(lower_t *L, const char *name, const uint32_t *av, int na); + +static template_def_t *tqpick(lower_t *L, const char *nm, const char *q, + const uint32_t *av, int na) +{ + template_def_t *t; + + tqset(L, nm, q); + t = na >= 0 ? tmpick(L, nm, av, na) : find_template(L, nm); + L->tqns[0] = 0; + return t; +} + static void tkfn(lower_t *L, const char *cname, uint32_t func_n, char *key, size_t keyz); static int qtsym(lower_t *L, char *cnm, size_t cz, uint32_t cal); @@ -2630,6 +2724,15 @@ static int tnorm(lower_t *L, uint32_t n, uint32_t *ty, uint16_t *qm) if (bguess(L, n)) return 0; *ty = resolve_type(L, n, tpdep(L, n), 0); if (L->rtbad || L->rtunk) return 0; + if (ND(L, n)->arrx) { + int64_t ex = 0; + + if (ND(L, n)->arrx == TS_AUNS) return 0; + if (!cival(L, ND(L, n)->arrx, &ex)) return 0; + if (ex <= 0 || ex > CE_MAXDIM) return 0; + *ty = bir_type_array(L->M, *ty, (uint32_t)ex); + if (!*ty) return 0; + } *qm = (uint16_t)(ND(L, n)->qualifiers & km); return 1; } @@ -2646,8 +2749,16 @@ static int tsame(lower_t *L, uint32_t ta, uint32_t tb, int *out) *out = 0; return 1; } - if (ra < L->M->num_types && L->M->types[ra].kind == BIR_TYPE_STRUCT - && tamb(L, ra) > 1) return 0; + { + uint32_t el = ra; + + KA_GUARD(g, LO_MAX_DIM); + while (g-- && el < L->M->num_types + && L->M->types[el].kind == BIR_TYPE_ARRAY) + el = L->M->types[el].inner; + if (el < L->M->num_types && L->M->types[el].kind == BIR_TYPE_STRUCT + && tamb(L, el) > 1) return 0; + } *out = 1; return 1; } @@ -5066,6 +5177,35 @@ static int fdflt(lower_t *L, const char *nm, int have, uint32_t *out, int max) return 0; } +static void mcset(lower_t *L, uint32_t lo, const char *nm) +{ + for (uint32_t i = lo; i < L->M->num_funcs; i++) { + if (L->M->funcs[i].name >= L->M->string_len) continue; + if (strcmp(&L->M->strings[L->M->funcs[i].name], nm) != 0) continue; + L->cmth[i >> 3] = (uint8_t)(L->cmth[i >> 3] | (1u << (i & 7u))); + return; + } +} + +static int mcget(const lower_t *L, uint32_t fi) +{ + return fi < BIR_MAX_FUNCS + && (L->cmth[fi >> 3] & (1u << (fi & 7u))) != 0; +} + +static int ocfil(const lower_t *L, uint32_t *cd, int nc, int cst) +{ + int nk = 0, ncst = 0; + + for (int i = 0; i < nc; i++) + if (mcget(L, cd[i])) ncst++; + if (ncst == 0 || ncst == nc) return nc; + if (cst < 0) return -1; + for (int i = 0; i < nc; i++) + if (mcget(L, cd[i]) == cst) cd[nk++] = cd[i]; + return nk ? nk : nc; +} + static int fcand(lower_t *L, const char *nm, int np, uint32_t *out, int cap) { char mng[BIR_SYM_MAX]; @@ -5143,18 +5283,27 @@ static uint32_t fpick(lower_t *L, const uint32_t *cd, int nc, for (int i = 0; i < nc; i++) { uint32_t fty = L->M->funcs[cd[i]].type; uint32_t rm = L->M->funcs[cd[i]].refm; - int sc = 0; + uint32_t rq = L->M->funcs[cd[i]].refq; + int sc = 0, viab = 1; - for (int a = 0; a < na; a++) { + for (int a = 0; a < na && viab; a++) { uint32_t pt = ftpar(L, fty, a); uint32_t ta = at[a]; - if (a < 32 && (rm & (1u << a))) pt = ptr_inner(L, pt); + if (a < 32 && (rm & (1u << a))) { + uint32_t pin = ptr_inner(L, pt); + uint32_t ain = ptr_inner(L, ta); + + if (ain && pin && ain != pin && !((rq >> a) & 1u)) + viab = 0; + pt = pin; + } if (an && aggv(L, an[a])) { if (ptr_inner(L, ta)) ta = ptr_inner(L, ta); if (aggt(L, ptr_inner(L, pt))) pt = ptr_inner(L, pt); } sc += acost(L, ta, pt); } + if (!viab) continue; if (sc > best) { best = sc; bi = cd[i]; *amb = 0; } else if (sc == best) *amb = 1; } @@ -5747,6 +5896,13 @@ static int lfind(lower_t *L, uint32_t node, uint32_t *cptr) *cptr = BIR_MAKE_VAL(s->ref); return s->lam - 1; } + if (s && s->is_alloca && s->type) { + for (int i = 0; i < L->nlam; i++) + if (!L->lams[i].gen && L->lams[i].cst == s->type) { + *cptr = BIR_MAKE_VAL(s->ref); + return i; + } + } } return -1; } @@ -6179,7 +6335,8 @@ static uint32_t mtmp(lower_t *L, uint32_t node) { uint32_t rv, rt, rp, al, sv; - if (ND(L, node)->type != AST_CALL) return lower_lvalue(L, node); + if (ND(L, node)->type != AST_CALL && ND(L, node)->type != AST_CAST) + return lower_lvalue(L, node); rv = lower_expr(L, node); if (rv == BIR_VAL_NONE) return BIR_VAL_NONE; rt = ref_type(L, rv); @@ -6193,6 +6350,79 @@ static uint32_t mtmp(lower_t *L, uint32_t node) return BIR_MAKE_VAL(al); } +static int ocobj(lower_t *L, uint32_t cal) +{ + char nm[128]; + + if (ND(L, cal)->type == AST_CAST) { + uint32_t t = ND(L, cal)->first_child; + uint32_t e = t ? ND(L, t)->next_sibling : 0; + + return e && ND(L, e)->type == AST_INIT_LIST; + } + if (ND(L, cal)->type != AST_IDENT || ND(L, cal)->first_child) return 0; + get_text(L, cal, nm, sizeof nm); + if (!find_sym(L, nm) || find_template(L, nm)) return 0; + return bir_fsym(L->M, nm, L->tu, -1) == BIR_SYM_NONE; +} + +static int ocnst(lower_t *L, uint32_t cal) +{ + char nm[128]; + const sym_t *s; + + if (ND(L, cal)->type == AST_CAST) return 0; + if (ND(L, cal)->type != AST_IDENT) return -1; + get_text(L, cal, nm, sizeof nm); + s = find_sym(L, nm); + return s ? s->cst : -1; +} + +static int omtpl(lower_t *L, int si) +{ + uint32_t tn, m; + char raw[96], nm[96]; + + if (si < 0 || si >= L->nstructs || !L->structs[si].node) return 0; + tn = ND(L, L->structs[si].node)->first_child; + if (!tn) return 0; + for (m = ND(L, tn)->next_sibling; m; m = ND(L, m)->next_sibling) { + if (ND(L, m)->type != AST_TEMPLATE_DECL) continue; + for (uint32_t f = ND(L, m)->first_child; f; + f = ND(L, f)->next_sibling) { + uint32_t nn; + + if (ND(L, f)->type != AST_FUNC_DEF + && ND(L, f)->type != AST_FUNC_DECL) continue; + nn = child_at(L, f, 1); + if (!nn || ND(L, nn)->type != AST_IDENT) continue; + get_text(L, nn, raw, sizeof raw); + normalize_op_name(raw, nm, (int)sizeof nm); + if (strcmp(nm, "operator()") == 0) return 1; + } + } + return 0; +} + +static int ocall(lower_t *L, uint32_t cal, char *cnm, size_t cz, + uint32_t *slf) +{ + uint32_t op, st; + int si; + + if (!ocobj(L, cal)) return 0; + op = mtmp(L, cal); + if (op == BIR_VAL_NONE) return 0; + st = ptr_inner(L, ref_type(L, op)); + si = sfind(L, st); + if (si < 0) return 0; + if (snprintf(cnm, cz, "%s$operator()", L->structs[si].name) < 0) return 0; + if (bir_fsym(L->M, cnm, L->tu, -1) == BIR_SYM_NONE && omtpl(L, si)) + return -1; + *slf = op; + return 1; +} + #define AC_DEEP 8 #define AC_LEAF 512 @@ -6777,10 +7007,6 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) lower_error(L, node, BC_E101); return BIR_VAL_NONE; } - if (s->lam > 0) { - lower_error(L, node, BC_E170, "a closure used as a value"); - return BIR_VAL_NONE; - } if (s->is_alloca) { /* Arrays and structs decay to pointer — return alloca addr * directly. Loading from an array alloca reads uninit @@ -7347,7 +7573,7 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) } char cname[128]; - int fbc = 0; + int fbc = 0, ocf = 0; uint32_t self = BIR_VAL_NONE; uint32_t hdst = L->srdst, hdty = L->srdty; L->srdst = BIR_VAL_NONE; @@ -7381,6 +7607,12 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) if (!smth(L, si, mn)) self = op; } } + ocf = ocall(L, callee_n, cname, sizeof(cname), &self); + if (ocf < 0) { + lower_error(L, node, BC_E030, + "operator() as a member template"); + return BIR_VAL_NONE; + } { const char *fb = fbfn(L, cname); cexp_t *ce = NULL; @@ -8311,31 +8543,6 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) return BIR_MAKE_VAL(inst); } - if (strcmp(cname, "assert") == 0) { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t cv, okb, bad, br; - if (!an) { - lower_error(L, node, BC_E143, cname); - return BIR_VAL_NONE; - } - cv = lower_expr(L, an); - okb = new_block(L, "asrt.ok"); - bad = new_block(L, "asrt.bad"); - br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); - set_op(L, br, 0, cv); - set_op(L, br, 1, okb); - set_op(L, br, 2, bad); - set_op(L, br, 3, okb); - set_block(L, bad); - emit(L, BIR_TRAP, bir_type_void(L->M), 0, 0); - if (!block_terminated(L)) { - uint32_t j = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, j, 0, okb); - } - set_block(L, okb); - return BIR_VAL_NONE; - } - if (strcmp(cname, "printf") == 0) return prntf(L, node, callee_n); @@ -8846,6 +9053,13 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) nargs++; } if (!haspk) ncand = fcand(L, cname, nargs, cand, OV_CAND); + if (ocf && ncand > 1) { + ncand = ocfil(L, cand, ncand, ocnst(L, callee_n)); + if (ncand < 0) { + lower_error(L, node, BC_E156, cname); + return BIR_VAL_NONE; + } + } if (!haspk && ncand == 0 && nargs < BC_MAX_ARGS) { ndef = fdflt(L, cname, nargs, defs, BC_MAX_ARGS - nargs); if (ndef > 0) @@ -9270,7 +9484,7 @@ static uint32_t dcty(lower_t *L, uint32_t node) return 0; sdres(L, nd, &dv); - if (L->sdty && !L->sdarr) { + if (L->sdty && L->sdarr != 2) { L->sdbad = 0; return L->sdty; } @@ -9717,6 +9931,7 @@ static void lower_var_decl(lower_t *L, uint32_t node) uint32_t type_n = child_at(L, node, 0); uint32_t name_n = child_at(L, node, 1); if (!name_n || ND(L, name_n)->type != AST_IDENT) return; + L->cpend = (n->qualifiers & QUAL_CONST) != 0; /* Embedded anonymous struct/union def? Register before resolve. */ uint32_t andef = ND(L, name_n)->next_sibling; @@ -10841,7 +11056,7 @@ static void cstat(lower_t *L, uint32_t node, const char *ovr) for (uint32_t m = ND(L, type_n)->next_sibling; m; m = ND(L, m)->next_sibling) { char fn[64], full[144]; - uint32_t fnn, rt = 0; + uint32_t fnn, rt = 0, nf0; uint16_t cu; if (ND(L, m)->type != AST_FUNC_DEF) continue; cu = ND(L, m)->cuda_flags; @@ -10861,7 +11076,9 @@ static void cstat(lower_t *L, uint32_t node, const char *ovr) L->mrec = rt; ncpy(L->scls, sizeof(L->scls), sn); tscan(L, m); + nf0 = L->M->num_funcs; lower_func_body(L, m, cu, full); + if (ND(L, m)->qualifiers & QUAL_CONST) mcset(L, nf0, full); L->scls[0] = 0; L->mrec = 0; } @@ -10983,7 +11200,16 @@ static int sdreg(lower_t *L, uint32_t mem, struct_def_t *sd) ncpy(e->cls, sizeof(e->cls), sd->name); get_text(L, nn, e->nm, sizeof(e->nm)); e->type = resolve_type(L, ft, ND(L, mem)->d.oper.flags, 0); - e->arr = ND(L, mem)->d.oper.op != 0; + if (ND(L, mem)->d.oper.op < 0) { + e->arr = 2; + } else if (ND(L, mem)->d.oper.op > 0) { + uint32_t aft = 0, abn = 0, at; + int abad = 0; + + at = farr(L, e->type, mem, nn, &aft, &abad, &abn); + e->arr = abad ? 2 : 1; + if (!abad) e->type = at; + } L->rtbad = 0; memset(&v, 0, sizeof(v)); if (!(q & (QUAL_CONST | QUAL_CONSTEXPR))) e->bad = 2; @@ -11591,6 +11817,7 @@ static void collect_template(lower_t *L, uint32_t node) template_def_t *td = &L->templates[L->ntemplates++]; td->ast = node; get_text(L, fn_name, td->name, sizeof(td->name)); + ncpy(td->ns, sizeof(td->ns), L->cns); } /* ---- Template Instantiation ---- */ @@ -11625,7 +11852,7 @@ static uint32_t arg_type(lower_t *L, uint32_t arg) get_text(L, arg, nm, (int)sizeof nm); sy = find_sym(L, nm); - if (sy && sy->type && !sy->lam) return sy->type; + if (sy && sy->type) return sy->type; } if (a->type == AST_SUBSCRIPT && a->first_child && L->atdp < MAX_CDEP) { uint32_t bt; @@ -12751,7 +12978,21 @@ static int tguess(const binding_t *nb, int ntp) static int tsym(lower_t *L, char *cname, size_t cz, uint32_t cal, uint32_t arg) { - template_def_t *tm = find_template(L, cname); + char bare[128], q[128]; + uint32_t idn = 0; + template_def_t *tm; + + q[0] = 0; + if (cal && ND(L, cal)->type == AST_SCOPE_RES) { + idn = tqcal(L, cal, bare, sizeof(bare), q, sizeof(q)); + if (idn && strcmp(bare, cname) != 0) { + idn = 0; + q[0] = 0; + } + } + if (!idn) idn = cal; + + tm = tqpick(L, cname, q, NULL, -1); if (!tm) return 0; uint32_t av[BC_MAX_ARGS]; @@ -12761,9 +13002,9 @@ static int tsym(lower_t *L, char *cname, size_t cz, uint32_t cal, uint32_t func_n = 0; char key[256], sym[128]; - if (na >= 0) tm = tmpick(L, cname, av, na); + if (na >= 0) tm = tqpick(L, cname, q, av, na); if (!tm) return 0; - if (na >= 0 && tdeduc(L, tm->ast, cal, av, na, nb, &ntp, &func_n) + if (na >= 0 && tdeduc(L, tm->ast, idn, av, na, nb, &ntp, &func_n) && !tguess(nb, ntp)) { tkeyb(nb, ntp, cname, key, sizeof(key)); tkfn(L, cname, func_n, key, sizeof(key)); @@ -12824,26 +13065,35 @@ static void tscall(lower_t *L, uint32_t node) { uint32_t cn = ND(L, node)->first_child; template_def_t *tm; - char cname[128]; + char cname[128], q[128]; const char *fb; - uint32_t av[BC_MAX_ARGS], func_n = 0; + uint32_t av[BC_MAX_ARGS], func_n = 0, idn; int na, ntp = 0; - if (!cn || ND(L, cn)->type != AST_IDENT) return; - get_text(L, cn, cname, sizeof(cname)); + if (!cn) return; + { + char fwm[32]; + + if (fwstd(L, cn, fwm, (int)sizeof fwm)) return; + } + idn = tqcal(L, cn, cname, sizeof(cname), q, sizeof(q)); + if (!idn) return; fb = fbfn(L, cname); - if (fb) ncpy(cname, sizeof(cname), fb); + if (fb) { + ncpy(cname, sizeof(cname), fb); + q[0] = 0; + } tm = fb && bir_fsym(L->M, cname, L->tu, -1) != BIR_SYM_NONE - ? NULL : find_template(L, cname); + ? NULL : tqpick(L, cname, q, NULL, -1); if (!tm) return; na = alist(L, ND(L, cn)->next_sibling, av, BC_MAX_ARGS); if (na < 0 || L->xdep >= MAX_NEST) return; - tm = tmpick(L, cname, av, na); + tm = tqpick(L, cname, q, av, na); if (!tm) return; { binding_t *nb = L->xnb[L->xdep++]; - if (tdeduc(L, tm->ast, cn, av, na, nb, &ntp, &func_n)) + if (tdeduc(L, tm->ast, idn, av, na, nb, &ntp, &func_n)) tinst(L, node, cname, nb, ntp, func_n); L->xdep--; } @@ -13170,7 +13420,7 @@ static template_def_t *ftmpl(lower_t *L, const char *name, int na) uint32_t fn, pv[MAX_PARM]; int np, nrq = 0, vg = 0; - if (strcmp(t->name, name) != 0) continue; + if (!tmhit(L, t, name)) continue; if (!first) first = t; if (na < 0) return t; fn = tfunc(L, t); @@ -13284,7 +13534,7 @@ static template_def_t *tmpick(lower_t *L, const char *name, uint32_t fn, pv[MAX_PARM]; int np, ntb, ok = 1, sure = 0; - if (strcmp(t->name, name) != 0) continue; + if (!tmhit(L, t, name)) continue; fn = tfunc(L, t); if (!fn) continue; np = collect_params(L, fn, pv, MAX_PARM); @@ -13938,27 +14188,69 @@ static int cfcol(lower_t *L, uint32_t root) return 1; } +static uint8_t tnsadd(lower_t *L, uint8_t par, uint32_t nsn) +{ + char nm[64], full[64]; + uint32_t id = ND(L, nsn)->first_child; + size_t pl, ml; + + if (!id || ND(L, id)->type != AST_IDENT) return par; + get_text(L, id, nm, sizeof(nm)); + if (!nm[0]) return par; + ncpy(full, sizeof(full), L->tnsp[par]); + pl = strlen(full); + ml = strlen(nm); + if (pl && pl + 2 < sizeof(full)) { + full[pl++] = ':'; + full[pl++] = ':'; + full[pl] = 0; + } + if (pl + ml >= sizeof(full)) return par; + memcpy(full + pl, nm, ml + 1); + for (int i = 0; i < L->ntnsp; i++) + if (strcmp(L->tnsp[i], full) == 0) return (uint8_t)i; + if (L->ntnsp >= MAX_TNS) return par; + ncpy(L->tnsp[L->ntnsp], sizeof(L->tnsp[0]), full); + return (uint8_t)L->ntnsp++; +} + +static const char *tnsof(const lower_t *L, int ti) +{ + uint8_t i = L->tlni[ti]; + + return i < MAX_TNS ? L->tnsp[i] : L->tnsp[0]; +} + static int tlcol(lower_t *L, uint32_t root) { uint32_t st[CE_NEST]; + uint8_t pi[CE_NEST]; uint32_t c = ND(L, root)->first_child; int sp = 0; + uint8_t cur = 0; L->ntlv = 0; + L->ntnsp = 1; + L->tnsp[0][0] = 0; KA_GUARD(g, 1 << 17); while (g--) { if (!c) { if (sp == 0) return 1; - c = ND(L, st[--sp])->next_sibling; + cur = pi[--sp]; + c = ND(L, st[sp])->next_sibling; continue; } if (ND(L, c)->type == AST_NAMESPACE) { if (sp >= CE_NEST) return 0; - st[sp++] = c; + st[sp] = c; + pi[sp] = cur; + sp++; + cur = tnsadd(L, cur, c); c = ND(L, c)->first_child; continue; } if (L->ntlv >= MAX_TLV) return 0; + L->tlni[L->ntlv] = cur; L->tlv[L->ntlv++] = c; c = ND(L, c)->next_sibling; } @@ -14023,6 +14315,7 @@ int bir_ltu(const parser_t *P, uint32_t ast_root, bir_module_t *M, for (int ti = 0; ti < L->ntlv; ti++) { uint32_t c = L->tlv[ti]; const ast_node_t *n = &P->nodes[c]; + ncpy(L->cns, sizeof(L->cns), tnsof(L, ti)); switch (n->type) { case AST_STRUCT_DEF: scoll(L, c); diff --git a/tests/tcpp.c b/tests/tcpp.c index 973ea10..77a3d72 100644 --- a/tests/tcpp.c +++ b/tests/tcpp.c @@ -345,10 +345,120 @@ static void cpp30(void) "__global__ void k(int *o, int n){\n" " auto f = [=](int x) -> int { return x + n; };\n" " o[0] = ap(f); }\n", "--ir"), 0); - CHNE(strstr(obuf, "E170"), NULL); + CHEQ(strstr(obuf, "E170"), NULL); + PASS(); +} +TH_REG("cpp", 30, "a closure the template cannot bind refuses", cpp30) + +/* ---- Calling an object ---- */ + +static void cpp44(void) +{ + CHEQ(cpptx("struct S { int p;\n" + " __device__ int operator()(int x) const { return x + 1000; }\n" + "};\n" + "__global__ void k(int *o){ S s; s.p = 0; o[0] = s(1); }\n"), 0); + CHNE(strstr(code, "1001"), NULL); + PASS(); +} +TH_REG("cpp", 44, "a named object calls its operator()", cpp44) + +static void cpp45(void) +{ + CHEQ(cprun("struct S { int p;\n" + " __device__ int operator()(int x) const { return x + 7; }\n" + "};\n" + "__global__ void k(int *o){ o[0] = S{0}(1); }\n", "--ir"), 0); + CHNE(strstr(obuf, "@S$operator()"), NULL); + PASS(); +} +TH_REG("cpp", 45, "a temporary calls its operator()", cpp45) + +static void cpp46(void) +{ + CHEQ(cprun("struct S { int p;\n" + " __device__ int operator()(int x) const { return x + 5; }\n" + "};\n" + "template __device__ int ap(const F &f)" + "{ return f(1); }\n" + "__global__ void k(int *o){ S s; s.p = 0; o[0] = ap(s); }\n", + "--ir"), 0); + PASS(); +} +TH_REG("cpp", 46, "an object called through a parameter", cpp46) + +static void cpp47(void) +{ + CHEQ(cprun("template struct U {\n" + " __device__ int operator()(int x) const { return x + n; }\n" + "};\n" + "__global__ void k(int *o){ U<3> u; o[0] = u(1); }\n", + "--ir"), 0); + PASS(); +} +TH_REG("cpp", 47, "a class template instance is callable", cpp47) + +static void cpp48(void) +{ + CHEQ(cpptx("struct S { int v;\n" + " __device__ int operator()(int x) { return x + 1000; }\n" + " __device__ int operator()(int x) const { return x + 2000; }\n" + "};\n" + "__global__ void k(int *o){ S s; s.v = 0; o[0] = s(1); }\n"), 0); + CHNE(strstr(code, "1001"), NULL); + CHEQ(strstr(code, "2001"), NULL); + PASS(); +} +TH_REG("cpp", 48, "a non-const object takes the non-const one", cpp48) + +static void cpp49(void) +{ + CHEQ(cpptx("struct S { int v;\n" + " __device__ int operator()(int x) { return x + 1000; }\n" + " __device__ int operator()(int x) const { return x + 2000; }\n" + "};\n" + "__global__ void k(int *o){ S s; s.v = 0; const S c = s;\n" + " o[0] = c(1); }\n"), 0); + CHNE(strstr(code, "2001"), NULL); + CHEQ(strstr(code, "1001"), NULL); + PASS(); +} +TH_REG("cpp", 49, "a const object takes the const one", cpp49) + +static void cpp50(void) +{ + CHNE(cprun("struct S {\n" + " __device__ int operator()(float x) { return (int)x + 1; }\n" + " __device__ int operator()(double x) { return (int)x + 2; }\n" + "};\n" + "__global__ void k(int *o){ S s; o[0] = s(1); }\n", "--ir"), 0); + CHNE(strstr(obuf, "E156"), NULL); + CHNE(strstr(obuf, "S$operator()"), NULL); + PASS(); +} +TH_REG("cpp", 50, "an even pair of operator() refuses by name", cpp50) + +static void cpp51(void) +{ + CHNE(cprun("struct S {\n" + " template __device__ T operator()(T x) const" + " { return x + 1; }\n" + "};\n" + "__global__ void k(int *o){ S s; o[0] = s(1); }\n", "--ir"), 0); + CHNE(strstr(obuf, "member template"), NULL); + PASS(); +} +TH_REG("cpp", 51, "operator() as a member template says so", cpp51) + +static void cpp52(void) +{ + CHNE(cprun("struct S { int p; };\n" + "__global__ void k(int *o){ S s; s.p = 1; o[0] = s(1); }\n", + "--ir"), 0); + CHNE(strstr(obuf, "S$operator()"), NULL); PASS(); } -TH_REG("cpp", 30, "a closure as a value is refused, not guessed", cpp30) +TH_REG("cpp", 52, "an object with no operator() names it", cpp52) static void cpp21(void) { diff --git a/tests/tcxp.c b/tests/tcxp.c index aaeed51..bb40f3c 100644 --- a/tests/tcxp.c +++ b/tests/tcxp.c @@ -616,3 +616,53 @@ static void cxp43(void) } TH_REG("cxp", 43, "a loop in a constexpr body is refused", cxp43) +static void cxp44(void) +{ + CHEQ(cxrun("struct t4 { static constexpr int ne = 4; half2 x[ne]; };\n" + "struct t8 { static constexpr int ne = 8; half2 x[ne]; };\n" + "__global__ void k(int *o){\n" + " if constexpr (std::is_same_v)" + " o[0] = 11; else o[0] = 22;\n" + " if constexpr (std::is_same_v)" + " o[1] = 33; else o[1] = 44;\n" + " if constexpr (std::is_same_v)" + " o[2] = 55; else o[2] = 66; }\n", "--ir"), 0); + CHNE(strstr(obuf, "store i32 11"), NULL); + CHNE(strstr(obuf, "store i32 44"), NULL); + CHNE(strstr(obuf, "store i32 55"), NULL); + CHEQ(strstr(obuf, "store i32 22"), NULL); + CHEQ(strstr(obuf, "store i32 33"), NULL); + CHEQ(strstr(obuf, "store i32 66"), NULL); + PASS(); +} +TH_REG("cxp", 44, "an array extent is part of type identity", cxp44) + +static void cxp45(void) +{ + CHEQ(cxrun("struct t4 { static constexpr int ne = 4; half2 x[ne]; };\n" + "__global__ void k(int *o){\n" + " if constexpr (std::is_same_v)" + " o[0] = 11; else o[0] = 22;\n" + " if constexpr (std::is_same_v)" + " o[1] = 33; else o[1] = 44; }\n", "--ir"), 0); + CHNE(strstr(obuf, "store i32 11"), NULL); + CHNE(strstr(obuf, "store i32 44"), NULL); + CHEQ(strstr(obuf, "store i32 22"), NULL); + CHEQ(strstr(obuf, "store i32 33"), NULL); + PASS(); +} +TH_REG("cxp", 45, "a dependent extent folds before comparison", cxp45) + +static void cxp46(void) +{ + CHNE(cxrun("struct t4 { static constexpr int ne = 4; half2 x[ne]; };\n" + "__global__ void k(int *o){\n" + " if constexpr (std::is_same_v)" + " o[0] = 11; else o[0] = 22; }\n", "--ir"), 0); + CHNE(strstr(obuf, "E158"), NULL); + CHEQ(strstr(obuf, "store i32 11"), NULL); + CHEQ(strstr(obuf, "store i32 22"), NULL); + PASS(); +} +TH_REG("cxp", 46, "an extent that will not fold is refused", cxp46) + diff --git a/tests/ttpl.c b/tests/ttpl.c index e7962b0..b02e902 100644 --- a/tests/ttpl.c +++ b/tests/ttpl.c @@ -498,3 +498,29 @@ static void tpl35(void) PASS(); } TH_REG("tpl", 35, "a local alias reaches the code under it", tpl35) + +static void tpl36(void) +{ + CHEQ(tprun("namespace na {\n" + "template\n" + "__device__ void ld(T & t, const T * p, const int s)\n" + "{ t = p[s] * 11; }\n" + "}\n" + "namespace nb {\n" + "template\n" + "__device__ void ld(T & t, const T * p, const int r,\n" + " const int c)\n" + "{ t = p[r*st + c] * 23; }\n" + "}\n" + "__global__ void k(float *d, const float *s){\n" + " float a = 0.0f, b = 0.0f;\n" + " na::ld(a, s, 3);\n" + " nb::ld<32>(b, s, 1, 2);\n" + " d[0] = a + b;\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "@ld$1"), NULL); + CHEQ(strstr(obuf, "E073"), NULL); + CHEQ(strstr(obuf, "E721"), NULL); + PASS(); +} +TH_REG("tpl", 36, "a namespace picks its own template overload", tpl36) From 5a985bd201687e36b2c374cf6838bc76fea123f1 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Thu, 17 Sep 2026 19:41:46 +1200 Subject: [PATCH 03/41] ldmatrix reaches SASS as LDSM, and the rest of inline asm says why not --- src/nvidia/emit_sass.c | 118 +++++++++++++++++++++++++++++++++++++++-- src/nvidia/isel.c | 3 +- src/nvidia/lt_nv.h | 2 + src/nvidia/lt_nvi.c | 17 ++++++ src/nvidia/nvidia.h | 3 +- tests/tasm.c | 75 ++++++++++++++++++++++++++ 6 files changed, 213 insertions(+), 5 deletions(-) diff --git a/src/nvidia/emit_sass.c b/src/nvidia/emit_sass.c index 170c593..c7a1b81 100644 --- a/src/nvidia/emit_sass.c +++ b/src/nvidia/emit_sass.c @@ -16,6 +16,7 @@ #define SA_TMP2 10u #define SA_NPR 6u #define SA_NOIX 0xFFFFu +#define SA_MAT 12u #define SA_STK 0x028u #define SA_NVW (SA_NV / 64u) #define SA_NIW 1024u @@ -369,10 +370,18 @@ static const nv_call_t *sacof(const nv_minst_t *I) return &sast.M->calls[I->flags % NV_MAX_CALL]; } +static const nv_asm_t *saaof(const nv_minst_t *I) +{ + if (I->op != (uint16_t)NV_ASM) return NULL; + return &sast.M->asms[I->flags % NV_MAX_ASM]; +} + static uint32_t sanop(const nv_minst_t *I) { const nv_call_t *C = sacof(I); + const nv_asm_t *A = saaof(I); + if (A != NULL) return (uint32_t)A->nops; if (C == NULL) return (uint32_t)I->num_defs + (uint32_t)I->num_uses; return (uint32_t)C->hasret + (uint32_t)C->nargs; } @@ -380,7 +389,9 @@ static uint32_t sanop(const nv_minst_t *I) static uint32_t sandf(const nv_minst_t *I) { const nv_call_t *C = sacof(I); + const nv_asm_t *A = saaof(I); + if (A != NULL) return (uint32_t)A->nout; if (C == NULL) return (uint32_t)I->num_defs; return (uint32_t)C->hasret; } @@ -388,7 +399,10 @@ static uint32_t sandf(const nv_minst_t *I) static const nv_opnd_t *saopd(const nv_minst_t *I, uint32_t k) { const nv_call_t *C = sacof(I); + const nv_asm_t *A = saaof(I); + if (A != NULL) + return (k < A->nops && k < NV_MAX_ASMOP) ? &A->ops[k] : NULL; if (C == NULL) return (k < NV_MAX_OPS) ? &I->ops[k] : NULL; if (C->hasret != 0u) { if (k == 0u) return &C->ret; @@ -440,7 +454,8 @@ static int sascan(void) if (v == SA_NOIX) return 1; sast.vwd[v] = (uint8_t)savw(o->rfile); sast.vpr[v] = (o->rfile == (uint8_t)NV_RF_PRED) ? 1u : 0u; - if (I->op != (uint16_t)NV_CALL) m++; + if (I->op != (uint16_t)NV_CALL + && I->op != (uint16_t)NV_ASM) m++; if (saterm(I) != TFALL) sast.vuse[v] = 0xFFFFu; else if (sast.vuse[v] < 0xFFFEu) sast.vuse[v]++; } @@ -2425,10 +2440,14 @@ static void sacall(const nv_minst_t *I) uint32_t g, ci, at; memset(&x, 0, sizeof x); - if (C->vprt != 0u || C->fn >= BIR_MAX_FUNCS) { - sabad(I->op, BC_E601); + if (C->vprt != 0u) { + (void)be_fail(BC_E541, "nvptx", + "a device-side printf, whose vprintf ABI has no SASS " + "form here"); + sast.nbad++; return; } + if (C->fn >= BIR_MAX_FUNCS) { sabad(I->op, BC_E609); return; } if (sast.isfn != 0u) { (void)be_fail(BC_E541, "nvptx", "a device function that itself calls, whose return " @@ -2731,6 +2750,98 @@ static void sansl(const nv_minst_t *I) safire(w, &x, 0u); } +static int sapfx(const char *t, const char *p) +{ + uint32_t i = 0u; + + while (i < (uint32_t)BIR_ASM_TMPLZ && p[i] != '\0') { + if (t[i] != p[i]) return 0; + i++; + } + return 1; +} + +static const char *saawhy(const char *t) +{ + if (sapfx(t, "mma.sync")) + return "a warp matrix multiply in inline asm, whose SASS shape field " + "no encoding source here records"; + if (sapfx(t, "cp.async")) + return "an asynchronous shared copy in inline asm"; + if (sapfx(t, "ldmatrix")) + return "an ldmatrix shape with no SASS form here"; + return "an inline asm template with no SASS form here"; +} + +static int saaok(const nv_asm_t *A, uint32_t n) +{ + if (A->nops != n + 1u || (uint32_t)A->nout != n) return 0; + for (uint32_t k = 0; k < n; k++) { + if (A->ops[k].kind != (uint8_t)NV_MOP_REG) return 0; + if (savw(A->ops[k].rfile) != 1u) return 0; + } + return A->ops[n].kind == (uint8_t)NV_MOP_REG; +} + +static void saldsm(const nv_minst_t *I, const nv_asm_t *A, uint32_t n, + uint32_t tr) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t ra; + + memset(&x, 0, sizeof x); + if (saaok(A, n) == 0) { sabad(I->op, BC_E609); return; } + ra = sarg(&A->ops[n]); + samsr(&x.rd, ra, savw(A->ops[n].rfile)); + samsr(&x.wr, SA_MAT, n); + lt_nvldsm(w, SA_MAT, ra, 0u, n, tr); + safire(w, &x, 3u); + for (uint32_t k = 0; k < n; k++) { + lt_nrw_t y; + uint32_t d = sarg(&A->ops[k]); + + memset(&y, 0, sizeof y); + samsr(&y.rd, SA_MAT + k, 1u); + samsr(&y.wr, d, 1u); + lt_nvmov(w, d, SA_MAT + k); + safire(w, &y, 0u); + } +} + +static void saasm(const nv_minst_t *I) +{ + const nv_asm_t *A = saaof(I); + const char *t; + + if (A == NULL || sast.M->bir == NULL + || A->tmpl >= sast.M->bir->string_len) { + sabad(I->op, BC_E609); + return; + } + t = sast.M->bir->strings + A->tmpl; + if (sapfx(t, "ldmatrix.sync.aligned.m8n8.x1.b16")) { + saldsm(I, A, 1u, 0u); return; + } + if (sapfx(t, "ldmatrix.sync.aligned.m8n8.x2.b16")) { + saldsm(I, A, 2u, 0u); return; + } + if (sapfx(t, "ldmatrix.sync.aligned.m8n8.x4.b16")) { + saldsm(I, A, 4u, 0u); return; + } + if (sapfx(t, "ldmatrix.sync.aligned.m8n8.x1.trans.b16")) { + saldsm(I, A, 1u, 1u); return; + } + if (sapfx(t, "ldmatrix.sync.aligned.m8n8.x2.trans.b16")) { + saldsm(I, A, 2u, 1u); return; + } + if (sapfx(t, "ldmatrix.sync.aligned.m8n8.x4.trans.b16")) { + saldsm(I, A, 4u, 1u); return; + } + (void)be_fail(BC_E541, "nvptx", saawhy(t)); + sast.nbad++; +} + static void samemc(const nv_minst_t *I) { switch (I->op) { @@ -2766,6 +2877,7 @@ static void samemc(const nv_minst_t *I) case NV_NANOSLP: sansl(I); return; case NV_RET: case NV_EXIT: saquit(); return; case NV_CALL: sacall(I); return; + case NV_ASM: saasm(I); return; case NV_ST_RETP: saretp(I); return; case NV_SHFL_IDX: case NV_SHFL_UP: case NV_SHFL_DOWN: case NV_SHFL_XOR: sashf(I); return; diff --git a/src/nvidia/isel.c b/src/nvidia/isel.c index 38392dc..69b1754 100644 --- a/src/nvidia/isel.c +++ b/src/nvidia/isel.c @@ -1092,7 +1092,8 @@ static void is_asm(const bir_inst_t *I) X = &S.nv->asms[S.nv->num_asm]; X->tmpl = A->tmpl; X->nops = (uint8_t)A->nops; - X->pad[0] = X->pad[1] = X->pad[2] = 0; + X->nout = (uint8_t)A->nout; + X->pad[0] = X->pad[1] = 0; if (!asmb(A, I, X, pv, pr)) return; zero[0] = mop_none(); diff --git a/src/nvidia/lt_nv.h b/src/nvidia/lt_nv.h index e21af49..022e880 100644 --- a/src/nvidia/lt_nv.h +++ b/src/nvidia/lt_nv.h @@ -325,6 +325,8 @@ void lt_nvldl(uint64_t *w, uint32_t dst, uint32_t ra, uint32_t off, uint32_t ty) void lt_nvstl(uint64_t *w, uint32_t ra, uint32_t rb, uint32_t off, uint32_t ty); void lt_nvlds(uint64_t *w, uint32_t dst, uint32_t ra, uint32_t off, uint32_t ty); void lt_nvsts(uint64_t *w, uint32_t ra, uint32_t rb, uint32_t off, uint32_t ty); +void lt_nvldsm(uint64_t *w, uint32_t d, uint32_t ra, uint32_t off, + uint32_t n, uint32_t tr); void lt_nvvot(uint64_t *w, uint32_t d, uint32_t pd, uint32_t p, uint32_t nt, uint32_t vop); void lt_nvsfl(uint64_t *w, uint32_t d, uint32_t pd, uint32_t ra, uint32_t rb, diff --git a/src/nvidia/lt_nvi.c b/src/nvidia/lt_nvi.c index 75da347..d640ac9 100644 --- a/src/nvidia/lt_nvi.c +++ b/src/nvidia/lt_nvi.c @@ -486,6 +486,23 @@ lt_nvsts(uint64_t *w, uint32_t ra, uint32_t rb, uint32_t off, uint32_t ty) lt_nvput(w, 75u, 73u, ty); } +void +lt_nvldsm(uint64_t *w, uint32_t d, uint32_t ra, uint32_t off, + uint32_t n, uint32_t tr) +{ + assert(w != NULL); + assert(d < 256u && ra < 256u && off < (1u << 24)); + assert(n == 1u || n == 2u || n == 4u); + assert(tr < 2u); + + head(w, 0x83Bu, 0u); /* per nak-mesa-90320e12 sm70_encode.rs:4622 */ + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 31u, 24u, ra); + lt_nvput(w, 63u, 40u, off); + lt_nvput(w, 73u, 72u, (n == 4u) ? 2u : ((n == 2u) ? 1u : 0u)); + lt_nvput(w, 79u, 78u, tr); +} + /* ---- Lanes ---- */ void diff --git a/src/nvidia/nvidia.h b/src/nvidia/nvidia.h index a61c3b6..e6174fd 100644 --- a/src/nvidia/nvidia.h +++ b/src/nvidia/nvidia.h @@ -310,7 +310,8 @@ typedef struct { typedef struct { uint32_t tmpl; /* BIR strings offset of the template text */ uint8_t nops; - uint8_t pad[3]; + uint8_t nout; + uint8_t pad[2]; nv_opnd_t ops[NV_MAX_ASMOP]; } nv_asm_t; diff --git a/tests/tasm.c b/tests/tasm.c index a8f33d0..d30b8b6 100644 --- a/tests/tasm.c +++ b/tests/tasm.c @@ -230,3 +230,78 @@ static void asm16(void) PASS(); } TH_REG("asm", 16, "a PTX template is refused on an AMD target", asm16) + +static int acub(const char *src) +{ + remove("build/tasm.cubin"); + return arun(src, "--nvidia-cubin -o build/tasm.cubin"); +} + +static const char *const ldm2 = + "__global__ void k(int *o) {\n" + " __shared__ int s[256];\n" + " s[threadIdx.x] = (int)threadIdx.x;\n" + " __syncthreads();\n" + " int a = 0, b = 0;\n" + " const int *p = s + (threadIdx.x & 7) * 2;\n" + " asm volatile(\"ldmatrix.sync.aligned.m8n8.x2.b16 {%0, %1}, [%2];\"\n" + " : \"=r\"(a), \"=r\"(b) : \"l\"(p));\n" + " o[threadIdx.x] = a + b;\n" + "}\n"; + +static const char *const ldm4 = + "__global__ void k(int *o) {\n" + " __shared__ int s[256];\n" + " s[threadIdx.x] = (int)threadIdx.x;\n" + " __syncthreads();\n" + " int a = 0, b = 0, c = 0, d = 0;\n" + " const int *p = s + (threadIdx.x & 7) * 4;\n" + " asm volatile(\"ldmatrix.sync.aligned.m8n8.x4.b16\"\n" + " \" {%0, %1, %2, %3}, [%4];\"\n" + " : \"=r\"(a), \"=r\"(b), \"=r\"(c), \"=r\"(d) : \"l\"(p));\n" + " o[threadIdx.x] = a + b + c + d;\n" + "}\n"; + +static void asm17(void) +{ + CHEQ(acub(ldm2), 0); + PASS(); +} +TH_REG("asm", 17, "ldmatrix x2 reaches SASS as LDSM", asm17) + +static void asm18(void) +{ + CHEQ(acub(ldm4), 0); + PASS(); +} +TH_REG("asm", 18, "ldmatrix x4 reaches SASS as LDSM", asm18) + +static void asm19(void) +{ + CHNE(acub( + "__global__ void k(int *o) {\n" + " int d0 = 0, d1 = 0, a0 = 1, a1 = 2, a2 = 3, a3 = 4;\n" + " int b0 = 5, b1 = 6;\n" + " asm(\"mma.sync.aligned.m16n8k16.row.col.f16.f16.f16.f16\"\n" + " \" {%0, %1}, {%2, %3, %4, %5}, {%6, %7}, {%0, %1};\"\n" + " : \"+r\"(d0), \"+r\"(d1)\n" + " : \"r\"(a0), \"r\"(a1), \"r\"(a2), \"r\"(a3),\n" + " \"r\"(b0), \"r\"(b1));\n" + " o[threadIdx.x] = d0 + d1;\n" + "}\n"), 0); + CHNE(strstr(obuf, "warp matrix multiply"), NULL); + PASS(); +} +TH_REG("asm", 19, "a mma.sync template refuses by name", asm19) + +static void asm20(void) +{ + CHNE(acub( + "__global__ void k(int *o) {\n" + " printf(\"%d\", (int)threadIdx.x);\n" + " o[threadIdx.x] = 1;\n" + "}\n"), 0); + CHNE(strstr(obuf, "vprintf"), NULL); + PASS(); +} +TH_REG("asm", 20, "a device printf refuses by name in SASS", asm20) From e39e8fb5757f489897d3aab16bf013225225f50f Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Thu, 17 Sep 2026 19:41:48 +1200 Subject: [PATCH 04/41] a header nobody can find gets a warning with a name on it --- lang/en.txt | 1 + src/barracuda.h | 4 ++++ src/fe/bc_err.c | 3 ++- src/fe/bc_err.h | 1 + src/fe/bc_render.c | 8 +++++--- src/fe/preproc.c | 41 +++++++++++++++++++++++++++++++++++------ src/fe/preproc.h | 5 +++++ tests/misshdr.cu | 3 +++ tests/rules.tbl | 2 +- tests/trpi.c | 29 +++++++++++++++++++++++++++++ 10 files changed, 86 insertions(+), 11 deletions(-) create mode 100644 tests/misshdr.cu diff --git a/lang/en.txt b/lang/en.txt index 8b08f46..ad3dcc2 100644 --- a/lang/en.txt +++ b/lang/en.txt @@ -41,6 +41,7 @@ E050=#include: cannot read '%s' E051=unknown directive: #%s E052=unterminated #if/#ifdef (missing %d #endif) E053=preprocessor output overflow (max %d bytes) +E054=#include: cannot find '%s' on any search path # ---- Sema (E070-E099) ---- E070=arrow on non-pointer diff --git a/src/barracuda.h b/src/barracuda.h index 1e84d31..4c46b48 100644 --- a/src/barracuda.h +++ b/src/barracuda.h @@ -71,8 +71,12 @@ typedef struct { char msg[256]; int code; uint16_t eid; /* bc_eid_t — language-neutral error ID */ + uint8_t sev; } bc_error_t; +#define BC_SEV_ERR 0u +#define BC_SEV_WARN 1u + #include "fe/bc_err.h" #endif /* BARRACUDA_H */ diff --git a/src/fe/bc_err.c b/src/fe/bc_err.c index 454f24e..02c716f 100644 --- a/src/fe/bc_err.c +++ b/src/fe/bc_err.c @@ -50,7 +50,8 @@ static const char *bc_dflt[BC_EID_MAX] = { /* E051 */ "unknown directive: #%s", /* E052 */ "unterminated #if/#ifdef (missing %d #endif)", /* E053 */ "preprocessor output overflow (max %d bytes)", - NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E054 */ "#include: cannot find '%s' on any search path", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, /* ---- Sema ---- */ /* E070 */ "arrow on non-pointer", /* E071 */ "no field '%s' in struct '%s'", diff --git a/src/fe/bc_err.h b/src/fe/bc_err.h index e840288..38b212d 100644 --- a/src/fe/bc_err.h +++ b/src/fe/bc_err.h @@ -64,6 +64,7 @@ typedef enum { BC_E051 = 51, /* unknown directive: #%s */ BC_E052 = 52, /* unterminated #if/#ifdef (missing %d #endif) */ BC_E053 = 53, /* preprocessor output overflow (max %d bytes) */ + BC_E054 = 54, /* #include: cannot find '%s' on any search path */ /* ---- Sema (E070-E099) ---- */ BC_E070 = 70, /* arrow on non-pointer */ diff --git a/src/fe/bc_render.c b/src/fe/bc_render.c index 3c1b2d7..455f901 100644 --- a/src/fe/bc_render.c +++ b/src/fe/bc_render.c @@ -47,12 +47,14 @@ static void render_one(const char *file, const char *src, const bc_error_t *er) { int c = use_colour(); - const char *red = c ? "\033[1;31m" : ""; + int w = er->sev == BC_SEV_WARN; + const char *red = c ? (w ? "\033[1;33m" : "\033[1;31m") : ""; const char *blue = c ? "\033[1;34m" : ""; const char *rst = c ? "\033[0m" : ""; - fprintf(stderr, "%serror%s[E%03u]: %s\n", - red, rst, (unsigned)er->eid, er->msg); + fprintf(stderr, "%s%s%s[E%03u]: %s\n", + red, w ? "warning" : "error", rst, + (unsigned)er->eid, er->msg); fprintf(stderr, " %s-->%s %s:%u:%u\n", blue, rst, file ? file : "", diff --git a/src/fe/preproc.c b/src/fe/preproc.c index b46ea67..c46dfb8 100644 --- a/src/fe/preproc.c +++ b/src/fe/preproc.c @@ -18,18 +18,38 @@ /* ---- Error reporting ---- */ -static void pp_error(preproc_t *pp, bc_eid_t eid, ...) +static void pp_rec(preproc_t *pp, bc_eid_t eid, uint8_t sev, va_list ap) { - if (pp->num_errors >= BC_MAX_ERRORS) return; bc_error_t *e = &pp->errors[pp->num_errors++]; + + if (sev == (uint8_t)BC_SEV_ERR) pp->nhard++; e->loc.line = pp->line; e->loc.col = 1; e->loc.offset = pp->pos; e->code = BC_ERR_PREPROC; e->eid = (uint16_t)eid; + e->sev = sev; + if (vsnprintf(e->msg, sizeof(e->msg), bc_efmt(eid), ap) < 0) + e->msg[0] = '\0'; +} + +static void pp_error(preproc_t *pp, bc_eid_t eid, ...) +{ va_list ap; + + if (pp->num_errors >= BC_MAX_ERRORS) return; va_start(ap, eid); - vsnprintf(e->msg, sizeof(e->msg), bc_efmt(eid), ap); + pp_rec(pp, eid, (uint8_t)BC_SEV_ERR, ap); + va_end(ap); +} + +static void pp_warn(preproc_t *pp, bc_eid_t eid, ...) +{ + va_list ap; + + if (pp->num_errors >= BC_MAX_ERRORS) return; + va_start(ap, eid); + pp_rec(pp, eid, (uint8_t)BC_SEV_WARN, ap); va_end(ap); } @@ -1329,13 +1349,22 @@ static void pp_dir_include(preproc_t *pp) } if (!found) { - /* Not found — skip with warning (allows test files with system includes) */ - /* Don't treat as error — common for , etc. */ if (pp->keepinc) { pp_emit_str(pp, "#include ", 9u); pp_emit_char(pp, is_angle ? '<' : '"'); pp_emit_str(pp, include_name, nlen); pp_emit_char(pp, is_angle ? '>' : '"'); + } else { + uint32_t m; + for (m = 0; m < pp->nmiss; m++) + if (strcmp(pp->miss[m], include_name) == 0) break; + if (m == pp->nmiss) { + if (pp->nmiss < PP_MAX_MISS + && snprintf(pp->miss[pp->nmiss], BC_MAX_PATH, "%s", + include_name) > 0) + pp->nmiss++; + pp_warn(pp, BC_E054, include_name); + } } return; } @@ -1591,7 +1620,7 @@ int pp_process(preproc_t *pp) pp->out[pp->out_len < pp->out_max ? pp->out_len : pp->out_max - 1] = '\0'; - return pp->num_errors > 0 ? BC_ERR_PREPROC : BC_OK; + return pp->nhard > 0 ? BC_ERR_PREPROC : BC_OK; } /* ---- Public API ---- */ diff --git a/src/fe/preproc.h b/src/fe/preproc.h index f33ed98..a3121e4 100644 --- a/src/fe/preproc.h +++ b/src/fe/preproc.h @@ -21,6 +21,7 @@ #define PP_MAX_EXPAND_DEPTH 32 #define PP_MAX_ONCE 256 #define PP_MAX_JOIN 256 +#define PP_MAX_MISS 64 #define PP_POOL_SIZE (256 * 1024) /* 256KB for macro names + bodies */ #define PP_LINE_BUF (64 * 1024) /* 64KB max logical line */ #define PP_EXPAND_BUF (128 * 1024) /* 128KB expansion workspace */ @@ -104,9 +105,13 @@ typedef struct { int keepinc; + char miss[PP_MAX_MISS][BC_MAX_PATH]; + uint32_t nmiss; + /* Errors */ bc_error_t errors[BC_MAX_ERRORS]; int num_errors; + int nhard; } preproc_t; void pp_init(preproc_t *pp, const char *src, uint32_t len, diff --git a/tests/misshdr.cu b/tests/misshdr.cu new file mode 100644 index 0000000..f86c98f --- /dev/null +++ b/tests/misshdr.cu @@ -0,0 +1,3 @@ +#include + +__global__ void mh(int *o) { o[0] = 1; } diff --git a/tests/rules.tbl b/tests/rules.tbl index 624269f..9191f71 100644 --- a/tests/rules.tbl +++ b/tests/rules.tbl @@ -5,5 +5,5 @@ goto 63 goto, setjmp or longjmp alloc 99 allocation calls fnptr 25 function pointers long 148 functions over 60 lines -comment 6510 comment lines +comment 6509 comment lines snprintf 83 snprintf calls whose return is discarded diff --git a/tests/trpi.c b/tests/trpi.c index fd75b0d..7124496 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6038,3 +6038,32 @@ static void rpi304(void) PASS(); } TH_REG("rpi", 304, "a grid barrier lowers to blocks, not one op", rpi304) + +static long rpi_fsz(const char *path) +{ + FILE *f = fopen(path, "rb"); + long n; + + if (!f) return -1; + fseek(f, 0, SEEK_END); + n = ftell(f); + fclose(f); + return n; +} + +static void rpi305(void) +{ + const char *path = scratch("rpi305.cu", + "#include \n" + "__global__ void k(int *o){ o[0] = 1; }\n"); + char cmd[512]; + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --nvidia-ptx %s -o build/rpi305.ptx", + BC_BIN, path); + CHEQ(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E054"), NULL); + CHNE(strstr(obuf, "no_such_header_anywhere.h"), NULL); + PASS(); +} +TH_REG("rpi", 305, "a header Booth cannot find is named", rpi305) From f7501cabe70f6627615fdca1469090cc277b0d2a Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Thu, 17 Sep 2026 19:41:49 +1200 Subject: [PATCH 05/41] assert traps on the device and falls through to the system header everywhere else --- runtime/include/cassert | 9 ++++ runtime/include/cuda_runtime.h | 14 +++--- tests/trpi.c | 80 ++++++++++++++++++++++++++++++++-- 3 files changed, 94 insertions(+), 9 deletions(-) create mode 100644 runtime/include/cassert diff --git a/runtime/include/cassert b/runtime/include/cassert new file mode 100644 index 0000000..626ef39 --- /dev/null +++ b/runtime/include/cassert @@ -0,0 +1,9 @@ +#undef assert + +#ifdef NDEBUG +#define assert(e) ((void)0) +#elif defined(__CUDACC__) +#define assert(e) do { if (!(e)) __trap(); } while (0) +#else +#include +#endif diff --git a/runtime/include/cuda_runtime.h b/runtime/include/cuda_runtime.h index aea2c33..72d85d9 100644 --- a/runtime/include/cuda_runtime.h +++ b/runtime/include/cuda_runtime.h @@ -301,6 +301,15 @@ CUDART_C cudaError_t cudaSetDeviceFlags(unsigned flags); CUDART_C cudaError_t cudaDeviceCanAccessPeer(int *out, int dev, int peer); CUDART_C cudaError_t cudaDeviceEnablePeerAccess(int peer, unsigned flags); +#if defined(__cplusplus) + +extern "C" cudaError_t cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, + unsigned flags = 0u); +extern "C" cudaError_t cudaMallocManaged(void **out, size_t n, + unsigned flags = cudaMemAttachGlobal); + +#endif + #if !defined(__CUDACC__) extern const uint3 threadIdx; @@ -353,11 +362,6 @@ static cudaError_t cudaGetDeviceProperties(cudaDeviceProp *prop, int dev) #if defined(__cplusplus) -extern "C" cudaError_t cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, - unsigned flags = 0u); -extern "C" cudaError_t cudaMallocManaged(void **out, size_t n, - unsigned flags = cudaMemAttachGlobal); - template static cudaError_t cudaFuncSetAttribute(T *fn, int attr, int val) { diff --git a/tests/trpi.c b/tests/trpi.c index 7124496..019f844 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -624,6 +624,33 @@ static const char *rpi_ptx(const char *src, const char *stem) return ptx; } +static const char *rpi_pti(const char *src, const char *stem, + const char *xtra) +{ + static char ptx[1 << 16]; + char cmd[512], cu[128], out[128]; + FILE *f, *g; + size_t n; + + ptx[0] = '\0'; + snprintf(cu, sizeof cu, "build/%s.cu", stem); + snprintf(out, sizeof out, "build/%s.ptx", stem); + f = fopen(cu, "w"); + if (!f) return NULL; + fputs(src, f); + fclose(f); + remove(out); + snprintf(cmd, sizeof cmd, "%s --nvidia-ptx %s %s -o %s", + BC_BIN, xtra, cu, out); + if (th_run(cmd, obuf, (int)sizeof obuf) != 0) return NULL; + g = fopen(out, "rb"); + if (!g) return NULL; + n = fread(ptx, 1, sizeof ptx - 1, g); + fclose(g); + ptx[n] = '\0'; + return ptx; +} + static void rpi17(void) { const char *p = rpi_ptx( @@ -688,12 +715,12 @@ static void rpi19(void) } TH_REG("rpi", 19, "a member of an anonymous union resolves", rpi19) -/* assert in device code traps and loses its message */ static void rpi20(void) { - const char *p = rpi_ptx( + const char *p = rpi_pti( + "#include \n" "__global__ void k(int *o, int n){ assert(n > 0); o[0] = n; }\n", - "rpi20"); + "rpi20", "-Iruntime/include"); CHNE(p, NULL); CHEQ(strstr(obuf, "E143"), NULL); @@ -701,7 +728,7 @@ static void rpi20(void) CHNE(strstr(p, "trap;"), NULL); PASS(); } -TH_REG("rpi", 20, "assert becomes a conditional trap", rpi20) +TH_REG("rpi", 20, "assert from is a conditional trap", rpi20) /* BIR_GLOBAL_REF reaches a __device__ table on PTX */ static void rpi21(void) @@ -6067,3 +6094,48 @@ static void rpi305(void) PASS(); } TH_REG("rpi", 305, "a header Booth cannot find is named", rpi305) + +static void rpi306(void) +{ + const char *path = scratch("rpi306.cu", + "__global__ void k(int *o, int n){ assert(n > 0); o[0] = n; }\n"); + char cmd[512]; + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --nvidia-ptx %s -o build/rpi306.ptx", + BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E105"), NULL); + PASS(); +} +TH_REG("rpi", 306, "assert with no declaration refuses by name", rpi306) + +static void rpi307(void) +{ + const char *p = rpi_pti( + "#include \n" + "__global__ void k(int *o, int n){\n" + " assert((128 <= 1024) && (128 % 32) == 0); o[0] = n; }\n", + "rpi307", "-Iruntime/include"); + + CHNE(p, NULL); + if (p) CHEQ(strstr(p, "trap;"), NULL); + PASS(); +} +TH_REG("rpi", 307, "a literal assert guard leaves no trap", rpi307) + +static void rpi308(void) +{ + static const char *const src = + "#include \n" + "__global__ void k(int *o, int n){ assert(n > 0); o[0] = n; }\n"; + const char *p = rpi_pti(src, "rpi308a", "-Iruntime/include"); + + CHNE(p, NULL); + if (p) CHNE(strstr(p, "trap;"), NULL); + p = rpi_pti(src, "rpi308b", "-Iruntime/include -DNDEBUG"); + CHNE(p, NULL); + if (p) CHEQ(strstr(p, "trap;"), NULL); + PASS(); +} +TH_REG("rpi", 308, "NDEBUG reaches the device compile", rpi308) From 2d2f2542fa03a77c0a5f3159b0bb3b1385978974 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Thu, 17 Sep 2026 19:41:51 +1200 Subject: [PATCH 06/41] kath cuda stops quietly dropping the flags you gave it --- src/exec/verbs.c | 139 ++++++++++++++++++++++++++++++++++++----------- src/host/hgen.c | 10 +++- src/host/hgen.h | 3 +- tests/trpi.c | 41 ++++++++++++++ 4 files changed, 159 insertions(+), 34 deletions(-) diff --git a/src/exec/verbs.c b/src/exec/verbs.c index 0337237..f335c14 100644 --- a/src/exec/verbs.c +++ b/src/exec/verbs.c @@ -21,6 +21,17 @@ #define MAXPASS 24 #define PATHN 512 #define MAXINC 16 +#define MAXDEF 64 +#define MAXFWD 16 + +typedef struct { + const char *file, *out; + const char *inc[MAXINC]; + const char *def[MAXDEF]; + const char *fwd[MAXFWD]; + int ninc, ndef, nfwd; + int obj, pic, fb; +} cuo_t; static const char VADD_SRC[] = "__global__ void vadd(int *out, int *a, int *b)\n" @@ -499,18 +510,24 @@ static int verb_doctor(void) /* ---- dispatch ---- */ static int cuda1(const char *flag, const char *file, const char *out, - const char *fat, const char *const *inc, int ninc) + const char *fat, const cuo_t *F) { - char *av[10 + 2 * MAXINC]; + char *av[12 + 2 * MAXINC + 2 * MAXDEF + MAXFWD]; int n = 0; av[n++] = (char *)"kath"; av[n++] = (char *)flag; if (fat != NULL) { av[n++] = (char *)"--fatbin"; av[n++] = (char *)fat; } - for (int i = 0; i < ninc; i++) { + for (int i = 0; i < F->ninc; i++) { av[n++] = (char *)"-I"; - av[n++] = (char *)inc[i]; + av[n++] = (char *)F->inc[i]; } + for (int i = 0; i < F->ndef; i++) { + av[n++] = (char *)"-D"; + av[n++] = (char *)F->def[i]; + } + for (int i = 0; i < F->nfwd; i++) + av[n++] = (char *)F->fwd[i]; av[n++] = (char *)file; av[n++] = (char *)"-o"; av[n++] = (char *)out; @@ -534,8 +551,12 @@ static int oinc(char *b, size_t n, size_t *u, const char *d) return oapp(b, n, u, " -I\"") && oapp(b, n, u, d) && oapp(b, n, u, "\""); } -static int cc_obj(const char *src, const char *out, const char *const *inc, - int ninc, int pic) +static int odef(char *b, size_t n, size_t *u, const char *d) +{ + return oapp(b, n, u, " -D\"") && oapp(b, n, u, d) && oapp(b, n, u, "\""); +} + +static int cc_obj(const char *src, const char *out, const cuo_t *F, int pic) { char cmd[4096], own[512]; const char *cc = getenv("BOOTH_CXX"); @@ -547,8 +568,10 @@ static int cc_obj(const char *src, const char *out, const char *const *inc, ok = oapp(cmd, sizeof cmd, &u, cc) && oapp(cmd, sizeof cmd, &u, " -std=c++17 -O2"); if (ok && pic) ok = oapp(cmd, sizeof cmd, &u, " -fPIC"); - for (int i = 0; ok && i < ninc; i++) - ok = oinc(cmd, sizeof cmd, &u, inc[i]); + for (int i = 0; ok && i < F->ndef; i++) + ok = odef(cmd, sizeof cmd, &u, F->def[i]); + for (int i = 0; ok && i < F->ninc; i++) + ok = oinc(cmd, sizeof cmd, &u, F->inc[i]); if (ok && hg_binc(own, sizeof own)) ok = oinc(cmd, sizeof cmd, &u, own); ok = ok && oapp(cmd, sizeof cmd, &u, " -c \"") @@ -560,59 +583,111 @@ static int cc_obj(const char *src, const char *out, const char *const *inc, return ok_status(system(cmd)) ? 0 : 1; } -static int verb_cuda(int argc, char **argv) +static int cutoo(const char *what, int max) { - const char *file = NULL, *out = NULL; - const char *inc[MAXINC]; - char cub[PATHN], ptx[PATHN], fat[PATHN], cpp[PATHN], obuf[PATHN]; - int ninc = 0, rc, obj = 0, pic = 0, fb = 1, nocub = 0; + fprintf(stderr, "kath cuda: too many %s (max %d)\n", what, max); + return 2; +} + +static int cufull(const char *s) +{ + return streq(s, "--no-cfold") || streq(s, "--no-dce") + || streq(s, "--no-mem2reg") || streq(s, "--no-sroa") + || streq(s, "--no-sched"); +} +static int cuparse(int argc, char **argv, cuo_t *O) +{ for (int i = 2; i < argc; i++) { - if (streq(argv[i], "-c")) { obj = 1; continue; } - if (streq(argv[i], "-fPIC")) { pic = 1; continue; } - if (streq(argv[i], "--ptx-fallback")) { fb = 1; continue; } - if (streq(argv[i], "--no-ptx-fallback")) { fb = 0; continue; } - if (streq(argv[i], "-o") && i + 1 < argc) { out = argv[++i]; continue; } + if (streq(argv[i], "-c")) { O->obj = 1; continue; } + if (streq(argv[i], "-fPIC")) { O->pic = 1; continue; } + if (streq(argv[i], "--ptx-fallback")) { O->fb = 1; continue; } + if (streq(argv[i], "--no-ptx-fallback")) { O->fb = 0; continue; } + if (streq(argv[i], "-o") && i + 1 < argc) { O->out = argv[++i]; continue; } if (streq(argv[i], "-I") && i + 1 < argc) { - if (ninc < MAXINC) inc[ninc++] = argv[++i]; - else i++; + if (O->ninc >= MAXINC) return cutoo("-I", MAXINC); + O->inc[O->ninc++] = argv[++i]; continue; } if (strncmp(argv[i], "-I", 2) == 0 && argv[i][2] != '\0') { - if (ninc < MAXINC) inc[ninc++] = argv[i] + 2; + if (O->ninc >= MAXINC) return cutoo("-I", MAXINC); + O->inc[O->ninc++] = argv[i] + 2; + continue; + } + if (streq(argv[i], "-D") && i + 1 < argc) { + if (O->ndef >= MAXDEF) return cutoo("-D", MAXDEF); + O->def[O->ndef++] = argv[++i]; + continue; + } + if (strncmp(argv[i], "-D", 2) == 0 && argv[i][2] != '\0') { + if (O->ndef >= MAXDEF) return cutoo("-D", MAXDEF); + O->def[O->ndef++] = argv[i] + 2; + continue; + } + if (streq(argv[i], "--lang") && i + 1 < argc) { + if (O->nfwd + 1 >= MAXFWD) return cutoo("--lang", MAXFWD); + O->fwd[O->nfwd++] = argv[i]; + O->fwd[O->nfwd++] = argv[++i]; + continue; + } + if (cufull(argv[i])) { + if (O->nfwd >= MAXFWD) return cutoo(argv[i], MAXFWD); + O->fwd[O->nfwd++] = argv[i]; continue; } - if (argv[i][0] != '-' && file == NULL) file = argv[i]; + if (argv[i][0] == '-') { + fprintf(stderr, "kath cuda: unknown option %s\n", argv[i]); + return 2; + } + if (O->file == NULL) O->file = argv[i]; } - if (file == NULL) { + return 0; +} + +static int verb_cuda(int argc, char **argv) +{ + char cub[PATHN], ptx[PATHN], fat[PATHN], cpp[PATHN], obuf[PATHN]; + const char *file, *out; + int rc, nocub = 0; + cuo_t O; + + memset(&O, 0, sizeof O); + O.fb = 1; + rc = cuparse(argc, argv, &O); + if (rc != 0) return rc; + if (O.file == NULL) { fprintf(stderr, "usage: kath cuda [-c] [-fPIC] [-o out]" - " [-I dir] [--ptx-fallback|--no-ptx-fallback]\n"); + " [-I dir] [-D name[=val]] [--lang file]" + " [--ptx-fallback|--no-ptx-fallback]\n"); return 2; } - if (out == NULL) { - repl_ext(obuf, sizeof obuf, file, obj ? "o" : "exe"); - out = obuf; + file = O.file; + if (O.out == NULL) { + repl_ext(obuf, sizeof obuf, file, O.obj ? "o" : "exe"); + O.out = obuf; } + out = O.out; tmppath(cub, sizeof cub, "cuda", "cubin"); tmppath(ptx, sizeof ptx, "cuda", "ptx"); tmppath(fat, sizeof fat, "cuda", "fatbin"); tmppath(cpp, sizeof cpp, "cuda", "cpp"); - rc = cuda1("--nvidia-cubin", file, cub, NULL, inc, ninc); - if (rc != 0 && fb) { nocub = 1; rc = 0; } + rc = cuda1("--nvidia-cubin", file, cub, NULL, &O); + if (rc != 0 && O.fb) { nocub = 1; rc = 0; } else if (rc != 0) fprintf(stderr, "kath cuda: %s: SASS refused this unit and " "--no-ptx-fallback is set, so this is a hard failure\n", file); - if (rc == 0) rc = cuda1("--nvidia-ptx", file, ptx, NULL, inc, ninc); + if (rc == 0) rc = cuda1("--nvidia-ptx", file, ptx, NULL, &O); if (rc == 0 && nocub) fprintf(stderr, "kath cuda: ==== PTX FALLBACK ==== %s\n" "kath cuda: SASS refused a kernel here, see the refusals above; " "PTX carries this unit and no SASS is in its fatbin\n", file); if (rc == 0) rc = hg_fat(nocub ? NULL : cub, ptx, 89u, fat); - if (rc == 0) rc = cuda1("--cuda-host", file, cpp, fat, inc, ninc); + if (rc == 0) rc = cuda1("--cuda-host", file, cpp, fat, &O); if (rc == 0) { - rc = obj ? cc_obj(cpp, out, inc, ninc, pic) : hg_cc(cpp, out, inc, ninc); + rc = O.obj ? cc_obj(cpp, out, &O, O.pic) + : hg_cc(cpp, out, O.inc, O.ninc, O.def, O.ndef); if (rc != 0) (void)be_fail(BC_E623, file, rc); } remove(cub); remove(ptx); remove(fat); diff --git a/src/host/hgen.c b/src/host/hgen.c index a4d5967..74c8888 100644 --- a/src/host/hgen.c +++ b/src/host/hgen.c @@ -786,7 +786,13 @@ static int cinc(char *b, size_t n, size_t *u, const char *d) return capp(b, n, u, " -I\"") && capp(b, n, u, d) && capp(b, n, u, "\""); } -int hg_cc(const char *src, const char *out, const char *const *inc, int ninc) +static int cdef(char *b, size_t n, size_t *u, const char *d) +{ + return capp(b, n, u, " -D\"") && capp(b, n, u, d) && capp(b, n, u, "\""); +} + +int hg_cc(const char *src, const char *out, const char *const *inc, int ninc, + const char *const *def, int ndef) { char cmd[4096], own[512]; const char *cc = getenv("BOOTH_CXX"); @@ -799,6 +805,8 @@ int hg_cc(const char *src, const char *out, const char *const *inc, int ninc) cmd[0] = '\0'; ok = capp(cmd, sizeof cmd, &u, cc) && capp(cmd, sizeof cmd, &u, " -std=c++17 -O2"); + for (int i = 0; ok && i < ndef; i++) + ok = cdef(cmd, sizeof cmd, &u, def[i]); for (int i = 0; ok && i < ninc; i++) ok = cinc(cmd, sizeof cmd, &u, inc[i]); if (ok && hg_binc(own, sizeof own)) diff --git a/src/host/hgen.h b/src/host/hgen.h index 77266c9..3d8a21b 100644 --- a/src/host/hgen.h +++ b/src/host/hgen.h @@ -20,6 +20,7 @@ int hg_fat(const char *cubin, const char *ptx, uint32_t sm, const char *out); int hg_binc(char *buf, size_t n); -int hg_cc(const char *src, const char *out, const char *const *inc, int ninc); +int hg_cc(const char *src, const char *out, const char *const *inc, int ninc, + const char *const *def, int ndef); #endif /* BOOTH_HGEN_H */ diff --git a/tests/trpi.c b/tests/trpi.c index 019f844..2419435 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6139,3 +6139,44 @@ static void rpi308(void) PASS(); } TH_REG("rpi", 308, "NDEBUG reaches the device compile", rpi308) + +static void rpi309(void) +{ + const char *path = scratch("rpi309.cu", + "#include \n" + "__global__ void k(int *o, int n){ assert(n > 0); o[0] = n; }\n"); + char cmd[512]; + long a, b; + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, + "%s cuda -c %s -o build/rpi309a.o -Iruntime/include", + BC_BIN, path); + CHEQ(th_run(cmd, obuf, (int)sizeof obuf), 0); + snprintf(cmd, sizeof cmd, + "%s cuda -c %s -o build/rpi309b.o -Iruntime/include -DNDEBUG", + BC_BIN, path); + CHEQ(th_run(cmd, obuf, (int)sizeof obuf), 0); + a = rpi_fsz("build/rpi309a.o"); + b = rpi_fsz("build/rpi309b.o"); + CHECK(a > 0); + CHECK(b > 0); + CHECK(a != b); + PASS(); +} +TH_REG("rpi", 309, "kath cuda forwards -D to its sub-compiles", rpi309) + +static void rpi310(void) +{ + const char *path = scratch("rpi310.cu", + "__global__ void k(int *o){ o[0] = 1; }\n"); + char cmd[512]; + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s cuda -c %s -o build/rpi310.o --bogus-flag", + BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "unknown option"), NULL); + PASS(); +} +TH_REG("rpi", 310, "kath cuda refuses a flag it would ignore", rpi310) From 5d2869a11bb6fbcfb31fd785c29cf10cc2e37938 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Thu, 17 Sep 2026 19:41:52 +1200 Subject: [PATCH 07/41] a branch on two literals only ever had one arm --- src/ir/bir_cfold.c | 73 ++++++++++++++++++++++- src/ir/bir_dce.c | 143 ++++++++++++++++++++++++++++++++++++++++++++- tests/cf_dead.cu | 4 ++ tests/tcfold.c | 17 ++++++ 4 files changed, 233 insertions(+), 4 deletions(-) create mode 100644 tests/cf_dead.cu diff --git a/src/ir/bir_cfold.c b/src/ir/bir_cfold.c index 80bcab6..c139c7f 100644 --- a/src/ir/bir_cfold.c +++ b/src/ir/bir_cfold.c @@ -92,12 +92,54 @@ static cf_t G; * If foldable, sets S->val_rewrite[ii] and returns 1. * Otherwise returns 0. */ -static int try_fold(cf_t *S, uint32_t ii) +static void cfpe(bir_module_t *M, uint32_t from, uint32_t b) +{ + const bir_block_t *B; + + if (b >= M->num_blocks) return; + B = &M->blocks[b]; + for (uint32_t j = 0; j < B->num_insts; j++) { + bir_inst_t *I = &M->insts[B->first_inst + j]; + uint32_t w = 0, k, n; + if (I->op != BIR_PHI) continue; + if (I->num_operands == BIR_OPERANDS_OVERFLOW) { + uint32_t st = I->operands[0]; + n = I->operands[1]; + for (k = 0; k + 1 < n; k += 2) { + if (st + k + 1 >= M->num_extra_ops) break; + if (M->extra_operands[st + k] == from) continue; + M->extra_operands[st + w] = M->extra_operands[st + k]; + M->extra_operands[st + w + 1] = M->extra_operands[st + k + 1]; + w += 2; + } + I->operands[1] = w; + } else { + n = I->num_operands; + for (k = 0; k + 1 < n; k += 2) { + if (I->operands[k] == from) continue; + I->operands[w] = I->operands[k]; + I->operands[w + 1] = I->operands[k + 1]; + w += 2; + } + I->num_operands = (uint8_t)w; + } + } +} + +static int try_fold(cf_t *S, uint32_t ii, uint32_t ab) { bir_module_t *M = S->M; bir_inst_t *I = &M->insts[ii]; uint16_t op = I->op; + if (op == BIR_PHI) { + uint32_t n = (I->num_operands == BIR_OPERANDS_OVERFLOW) + ? I->operands[1] : I->num_operands; + if (n != 2) return 0; + S->val_rewrite[ii] = bir_oper(M, I, 1u); + return 1; + } + /* SELECT with constant condition — propagate chosen operand */ if (op == BIR_SELECT && I->num_operands >= 3) { uint32_t cond = I->operands[0]; @@ -110,6 +152,26 @@ static int try_fold(cf_t *S, uint32_t ii) return 1; } + if (op == BIR_BR_COND && I->num_operands >= 3) { + uint32_t cond = I->operands[0]; + if (!BIR_VAL_IS_CONST(cond)) return 0; + uint32_t ci = BIR_VAL_INDEX(cond); + if (ci >= M->num_consts) return 0; + const bir_const_t *c = &M->consts[ci]; + uint32_t keep, lost; + int taken; + if (c->kind == BIR_CONST_INT) taken = c->d.ival != 0; + else if (c->kind == BIR_CONST_ZERO) taken = 0; + else return 0; + keep = taken ? I->operands[1] : I->operands[2]; + lost = taken ? I->operands[2] : I->operands[1]; + I->operands[0] = keep; + I->op = BIR_BR; + I->num_operands = 1; + if (lost != keep) cfpe(M, ab, lost); + return 1; + } + /* From here, require all value operands to be constants */ if (I->num_operands == 0 || I->num_operands == BIR_OPERANDS_OVERFLOW) return 0; @@ -366,7 +428,11 @@ static int cf_run_func(cf_t *S, uint32_t fi) for (uint32_t i = base; i < end; i++) S->val_rewrite[i] = BIR_VAL_NONE; - for (uint32_t i = base; i < end; i++) { + for (uint32_t bi = 0; bi < F->num_blocks; bi++) { + uint32_t ab = F->first_block + bi; + const bir_block_t *BB = &M->blocks[ab]; + for (uint32_t bj = 0; bj < BB->num_insts; bj++) { + uint32_t i = BB->first_inst + bj; bir_inst_t *I = &M->insts[i]; /* Rewrite operands through val_rewrite[] */ @@ -390,7 +456,8 @@ static int cf_run_func(cf_t *S, uint32_t fi) } /* Try to fold */ - changes += try_fold(S, i); + changes += try_fold(S, i, ab); + } } return changes; diff --git a/src/ir/bir_dce.c b/src/ir/bir_dce.c index 97cd318..523eeaf 100644 --- a/src/ir/bir_dce.c +++ b/src/ir/bir_dce.c @@ -23,6 +23,7 @@ typedef struct { uint32_t dead[BIR_MAX_INSTS / 32]; uint32_t use_count[BIR_MAX_INSTS]; uint32_t inst_renum[BIR_MAX_INSTS]; + uint8_t rch[BIR_MAX_BLOCKS]; } opt_t; static opt_t G; @@ -250,6 +251,144 @@ static void compact(opt_t *S) } } +static uint32_t nsuc(const bir_module_t *M, const bir_block_t *B) +{ + const bir_inst_t *I; + + if (B->num_insts == 0u || B->first_inst >= M->num_insts) return 0u; + I = &M->insts[B->first_inst + B->num_insts - 1u]; + if (I->op == BIR_BR) return 1u; + if (I->op == BIR_BR_COND) return 2u; + if (I->op != BIR_SWITCH) return 0u; + if (I->num_operands != BIR_OPERANDS_OVERFLOW) return 1u; + if (I->operands[1] < 2u) return 0u; + return 1u + (I->operands[1] - 2u) / 2u; +} + +static uint32_t suc(const bir_module_t *M, const bir_block_t *B, uint32_t k) +{ + const bir_inst_t *I = &M->insts[B->first_inst + B->num_insts - 1u]; + + if (I->op == BIR_BR) return bir_oper(M, I, 0u); + if (I->op == BIR_BR_COND) return bir_oper(M, I, 1u + k); + if (I->num_operands != BIR_OPERANDS_OVERFLOW) return bir_oper(M, I, 1u); + return (k == 0u) ? bir_oper(M, I, 1u) : bir_oper(M, I, 2u * k + 1u); +} + +static int plive(const opt_t *S, uint32_t p, uint32_t b) +{ + const bir_module_t *M = S->M; + uint32_t lp, ns, k; + + if (p < S->base_block) return 1; + lp = p - S->base_block; + if (lp >= S->num_blocks) return 1; + if (!S->rch[lp]) return 0; + ns = nsuc(M, &M->blocks[p]); + for (k = 0u; k < ns; k++) + if (suc(M, &M->blocks[p], k) == b) return 1; + return 0; +} + +static int phix(opt_t *S, uint32_t b, bir_inst_t *I) +{ + bir_module_t *M = S->M; + uint32_t w = 0u, k, n; + int drop = 0; + + if (I->num_operands == BIR_OPERANDS_OVERFLOW) { + uint32_t st = I->operands[0]; + n = I->operands[1]; + for (k = 0u; k + 1u < n; k += 2u) { + if (st + k + 1u >= M->num_extra_ops) break; + if (!plive(S, M->extra_operands[st + k], b)) { drop = 1; continue; } + M->extra_operands[st + w] = M->extra_operands[st + k]; + M->extra_operands[st + w + 1u] = M->extra_operands[st + k + 1u]; + w += 2u; + } + I->operands[1] = w; + return drop; + } + + n = I->num_operands; + for (k = 0u; k + 1u < n; k += 2u) { + if (!plive(S, I->operands[k], b)) { drop = 1; continue; } + I->operands[w] = I->operands[k]; + I->operands[w + 1u] = I->operands[k + 1u]; + w += 2u; + } + I->num_operands = (uint8_t)w; + return drop; +} + +static void rmark(opt_t *S) +{ + bir_module_t *M = S->M; + uint32_t nb = S->num_blocks, i, k; + int chg = 1, g = (int)nb + 1; + + for (i = 0u; i < nb; i++) S->rch[i] = 0u; + S->rch[0] = 1u; + + while (chg && g-- > 0) { + chg = 0; + for (i = 0u; i < nb; i++) { + const bir_block_t *B = &M->blocks[S->base_block + i]; + uint32_t ns; + if (!S->rch[i]) continue; + ns = nsuc(M, B); + for (k = 0u; k < ns; k++) { + uint32_t t = suc(M, B, k); + if (t < S->base_block) continue; + t -= S->base_block; + if (t >= nb || S->rch[t]) continue; + S->rch[t] = 1u; + chg = 1; + } + } + } +} + +static int rchk(opt_t *S) +{ + bir_module_t *M = S->M; + uint32_t nb = S->num_blocks, i, k; + int n = 0; + + rmark(S); + + for (i = 1u; i < nb; i++) { + bir_block_t *B = &M->blocks[S->base_block + i]; + bir_inst_t *I; + if (S->rch[i] || B->num_insts == 0u) continue; + for (k = 1u; k < B->num_insts; k++) { + uint32_t ii = B->first_inst + k; + S->dead[ii / 32] |= 1u << (ii % 32); + n++; + } + I = &M->insts[B->first_inst]; + if (I->op == BIR_UNREACHABLE) continue; + I->op = BIR_UNREACHABLE; + I->subop = 0; + I->num_operands = 0; + I->type = bir_type_void(M); + n++; + } + + for (i = 0u; i < nb; i++) { + const bir_block_t *B = &M->blocks[S->base_block + i]; + if (!S->rch[i]) continue; + for (k = 0u; k < B->num_insts; k++) { + uint32_t ii = B->first_inst + k; + if (M->insts[ii].op != BIR_PHI) continue; + if ((S->dead[ii / 32] >> (ii % 32)) & 1u) continue; + n += phix(S, S->base_block + i, &M->insts[ii]); + } + } + + return n; +} + /* ---- Per-Function Driver ---- */ static int opt_run_func(opt_t *S, uint32_t fi) @@ -269,7 +408,9 @@ static int opt_run_func(opt_t *S, uint32_t fi) memset(S->dead + lo, 0, (hi - lo) * sizeof(uint32_t)); } - int changes = dce_pass(S); + int changes = rchk(S); + + changes += dce_pass(S); if (changes > 0) compact(S); diff --git a/tests/cf_dead.cu b/tests/cf_dead.cu new file mode 100644 index 0000000..f1c0d57 --- /dev/null +++ b/tests/cf_dead.cu @@ -0,0 +1,4 @@ +__global__ void cf_deadarm(int *out, int x) { + if ((128 <= 1024) && (128 % 32) == 0) out[0] = x; + else out[0] = 99; +} diff --git a/tests/tcfold.c b/tests/tcfold.c index 8d91ce3..5741cce 100644 --- a/tests/tcfold.c +++ b/tests/tcfold.c @@ -151,3 +151,20 @@ static void cfd07(void) PASS(); } TH_REG("cfd", 7, "subtraction folds in order", cfd07) + +static void cfd08(void) +{ + int rc = th_run(BC_BIN " --ir tests/cf_dead.cu", obuf, TH_BUFSZ); + CHEQ(rc, 0); + const char *fn = strstr(obuf, "cf_deadarm"); + CHECK(fn != NULL); + const char *body = strchr(fn, '\n'); + CHECK(body != NULL); + const char *fn_end = strstr(body, "\n}"); + CHECK(fn_end != NULL); + CHECK(strnstr_range(body, fn_end, "br_cond") == NULL); + CHECK(strnstr_range(body, fn_end, "store i32 99") == NULL); + CHECK(strnstr_range(body, fn_end, "unreachable") != NULL); + PASS(); +} +TH_REG("cfd", 8, "a branch on two literals drops its dead arm", cfd08) From c91de00234831bc1e954a5f1f75e8804c0fa2e06 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Thu, 17 Sep 2026 19:41:52 +1200 Subject: [PATCH 08/41] a shared kernel names its own section and rounds up to sixteen --- src/nvidia/emit_sass.c | 3 +- src/nvidia/lt_nv.c | 6 +++- tests/trpi.c | 64 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 2 deletions(-) diff --git a/src/nvidia/emit_sass.c b/src/nvidia/emit_sass.c index c7a1b81..1a9deed 100644 --- a/src/nvidia/emit_sass.c +++ b/src/nvidia/emit_sass.c @@ -3290,7 +3290,8 @@ static int saone(nv_module_t *nv, uint32_t fi, int text) sast.k.nreg = sast.nreg + 2u; sast.k.isfn = sast.isfn; if (sast.isfn == 0u && sast.k.nreg > sast.ktop) sast.ktop = sast.k.nreg; - sast.k.smem = sast.F->lds_bytes; + sast.k.smem = (sast.M->dyn_alg != 0u) + ? ((sast.F->lds_bytes + 15u) & ~15u) : sast.F->lds_bytes; sast.k.lmem = sast.F->lcl_bytes + 8u * sast.nspl; if (sast.clen == 0u || sast.clen > LT_MAX_NVCODE) { (void)be_fail(BC_E607, "nvptx", sast.name, diff --git a/src/nvidia/lt_nv.c b/src/nvidia/lt_nv.c index 758d6f1..0df53fe 100644 --- a/src/nvidia/lt_nv.c +++ b/src/nvidia/lt_nv.c @@ -266,7 +266,11 @@ static lt_res_t plkrn(lay_t *L, str_t *sst, str_t *st, const lt_nvk_t *k, L->iinf = sx; L->nsym = yx; for (uint32_t i = 0; i < nk; i++) - if (k[i].smem != 0u) L->k[i].ishr = L->iinf + 1u + lt_nv_noten + ns++; + if (k[i].smem != 0u) { + L->k[i].shr = sadd(sst, ".nv.shared.", k[i].name); + if (L->k[i].shr == 0u) return LT_EFULL; + L->k[i].ishr = L->iinf + 1u + lt_nv_noten + ns++; + } L->isym = L->iinf + 1u + lt_nv_noten + ns; L->istr = L->isym + 1u; L->issh = L->istr + 1u; diff --git a/tests/trpi.c b/tests/trpi.c index 2419435..6618fd6 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6180,3 +6180,67 @@ static void rpi310(void) PASS(); } TH_REG("rpi", 310, "kath cuda refuses a flag it would ignore", rpi310) + +static uint32_t rpi_r16(const uint8_t *p) +{ + return (uint32_t)p[0] | ((uint32_t)p[1] << 8); +} + +static uint32_t rpi_r32(const uint8_t *p) +{ + return rpi_r16(p) | (rpi_r16(p + 2) << 16); +} + +static void rpi311(void) +{ + static uint8_t cub[1 << 18]; + const char *path = scratch("rpi311.cu", + "__global__ void k(int *o){\n" + " __shared__ int s[256];\n" + " s[threadIdx.x] = (int)threadIdx.x;\n" + " __syncthreads();\n" + " o[threadIdx.x] = s[255 - threadIdx.x];\n" + "}\n"); + char cmd[512]; + FILE *f; + size_t n; + uint32_t sho, nse, sxi, sto, got = 0u, zsh = 0u, tsh = 0u; + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --nvidia-cubin -o build/rpi311.cubin %s", + BC_BIN, path); + CHEQ(th_run(cmd, obuf, (int)sizeof obuf), 0); + + f = fopen("build/rpi311.cubin", "rb"); + CHNE(f, NULL); + n = fread(cub, 1u, sizeof cub, f); + fclose(f); + CHECK(n > 64u); + + sho = rpi_r32(cub + 40); + nse = rpi_r16(cub + 60); + sxi = rpi_r16(cub + 62); + CHECK(nse != 0u && sxi < nse); + CHECK(sho + (size_t)nse * 64u <= n); + + sto = rpi_r32(cub + sho + (size_t)sxi * 64u + 24u); + CHECK(sto < n); + + for (uint32_t i = 0; i < nse; i++) { + const uint8_t *s = cub + sho + (size_t)i * 64u; + uint32_t nm = sto + rpi_r32(s); + + if (nm >= n) continue; + if (strcmp((const char *)cub + nm, ".nv.shared.k") == 0) { + got = 1u; + tsh = rpi_r32(s + 4u); + zsh = rpi_r32(s + 32u); + } + } + + CHEQ(got, 1u); + CHEQ(tsh, 8u); + CHEQ(zsh, 1024u); + PASS(); +} +TH_REG("rpi", 311, "a __shared__ kernel declares its size", rpi311) From 97e4ce0973f37c6978fee675dd319e92fcd0060c Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Thu, 17 Sep 2026 19:41:53 +1200 Subject: [PATCH 09/41] a ternary is control flow the moment its arms do something --- src/fe/parser.c | 6 +- src/ir/bir_lower.c | 410 +++++++++++++++++++++++++++++++++++++++++++-- tests/trpi.c | 65 +++++++ 3 files changed, 467 insertions(+), 14 deletions(-) diff --git a/src/fe/parser.c b/src/fe/parser.c index 8c4e2bb..47a3fbf 100644 --- a/src/fe/parser.c +++ b/src/fe/parser.c @@ -2846,10 +2846,14 @@ static uint32_t parse_stmt(parser_t *P) expect(P, TOK_LPAREN); uint16_t q2 = 0, c2 = 0; uint32_t dt = parse_type_spec(P, &q2, &c2); + int pd = 0; if (dt) add_child(P, n, dt); while (cur_type(P) == TOK_STAR || cur_type(P) == TOK_AMP || - cur_type(P) == TOK_CONST) + cur_type(P) == TOK_CONST) { + if (cur_type(P) == TOK_STAR) pd++; advance(P); + } + P->nodes[n].d.oper.flags = pd; if (match(P, TOK_LBRACKET)) { while (cur_type(P) != TOK_RBRACKET && cur_type(P) != TOK_EOF) { if (cur_type(P) == TOK_IDENT) { diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index e39879c..ba3bb75 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -32,7 +32,7 @@ #define MAX_FPACKS 4 #define MAX_INSTS 16384 #define MAX_LNCH 4096 -#define MAX_TPARM 16 +#define MAX_TPARM 24 #define MAX_BIND 64 #define MAX_TDEP 7 #define MAX_NEST 8 @@ -66,6 +66,8 @@ #define LO_MAXALG 4096 #define LO_MAX_DIM 4 #define CE_NEST 16 +#define RF_ELEM 64 +#define MAX_XINS 512 #define CE_STMT 256 #define CF_BODY 2048 #define MAX_CAGF 12 @@ -371,6 +373,8 @@ typedef struct { int tsc; struct { char key[256]; char sym[128]; } inst[MAX_INSTS]; int ninst; + struct { char key[256]; } xins[MAX_XINS]; + int nxins; uint8_t cmth[BIR_MAX_FUNCS / 8]; int tdep; @@ -3175,7 +3179,19 @@ static uint32_t cfsee(lower_t *L, uint32_t cn, char *nm, size_t nz, int *mem, if (cqfnd(L, cn, nm, nz, &ce) == 0 && !nm[0]) return 0; *mem = 1; } else if (ND(L, cn)->type == AST_IDENT) { + uint32_t f; + char q[CE_NAMEZ]; + get_text(L, cn, nm, (int)nz); + f = cffnd(L, nm, na); + if (f || !L->scls[0]) return f; + if (snprintf(q, sizeof q, "%s::%s", L->scls, nm) < 0) return 0; + f = cffnd(L, q, na); + if (f) { + ncpy(nm, nz, q); + *mem = 1; + } + return f; } else { return 0; } @@ -3688,7 +3704,7 @@ static int vtbnd(lower_t *L, uint32_t ta, binding_t *nb, int ntp) static int vteval(lower_t *L, uint32_t node, cval_t *out) { - binding_t nb[MAX_TPARM]; + binding_t *nb; char nm[CE_NAMEZ]; uint32_t ta, ty; int vi, ntp, onb, obs, ok; @@ -3703,12 +3719,15 @@ static int vteval(lower_t *L, uint32_t node, cval_t *out) if (vi < 0) return 0; ta = targs(L, node); if (!ta || L->cdep >= MAX_CDEP) return 0; + if (L->xdep >= MAX_NEST) return 0; + nb = L->xnb[L->xdep++]; ntp = tparm(L, L->vtpl[vi].tdcl, nb); - if (ntp <= 0) return 0; - if (!vtbnd(L, ta, nb, ntp)) return 0; + if (ntp <= 0) { L->xdep--; return 0; } + if (!vtbnd(L, ta, nb, ntp)) { L->xdep--; return 0; } if (ntp > MAX_BIND - L->nbindings) { lower_error(L, node, BC_E340, L->vtpl[vi].name, MAX_BIND); + L->xdep--; return 0; } @@ -3725,6 +3744,7 @@ static int vteval(lower_t *L, uint32_t node, cval_t *out) L->cdep--; L->nbindings = onb; L->nbbase = obs; + L->xdep--; return ok; } @@ -6858,6 +6878,112 @@ static int wmcall(lower_t *L, uint32_t node, uint32_t cal, const char *nm, return 1; } +static int tpure(const lower_t *L, uint32_t node) +{ + uint32_t wk[64]; + int wn = 0; + + if (!node) return 1; + wk[wn++] = node; + + KA_GUARD(g, 4096); + while (wn > 0 && g--) { + const ast_node_t *p = ND(L, wk[--wn]); + uint32_t c = p->first_child; + + switch (p->type) { + case AST_INT_LIT: case AST_FLOAT_LIT: case AST_CHAR_LIT: + case AST_BOOL_LIT: case AST_NULL_LIT: case AST_STRING_LIT: + case AST_IDENT: case AST_SCOPE_RES: case AST_SIZEOF: + case AST_PACK_SIZE: + continue; + + case AST_CAST: + c = c ? ND(L, c)->next_sibling : 0; + break; + + case AST_BINARY: + if (p->d.oper.op == TOK_ASSIGN + || is_compound_assign(p->d.oper.op)) return 0; + break; + + case AST_UNARY_PREFIX: + case AST_UNARY_POSTFIX: + if (p->d.oper.op == TOK_INC || p->d.oper.op == TOK_DEC) return 0; + break; + + case AST_PAREN: case AST_MEMBER: + case AST_SUBSCRIPT: case AST_TERNARY: + break; + + default: + return 0; + } + + while (c) { + if (wn >= (int)(sizeof wk / sizeof wk[0])) return 0; + wk[wn++] = c; + c = ND(L, c)->next_sibling; + } + } + return wn == 0; +} + +static uint32_t tbrnc(lower_t *L, uint32_t cnd_n, uint32_t thn_n, + uint32_t els_n) +{ + uint32_t vd = bir_type_void(L->M); + uint32_t cnd = lower_expr(L, cnd_n); + uint32_t tb = new_block(L, "tern.then"); + uint32_t eb = new_block(L, "tern.else"); + uint32_t jb = new_block(L, "tern.end"); + uint32_t br, j, tv, ev, tp = 0, ep = 0, phi, rt; + int tr = 0, er = 0; + + br = emit(L, BIR_BR_COND, vd, 4, 0); + set_op(L, br, 0, cnd); + set_op(L, br, 1, tb); + set_op(L, br, 2, eb); + set_op(L, br, 3, jb); + + set_block(L, tb); + tv = lower_expr(L, thn_n); + if (!block_terminated(L)) { + j = emit(L, BIR_BR, vd, 1, 0); + set_op(L, j, 0, jb); + tp = L->cur_block; + tr = 1; + } + + set_block(L, eb); + ev = lower_expr(L, els_n); + if (!block_terminated(L)) { + j = emit(L, BIR_BR, vd, 1, 0); + set_op(L, j, 0, jb); + ep = L->cur_block; + er = 1; + } + + set_block(L, jb); + if (!tr && !er) { + emit(L, BIR_UNREACHABLE, vd, 0, 0); + return BIR_VAL_NONE; + } + if (!tr) return ev; + if (!er) return tv; + if (tv == BIR_VAL_NONE || ev == BIR_VAL_NONE) return BIR_VAL_NONE; + + rt = ref_type(L, tv); + if (!rt || rt == vd || ref_type(L, ev) == vd) return BIR_VAL_NONE; + + phi = emit(L, BIR_PHI, rt, 4, 0); + set_op(L, phi, 0, tp); + set_op(L, phi, 1, tv); + set_op(L, phi, 2, ep); + set_op(L, phi, 3, ev); + return BIR_MAKE_VAL(phi); +} + static uint32_t lower_expr(lower_t *L, uint32_t node) { if (!node) return BIR_VAL_NONE; @@ -7491,6 +7617,9 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) uint32_t then_n = ND(L, cond_n)->next_sibling; uint32_t else_n = ND(L, then_n)->next_sibling; + if (!tpure(L, then_n) || !tpure(L, else_n)) + return tbrnc(L, cond_n, then_n, else_n); + uint32_t cond = lower_expr(L, cond_n); uint32_t tv = lower_expr(L, then_n); uint32_t ev = lower_expr(L, else_n); @@ -7632,7 +7761,7 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) } } if (ND(L, callee_n)->type == AST_SCOPE_RES) { - char qn[144], cd[144]; + char qn[144], cd[144], nrm[144]; char *sep; qtxt(L, callee_n, qn, sizeof(qn)); sep = strstr(qn, "::"); @@ -7646,7 +7775,10 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) base = sn && strchr(sn, CI_SEP) && tamb(L, bt) > 1 ? NULL : sn; } else if (!base) { - base = qn; + uint16_t sv = L->sdbad; + + base = sdnrm(L, qn, nrm, sizeof(nrm)) ? nrm : qn; + L->sdbad = sv; } lst = strrchr(tail, ':'); if (lst) tail = lst + 1; @@ -10665,9 +10797,135 @@ static void lower_stmt(lower_t *L, uint32_t node) break; } - case AST_RANGE_FOR: - lower_error(L, node, BC_E135); + case AST_RANGE_FOR: { + uint32_t kid[8], ts = 0, idn = 0, rng = 0, body = 0; + uint32_t i32 = bir_type_int(L->M, 32); + uint32_t et = 0, arr, vsl, isl, ept; + uint32_t cond_b, body_b, inc_b, end_b; + int nk = 0, nid = 0, ne = 0, i, bad = 0; + char vn[128]; + + for (uint32_t c = n->first_child; c; c = ND(L, c)->next_sibling) { + if (nk >= 8) { bad = 1; break; } + kid[nk++] = c; + } + if (bad || nk < 3) { lower_error(L, node, BC_E135); break; } + body = kid[nk - 1]; + rng = kid[nk - 2]; + for (i = 0; i < nk - 2; i++) { + if (ND(L, kid[i])->type == AST_TYPE_SPEC) ts = kid[i]; + else if (ND(L, kid[i])->type == AST_IDENT) { idn = kid[i]; nid++; } + } + if (nid != 1 || ND(L, rng)->type != AST_INIT_LIST) { + lower_error(L, node, BC_E135); + break; + } + for (uint32_t c = ND(L, rng)->first_child; c; + c = ND(L, c)->next_sibling) { + if (ne >= RF_ELEM) { bad = 1; break; } + ne++; + } + if (bad || ne == 0) { lower_error(L, node, BC_E135); break; } + if (ts && ND(L, ts)->d.btype.kind != TYPE_AUTO) { + et = resolve_type(L, ts, n->d.oper.flags, n->cuda_flags); + if (L->rtbad || L->rtunk) et = 0; + L->rtbad = 0; + L->rtunk = 0; + } + if (!et) et = arg_type(L, ND(L, rng)->first_child); + if (!et || et >= L->M->num_types) { + lower_error(L, node, BC_E135); + break; + } + + get_text(L, idn, vn, sizeof(vn)); + ept = bir_type_ptr(L->M, et, BIR_AS_PRIVATE); + push_scope(L); + + arr = BIR_MAKE_VAL(emalc(L, BIR_ALLOCA, + bir_type_ptr(L->M, bir_type_array(L->M, et, (uint32_t)ne), + BIR_AS_PRIVATE), 0)); + i = 0; + for (uint32_t c = ND(L, rng)->first_child; c; + c = ND(L, c)->next_sibling) { + astor(L, stfit(L, lower_expr(L, c), et, c), + agep(L, arr, et, i)); + i++; + } + vsl = BIR_MAKE_VAL(emalc(L, BIR_ALLOCA, ept, 0)); + isl = BIR_MAKE_VAL(emalc(L, BIR_ALLOCA, + bir_type_ptr(L->M, i32, BIR_AS_PRIVATE), 0)); + astor(L, BIR_MAKE_CONST(bir_const_int(L->M, i32, 0)), isl); + + cond_b = new_block(L, "rfor.cond"); + body_b = new_block(L, "rfor.body"); + inc_b = new_block(L, "rfor.inc"); + end_b = new_block(L, "rfor.end"); + { + uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, br, 0, cond_b); + } + + set_block(L, cond_b); + { + uint32_t ld = emit(L, BIR_LOAD, i32, 1, 0); + uint32_t cl, br; + + set_op(L, ld, 0, isl); + cl = emit(L, BIR_ICMP, bir_type_int(L->M, 1), 2, BIR_ICMP_SLT); + set_op(L, cl, 0, BIR_MAKE_VAL(ld)); + set_op(L, cl, 1, BIR_MAKE_CONST(bir_const_int(L->M, i32, ne))); + br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); + set_op(L, br, 0, BIR_MAKE_VAL(cl)); + set_op(L, br, 1, body_b); + set_op(L, br, 2, end_b); + set_op(L, br, 3, end_b); + } + + set_block(L, body_b); + { + uint32_t ld = emit(L, BIR_LOAD, i32, 1, 0); + uint32_t g, lv; + + set_op(L, ld, 0, isl); + g = emit(L, BIR_GEP, ept, 2, 0); + set_op(L, g, 0, arr); + set_op(L, g, 1, BIR_MAKE_VAL(ld)); + lv = emit(L, BIR_LOAD, et, 1, 0); + set_op(L, lv, 0, BIR_MAKE_VAL(g)); + astor(L, BIR_MAKE_VAL(lv), vsl); + } + add_sym(L, vn, vsl, et, 1); + if (L->loop_depth < MAX_LOOPS) { + L->break_tgt[L->loop_depth] = end_b; + L->cont_tgt[L->loop_depth] = inc_b; + L->loop_depth++; + } + lower_stmt(L, body); + if (L->loop_depth > 0) L->loop_depth--; + if (!block_terminated(L)) { + uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, br, 0, inc_b); + } + + set_block(L, inc_b); + { + uint32_t ld = emit(L, BIR_LOAD, i32, 1, 0); + uint32_t ad, br; + + set_op(L, ld, 0, isl); + ad = emit(L, BIR_ADD, i32, 2, 0); + set_op(L, ad, 0, BIR_MAKE_VAL(ld)); + set_op(L, ad, 1, BIR_MAKE_CONST(bir_const_int(L->M, i32, 1))); + astor(L, BIR_MAKE_VAL(ad), isl); + br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, br, 0, cond_b); + } + + set_block(L, end_b); + pop_scope(L); break; + } case AST_PP_DIRECTIVE: /* Preprocessor directives skipped */ @@ -12882,12 +13140,31 @@ static int tmang(lower_t *L, const char *cname, int slot, } } +static int xkey(const lower_t *L, const char *key) +{ + for (int i = 0; i < L->nxins; i++) + if (strcmp(L->xins[i].key, key) == 0) return 1; + return 0; +} + +static int xhit(lower_t *L, const char *cname, const binding_t *nb, + int ntp, uint32_t func_n) +{ + char key[256]; + + if (L->nxins <= 0) return 0; + tkeyb(nb, ntp, cname, key, sizeof key); + tkfn(L, cname, func_n, key, sizeof key); + return xkey(L, key); +} + static int tinst(lower_t *L, uint32_t node, const char *cname, const binding_t *nb, int ntp, uint32_t func_n) { char key[256]; tkeyb(nb, ntp, cname, key, sizeof(key)); tkfn(L, cname, func_n, key, sizeof(key)); + if (xkey(L, key)) return 0; int nsame = 0; size_t cl = strlen(cname); @@ -13715,6 +13992,8 @@ static int swrap(lower_t *L, uint32_t node) uint32_t dfn = 0; int have = tdeduc(L, tmpl->ast, cn, av, na, nb, &ntp, &dfn); + if (have && xhit(L, cname, nb, ntp, dfn)) return 1; + int old_nb = L->nbindings, old_bs = L->nbbase; if (have && ntp > MAX_BIND - old_nb) { lower_error(L, node, BC_E157, cname); @@ -14003,6 +14282,16 @@ static void scan_launches(lower_t *L, uint32_t node) if (!node) return; const ast_node_t *n = ND(L, node); + if (n->type == AST_IF && (n->d.oper.flags & IF_CEXP)) { + uint32_t arm = 0; + + if (cxarm(L, node, &arm)) { + scan_launches(L, child_at(L, node, 0)); + if (arm) scan_launches(L, arm); + return; + } + } + if (n->type == AST_LAMBDA && lgen(L, node)) return; if (n->type == AST_FOLD && sfld(L, node)) return; if (n->type == AST_BINARY && n->d.oper.op == TOK_ASSIGN) fnfil(L, node); @@ -14057,6 +14346,62 @@ static uint32_t tixnm(const lower_t *L, uint32_t node, uint32_t *ta, return nm; } +static void tixx(lower_t *L, uint32_t node) +{ + uint32_t ta, nm, fd, func_n, pv[MAX_PARM]; + binding_t *nb = L->tnb; + template_def_t *tm; + char cname[128], key[256]; + int ntp, np; + + if (!(ND(L, node)->qualifiers & QUAL_EXTERN)) return; + if (L->nxins >= MAX_XINS) return; + nm = tixnm(L, node, &ta, &fd); + if (!nm) return; + get_text(L, nm, cname, sizeof(cname)); + np = collect_params(L, fd, pv, MAX_PARM); + tm = ftmpl(L, cname, np); + if (!tm) return; + func_n = tfunc(L, tm); + if (!func_n) return; + ntp = tparm(L, tm->ast, nb); + if (ntp < 0) return; + if (!texpl(L, nm, nb, ntp) || !tdflt(L, nb, ntp)) return; + tkeyb(nb, ntp, cname, key, sizeof(key)); + tkfn(L, cname, func_n, key, sizeof(key)); + ncpy(L->xins[L->nxins].key, sizeof(L->xins[0].key), key); + L->nxins++; +} + +static void tixd(lower_t *L, uint32_t node) +{ + uint32_t ta, nm, fd, func_n, pv[MAX_PARM]; + binding_t *nb = L->tnb; + template_def_t *tm; + char cname[128], key[256]; + int ntp, np, w = 0; + + if (ND(L, node)->qualifiers & QUAL_EXTERN) return; + if (L->nxins <= 0) return; + nm = tixnm(L, node, &ta, &fd); + if (!nm) return; + get_text(L, nm, cname, sizeof(cname)); + np = collect_params(L, fd, pv, MAX_PARM); + tm = ftmpl(L, cname, np); + if (!tm) return; + func_n = tfunc(L, tm); + if (!func_n) return; + ntp = tparm(L, tm->ast, nb); + if (ntp < 0) return; + if (!texpl(L, nm, nb, ntp) || !tdflt(L, nb, ntp)) return; + tkeyb(nb, ntp, cname, key, sizeof(key)); + tkfn(L, cname, func_n, key, sizeof(key)); + for (int i = 0; i < L->nxins; i++) + if (strcmp(L->xins[i].key, key) != 0) + L->xins[w++] = L->xins[i]; + L->nxins = w; +} + static void tixp(lower_t *L, uint32_t node) { uint32_t ta, nm, fd, func_n, body, pv[MAX_PARM]; @@ -14156,33 +14501,65 @@ static void cscan(lower_t *L, uint32_t root) } } +static int cfadd(lower_t *L, const char *nm, uint32_t ast) +{ + if (L->ncfn >= MAX_CFNS) return 0; + ncpy(L->cfns[L->ncfn].name, sizeof(L->cfns[0].name), nm); + L->cfns[L->ncfn].ast = ast; + L->ncfn++; + return 1; +} + static int cfcol(lower_t *L, uint32_t root) { uint32_t wk[CE_NEST]; + char pf[CE_NEST][64]; int wn = 1; wk[0] = root; + pf[0][0] = 0; KA_GUARD(g, 4096); while (wn > 0 && g--) { uint32_t nd = wk[--wn]; + char cur[64]; + ncpy(cur, sizeof cur, pf[wn]); for (uint32_t c = ND(L, nd)->first_child; c; c = ND(L, c)->next_sibling) { const ast_node_t *n = ND(L, c); + char bare[64], qual[64]; uint32_t id; if (n->type == AST_NAMESPACE) { - if (wn < CE_NEST) wk[wn++] = c; + uint32_t nn = ND(L, c)->first_child; + + if (wn >= CE_NEST) continue; + wk[wn] = c; + pf[wn][0] = 0; + if (nn && ND(L, nn)->type == AST_IDENT) { + char one[64]; + + get_text(L, nn, one, sizeof one); + if (!cur[0]) + ncpy(pf[wn], sizeof pf[0], one); + else if (snprintf(pf[wn], sizeof pf[0], "%s::%s", + cur, one) < 0) + pf[wn][0] = 0; + } else { + ncpy(pf[wn], sizeof pf[0], cur); + } + wn++; continue; } if (n->type != AST_FUNC_DEF) continue; if (!(n->qualifiers & QUAL_CONSTEXPR)) continue; id = child_at(L, c, 1); if (!id || ND(L, id)->type != AST_IDENT) continue; - if (L->ncfn >= MAX_CFNS) return 0; - get_text(L, id, L->cfns[L->ncfn].name, sizeof(L->cfns[0].name)); - L->cfns[L->ncfn].ast = c; - L->ncfn++; + get_text(L, id, bare, sizeof bare); + if (!cfadd(L, bare, c)) return 0; + if (cur[0] + && snprintf(qual, sizeof qual, "%s::%s", cur, bare) > 0 + && !cfadd(L, qual, c)) return 0; } } return 1; @@ -14339,6 +14716,13 @@ int bir_ltu(const parser_t *P, uint32_t ast_root, bir_module_t *M, L->ncexp = csv; cscan(L, ast_root); + for (int ti = 0; ti < L->ntlv; ti++) + if (P->nodes[L->tlv[ti]].type == AST_TEMPLATE_INST) + tixx(L, L->tlv[ti]); + for (int ti = 0; ti < L->ntlv; ti++) + if (P->nodes[L->tlv[ti]].type == AST_TEMPLATE_INST) + tixd(L, L->tlv[ti]); + for (int ti = 0; ti < L->ntlv; ti++) { uint32_t c = L->tlv[ti]; const ast_node_t *n = &P->nodes[c]; diff --git a/tests/trpi.c b/tests/trpi.c index 6618fd6..0604e95 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6244,3 +6244,68 @@ static void rpi311(void) PASS(); } TH_REG("rpi", 311, "a __shared__ kernel declares its size", rpi311) + + +static void rpi312(void) +{ + const char *b, *t; + + CHNE(scratch("rpi312.cu", + "#define assert(e) ((e) ? (void)0 : __trap())\n" + "__global__ void k(int *o, int n) {\n" + " int i = threadIdx.x; assert(i < n); o[i] = i; }\n"), NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi312.cu", obuf, (int)sizeof obuf), 0); + + b = strstr(obuf, "br_cond"); + t = strstr(obuf, "trap"); + CHNE(b, NULL); + CHNE(t, NULL); + CHEQ(t > b, 1); + CHNE(strstr(obuf, "tern.else"), NULL); + PASS(); +} +TH_REG("rpi", 312, "a void ternary keeps its test", rpi312) + +static void rpi313(void) +{ + CHNE(scratch("rpi313.cu", + "__device__ int f(int a) { return a + 1; }\n" + "__device__ int g(int a) { return a + 2; }\n" + "__global__ void k(int *o, int n) {\n" + " int i = threadIdx.x; o[i] = (i < n) ? f(1) : g(2); }\n"), NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi313.cu", obuf, (int)sizeof obuf), 0); + + CHNE(strstr(obuf, "phi i32"), NULL); + CHNE(strstr(obuf, "tern.then"), NULL); + CHEQ(strstr(obuf, "select"), NULL); + PASS(); +} +TH_REG("rpi", 313, "only one arm of a calling ternary runs", rpi313) + +static void rpi314(void) +{ + CHNE(scratch("rpi314.cu", + "__global__ void k(int *o, int n) {\n" + " int i = threadIdx.x; ((i < n) ? (o[0] = 1) : (o[0] = 2)); }\n"), + NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi314.cu", obuf, (int)sizeof obuf), 0); + + CHNE(strstr(obuf, "br_cond"), NULL); + CHNE(strstr(obuf, "tern.then"), NULL); + CHNE(strstr(obuf, "tern.else"), NULL); + PASS(); +} +TH_REG("rpi", 314, "a storing ternary stores once", rpi314) + +static void rpi315(void) +{ + CHNE(scratch("rpi315.cu", + "__global__ void k(int *o, const int *a, int n) {\n" + " int i = threadIdx.x; o[i] = (i < n) ? a[i] : 0; }\n"), NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi315.cu", obuf, (int)sizeof obuf), 0); + + CHNE(strstr(obuf, "select i32"), NULL); + CHEQ(strstr(obuf, "tern.then"), NULL); + PASS(); +} +TH_REG("rpi", 315, "a ternary that only reads stays a select", rpi315) From 1e7c940dad546d937e119c186069a203117f769c Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Thu, 17 Sep 2026 21:23:51 +1200 Subject: [PATCH 10/41] a functor is a call too, and forty kernels were missing because of it --- src/ir/bir_lower.c | 185 +++++++++++++++++++++++++++++++++++++++++++++ tests/hfun.cu | 56 ++++++++++++++ tests/thost.c | 10 +++ 3 files changed, 251 insertions(+) create mode 100644 tests/hfun.cu diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index ba3bb75..4f6ad86 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -368,6 +368,8 @@ typedef struct { binding_t pnb[MAX_NEST][MAX_TPARM]; int pdep; binding_t tnb[MAX_TPARM]; + binding_t fnb[MAX_TPARM]; + int fdep; binding_t xnb[MAX_NEST][MAX_TPARM]; int xdep; int tsc; @@ -13850,6 +13852,12 @@ static int hasl(lower_t *L, uint32_t nd, int depth, int hop) if (ND(L, nd)->type == AST_LAUNCH) return 1; if (ND(L, nd)->type == AST_CALL && hop > 0) { uint32_t cn = ND(L, nd)->first_child; + if (cn && ND(L, cn)->type == AST_CAST) { + uint32_t t = ND(L, cn)->first_child; + uint32_t e = t ? ND(L, t)->next_sibling : 0; + + if (e && ND(L, e)->type == AST_INIT_LIST) return 1; + } if (cn && ND(L, cn)->type == AST_IDENT) { char nm[128]; get_text(L, cn, nm, sizeof(nm)); @@ -14017,6 +14025,182 @@ static int swrap(lower_t *L, uint32_t node) return 1; } +static int clsf(const char *key, int k, char *mk, char *val, size_t vz) +{ + const char *p = key; + size_t n = 0; + + for (int i = 0; i <= k; i++) { + p = strchr(p, '|'); + if (p == NULL) return 0; + p++; + } + if (*p == '\0') return 0; + *mk = *p++; + while (*p != '\0' && *p != '|' && n + 1u < vz) val[n++] = *p++; + val[n] = '\0'; + return 1; +} + +static int clsb(lower_t *L, uint32_t ty, binding_t *nb, int *ntpo) +{ + const char *h; + char key[256]; + int ci, ntp; + + *ntpo = 0; + if (!ckey(L, ty, key, sizeof key)) return 0; + h = strchr(key, '#'); + if (!h) return 0; + ci = (int)strtol(h + 1, NULL, 10); + if (ci < 0 || ci >= L->nclss || !L->clss[ci].ast) return 0; + ntp = tparm(L, L->clss[ci].ast, nb); + if (ntp < 0) return 0; + for (int k = 0; k < ntp; k++) { + char mk = 0, val[96]; + + if (nb[k].is_pack || !clsf(key, k, &mk, val, sizeof val)) return 0; + if (mk == 't') { + nb[k].is_type = 1; + nb[k].type = (uint32_t)strtoul(val, NULL, 10); + } else if (mk == 'n') { + nb[k].is_type = 0; + nb[k].ival = (int64_t)strtoll(val, NULL, 10); + } else if (mk == 'f') { + nb[k].is_type = 0; + nb[k].is_fn = 1; + ncpy(nb[k].fnm, sizeof nb[k].fnm, val); + } else { + return 0; + } + nb[k].fixed = 1; + } + *ntpo = ntp; + return 1; +} + +static uint32_t fcty(lower_t *L, uint32_t cal) +{ + uint32_t ty = 0, ts, nm; + char n[64]; + + if (ND(L, cal)->type == AST_CAST) { + uint16_t sb; + int su; + + ts = ND(L, cal)->first_child; + nm = ts ? ND(L, ts)->next_sibling : 0; + if (!ts || !nm || ND(L, nm)->type != AST_INIT_LIST) return 0; + if (ND(L, ts)->type != AST_TYPE_SPEC + || ND(L, ts)->d.btype.kind != TYPE_NAME) return 0; + nm = ND(L, ts)->first_child; + if (!nm || ND(L, nm)->type != AST_IDENT) return 0; + get_text(L, nm, n, sizeof n); + if (find_binding(L, n, &ty)) return ty; + sb = L->rtbad; + su = L->rtunk; + ty = resolve_type(L, ts, 0, 0); + if (L->rtbad || L->rtunk) ty = 0; + L->rtbad = sb; + L->rtunk = su; + return ty; + } + if (ND(L, cal)->type == AST_IDENT && !ND(L, cal)->first_child) { + const sym_t *s; + + get_text(L, cal, n, sizeof n); + s = find_sym(L, n); + return s ? s->type : 0; + } + return 0; +} + +static uint32_t fopm(lower_t *L, uint32_t sd, int *tpl) +{ + uint32_t tn, m; + char raw[96], nm[96]; + + *tpl = 0; + tn = sd ? ND(L, sd)->first_child : 0; + if (!tn) return 0; + for (m = ND(L, tn)->next_sibling; m; m = ND(L, m)->next_sibling) { + uint32_t f = m, nn; + + if (ND(L, m)->type == AST_TEMPLATE_DECL) { + for (f = ND(L, m)->first_child; f; f = ND(L, f)->next_sibling) + if (ND(L, f)->type == AST_FUNC_DEF) break; + if (!f) continue; + } else if (ND(L, m)->type != AST_FUNC_DEF) { + continue; + } + nn = child_at(L, f, 1); + if (!nn || ND(L, nn)->type != AST_IDENT) continue; + get_text(L, nn, raw, sizeof raw); + normalize_op_name(raw, nm, (int)sizeof nm); + if (strcmp(nm, "operator()") != 0) continue; + *tpl = ND(L, m)->type == AST_TEMPLATE_DECL; + return m; + } + return 0; +} + +static int sfun(lower_t *L, uint32_t node) +{ + uint32_t cal = ND(L, node)->first_child; + uint32_t ty, sd, mem, body, fn2 = 0; + uint32_t av[BC_MAX_ARGS]; + const char *sn; + int si, tpl = 0, ntp = 0, nt2 = 0, na, onb, obs, hit = 0; + + if (!cal || L->fdep >= MAX_FWD) return 0; + ty = fcty(L, cal); + if (!ty) return 0; + sn = sname(L, ty); + if (!sn) return 0; + si = cslot(L, sn); + if (si < 0) return 0; + sd = L->structs[si].node; + mem = fopm(L, sd, &tpl); + if (!mem) return 0; + if (!clsb(L, ty, L->fnb, &ntp)) return 0; + + onb = L->nbindings; + obs = L->nbbase; + if (ntp > MAX_BIND - onb) return 0; + for (int i = 0; i < ntp; i++) L->bindings[L->nbindings++] = L->fnb[i]; + L->fdep++; + + if (!tpl) { + body = find_func_body(L, mem); + if (body && hasl(L, body, 0, MAX_FWD)) { + scan_launches(L, body); + hit = 1; + } + } else { + L->pkbad = 0; + na = subav(L, ND(L, cal)->next_sibling, av, BC_MAX_ARGS); + if (na >= 0 + && tdeduc(L, mem, cal, av, na, L->fnb, &nt2, &fn2) && fn2 + && nt2 <= MAX_BIND - L->nbindings) { + body = find_func_body(L, fn2); + if (body && hasl(L, body, 0, MAX_FWD)) { + for (int i = 0; i < nt2; i++) + L->bindings[L->nbindings++] = L->fnb[i]; + if (fwpush(L, fn2, av, na)) { + scan_launches(L, body); + L->nfwf--; + hit = 1; + } + } + } + } + + L->fdep--; + L->nbbase = obs; + L->nbindings = onb; + return hit; +} + static int lgen(const lower_t *L, uint32_t lam) { for (uint32_t c = ND(L, lam)->first_child; c; c = ND(L, c)->next_sibling) { @@ -14298,6 +14482,7 @@ static void scan_launches(lower_t *L, uint32_t node) if (n->type == AST_LAUNCH && slnal(L, node)) return; if (n->type == AST_CALL && sglc(L, node)) return; if (n->type == AST_CALL && swrap(L, node)) return; + if (n->type == AST_CALL && sfun(L, node)) return; if (n->type == AST_BLOCK) { int gsv = L->nglm, fsv = L->nfnal; diff --git a/tests/hfun.cu b/tests/hfun.cu new file mode 100644 index 0000000..486918c --- /dev/null +++ b/tests/hfun.cu @@ -0,0 +1,56 @@ +#include +#include + +template +__global__ void kern(float *o, int n) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + + if (i < n) o[i] = (float)tag; +} + +template +static void fire(float *o, int n) +{ + kern<<<(n + 63) / 64, 64>>>(o, n); +} + +template +struct maker { + template + void operator()(T *o, int n) const + { + fire(o, n); + } +}; + +template +static void thru(float *o, int n) +{ + M()(o, n); +} + +int main(void) +{ + enum { N = 64 }; + float h[N]; + float *d; + int bad = 0; + + cudaMalloc((void **)&d, N * sizeof(float)); + fire<3>(d, N); + cudaDeviceSynchronize(); + thru >(d, N); + cudaDeviceSynchronize(); + cudaMemcpy(h, d, N * sizeof(float), cudaMemcpyDeviceToHost); + for (int i = 0; i < N; i++) + if (h[i] != 5.0f) bad++; + cudaFree(d); + + if (bad != 0) { + printf("hfun: %d disagreements over %d lanes\n", bad, (int)N); + return 1; + } + printf("hfun: %d lanes, v=%g, all agree\n", (int)N, (double)h[0]); + return 0; +} diff --git a/tests/thost.c b/tests/thost.c index 6910046..c58c90c 100644 --- a/tests/thost.c +++ b/tests/thost.c @@ -411,3 +411,13 @@ static void hst25(void) PASS(); } TH_REG("hst", 25, "every byte value survives the fatbin literal", hst25) + +static void hst26(void) +{ + CHECK(emit("tests/hfun.cu", "tests/hst26.cpp")); + CHECK(strstr(hbuf, "\"kern\"") != NULL); + CHECK(strstr(hbuf, "\"kern$1\"") != NULL); + remove("tests/hst26.cpp"); + PASS(); +} +TH_REG("hst", 26, "a functor's operator() registers its kernel", hst26) From d1a2df86eed0360078d493528ed711a61a75ec76 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Fri, 18 Sep 2026 19:51:07 +1200 Subject: [PATCH 11/41] nvptx: a uint3 is twelve bytes, not four --- src/ir/bir.c | 14 +++ src/ir/bir.h | 1 + src/ir/bir_lower.c | 5 +- src/nvidia/emit.c | 22 ++++- src/nvidia/emit_sass.c | 36 ++++--- src/nvidia/isel.c | 218 +++++++++++++++++++++++++++++++++++++++-- src/nvidia/lt_nv.c | 6 +- src/nvidia/lt_nv.h | 3 +- src/nvidia/nvidia.h | 10 +- 9 files changed, 285 insertions(+), 30 deletions(-) diff --git a/src/ir/bir.c b/src/ir/bir.c index b002b1f..bdc28bf 100644 --- a/src/ir/bir.c +++ b/src/ir/bir.c @@ -491,6 +491,17 @@ int bir_umrk(bir_module_t *M, uint32_t ty) return 1; } +/* A struct may be declared more aligned than its members need: CUDA's + * uint4 wants 16 where four u32s would settle for 4. width is dead on a + * STRUCT, so the declared alignment lives there and bir_balg believes it. */ +int bir_salg(bir_module_t *M, uint32_t ty, uint32_t a) +{ + if (ty >= M->num_types || M->types[ty].kind != BIR_TYPE_STRUCT) return 0; + if (a == 0u || a > 0xFFFFu || (a & (a - 1u)) != 0u) return 0; + M->types[ty].width = (uint16_t)a; + return 1; +} + uint32_t bir_tcst(bir_module_t *M, uint32_t ty) { bir_type_t t; @@ -565,6 +576,8 @@ uint32_t bir_bsz(const bir_module_t *M, uint32_t ty, uint32_t psz) sp++; continue; } + if ((uint32_t)T->width > fr[i].alg) + fr[i].alg = (uint32_t)T->width; w = bsz_up(fr[i].sum, fr[i].alg); va = fr[i].alg; } else { @@ -613,6 +626,7 @@ uint32_t bir_balg(const bir_module_t *M, uint32_t ty, uint32_t psz) continue; } if (T->kind == BIR_TYPE_STRUCT) { + if ((uint32_t)T->width > best) best = (uint32_t)T->width; for (uint16_t f = 0; f < T->num_fields; f++) { if (T->count + f >= M->num_type_fields) return 0; if (sp >= BIR_BSZ_DEEP) return 0; diff --git a/src/ir/bir.h b/src/ir/bir.h index 15a4ddb..653284a 100644 --- a/src/ir/bir.h +++ b/src/ir/bir.h @@ -408,6 +408,7 @@ uint32_t bir_tunq(const bir_module_t *M, uint32_t ty); uint32_t bir_type_array(bir_module_t *M, uint32_t elem, uint32_t count); uint32_t bir_type_vector(bir_module_t *M, uint32_t elem, uint32_t count); uint32_t bir_type_struct(bir_module_t *M, const uint32_t *fields, int nfields); +int bir_salg(bir_module_t *M, uint32_t ty, uint32_t a); uint32_t bir_sfwd(bir_module_t *M); int bir_sfin(bir_module_t *M, uint32_t ty, const uint32_t *fields, int nfields); diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index 4f6ad86..5de297a 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -1482,6 +1482,7 @@ static struct_def_t *vreg(lower_t *L, const vecty_t *v) sd->algn = (uint8_t)valgn(v); sd->bir_type = vnty(L, v->kind, v->bits, v->lanes); if (!sd->bir_type) return NULL; + (void)bir_salg(L->M, sd->bir_type, sd->algn); for (int fi = 0; fi < v->lanes; fi++) { sd->field_types[fi] = et; ncpy(sd->field_names[fi], sizeof(sd->field_names[0]), xyzw[fi]); @@ -11399,8 +11400,10 @@ static void salgn(lower_t *L, struct_def_t *sd, uint32_t node) onat += sz; ocud += sz; } - if (want > bir_balg(L->M, sd->bir_type, 8)) + if (want > bir_balg(L->M, sd->bir_type, 8)) { sd->algn = (uint16_t)want; + (void)bir_salg(L->M, sd->bir_type, want); + } } static int malfnd(const lower_t *L, const char *cls, const char *nm, diff --git a/src/nvidia/emit.c b/src/nvidia/emit.c index bc092f5..9fc389e 100644 --- a/src/nvidia/emit.c +++ b/src/nvidia/emit.c @@ -926,9 +926,14 @@ static void em_inst(nv_module_t *nv, const nv_minst_t *I) case NV_LD_PARAM_B16: tsuf = ".b16"; break; default: tsuf = ".u32"; break; } + int32_t po = (I->num_uses >= 2 && I->ops[2].kind == NV_MOP_IMM) + ? I->ops[2].imm : 0; nv_apnd(nv, "ld.param%s ", tsuf); - em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", [param%d]", - I->ops[1].imm); + em_opnd(nv, &I->ops[0]); + if (po != 0) + nv_apnd(nv, ", [param%d+%d]", I->ops[1].imm, po); + else + nv_apnd(nv, ", [param%d]", I->ops[1].imm); break; } @@ -1464,10 +1469,17 @@ static void em_fhdr(nv_module_t *nv, const nv_mfunc_t *MF) } for (uint32_t pi = 0; pi < MF->num_params; pi++) { - const char *tsuf = MF->is_kern ? rf_param(MF->params[pi].rfile) - : rf_bits(MF->params[pi].rfile); + const nv_param_t *P = &MF->params[pi]; + if (pi > 0) nv_apnd(nv, ",\n"); - nv_apnd(nv, "\t.param %s param%u", tsuf, pi); + if (NV_PAGG(P)) { + nv_apnd(nv, "\t.param .align %u .b8 param%u[%u]", + (unsigned)(P->algn ? P->algn : 4u), pi, + (unsigned)P->size); + continue; + } + nv_apnd(nv, "\t.param %s param%u", + MF->is_kern ? rf_param(P->rfile) : rf_bits(P->rfile), pi); } if (nv->bkhit && MF->is_kern) nv_apnd(nv, ",\n\t.param .u64 __bkhit"); diff --git a/src/nvidia/emit_sass.c b/src/nvidia/emit_sass.c index 1a9deed..7ccca5f 100644 --- a/src/nvidia/emit_sass.c +++ b/src/nvidia/emit_sass.c @@ -2641,7 +2641,7 @@ static void sapld(const nv_minst_t *I) { lt_nrw_t x; uint64_t w[2]; - uint32_t d, o, n; + uint32_t d, o, n, po; memset(&x, 0, sizeof x); n = sadw(I); @@ -2656,15 +2656,18 @@ static void sapld(const nv_minst_t *I) sabad(I->op, BC_E609); return; } + po = (I->num_uses >= 2u && I->ops[2].kind == (uint8_t)NV_MOP_IMM + && I->ops[2].imm > 0) ? (uint32_t)I->ops[2].imm : 0u; + if (sast.isfn != 0u) { - uint32_t s = LT_NV_ARG0 + sast.pofs[I->ops[1].imm] / 4u; + uint32_t s = LT_NV_ARG0 + (sast.pofs[I->ops[1].imm] + po) / 4u; lt_nvmov(w, d, s); safire(w, &x, 0u); if (n == 2u) { lt_nvmov(w, d + 1u, s + 1u); safire(w, &x, 0u); } return; } - o = LT_NV_PBASE + sast.pofs[I->ops[1].imm]; + o = LT_NV_PBASE + sast.pofs[I->ops[1].imm] + po; lt_nvmovc(w, d, 0u, o); safire(w, &x, 0u); if (I->op == (uint16_t)NV_LD_PARAM_B16) { @@ -3046,11 +3049,20 @@ static void saspst(const nv_minst_t *I) if ((v = saspv(I, k)) != SA_NOIX) sast.rmap[v] = (uint16_t)SA_NOIX; } -static uint32_t sapsz(uint8_t rf) +/* The type says how big a parameter is. The register file only ever says + * how much of it fits in one register, which for a uint3 is a third. */ +static uint32_t sapsz(const nv_param_t *P) { - if (rf == (uint8_t)NV_RF_U64 || rf == (uint8_t)NV_RF_F64) return 8u; - if (rf == (uint8_t)NV_RF_U16 || rf == (uint8_t)NV_RF_F16) return 2u; - return 4u; + if (P->size != 0u) return P->size; + return NV_RFSZ(P->rfile); +} + +static uint32_t sapal(const nv_param_t *P) +{ + uint32_t a = P->algn; + + if (a == 0u || (a & (a - 1u)) != 0u) a = sapsz(P); + return a > 16u ? 16u : a; } static void sapar(void) @@ -3059,12 +3071,14 @@ static void sapar(void) sast.k.np = sast.F->num_params; for (uint32_t i = 0; i < sast.k.np && i < LT_MAX_NVPRM; i++) { - uint32_t z = sapsz(sast.F->params[i].rfile); + uint32_t z = sapsz(&sast.F->params[i]); + uint32_t a = sapal(&sast.F->params[i]); - if (sast.isfn != 0u && z < 4u) z = 4u; - o = (o + z - 1u) & ~(z - 1u); + if (sast.isfn != 0u && z < 4u) { z = 4u; a = 4u; } + o = (o + a - 1u) & ~(a - 1u); sast.pofs[i] = o; - sast.k.psz[i] = (uint8_t)z; + sast.k.psz[i] = (uint16_t)z; + sast.k.palg[i] = (uint8_t)a; o += z; } } diff --git a/src/nvidia/isel.c b/src/nvidia/isel.c index 69b1754..c669278 100644 --- a/src/nvidia/isel.c +++ b/src/nvidia/isel.c @@ -117,6 +117,9 @@ static uint16_t new_vreg(uint8_t rf) return S.nv->rc[rf]++; } +static int pagg(uint32_t ty); +static uint32_t vtyof(uint32_t val); + /* BIR type -> PTX register file */ static uint8_t bir_rfile(uint32_t type_idx) { @@ -142,6 +145,25 @@ static uint8_t bir_rfile(uint32_t type_idx) } } +/* A parameter's size and alignment come from its type. Scalars stay at + * zero and are sized by their register file, as they always were. */ +static int psinf(nv_param_t *P, uint32_t ty) +{ + uint32_t z, a; + + P->rfile = bir_rfile(ty); + P->size = 0u; + P->algn = 0u; + if (!pagg(ty)) return 1; + + z = bir_bsz(S.bir, ty, 8); + a = bir_balg(S.bir, ty, 8); + if (z == 0u || z > 0xFFFFu || a == 0u || a > 16u) return 0; + P->size = (uint16_t)z; + P->algn = (uint8_t)a; + return 1; +} + static uint8_t def_rf(uint32_t idx, uint32_t type_idx) { if (idx < S.bir->num_insts) { @@ -284,6 +306,21 @@ static uint32_t algnb(uint8_t subop) return (k > 12u) ? (1u << 12) : (1u << k); } +/* An aggregate's value is its address, so it needs a u64 home whatever + * the register file would otherwise make of its type. */ +static nv_opnd_t mapu64(uint32_t idx) +{ + uint16_t rn; + + if (idx >= BIR_MAX_INSTS) return mop_reg(NV_RF_U64, 0); + if (S.nv->val_vreg[idx] != 0) + return mop_reg(S.nv->val_rfile[idx], S.nv->val_vreg[idx]); + rn = new_vreg(NV_RF_U64); + S.nv->val_vreg[idx] = rn; + S.nv->val_rfile[idx] = NV_RF_U64; + return mop_reg(NV_RF_U64, rn); +} + static void unsz(const char *what, uint32_t ty) { char buf[128]; @@ -991,14 +1028,125 @@ static uint16_t stop(int as, uint8_t vrf, uint32_t psz) } } +/* ---- Aggregates ---- + * + * An aggregate has no register wide enough to be, so it lives in .local + * and travels as its address. Copying is the only move it has. */ + +static int pagg(uint32_t ty) +{ + uint8_t k; + + if (ty >= S.bir->num_types) return 0; + k = S.bir->types[ty].kind; + return k == BIR_TYPE_STRUCT || k == BIR_TYPE_ARRAY + || k == BIR_TYPE_VECTOR; +} + +/* Widest step the offset, the remainder and the alignment will all bear. + * The alignment is the one that bites: a uint3 sits on 4, so copying it + * eight bytes at a time faults the moment it lands on an odd slot. */ +static uint32_t agstp(uint32_t off, uint32_t rem, uint32_t al) +{ + uint32_t w = (al < 8u) ? al : 8u; + + while (w > 1u && (rem < w || (off & (w - 1u)) != 0u)) w >>= 1; + return w; +} + +static uint8_t agrf(uint32_t w) +{ + return (w == 8u) ? (uint8_t)NV_RF_U64 + : (w == 2u) ? (uint8_t)NV_RF_U16 : (uint8_t)NV_RF_U32; +} + +/* Reserve a local slot, the way an alloca would. */ +static uint32_t lslot(uint32_t sz, uint32_t a) +{ + uint32_t off = (S.lcl_off + a - 1u) & ~(a - 1u); + + if (off < S.lcl_off || off >= NV_MAX_FRAME || sz > NV_MAX_FRAME - off) + return NV_MAX_FRAME; + S.lcl_off = off + sz; + if (a > S.lcl_alg) S.lcl_alg = a; + return off; +} + +static nv_opnd_t agadd(nv_opnd_t base, uint32_t off) +{ + nv_opnd_t d; + + if (off == 0u) return base; + d = mop_reg(NV_RF_U64, new_vreg(NV_RF_U64)); + em1(NV_ADD_U64, d, base, mop_imm((int32_t)off)); + return d; +} + +/* An aggregate's home: a local slot, with its address in a u64. */ +static int aghome(uint32_t idx, uint32_t ty, nv_opnd_t *out, + uint32_t *psz, uint32_t *pal) +{ + uint32_t sz = bir_bsz(S.bir, ty, 8); + uint32_t al = bir_balg(S.bir, ty, 8); + uint32_t off; + + if (sz == 0u || al == 0u) { unsz("aggregate", ty); return 0; } + off = lslot(sz, al); + if (off >= NV_MAX_FRAME) { + nv_refuse("a local frame this large"); + return 0; + } + *out = mapu64(idx); + *psz = sz; + *pal = al; + em1u(NV_LEA_LOCAL, *out, mop_imm((int32_t)off)); + return 1; +} + +static void agcpy(nv_opnd_t dst, int das, nv_opnd_t src, int sas, + uint32_t sz, uint32_t al) +{ + uint32_t off = 0u, g = sz + 8u; + + while (off < sz && g--) { + uint32_t w = agstp(off, sz - off, al); + uint8_t rf; + nv_opnd_t t, ops[2]; + + if (w == 1u) { + nv_refuse("an aggregate with an odd byte size"); + return; + } + rf = agrf(w); + t = mop_reg(rf, new_vreg(rf)); + em1u(ldop(sas, rf, 0u), t, agadd(src, off)); + ops[0] = agadd(dst, off); + ops[1] = t; + emit(stop(das, rf, 0u), 0, 2, ops, 0); + off += w; + } +} + +/* ---- Memory: Load ---- */ + static void is_load(uint32_t idx, const bir_inst_t *I) { - nv_opnd_t d = map_val(idx, I->type); - uint8_t drf = S.nv->val_rfile[idx]; uint32_t ptr_val = I->operands[0]; int as = pas(ptr_val); nv_opnd_t addr = mat_const(ptr_val, NV_RF_U64); + nv_opnd_t d; + uint8_t drf; + + if (pagg(I->type)) { + uint32_t sz, al; + + if (!aghome(idx, I->type, &d, &sz, &al)) return; + agcpy(d, BIR_AS_PRIVATE, addr, as, sz, al); + return; + } + d = map_val(idx, I->type); + drf = S.nv->val_rfile[idx]; em1u(ldop(as, drf, pntsz(ptr_val)), d, addr); } @@ -1007,15 +1155,31 @@ static void is_load(uint32_t idx, const bir_inst_t *I) static void is_store(const bir_inst_t *I) { /* BIR store: ops[0]=value, ops[1]=address */ - nv_opnd_t val = rslv(I->operands[0]); - uint8_t vrf = rslv_rf(I->operands[0]); + uint32_t vval = I->operands[0]; + uint32_t vty = vtyof(vval); uint32_t ptr_val = I->operands[1]; int as = pas(ptr_val); nv_opnd_t addr = mat_const(ptr_val, NV_RF_U64); + nv_opnd_t val; + uint8_t vrf; + + /* An aggregate is an address, so storing one is a copy. Its home is + * always .local, whatever the pointer it is being written through. */ + if (pagg(vty)) { + uint32_t sz = bir_bsz(S.bir, vty, 8); + uint32_t al = bir_balg(S.bir, vty, 8); + + if (sz == 0u || al == 0u) { unsz("store", vty); return; } + agcpy(addr, as, mat_const(vval, NV_RF_U64), BIR_AS_PRIVATE, sz, al); + return; + } + + val = rslv(vval); + vrf = rslv_rf(vval); /* Value must be in a register for stores */ if (val.kind != NV_MOP_REG) - val = mat_const(I->operands[0], vrf); + val = mat_const(vval, vrf); /* Store: 0 defs, 2 uses (addr, value) */ nv_opnd_t ops[2] = { addr, val }; @@ -1229,10 +1393,44 @@ static void is_gep(uint32_t idx, const bir_inst_t *I) static void is_param(uint32_t idx, const bir_inst_t *I) { uint8_t rf = bir_rfile(I->type); - nv_opnd_t d = map_val(idx, I->type); uint32_t pi = I->subop; - + nv_opnd_t d; uint16_t op; + + /* An aggregate parameter is wider than any register, so it is read + * out of .param a chunk at a time into a local slot, and what the + * rest of the function sees is that slot's address. */ + if (pagg(I->type)) { + uint32_t sz, al, o = 0u, g; + + if (!aghome(idx, I->type, &d, &sz, &al)) return; + g = sz + 8u; + while (o < sz && g--) { + uint32_t w = agstp(o, sz - o, al); + uint8_t crf; + nv_opnd_t t, lops[3], sops[2]; + + if (w == 1u) { + nv_refuse("an aggregate with an odd byte size"); + return; + } + crf = agrf(w); + t = mop_reg(crf, new_vreg(crf)); + lops[0] = t; + lops[1] = mop_imm((int32_t)pi); + lops[2] = mop_imm((int32_t)o); + emit(w == 8u ? NV_LD_PARAM_U64 + : w == 2u ? NV_LD_PARAM_B16 : NV_LD_PARAM_U32, + 1, 2, lops, 0); + sops[0] = agadd(d, o); + sops[1] = t; + emit(stop(BIR_AS_PRIVATE, crf, 0u), 0, 2, sops, 0); + o += w; + } + return; + } + + d = map_val(idx, I->type); switch (rf) { case NV_RF_U64: op = NV_LD_PARAM_U64; break; case NV_RF_F32: op = NV_LD_PARAM_F32; break; @@ -3285,7 +3483,8 @@ static void fsig(nv_mfunc_t *MF, const bir_func_t *F) for (i = 0; i < np; i++) { uint32_t pt = (FT->count + i < S.bir->num_type_fields) ? S.bir->type_fields[FT->count + i] : 0; - MF->params[i].rfile = bir_rfile(pt); + if (!psinf(&MF->params[i], pt)) + nv_refuse("a parameter this large"); } MF->num_params = np; @@ -3353,7 +3552,8 @@ static int isel_func(uint32_t fi) nv_cap("kernel parameters", (unsigned)NV_MAX_PARAMS); break; } - MF->params[pi].rfile = bir_rfile(I->type); + if (!psinf(&MF->params[pi], I->type)) + nv_refuse("a parameter this large"); pi++; } MF->num_params = pi; diff --git a/src/nvidia/lt_nv.c b/src/nvidia/lt_nv.c index 0df53fe..48ebedc 100644 --- a/src/nvidia/lt_nv.c +++ b/src/nvidia/lt_nv.c @@ -130,8 +130,9 @@ static uint32_t pblock(const lt_nvk_t *k) for (uint32_t i = 0; i < k->np; i++) { uint32_t w = k->psz[i]; + uint32_t a = k->palg[i] != 0u ? k->palg[i] : (w != 0u ? w : 1u); - o = align(o, w != 0u ? w : 1u); + o = align(o, a); o += w; } return o; @@ -150,8 +151,9 @@ static uint32_t nvinfo(uint8_t *p, const lt_nvk_t *k, uint32_t symi) for (uint32_t i = 0; i < k->np; i++) { uint32_t w = k->psz[i]; + uint32_t a = k->palg[i] != 0u ? k->palg[i] : (w != 0u ? w : 1u); - o = align(o, w != 0u ? w : 1u); + o = align(o, a); p[n++] = 0x04u; p[n++] = 0x17u; w16(p + n, 12u); n += 2u; w32(p + n, 0u); n += 4u; w16(p + n, i); n += 2u; diff --git a/src/nvidia/lt_nv.h b/src/nvidia/lt_nv.h index 022e880..8a4aa88 100644 --- a/src/nvidia/lt_nv.h +++ b/src/nvidia/lt_nv.h @@ -140,7 +140,8 @@ typedef struct { uint32_t nreg; uint32_t smem; uint32_t lmem; - uint8_t psz[LT_MAX_NVPRM]; + uint16_t psz[LT_MAX_NVPRM]; + uint8_t palg[LT_MAX_NVPRM]; uint32_t np; uint32_t wave; uint32_t mthr; diff --git a/src/nvidia/nvidia.h b/src/nvidia/nvidia.h index e6174fd..963d2d6 100644 --- a/src/nvidia/nvidia.h +++ b/src/nvidia/nvidia.h @@ -329,9 +329,17 @@ typedef struct { typedef struct { uint32_t name; /* string table offset */ uint8_t rfile; /* NV_RF_U32/U64/F32/F64 */ - uint8_t pad[3]; + uint8_t algn; /* bytes, from the type, not the register file */ + uint16_t size; /* bytes, ditto */ } nv_param_t; +/* Scalars leave size and algn at zero and are sized by their register + * file, exactly as they always were. An aggregate carries its real size, + * because the register file only knows the part of it that fits. */ +#define NV_RFSZ(rf) (((rf) == NV_RF_U64 || (rf) == NV_RF_F64) ? 8u : \ + ((rf) == NV_RF_U16 || (rf) == NV_RF_F16) ? 2u : 4u) +#define NV_PAGG(P) ((P)->size != 0u) + typedef struct { uint32_t name; /* string table offset */ uint32_t first_blk; From 3efe4d4e270ddec5bac17147ec815561407ea45b Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Fri, 18 Sep 2026 20:07:44 +1200 Subject: [PATCH 12/41] nvptx: alignment is a walk, not a stack, and four bools make a word --- src/ir/bir.c | 30 ++++++++++++++++-------------- src/nvidia/emit_sass.c | 6 +++--- src/nvidia/isel.c | 31 ++++++++----------------------- src/nvidia/nvidia.h | 7 ++----- tests/tvec.c | 13 +++++++------ 5 files changed, 36 insertions(+), 51 deletions(-) diff --git a/src/ir/bir.c b/src/ir/bir.c index bdc28bf..9862a87 100644 --- a/src/ir/bir.c +++ b/src/ir/bir.c @@ -491,9 +491,6 @@ int bir_umrk(bir_module_t *M, uint32_t ty) return 1; } -/* A struct may be declared more aligned than its members need: CUDA's - * uint4 wants 16 where four u32s would settle for 4. width is dead on a - * STRUCT, so the declared alignment lives there and bir_balg believes it. */ int bir_salg(bir_module_t *M, uint32_t ty, uint32_t a) { if (ty >= M->num_types || M->types[ty].kind != BIR_TYPE_STRUCT) return 0; @@ -609,29 +606,33 @@ uint32_t bir_bsz(const bir_module_t *M, uint32_t ty, uint32_t psz) uint32_t bir_balg(const bir_module_t *M, uint32_t ty, uint32_t psz) { - uint32_t st[BIR_BSZ_DEEP], sp = 0, guard = 4u * BIR_MAX_TYPE_FIELDS; + struct { uint32_t ty, fld; } fr[BIR_BSZ_DEEP]; + uint32_t sp = 1, guard = 4u * BIR_MAX_TYPE_FIELDS; uint32_t best = 1; - st[sp++] = ty; + fr[0].ty = ty; fr[0].fld = 0; while (sp && guard--) { - uint32_t t = st[--sp], w; + uint32_t i = sp - 1, w; const bir_type_t *T; - if (t >= M->num_types) return 0; - T = &M->types[t]; + if (fr[i].ty >= M->num_types) return 0; + T = &M->types[fr[i].ty]; if (T->kind == BIR_TYPE_ARRAY || T->kind == BIR_TYPE_VECTOR) { - if (sp >= BIR_BSZ_DEEP) return 0; - st[sp++] = T->inner; + fr[i].ty = T->inner; continue; } if (T->kind == BIR_TYPE_STRUCT) { if ((uint32_t)T->width > best) best = (uint32_t)T->width; - for (uint16_t f = 0; f < T->num_fields; f++) { - if (T->count + f >= M->num_type_fields) return 0; - if (sp >= BIR_BSZ_DEEP) return 0; - st[sp++] = M->type_fields[T->count + f]; + if (fr[i].fld < (uint32_t)T->num_fields) { + uint32_t f = T->count + fr[i].fld++; + if (f >= M->num_type_fields || sp >= BIR_BSZ_DEEP) return 0; + fr[sp].ty = M->type_fields[f]; + fr[sp].fld = 0; + sp++; + continue; } + sp--; continue; } switch (T->kind) { @@ -643,6 +644,7 @@ uint32_t bir_balg(const bir_module_t *M, uint32_t ty, uint32_t psz) } w = bsz_al(w, psz); if (w > best) best = w; + sp--; } return sp ? 0 : best; } diff --git a/src/nvidia/emit_sass.c b/src/nvidia/emit_sass.c index 7ccca5f..07cd7a4 100644 --- a/src/nvidia/emit_sass.c +++ b/src/nvidia/emit_sass.c @@ -3049,8 +3049,6 @@ static void saspst(const nv_minst_t *I) if ((v = saspv(I, k)) != SA_NOIX) sast.rmap[v] = (uint16_t)SA_NOIX; } -/* The type says how big a parameter is. The register file only ever says - * how much of it fits in one register, which for a uint3 is a third. */ static uint32_t sapsz(const nv_param_t *P) { if (P->size != 0u) return P->size; @@ -3059,9 +3057,11 @@ static uint32_t sapsz(const nv_param_t *P) static uint32_t sapal(const nv_param_t *P) { + uint32_t z = sapsz(P); uint32_t a = P->algn; - if (a == 0u || (a & (a - 1u)) != 0u) a = sapsz(P); + if (a == 0u || (a & (a - 1u)) != 0u) a = z; + if (P->size != 0u && a < 4u && (z & 3u) == 0u) a = 4u; return a > 16u ? 16u : a; } diff --git a/src/nvidia/isel.c b/src/nvidia/isel.c index c669278..3c8a8c2 100644 --- a/src/nvidia/isel.c +++ b/src/nvidia/isel.c @@ -145,8 +145,6 @@ static uint8_t bir_rfile(uint32_t type_idx) } } -/* A parameter's size and alignment come from its type. Scalars stay at - * zero and are sized by their register file, as they always were. */ static int psinf(nv_param_t *P, uint32_t ty) { uint32_t z, a; @@ -306,8 +304,6 @@ static uint32_t algnb(uint8_t subop) return (k > 12u) ? (1u << 12) : (1u << k); } -/* An aggregate's value is its address, so it needs a u64 home whatever - * the register file would otherwise make of its type. */ static nv_opnd_t mapu64(uint32_t idx) { uint16_t rn; @@ -1028,11 +1024,6 @@ static uint16_t stop(int as, uint8_t vrf, uint32_t psz) } } -/* ---- Aggregates ---- - * - * An aggregate has no register wide enough to be, so it lives in .local - * and travels as its address. Copying is the only move it has. */ - static int pagg(uint32_t ty) { uint8_t k; @@ -1043,9 +1034,11 @@ static int pagg(uint32_t ty) || k == BIR_TYPE_VECTOR; } -/* Widest step the offset, the remainder and the alignment will all bear. - * The alignment is the one that bites: a uint3 sits on 4, so copying it - * eight bytes at a time faults the moment it lands on an odd slot. */ +static uint32_t agea(uint32_t al, uint32_t sz) +{ + return (al < 4u && (sz & 3u) == 0u) ? 4u : al; +} + static uint32_t agstp(uint32_t off, uint32_t rem, uint32_t al) { uint32_t w = (al < 8u) ? al : 8u; @@ -1060,7 +1053,6 @@ static uint8_t agrf(uint32_t w) : (w == 2u) ? (uint8_t)NV_RF_U16 : (uint8_t)NV_RF_U32; } -/* Reserve a local slot, the way an alloca would. */ static uint32_t lslot(uint32_t sz, uint32_t a) { uint32_t off = (S.lcl_off + a - 1u) & ~(a - 1u); @@ -1082,7 +1074,6 @@ static nv_opnd_t agadd(nv_opnd_t base, uint32_t off) return d; } -/* An aggregate's home: a local slot, with its address in a u64. */ static int aghome(uint32_t idx, uint32_t ty, nv_opnd_t *out, uint32_t *psz, uint32_t *pal) { @@ -1098,7 +1089,7 @@ static int aghome(uint32_t idx, uint32_t ty, nv_opnd_t *out, } *out = mapu64(idx); *psz = sz; - *pal = al; + *pal = agea(al, sz); em1u(NV_LEA_LOCAL, *out, mop_imm((int32_t)off)); return 1; } @@ -1127,8 +1118,6 @@ static void agcpy(nv_opnd_t dst, int das, nv_opnd_t src, int sas, } } -/* ---- Memory: Load ---- */ - static void is_load(uint32_t idx, const bir_inst_t *I) { uint32_t ptr_val = I->operands[0]; @@ -1163,14 +1152,13 @@ static void is_store(const bir_inst_t *I) nv_opnd_t val; uint8_t vrf; - /* An aggregate is an address, so storing one is a copy. Its home is - * always .local, whatever the pointer it is being written through. */ if (pagg(vty)) { uint32_t sz = bir_bsz(S.bir, vty, 8); uint32_t al = bir_balg(S.bir, vty, 8); if (sz == 0u || al == 0u) { unsz("store", vty); return; } - agcpy(addr, as, mat_const(vval, NV_RF_U64), BIR_AS_PRIVATE, sz, al); + agcpy(addr, as, mat_const(vval, NV_RF_U64), BIR_AS_PRIVATE, sz, + agea(al, sz)); return; } @@ -1397,9 +1385,6 @@ static void is_param(uint32_t idx, const bir_inst_t *I) nv_opnd_t d; uint16_t op; - /* An aggregate parameter is wider than any register, so it is read - * out of .param a chunk at a time into a local slot, and what the - * rest of the function sees is that slot's address. */ if (pagg(I->type)) { uint32_t sz, al, o = 0u, g; diff --git a/src/nvidia/nvidia.h b/src/nvidia/nvidia.h index 963d2d6..e5a77cc 100644 --- a/src/nvidia/nvidia.h +++ b/src/nvidia/nvidia.h @@ -329,13 +329,10 @@ typedef struct { typedef struct { uint32_t name; /* string table offset */ uint8_t rfile; /* NV_RF_U32/U64/F32/F64 */ - uint8_t algn; /* bytes, from the type, not the register file */ - uint16_t size; /* bytes, ditto */ + uint8_t algn; + uint16_t size; } nv_param_t; -/* Scalars leave size and algn at zero and are sized by their register - * file, exactly as they always were. An aggregate carries its real size, - * because the register file only knows the part of it that fits. */ #define NV_RFSZ(rf) (((rf) == NV_RF_U64 || (rf) == NV_RF_F64) ? 8u : \ ((rf) == NV_RF_U16 || (rf) == NV_RF_F16) ? 2u : 4u) #define NV_PAGG(P) ((P)->size != 0u) diff --git a/tests/tvec.c b/tests/tvec.c index f5de8f5..205cb1c 100644 --- a/tests/tvec.c +++ b/tests/tvec.c @@ -109,17 +109,18 @@ static void vec05(void) } TH_REG("vec", 5, "__half22float2 widens both lanes", vec05) -/* ---- Alignment, which BIR's type record cannot carry ---- */ +/* ---- Alignment, which BIR's type record now carries ---- */ static void vec06(void) { - CHNE(vcrun("struct s { char c; float4 v; };\n" - "__global__ void k(float *o){ struct s q; q.v.x = 1.0f;" - " o[0] = q.v.x; }\n", "--ir"), 0); - CHNE(strstr(obuf, "E142"), NULL); + CHEQ(vcrun("struct s { char c; float4 v; };\n" + "__global__ void k(unsigned *o){ struct s q; q.v.x = 1.0f;" + " o[0] = (unsigned)sizeof(s); }\n", "--ir"), 0); + CHEQ(strstr(obuf, "E142"), NULL); + CHNE(strstr(obuf, "store i32 32"), NULL); PASS(); } -TH_REG("vec", 6, "float4 after a char refuses", vec06) +TH_REG("vec", 6, "float4 after a char lands on sixteen", vec06) static void vec07(void) { From 57e771837c3e77e2b846aadda8bb340ed16d72ac Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Sat, 19 Sep 2026 14:33:23 +1200 Subject: [PATCH 13/41] bir: a pointer keeps the address space of the value it came from A __shared__ array passed to a __device__ helper kept the callee's ptr type once mem2reg forwarded it past the parameter copy, so isel picked a global access for shared memory. --- src/ir/bir_inline.c | 57 +++++++++++++++++++++++++++++++++++++++++++++ src/ir/bir_inline.h | 8 +++++++ src/main.c | 1 + 3 files changed, 66 insertions(+) diff --git a/src/ir/bir_inline.c b/src/ir/bir_inline.c index 677c1f3..2620114 100644 --- a/src/ir/bir_inline.c +++ b/src/ir/bir_inline.c @@ -371,6 +371,63 @@ static uint32_t emit_phi(inl_t *X, uint32_t type, const uint32_t *preds, return ni; } +/* ---- Address space of the bound argument ---- */ + +/* A pointer's address space belongs to the argument it was bound to, not to + the `T *` the callee declared, so shared memory handed to a device helper + keeps its space through the clones that index it. */ +static uint32_t vasof(const bir_module_t *M, uint32_t v, int *ok) +{ + uint32_t i = BIR_VAL_INDEX(v), t; + + *ok = 0; + if (v == BIR_VAL_NONE || BIR_VAL_IS_CONST(v)) return 0; + if (i >= M->num_insts) return 0; + t = M->insts[i].type; + if (t >= M->num_types || M->types[t].kind != BIR_TYPE_PTR) return 0; + *ok = 1; + return M->types[t].addrspace; +} + +static uint32_t aspass(bir_module_t *M) +{ + uint32_t ni, hit = 0; + + for (ni = 0; ni < M->num_insts; ni++) { + bir_inst_t *I = &M->insts[ni]; + uint32_t t = I->type, base, inner, as; + int ok; + + if (I->op != BIR_GEP && I->op != BIR_BITCAST) continue; + if (t >= M->num_types || M->types[t].kind != BIR_TYPE_PTR) continue; + if (I->num_operands == BIR_OPERANDS_OVERFLOW) + base = (I->operands[1] >= 1u) + ? M->extra_operands[I->operands[0]] : BIR_VAL_NONE; + else + base = (I->num_operands >= 1u) ? I->operands[0] : BIR_VAL_NONE; + as = vasof(M, base, &ok); + if (!ok || as == M->types[t].addrspace) continue; + inner = M->types[t].inner; + I->type = bir_type_ptr(M, inner, (int)as); + hit++; + } + return hit; +} + +int bir_asfix(bir_module_t *M) +{ + uint32_t round, n = 0; + + if (M == NULL) return 0; + for (round = 0; round < 16u; round++) { + uint32_t hit = aspass(M); + + n += hit; + if (hit == 0u) break; + } + return (int)n; +} + /* ---- Splice one call ---- */ /* Splice a single straight-line block callee at `call_oi`. Its parameters diff --git a/src/ir/bir_inline.h b/src/ir/bir_inline.h index 9611552..345a2c9 100644 --- a/src/ir/bir_inline.h +++ b/src/ir/bir_inline.h @@ -24,4 +24,12 @@ */ int bir_inline_device(bir_module_t *M, int drop); +/* Settle every pointer's address space against the value it derives from. + * A callee declares `T *`, which lowers to ptr, so a __shared__ array + * passed to a device helper keeps the callee's global type once mem2reg has + * forwarded the argument past the parameter copy. isel reads that type to pick + * between a shared and a global access, so the mismatch has to be settled + * before it runs. Returns the number of types corrected. */ +int bir_asfix(bir_module_t *M); + #endif /* BARRACUDA_BIR_INLINE_H */ diff --git a/src/main.c b/src/main.c index 6815b2f..430f211 100644 --- a/src/main.c +++ b/src/main.c @@ -140,6 +140,7 @@ static int run_bir_backends(bir_module_t *bir, const backend_cfg_t *cfg) /* Optimisation passes: same shape regardless of frontend. */ if (!cfg->no_sroa) bir_sroa(bir); if (!cfg->no_mem2reg) bir_mem2reg(bir); + (void)bir_asfix(bir); if (!cfg->no_cfold) bir_cfold(bir); if (!cfg->no_dce) bir_dce(bir); From 513a52fb525ce55926edc5aa35f1b515628a31ce Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Sat, 19 Sep 2026 15:28:33 +1200 Subject: [PATCH 14/41] bir: a constexpr local that folds is a constant, not a call --- src/ir/bir_lower.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index 5de297a..1ec2666 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -10121,6 +10121,9 @@ static void lower_var_decl(lower_t *L, uint32_t node) return; } + int cxok = 0; + uint32_t cxv = BIR_VAL_NONE; + if ((n->qualifiers & (QUAL_CONSTEXPR | QUAL_CONST)) && n->d.oper.op == 0) { uint32_t ci = ND(L, name_n)->next_sibling; int n0 = L->ncag; @@ -10138,6 +10141,10 @@ static void lower_var_decl(lower_t *L, uint32_t node) L->ncag = n0; return; } + if (!cv.agg && !cv.fnd) { + cxv = sdemv(L, &cv, elem_t); + cxok = 1; + } } L->ncag = n0; } @@ -10224,6 +10231,11 @@ static void lower_var_decl(lower_t *L, uint32_t node) L->nzst = 0; ainit(L, node, BIR_MAKE_VAL(alloca), elem_t, init_n, 0, name); } + } else if (cxok) { + uint32_t st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + + set_op(L, st, 0, cxv); + set_op(L, st, 1, BIR_MAKE_VAL(alloca)); } else if (init_n && ND(L, init_n)->type != AST_NONE) { uint32_t init_v; uint32_t vt; From 873ea7d4752777d9173ec926479af6f4755ae4c8 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Sat, 19 Sep 2026 15:28:33 +1200 Subject: [PATCH 15/41] inline: take back the comments the ratchet counted --- src/ir/bir_inline.c | 5 ----- src/ir/bir_inline.h | 6 ------ 2 files changed, 11 deletions(-) diff --git a/src/ir/bir_inline.c b/src/ir/bir_inline.c index 2620114..bdfdda7 100644 --- a/src/ir/bir_inline.c +++ b/src/ir/bir_inline.c @@ -371,11 +371,6 @@ static uint32_t emit_phi(inl_t *X, uint32_t type, const uint32_t *preds, return ni; } -/* ---- Address space of the bound argument ---- */ - -/* A pointer's address space belongs to the argument it was bound to, not to - the `T *` the callee declared, so shared memory handed to a device helper - keeps its space through the clones that index it. */ static uint32_t vasof(const bir_module_t *M, uint32_t v, int *ok) { uint32_t i = BIR_VAL_INDEX(v), t; diff --git a/src/ir/bir_inline.h b/src/ir/bir_inline.h index 345a2c9..ba8efaf 100644 --- a/src/ir/bir_inline.h +++ b/src/ir/bir_inline.h @@ -24,12 +24,6 @@ */ int bir_inline_device(bir_module_t *M, int drop); -/* Settle every pointer's address space against the value it derives from. - * A callee declares `T *`, which lowers to ptr, so a __shared__ array - * passed to a device helper keeps the callee's global type once mem2reg has - * forwarded the argument past the parameter copy. isel reads that type to pick - * between a shared and a global access, so the mismatch has to be settled - * before it runs. Returns the number of types corrected. */ int bir_asfix(bir_module_t *M); #endif /* BARRACUDA_BIR_INLINE_H */ From 674223acc31571b56e6c256a5caf4fd2bf0121b0 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Sat, 19 Sep 2026 17:40:05 +1200 Subject: [PATCH 16/41] bir: two integers of different width meet at the wider one --- src/ir/bir_lower.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index 1ec2666..1f91f2b 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -4405,6 +4405,16 @@ static uint32_t bin_val(lower_t *L, uint32_t node, int op, rhs = coerce_to(L, rhs, lt, 0); res_t = lt; } + } else if (op != TOK_SHL && op != TOK_SHR + && lt < L->M->num_types && rt < L->M->num_types + && L->M->types[lt].kind == BIR_TYPE_INT + && L->M->types[rt].kind == BIR_TYPE_INT) { + if (L->M->types[rt].width > L->M->types[lt].width) { + lhs = coerce_to(L, lhs, rt, node_is_unsigned(L, lhs_n)); + res_t = rt; + } else if (L->M->types[lt].width > L->M->types[rt].width) { + rhs = coerce_to(L, rhs, lt, node_is_unsigned(L, rhs_n)); + } } int fp = is_float_type(L, res_t); int opc = bin_op_code(op, fp, node_is_unsigned(L, node)); From 6b667b90bc22f7f054bfa647d270d942acf9a27c Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Sat, 19 Sep 2026 19:56:28 +1200 Subject: [PATCH 17/41] sass: a predicated branch ends a block wherever it sits sasplit only split at the pair form, a predicated branch directly before the closing branch. isel puts a phi copy between the two, so the block stayed whole, the taken edge never reached the liveness graph, and a value used only on that edge lost its registers straight after its def. rope_neox read row_indices out of a pair that by then held row_dst and i3, which is the null load the ggml run died on. --- src/nvidia/emit_sass.c | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/nvidia/emit_sass.c b/src/nvidia/emit_sass.c index 07cd7a4..ec2bd22 100644 --- a/src/nvidia/emit_sass.c +++ b/src/nvidia/emit_sass.c @@ -290,11 +290,6 @@ static uint32_t satgt(const nv_opnd_t *o) return sast.bmap[g]; } -static int sapair(const nv_minst_t *a, const nv_minst_t *b) -{ - return a->op == (uint16_t)NV_BRA_PRED && b->op == (uint16_t)NV_BRA; -} - static uint32_t saterm(const nv_minst_t *I) { if (I->op == (uint16_t)NV_BRA) return TBR; @@ -317,10 +312,10 @@ static int sasplit(void) sast.bmap[bi] = (uint16_t)n; sast.ist[n] = s; n++; - if (B->num_insts >= 2u - && sapair(&M->minsts[B->first_inst + B->num_insts - 2u], - &M->minsts[B->first_inst + B->num_insts - 1u])) { - sast.ist[n] = e - 1u; + for (uint32_t i = s; i + 1u < e; i++) { + if (M->minsts[sast.f0 + i].op != (uint16_t)NV_BRA_PRED) continue; + if (n + 2u >= SA_NBB) return 1; + sast.ist[n] = i + 1u; n++; } } From 89dab4d9b5447ae35ba2961a82eae876f5961c0b Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Sat, 19 Sep 2026 19:56:28 +1200 Subject: [PATCH 18/41] bir: a launch scan types a wrapper's locals under its bindings scan_launches never registered the locals of the body it walked, so an argument naming one fell through to sema, which types an unresolved name as int. set_rows_cuda deduced its inner call from const src_t * and const idx_t * locals and built k_set_rows three times over instead of the twelve real instances. vscn already does this for tscan. --- src/ir/bir_lower.c | 1 + tests/trpi.c | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index 1f91f2b..a2dcd3f 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -14526,6 +14526,7 @@ static void scan_launches(lower_t *L, uint32_t node) continue; } scan_launches(L, c); + if (ND(L, c)->type == AST_VAR_DECL) vscn(L, c); } pop_scope(L); L->nglm = gsv; diff --git a/tests/trpi.c b/tests/trpi.c index 0604e95..34bd0de 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6309,3 +6309,26 @@ static void rpi315(void) PASS(); } TH_REG("rpi", 315, "a ternary that only reads stays a select", rpi315) + +static void rpi316(void) +{ + CHNE(scratch("rpi316.cu", + "template \n" + "__global__ void kk(const S *s, D *d, int n) {\n" + " int i = threadIdx.x; if (i < n) d[i] = (D)s[i]; }\n" + "template \n" + "static void inner(const S *s, D *d, int n) {\n" + " kk<<<1, n>>>(s, d, n); }\n" + "template \n" + "static void outer(const void *p, float *d, int n) {\n" + " const S *s = (const S *)p;\n" + " inner(s, d, n); }\n" + "void host(const void *p, float *d, int n) {\n" + " outer(p, d, n); }\n"), NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi316.cu", obuf, (int)sizeof obuf), 0); + + CHNE(strstr(obuf, "func @kk(ptr"), NULL); + CHEQ(strstr(obuf, "func @kk(ptr"), NULL); + PASS(); +} +TH_REG("rpi", 316, "a wrapper's local keeps its dependent type", rpi316) From 961748882156737b2d3b936ad0a45ff679b763d4 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Sat, 19 Sep 2026 20:12:35 +1200 Subject: [PATCH 19/41] nvptx: an aggregate phi carries an address and copies at the merge A struct lives in a frame slot here, but is_phi took its register file from the type and moved it as a u32, which the verifier refused as E840. Each predecessor now hands the merge the address of its value's slot through the ordinary phi copy, and the merge copies into a slot of the phi's own, so a value redefined round a loop cannot change under it. A phi fed by another phi of the same block would need the copies ordered, and one fed by a constant has no slot, so both refuse by name. All sixteen mmf instances stopped here. --- src/nvidia/isel.c | 42 +++++++++++++++++++++++++++++++++++++++--- tests/trpi.c | 18 ++++++++++++++++++ 2 files changed, 57 insertions(+), 3 deletions(-) diff --git a/src/nvidia/isel.c b/src/nvidia/isel.c index 3c8a8c2..14cc8ea 100644 --- a/src/nvidia/isel.c +++ b/src/nvidia/isel.c @@ -1593,6 +1593,35 @@ static void is_brcond(const bir_inst_t *I) /* ---- PHI Nodes ---- */ +static int aphsrc(uint32_t val, uint32_t idx, uint32_t bir_bi, + nv_opnd_t *src) +{ + const bir_block_t *B = &S.bir->blocks[bir_bi]; + uint32_t vi = BIR_VAL_INDEX(val); + + if (val == BIR_MAKE_VAL(idx)) return 1; + if (BIR_VAL_IS_CONST(val) || vi >= S.bir->num_insts) { + nv_refuse("an aggregate phi fed by a constant"); + return 2; + } + if (S.bir->insts[vi].op == BIR_PHI && vi >= B->first_inst + && vi < B->first_inst + B->num_insts) { + nv_refuse("an aggregate phi fed by another phi of its own block"); + return 2; + } + *src = mapu64(vi); + return 0; +} + +static void aphend(uint32_t idx, uint32_t ty, nv_opnd_t from) +{ + nv_opnd_t h; + uint32_t sz, al; + + if (!aghome(idx, ty, &h, &sz, &al)) return; + agcpy(h, BIR_AS_PRIVATE, from, BIR_AS_PRIVATE, sz, al); +} + static void is_phi(uint32_t idx, const bir_inst_t *I, uint32_t cur_bir_blk) { @@ -1601,8 +1630,10 @@ static void is_phi(uint32_t idx, const bir_inst_t *I, * positions, value at odd. Getting this backwards gives you * undefined predicate registers and a kernel that treats GPU * memory like a pinball machine. We learned this the hard way. */ - uint8_t rf = bir_rfile(I->type); - nv_opnd_t d = map_val(idx, I->type); + int ag = pagg(I->type); + uint8_t rf = ag ? (uint8_t)NV_RF_U64 : bir_rfile(I->type); + nv_opnd_t d = ag ? mop_reg(NV_RF_U64, new_vreg(NV_RF_U64)) + : map_val(idx, I->type); uint32_t nop = n_ops(I); uint16_t mop = movof(rf); @@ -1621,7 +1652,11 @@ static void is_phi(uint32_t idx, const bir_inst_t *I, if (mblkl(pred_bir, &m_pred) != 0) return; if (m_pred >= NV_MAX_MBLK) continue; - nv_opnd_t src = rslv_p(val); + nv_opnd_t src = ag ? mop_imm(0) : rslv_p(val); + int ar = ag ? aphsrc(val, idx, cur_bir_blk, &src) : 0; + + if (ar == 2) return; + if (ar == 1) continue; /* Self-copy: skip */ if (src.kind == NV_MOP_REG && src.rfile == d.rfile && @@ -1640,6 +1675,7 @@ static void is_phi(uint32_t idx, const bir_inst_t *I, S_npc++; } } + if (ag) aphend(idx, I->type, d); } /* ---- Barriers ---- */ diff --git a/tests/trpi.c b/tests/trpi.c index 34bd0de..59b941e 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6332,3 +6332,21 @@ static void rpi316(void) PASS(); } TH_REG("rpi", 316, "a wrapper's local keeps its dependent type", rpi316) + +static void rpi317(void) +{ + const char *p = rpi_ptx( + "struct cf { float re, im; };\n" + "static __device__ float pick(cf v) { return v.re + v.im; }\n" + "__global__ void k(float *o, const float *p, int n, int m) {\n" + " int i = threadIdx.x;\n" + " const cf v = (i < n && i < m) ? *(const cf *)(p + 2 * i)\n" + " : cf{0.0f, 0.0f};\n" + " o[i] = pick(v); }\n", "rpi317"); + + CHNE(p, NULL); + CHEQ(strstr(obuf, "E840"), NULL); + CHNE(strstr(p, "st.global.f32"), NULL); + PASS(); +} +TH_REG("rpi", 317, "either arm of a ternary can yield a struct", rpi317) From 47d7bf02fff89969eae4f92cdd9f710053f52008 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Sat, 19 Sep 2026 22:58:41 +1200 Subject: [PATCH 20/41] hgen: a 64-bit template argument is spelt int64_t, for now A binding holds a BIR type, which has a width and no C identity, so the host registration has to guess a spelling. long long named a second instantiation on Linux, where int64_t is long, and the launch went to a stub nothing had registered: invalid device function from set_rows and cpy. int64_t is what nearly all CUDA source writes and is right on both ABIs when it does. The prologue brings in stdint.h so the name is always there. Interim, the spelling is still a guess until bindings carry C identity or the stubs key on Booth's own type. --- src/host/hgen.c | 1 + src/ir/bir_lower.c | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/host/hgen.c b/src/host/hgen.c index 74c8888..fce5a25 100644 --- a/src/host/hgen.c +++ b/src/host/hgen.c @@ -1006,6 +1006,7 @@ static void opro(const hg_in_t *in) if (c == 1u) fprintf(stderr, "kath: %s: the fatbin carries PTX only, no cubin\n", in->file != NULL ? in->file : "?"); + os_("#include \n"); os_("#include \n"); os_("static void __bl(const void *f, void **a)\n{\n"); os_(" dim3 g, b;\n size_t s;\n void *t;\n\n"); diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index a2dcd3f..4b7e971 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -528,7 +528,7 @@ static void lnsc(const lower_t *L, uint32_t t, char *out, size_t oz) else if (y->width == 8u) ncpy(out, oz, "signed char"); else if (y->width == 16u) ncpy(out, oz, "short"); else if (y->width == 32u) ncpy(out, oz, "int"); - else if (y->width == 64u) ncpy(out, oz, "long long"); + else if (y->width == 64u) ncpy(out, oz, "int64_t"); } else if (y->kind == BIR_TYPE_FLOAT) { if (y->width == 16u) ncpy(out, oz, "__half"); else if (y->width == 32u) ncpy(out, oz, "float"); From a4a9f7516479ac3f0d7cea1a94c0d2e20c2b734d Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Sat, 19 Sep 2026 23:20:23 +1200 Subject: [PATCH 21/41] bir: an address space follows a pointer through select and phi asfix walked gep and bitcast only. A ternary over two pointers is a select typed from the declared char *, so it read as global, the pass stopped there, and cfold then folded the constant condition away and left a global cast of a shared pointer. mmf's tile is exactly that, compute_base = has_ids ? shmem_base + n : shmem_base, and every store into it came out st.global through a shared offset, which on Latimer is a store to nought. The pass is a meet now. Roots keep the space they were made with, a derived pointer takes the one its operands agree on, an operand not yet known is passed over so a pointer stepped round a loop settles, and a real disagreement stays as declared. --- src/ir/bir_inline.c | 104 +++++++++++++++++++++++++++++++------------- tests/trpi.c | 22 ++++++++++ 2 files changed, 95 insertions(+), 31 deletions(-) diff --git a/src/ir/bir_inline.c b/src/ir/bir_inline.c index bdfdda7..0b74f44 100644 --- a/src/ir/bir_inline.c +++ b/src/ir/bir_inline.c @@ -371,39 +371,74 @@ static uint32_t emit_phi(inl_t *X, uint32_t type, const uint32_t *preds, return ni; } -static uint32_t vasof(const bir_module_t *M, uint32_t v, int *ok) +#define AS_UNK 0xFFu +#define AS_MIX 0xFEu + +static uint8_t ASST[BIR_MAX_INSTS]; + +static int asder(uint16_t op) { - uint32_t i = BIR_VAL_INDEX(v), t; - - *ok = 0; - if (v == BIR_VAL_NONE || BIR_VAL_IS_CONST(v)) return 0; - if (i >= M->num_insts) return 0; - t = M->insts[i].type; - if (t >= M->num_types || M->types[t].kind != BIR_TYPE_PTR) return 0; - *ok = 1; - return M->types[t].addrspace; + return op == BIR_GEP || op == BIR_BITCAST || op == BIR_SELECT + || op == BIR_PHI; } -static uint32_t aspass(bir_module_t *M) +static uint32_t asopv(const bir_module_t *M, const bir_inst_t *I, uint32_t k) { - uint32_t ni, hit = 0; + if (I->num_operands != BIR_OPERANDS_OVERFLOW) + return (k < I->num_operands) ? I->operands[k] : BIR_VAL_NONE; + if (k >= I->operands[1] + || I->operands[0] + k >= M->num_extra_ops) return BIR_VAL_NONE; + return M->extra_operands[I->operands[0] + k]; +} - for (ni = 0; ni < M->num_insts; ni++) { - bir_inst_t *I = &M->insts[ni]; - uint32_t t = I->type, base, inner, as; - int ok; +static uint8_t asmeet(const bir_module_t *M, uint32_t ni) +{ + const bir_inst_t *I = &M->insts[ni]; + uint32_t n = (I->num_operands == BIR_OPERANDS_OVERFLOW) + ? I->operands[1] : I->num_operands; + uint32_t lo = (I->op == BIR_SELECT || I->op == BIR_PHI) ? 1u : 0u; + uint32_t st = (I->op == BIR_PHI) ? 2u : 1u; + uint8_t r = AS_UNK; + + if (I->op == BIR_GEP || I->op == BIR_BITCAST) n = (n > 1u) ? 1u : n; + for (uint32_t k = lo; k < n && k < 4096u; k += st) { + uint32_t v = asopv(M, I, k), vi = BIR_VAL_INDEX(v); + uint8_t s; + + if (v == BIR_VAL_NONE || BIR_VAL_IS_CONST(v)) continue; + if (vi >= M->num_insts || vi == ni) continue; + s = ASST[vi]; + if (s == AS_UNK) continue; + if (s == AS_MIX || (r != AS_UNK && r != s)) return AS_MIX; + r = s; + } + return r; +} + +static void asinit(const bir_module_t *M) +{ + for (uint32_t ni = 0; ni < M->num_insts; ni++) { + uint32_t t = M->insts[ni].type; - if (I->op != BIR_GEP && I->op != BIR_BITCAST) continue; + ASST[ni] = AS_UNK; if (t >= M->num_types || M->types[t].kind != BIR_TYPE_PTR) continue; - if (I->num_operands == BIR_OPERANDS_OVERFLOW) - base = (I->operands[1] >= 1u) - ? M->extra_operands[I->operands[0]] : BIR_VAL_NONE; - else - base = (I->num_operands >= 1u) ? I->operands[0] : BIR_VAL_NONE; - as = vasof(M, base, &ok); - if (!ok || as == M->types[t].addrspace) continue; - inner = M->types[t].inner; - I->type = bir_type_ptr(M, inner, (int)as); + if (!asder(M->insts[ni].op)) ASST[ni] = M->types[t].addrspace; + } +} + +static uint32_t aspass(const bir_module_t *M) +{ + uint32_t hit = 0; + + for (uint32_t ni = 0; ni < M->num_insts; ni++) { + uint32_t t = M->insts[ni].type; + uint8_t s; + + if (!asder(M->insts[ni].op) || ASST[ni] == AS_MIX) continue; + if (t >= M->num_types || M->types[t].kind != BIR_TYPE_PTR) continue; + s = asmeet(M, ni); + if (s == ASST[ni] || s == AS_UNK) continue; + ASST[ni] = s; hit++; } return hit; @@ -411,14 +446,21 @@ static uint32_t aspass(bir_module_t *M) int bir_asfix(bir_module_t *M) { - uint32_t round, n = 0; + uint32_t n = 0; if (M == NULL) return 0; - for (round = 0; round < 16u; round++) { - uint32_t hit = aspass(M); + asinit(M); + for (uint32_t round = 0; round < 64u; round++) + if (aspass(M) == 0u) break; + for (uint32_t ni = 0; ni < M->num_insts; ni++) { + bir_inst_t *I = &M->insts[ni]; + uint32_t t = I->type; - n += hit; - if (hit == 0u) break; + if (!asder(I->op) || ASST[ni] >= AS_MIX) continue; + if (t >= M->num_types || M->types[t].kind != BIR_TYPE_PTR) continue; + if (M->types[t].addrspace == ASST[ni]) continue; + I->type = bir_type_ptr(M, M->types[t].inner, (int)ASST[ni]); + n++; } return (int)n; } diff --git a/tests/trpi.c b/tests/trpi.c index 59b941e..0dcfed7 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6350,3 +6350,25 @@ static void rpi317(void) PASS(); } TH_REG("rpi", 317, "either arm of a ternary can yield a struct", rpi317) + +static void rpi318(void) +{ + const char *p = rpi_ptx( + "template \n" + "__global__ void k(const T *x, int n) {\n" + " extern __shared__ char data[];\n" + " char *shb = data;\n" + " char *cb = ids ? (shb + 64) : shb;\n" + " T *t = (T *) cb + threadIdx.y * 4;\n" + " int i = threadIdx.x;\n" + " if (i < n) t[i] = x[i]; }\n" + "template __global__ void k(const float *, int);\n" + "template __global__ void k(const float *, int);\n", + "rpi318"); + + CHNE(p, NULL); + CHNE(strstr(p, "st.shared.f32"), NULL); + CHEQ(strstr(p, "st.global.f32"), NULL); + PASS(); +} +TH_REG("rpi", 318, "a shared pointer stays shared past a ternary", rpi318) From f3b01141eb81a77026df55b4f2d1bca173862918 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Mon, 21 Sep 2026 17:52:47 +1200 Subject: [PATCH 22/41] tdf: fission follows a param through its spill slot trace_to_param said it walked alloca-load chains and stopped dead at the alloca, so a pointer param mem2reg had left in its entry slot was never seen as read and its channel went missing. It follows the one store that fills the slot now. A load or store whose own address is a local is not an access through a param either, so those are passed over, or a scalar read back out of its slot counted as a channel. --- src/tdf/tdf_fission.c | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/src/tdf/tdf_fission.c b/src/tdf/tdf_fission.c index 275524f..bcb91ed 100644 --- a/src/tdf/tdf_fission.c +++ b/src/tdf/tdf_fission.c @@ -29,6 +29,37 @@ * originally produced the address. Returns the parameter index or * -1 if the trail goes cold. */ +static uint32_t alsrc(const bir_module_t *bir, uint32_t slot) +{ + uint32_t hit = BIR_VAL_NONE; + + for (uint32_t i = 0; i < bir->num_insts; i++) { + const bir_inst_t *I = &bir->insts[i]; + + if (I->op != BIR_STORE || I->operands[1] != slot) continue; + if (hit != BIR_VAL_NONE) return BIR_VAL_NONE; + hit = I->operands[0]; + } + return hit; +} + +static int isloc(const bir_module_t *bir, uint32_t val) +{ + int guard = FS_TRACE_GUARD; + + while (guard-- > 0) { + const bir_inst_t *I; + + if (val == BIR_VAL_NONE || BIR_VAL_IS_CONST(val)) return 0; + if (BIR_VAL_INDEX(val) >= bir->num_insts) return 0; + I = &bir->insts[BIR_VAL_INDEX(val)]; + if (I->op == BIR_ALLOCA) return 1; + if (I->op != BIR_GEP && I->op != BIR_BITCAST) return 0; + val = I->operands[0]; + } + return 0; +} + static int trace_to_param(const bir_module_t *bir, uint32_t val) { int guard = FS_TRACE_GUARD; @@ -50,6 +81,10 @@ static int trace_to_param(const bir_module_t *bir, uint32_t val) val = I->operands[0]; continue; } + if (I->op == BIR_ALLOCA) { + val = alsrc(bir, val); + continue; + } return -1; } return -1; @@ -142,11 +177,11 @@ static int classify_params(const bir_module_t *bir, uint32_t func_idx, return BC_ERR_TDF; } - if (I->op == BIR_LOAD) { + if (I->op == BIR_LOAD && !isloc(bir, I->operands[0])) { int pi = trace_to_param(bir, I->operands[0]); if (pi >= 0 && (uint32_t)pi < nparams) params[(uint32_t)pi].loaded = 1; - } else if (I->op == BIR_STORE) { + } else if (I->op == BIR_STORE && !isloc(bir, I->operands[1])) { int pi = trace_to_param(bir, I->operands[1]); if (pi >= 0 && (uint32_t)pi < nparams) params[(uint32_t)pi].stored = 1; From eb07af13d02865a2875c9e145a7be3bdcb06e16a Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Mon, 21 Sep 2026 17:52:47 +1200 Subject: [PATCH 23/41] bir: a ternary does not run the arm it did not take, if the arm reads memory tpure let a subscript, a deref and an arrow through as safe to evaluate on both sides, so p ? p[i] : x loaded through p before asking whether p was there. soft_max does exactly that with sinks, which Qwen2 does not have, and the load went to nought. canonical.cu has said as much in a comment all along. Arms made of values still fold to a select, and rpi315 pins both halves now. --- src/ir/bir_lower.c | 10 +++++++--- tests/trpi.c | 14 ++++++++++---- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index 4b7e971..3040e83 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -6922,11 +6922,15 @@ static int tpure(const lower_t *L, uint32_t node) case AST_UNARY_PREFIX: case AST_UNARY_POSTFIX: - if (p->d.oper.op == TOK_INC || p->d.oper.op == TOK_DEC) return 0; + if (p->d.oper.op == TOK_INC || p->d.oper.op == TOK_DEC + || p->d.oper.op == TOK_STAR) return 0; break; - case AST_PAREN: case AST_MEMBER: - case AST_SUBSCRIPT: case AST_TERNARY: + case AST_MEMBER: + if (p->d.member.is_arrow) return 0; + break; + + case AST_PAREN: case AST_TERNARY: break; default: diff --git a/tests/trpi.c b/tests/trpi.c index 0dcfed7..bfadefa 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6300,15 +6300,21 @@ TH_REG("rpi", 314, "a storing ternary stores once", rpi314) static void rpi315(void) { CHNE(scratch("rpi315.cu", - "__global__ void k(int *o, const int *a, int n) {\n" - " int i = threadIdx.x; o[i] = (i < n) ? a[i] : 0; }\n"), NULL); + "__global__ void k(int *o, int m, int n) {\n" + " int i = threadIdx.x; o[i] = (i < n) ? m + i : 0; }\n"), NULL); CHEQ(th_run(BC_BIN " --ir build/rpi315.cu", obuf, (int)sizeof obuf), 0); - CHNE(strstr(obuf, "select i32"), NULL); CHEQ(strstr(obuf, "tern.then"), NULL); + + CHNE(scratch("rpi315b.cu", + "__global__ void k(float *o, const float *p) {\n" + " int i = threadIdx.x; o[i] = p ? p[i] : 2.0f; }\n"), NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi315b.cu", obuf, (int)sizeof obuf), 0); + CHEQ(strstr(obuf, "select f32"), NULL); + CHNE(strstr(obuf, "tern.then"), NULL); PASS(); } -TH_REG("rpi", 315, "a ternary that only reads stays a select", rpi315) +TH_REG("rpi", 315, "a ternary selects values and branches on reads", rpi315) static void rpi316(void) { From 05274ff658e7e297a4ef45e35b4644b5ee6b3e3b Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Mon, 21 Sep 2026 18:25:37 +1200 Subject: [PATCH 24/41] nvptx: a 64-bit integer constant is built from its halves rslv_p cast every integer constant to a 32-bit immediate, so i * 3000000007LL multiplied by -1294967289. One that does not survive the cast is put together in a register now, low half zero-extended, high half shifted up, the two ored. A phi cannot take one, its copy runs in the predecessor and the register would be made in the merge, so that refuses by name. --- src/nvidia/isel.c | 46 +++++++++++++++++++++++++++++++++++++++++++--- tests/trpi.c | 16 ++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/src/nvidia/isel.c b/src/nvidia/isel.c index 14cc8ea..5e9a440 100644 --- a/src/nvidia/isel.c +++ b/src/nvidia/isel.c @@ -35,6 +35,7 @@ static void nv_refuse(const char *what) /* Forward declaration — rslv needs em1 for f64 constant materialisation */ static void em1(uint16_t op, nv_opnd_t d, nv_opnd_t a, nv_opnd_t b); +static void em1u(uint16_t op, nv_opnd_t d, nv_opnd_t a); static nv_opnd_t mat_pred(nv_opnd_t op); static uint16_t movof(uint8_t rf); @@ -188,6 +189,33 @@ static nv_opnd_t map_val(uint32_t idx, uint32_t type_idx) return mop_reg(rf, rn); } +static int kwide(uint32_t val) +{ + const bir_const_t *C; + + if (val == BIR_VAL_NONE || !BIR_VAL_IS_CONST(val)) return 0; + if (BIR_VAL_INDEX(val) >= S.bir->num_consts) return 0; + C = &S.bir->consts[BIR_VAL_INDEX(val)]; + return C->kind == BIR_CONST_INT && bir_rfile(C->type) == NV_RF_U64 + && C->d.ival != (int64_t)(int32_t)C->d.ival; +} + +static nv_opnd_t k64(int64_t v) +{ + nv_opnd_t lo = mop_reg(NV_RF_U32, new_vreg(NV_RF_U32)); + nv_opnd_t zl = mop_reg(NV_RF_U64, new_vreg(NV_RF_U64)); + nv_opnd_t hi = mop_reg(NV_RF_U64, new_vreg(NV_RF_U64)); + nv_opnd_t sh = mop_reg(NV_RF_U64, new_vreg(NV_RF_U64)); + nv_opnd_t d = mop_reg(NV_RF_U64, new_vreg(NV_RF_U64)); + + em1u(NV_MOV_U32, lo, mop_imm((int32_t)(uint32_t)v)); + em1u(NV_CVT_U64_U32, zl, lo); + em1u(NV_MOV_U64, hi, mop_imm((int32_t)(v >> 32))); + em1(NV_SHL_B64, sh, hi, mop_imm(32)); + em1(NV_OR_B64, d, sh, zl); + return d; +} + static nv_opnd_t rslv_p(uint32_t val) { if (val == BIR_VAL_NONE) return mop_imm(0); @@ -200,7 +228,7 @@ static nv_opnd_t rslv_p(uint32_t val) if (C->kind == BIR_CONST_ZERO || C->kind == BIR_CONST_NULL) return mop_imm(0); if (C->kind == BIR_CONST_INT) - return mop_imm((int32_t)C->d.ival); + return kwide(val) ? k64(C->d.ival) : mop_imm((int32_t)C->d.ival); if (C->kind == BIR_CONST_FLOAT) { uint8_t rf = bir_rfile(C->type); if (rf == NV_RF_F64) { @@ -1613,6 +1641,18 @@ static int aphsrc(uint32_t val, uint32_t idx, uint32_t bir_bi, return 0; } +static int phsrc(uint32_t val, uint32_t idx, uint32_t bir_bi, int ag, + nv_opnd_t *src) +{ + if (kwide(val)) { + nv_refuse("a phi fed by a 64-bit constant wider than an immediate"); + return 2; + } + if (ag) return aphsrc(val, idx, bir_bi, src); + *src = rslv_p(val); + return 0; +} + static void aphend(uint32_t idx, uint32_t ty, nv_opnd_t from) { nv_opnd_t h; @@ -1652,8 +1692,8 @@ static void is_phi(uint32_t idx, const bir_inst_t *I, if (mblkl(pred_bir, &m_pred) != 0) return; if (m_pred >= NV_MAX_MBLK) continue; - nv_opnd_t src = ag ? mop_imm(0) : rslv_p(val); - int ar = ag ? aphsrc(val, idx, cur_bir_blk, &src) : 0; + nv_opnd_t src = mop_imm(0); + int ar = phsrc(val, idx, cur_bir_blk, ag, &src); if (ar == 2) return; if (ar == 1) continue; diff --git a/tests/trpi.c b/tests/trpi.c index bfadefa..e3ad47f 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6378,3 +6378,19 @@ static void rpi318(void) PASS(); } TH_REG("rpi", 318, "a shared pointer stays shared past a ternary", rpi318) + +static void rpi319(void) +{ + const char *p = rpi_ptx( + "__global__ void k(float *o, int n) {\n" + " int t = threadIdx.x; long long i = t;\n" + " if (t < n) o[t] = (float)(int)((i * 3000000007LL + 5) >> 20); }\n", + "rpi319"); + + CHNE(p, NULL); + CHNE(strstr(p, "mul.lo.u64"), NULL); + CHEQ(strstr(strstr(p, "mul.lo.u64"), "-1294967289"), NULL); + CHNE(strstr(p, "shl.b64"), NULL); + PASS(); +} +TH_REG("rpi", 319, "a 64-bit constant is built, not cut to 32 bits", rpi319) From f374594d63a0415952c4549480cfbaed7f303370 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Tue, 22 Sep 2026 00:59:03 +1200 Subject: [PATCH 25/41] bir: p += n, p -= n, p++ and p-- step a pointer by elements p + n was a gep and the other four spellings were an add or a sub on the pointer, which every back end read as bytes. x += row * stride moved a float pointer a quarter of the way, so any kernel that steps its arguments per block wrote over its neighbours: rms_norm, get_rows, set_rows, cpy, soft_max and mul_mat, which is most of ggml. One block hides it because row is nought. They are all a gep now, and anything else done to a pointer in place refuses with E102. --- src/ir/bir_lower.c | 35 +++++++++++++++++++++++++++++++++++ tests/trpi.c | 16 ++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index 3040e83..e791435 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -4377,6 +4377,32 @@ static int ptr_t(const lower_t *L, uint32_t t) return t < L->M->num_types && L->M->types[t].kind == BIR_TYPE_PTR; } +static uint32_t pstep(lower_t *L, uint32_t node, int base, uint32_t slot, + uint32_t pt, uint32_t old, uint32_t n) +{ + uint32_t it = ref_type(L, n), g, st; + + if ((base != TOK_PLUS && base != TOK_MINUS) || it >= L->M->num_types + || L->M->types[it].kind != BIR_TYPE_INT) { + lower_error(L, node, BC_E102); + return BIR_VAL_NONE; + } + if (base == TOK_MINUS) { + uint32_t ng = emit(L, BIR_SUB, it, 2, 0); + + set_op(L, ng, 0, BIR_MAKE_CONST(bir_const_int(L->M, it, 0))); + set_op(L, ng, 1, n); + n = BIR_MAKE_VAL(ng); + } + g = emit(L, BIR_GEP, pt, 2, 0); + set_op(L, g, 0, BIR_MAKE_VAL(old)); + set_op(L, g, 1, n); + st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, st, 0, BIR_MAKE_VAL(g)); + set_op(L, st, 1, slot); + return BIR_MAKE_VAL(g); +} + static uint32_t bin_val(lower_t *L, uint32_t node, int op, uint32_t lhs, uint32_t lhs_n, uint32_t rhs, uint32_t rhs_n) @@ -7349,6 +7375,7 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) set_op(L, old, 0, ptr); uint32_t rhs = lower_expr(L, rhs_n); + if (ptr_t(L, et)) return pstep(L, node, base, ptr, et, old, rhs); if (base != TOK_SHL && base != TOK_SHR) rhs = stfit(L, rhs, et, rhs_n); int fp = is_float_type(L, et); @@ -7573,6 +7600,10 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) if (is_float_type(L, et)) { one = BIR_MAKE_CONST(bir_const_float(L->M, et, 1.0)); res = emit(L, op==TOK_INC ? BIR_FADD : BIR_FSUB, et, 2, 0); + } else if (ptr_t(L, et)) { + one = BIR_MAKE_CONST(bir_const_int(L->M, bir_type_int(L->M, 32), + op == TOK_INC ? 1 : -1)); + res = emit(L, BIR_GEP, et, 2, 0); } else { one = BIR_MAKE_CONST(bir_const_int(L->M, et, 1)); res = emit(L, op==TOK_INC ? BIR_ADD : BIR_SUB, et, 2, 0); @@ -7613,6 +7644,10 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) if (is_float_type(L, et)) { one = BIR_MAKE_CONST(bir_const_float(L->M, et, 1.0)); res = emit(L, op==TOK_INC ? BIR_FADD : BIR_FSUB, et, 2, 0); + } else if (ptr_t(L, et)) { + one = BIR_MAKE_CONST(bir_const_int(L->M, bir_type_int(L->M, 32), + op == TOK_INC ? 1 : -1)); + res = emit(L, BIR_GEP, et, 2, 0); } else { one = BIR_MAKE_CONST(bir_const_int(L->M, et, 1)); res = emit(L, op==TOK_INC ? BIR_ADD : BIR_SUB, et, 2, 0); diff --git a/tests/trpi.c b/tests/trpi.c index e3ad47f..300dedd 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6394,3 +6394,19 @@ static void rpi319(void) PASS(); } TH_REG("rpi", 319, "a 64-bit constant is built, not cut to 32 bits", rpi319) + +static void rpi320(void) +{ + CHNE(scratch("rpi320.cu", + "__global__ void k(float *o, const float *x, int bs) {\n" + " int t = threadIdx.x, row = blockIdx.x;\n" + " o += row * bs; x -= t; x++; ++x; x--;\n" + " o[t] = *x; }\n"), NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi320.cu", obuf, (int)sizeof obuf), 0); + + CHEQ(strstr(obuf, "add ptr<"), NULL); + CHEQ(strstr(obuf, "sub ptr<"), NULL); + CHNE(strstr(obuf, "gep ptr, %0"), NULL); + PASS(); +} +TH_REG("rpi", 320, "a pointer steps by elements, however written", rpi320) From 0bb375e96a9995db87c21534df3877d91beaa4bf Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Tue, 22 Sep 2026 01:23:25 +1200 Subject: [PATCH 26/41] bir: say why pstep is there, where the next person will look One comment line, asked for, so the comment row of the ratchet goes to 6510 with it. --- src/ir/bir_lower.c | 1 + tests/rules.tbl | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index e791435..d226650 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -4377,6 +4377,7 @@ static int ptr_t(const lower_t *L, uint32_t t) return t < L->M->num_types && L->M->types[t].kind == BIR_TYPE_PTR; } +/* Ollama was producing garbage tokens cuz p += n stepped a pointer by bytes, not elements. */ static uint32_t pstep(lower_t *L, uint32_t node, int base, uint32_t slot, uint32_t pt, uint32_t old, uint32_t n) { diff --git a/tests/rules.tbl b/tests/rules.tbl index 9191f71..624269f 100644 --- a/tests/rules.tbl +++ b/tests/rules.tbl @@ -5,5 +5,5 @@ goto 63 goto, setjmp or longjmp alloc 99 allocation calls fnptr 25 function pointers long 148 functions over 60 lines -comment 6509 comment lines +comment 6510 comment lines snprintf 83 snprintf calls whose return is discarded From 33bd8741dcbde301c2ead679b7ac9260ea87bd2f Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Tue, 22 Sep 2026 12:57:33 +1200 Subject: [PATCH 27/41] nvptx: a signed byte is extended from bit 7, not bit 15 There is no 8-bit register file, so an i8 load is a u8 into a 16-bit register, and sext and sitofp then extended from 16. -120 came back as 136. Every q8_0 quant is an int8, so get_rows on a Q8_0 embedding table handed the model the wrong vector for every token, and the K-quants went with it. A signed widen of an 8-bit value goes through shl 24 and an arithmetic shr 24 first now. Unsigned bytes were right already. --- src/nvidia/isel.c | 21 ++++++++++++++++++++- tests/trpi.c | 16 ++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/nvidia/isel.c b/src/nvidia/isel.c index 5e9a440..ad592ef 100644 --- a/src/nvidia/isel.c +++ b/src/nvidia/isel.c @@ -894,10 +894,27 @@ static void is_f2i(nv_opnd_t d, nv_opnd_t s, uint32_t v0, int sgn) cocpy(d, t, sgn); } +static nv_opnd_t sx8(uint32_t v0, nv_opnd_t s) +{ + uint32_t ty = vtyof(v0); + nv_opnd_t w, l, r; + + if (s.kind != NV_MOP_REG || ty >= S.bir->num_types + || S.bir->types[ty].kind != BIR_TYPE_INT + || S.bir->types[ty].width != 8u) return s; + w = cofit(s, NV_RF_U32, 0); + l = mop_reg(NV_RF_U32, new_vreg(NV_RF_U32)); + r = mop_reg(NV_RF_U32, new_vreg(NV_RF_U32)); + em1(NV_SHL_B32, l, w, mop_imm(24)); + em1(NV_SHR_S32, r, l, mop_imm(24)); + return r; +} + static void is_i2f(nv_opnd_t d, nv_opnd_t s, uint32_t v0, int sgn) { uint8_t drf = d.rfile; - uint8_t srf = rslv_rf(v0); + uint8_t srf = (s.kind == NV_MOP_REG && s.rfile == NV_RF_U32) + ? (uint8_t)NV_RF_U32 : rslv_rf(v0); uint16_t op; nv_opnd_t t; @@ -961,12 +978,14 @@ static void is_cvt(uint32_t idx, const bir_inst_t *I) is_f2i(d, s, v0, I->op == BIR_FPTOSI); return; case BIR_SITOFP: case BIR_UITOFP: + if (I->op == BIR_SITOFP) s = sx8(v0, s); is_i2f(d, s, v0, I->op == BIR_SITOFP); return; case BIR_FPTRUNC: case BIR_FPEXT: is_fext(d, s, v0, I->type); return; case BIR_ZEXT: case BIR_SEXT: case BIR_TRUNC: + if (I->op == BIR_SEXT) s = sx8(v0, s); cocpy(d, s, I->op == BIR_SEXT); return; default: diff --git a/tests/trpi.c b/tests/trpi.c index 300dedd..63c5199 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6410,3 +6410,19 @@ static void rpi320(void) PASS(); } TH_REG("rpi", 320, "a pointer steps by elements, however written", rpi320) + +static void rpi321(void) +{ + const char *p = rpi_ptx( + "__global__ void k(float *o, const signed char *q,\n" + " const unsigned char *u, int n) {\n" + " int i = threadIdx.x;\n" + " if (i < n) o[i] = (float)q[i] * 0.5f + (float)u[i]; }\n", "rpi321"); + + CHNE(p, NULL); + CHNE(strstr(p, "shr.s32"), NULL); + CHEQ(strstr(p, "cvt.s32.s16"), NULL); + CHNE(strstr(p, "cvt.rn.f32.u32"), NULL); + PASS(); +} +TH_REG("rpi", 321, "a signed byte keeps its sign when it widens", rpi321) From 0b2129f8052c3dd5c01d031a50bf9d0a83566a18 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Tue, 22 Sep 2026 13:47:13 +1200 Subject: [PATCH 28/41] bir: a vector constructor converts each argument to its field make_half2(float, float) stored two floats into two halves as they came, four bytes into a two byte slot each, so the pair read back as whatever the second write left and every product in the half2 branch of mul_mat_vec_f was nought. Both constructor sites go through stfit now, the same coercion an assignment gets. Found by a probe that printed the products, after the PTX and SASS images were both wrong the same way, which put it in the front end. --- src/ir/bir_lower.c | 6 ++++-- tests/trpi.c | 26 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index d226650..132e630 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -1836,6 +1836,8 @@ static uint32_t vlane(lower_t *L, uint32_t val, int lane) return BIR_MAKE_VAL(ld); } +static uint32_t stfit(lower_t *L, uint32_t val, uint32_t dt, uint32_t src_n); + static uint32_t vmake(lower_t *L, const struct_def_t *sd, const uint32_t *vals, int n) { @@ -1853,7 +1855,7 @@ static uint32_t vmake(lower_t *L, const struct_def_t *sd, set_op(L, gep, 0, BIR_MAKE_VAL(al)); set_op(L, gep, 1, ci); sv = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, sv, 0, vals[i]); + set_op(L, sv, 0, stfit(L, vals[i], sd->field_types[i], 0)); set_op(L, sv, 1, BIR_MAKE_VAL(gep)); } ld = emit(L, BIR_LOAD, st, 1, 0); @@ -8176,7 +8178,7 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) set_op(L, gep, 0, BIR_MAKE_VAL(al)); set_op(L, gep, 1, ci); uint32_t sv = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, sv, 0, val); + set_op(L, sv, 0, stfit(L, val, vsd->field_types[fi], an)); set_op(L, sv, 1, BIR_MAKE_VAL(gep)); an = ND(L, an)->next_sibling; } diff --git a/tests/trpi.c b/tests/trpi.c index 63c5199..95628a1 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6426,3 +6426,29 @@ static void rpi321(void) PASS(); } TH_REG("rpi", 321, "a signed byte keeps its sign when it widens", rpi321) + +static void rpi322(void) +{ + CHNE(scratch("rpi322.cu", + "__global__ void k(float *o, const half2 *x, const float2 *y) {\n" + " int i = threadIdx.x;\n" + " const float2 t = y[i];\n" + " const half2 p = x[i] * make_half2(t.x, t.y);\n" + " o[i] = __low2float(p) + __high2float(p); }\n"), NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi322.cu", obuf, (int)sizeof obuf), 0); + + CHNE(strstr(obuf, "fptrunc f32"), NULL); + CHEQ(strstr(obuf, "store f32 %"), strstr(obuf, "store f32 %")); + { + const char *p = obuf; + int bad = 0; + while ((p = strstr(p, "store f32 ")) != NULL) { + const char *q = strchr(p, ','); + if (q && strstr(q, "ptr") == q + 2) bad++; + p += 10; + } + CHEQ(bad, 0); + } + PASS(); +} +TH_REG("rpi", 322, "make_half2 narrows its floats before it stores", rpi322) From 71630ea4229c429842ea4329e9538f93513cfa5f Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Tue, 22 Sep 2026 14:59:23 +1200 Subject: [PATCH 29/41] bir: the constructor's conversion goes in before the store that reads it 0b2129f called stfit inside set_op, after the store was already emitted, so the fptrunc came out one instruction too late and the store read a value nothing had written yet. Every make_half2 was a pair of noughts, which is the same symptom as before with a different cause. rpi322 now checks the order as well as the presence. --- src/ir/bir_lower.c | 8 +++++--- tests/trpi.c | 7 ++++++- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index 132e630..ba68dc9 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -1851,11 +1851,12 @@ static uint32_t vmake(lower_t *L, const struct_def_t *sd, uint32_t ci = BIR_MAKE_CONST(bir_const_int(L->M, bir_type_int(L->M, 32), i)); uint32_t gep = emit(L, BIR_GEP, fpt, 2, 0); - uint32_t sv; + uint32_t sv, fv; set_op(L, gep, 0, BIR_MAKE_VAL(al)); set_op(L, gep, 1, ci); + fv = stfit(L, vals[i], sd->field_types[i], 0); sv = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, sv, 0, stfit(L, vals[i], sd->field_types[i], 0)); + set_op(L, sv, 0, fv); set_op(L, sv, 1, BIR_MAKE_VAL(gep)); } ld = emit(L, BIR_LOAD, st, 1, 0); @@ -8177,8 +8178,9 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) uint32_t gep = emit(L, BIR_GEP, fpt, 2, 0); set_op(L, gep, 0, BIR_MAKE_VAL(al)); set_op(L, gep, 1, ci); + uint32_t fv = stfit(L, val, vsd->field_types[fi], an); uint32_t sv = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, sv, 0, stfit(L, val, vsd->field_types[fi], an)); + set_op(L, sv, 0, fv); set_op(L, sv, 1, BIR_MAKE_VAL(gep)); an = ND(L, an)->next_sibling; } diff --git a/tests/trpi.c b/tests/trpi.c index 95628a1..7872cbc 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6438,7 +6438,12 @@ static void rpi322(void) CHEQ(th_run(BC_BIN " --ir build/rpi322.cu", obuf, (int)sizeof obuf), 0); CHNE(strstr(obuf, "fptrunc f32"), NULL); - CHEQ(strstr(obuf, "store f32 %"), strstr(obuf, "store f32 %")); + { + const char *t = strstr(obuf, "fptrunc f32"); + const char *st = strstr(obuf, "store f16 %"); + CHNE(st, NULL); + CHECK(t < st); + } { const char *p = obuf; int bad = 0; From 17145075aa1474430a73e55f0c68be694c8c9dc2 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Tue, 22 Sep 2026 17:14:46 +1200 Subject: [PATCH 30/41] bir: a deduced argument may be *(T *)p as well as p[i] arg_type saw through a subscript to its element but not through a dereference, so conv(*(const S *) ci) deduced S as int and ggml_cuda_cast(float) went through fptosi. Every scalar copy in ggml, cpy_1_scalar, did that, so the KV cache held floats rounded to whole numbers. The pointee lookup is shared between the two shapes now. --- src/ir/bir_lower.c | 30 ++++++++++++++++++++---------- tests/trpi.c | 19 +++++++++++++++++++ 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index ba68dc9..5e156a7 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -12157,6 +12157,21 @@ static void collect_template(lower_t *L, uint32_t node) * - callee = "scale" * - Deduce T from literal arguments */ +static uint32_t apointee(lower_t *L, uint32_t base) +{ + uint32_t bt; + + L->atdp++; + bt = arg_type(L, base); + L->atdp--; + if (bt < L->M->num_types + && (L->M->types[bt].kind == BIR_TYPE_ARRAY + || L->M->types[bt].kind == BIR_TYPE_PTR) + && L->M->types[bt].inner) + return bir_tunq(L->M, L->M->types[bt].inner); + return 0; +} + static uint32_t arg_type(lower_t *L, uint32_t arg) { const ast_node_t *a; @@ -12183,17 +12198,12 @@ static uint32_t arg_type(lower_t *L, uint32_t arg) sy = find_sym(L, nm); if (sy && sy->type) return sy->type; } - if (a->type == AST_SUBSCRIPT && a->first_child && L->atdp < MAX_CDEP) { - uint32_t bt; + if ((a->type == AST_SUBSCRIPT + || (a->type == AST_UNARY_PREFIX && a->d.oper.op == TOK_STAR)) + && a->first_child && L->atdp < MAX_CDEP) { + uint32_t et = apointee(L, a->first_child); - L->atdp++; - bt = arg_type(L, a->first_child); - L->atdp--; - if (bt < L->M->num_types - && (L->M->types[bt].kind == BIR_TYPE_ARRAY - || L->M->types[bt].kind == BIR_TYPE_PTR) - && L->M->types[bt].inner) - return bir_tunq(L->M, L->M->types[bt].inner); + if (et) return et; } if (a->type == AST_MEMBER && a->first_child && L->atdp < MAX_CDEP) { uint32_t obj = a->first_child; diff --git a/tests/trpi.c b/tests/trpi.c index 7872cbc..ee18923 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6457,3 +6457,22 @@ static void rpi322(void) PASS(); } TH_REG("rpi", 322, "make_half2 narrows its floats before it stores", rpi322) + +static void rpi323(void) +{ + CHNE(scratch("rpi323.cu", + "template \n" + "static __device__ D conv(S x) { return D(x); }\n" + "template \n" + "static __device__ void one(const char *ci, char *co) {\n" + " *(D *) co = conv(*(const S *) ci); }\n" + "__global__ void k(const char *a, char *b) {\n" + " one(a + 4 * threadIdx.x, b + 4 * threadIdx.x); }\n"), + NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi323.cu", obuf, (int)sizeof obuf), 0); + + CHNE(strstr(obuf, "func @conv(f32"), NULL); + CHEQ(strstr(obuf, "fptosi"), NULL); + PASS(); +} +TH_REG("rpi", 323, "a deduction sees through a dereferenced cast", rpi323) From 0cb9afa1c6bcac9ffce1da9fcd4e888cedf53a3f Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Wed, 23 Sep 2026 00:43:09 +1200 Subject: [PATCH 31/41] bir: a short or a char promotes to int before it meets an operator --- src/ir/bir_lower.c | 14 +++++++++++--- tests/trpi.c | 17 +++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index 5e156a7..bee6d40 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -4407,15 +4407,23 @@ static uint32_t pstep(lower_t *L, uint32_t node, int base, uint32_t slot, return BIR_MAKE_VAL(g); } +static void iprom(lower_t *L, uint32_t *v, uint32_t *t, uint32_t n) +{ + uint32_t t32 = bir_type_int(L->M, 32); + if (*t >= L->M->num_types || L->M->types[*t].kind != BIR_TYPE_INT + || L->M->types[*t].width >= 32) return; + *v = coerce_to(L, *v, t32, is_i1(L, *t) || node_is_unsigned(L, n)); + *t = t32; +} + static uint32_t bin_val(lower_t *L, uint32_t node, int op, uint32_t lhs, uint32_t lhs_n, uint32_t rhs, uint32_t rhs_n) { uint32_t lt = ref_type(L, lhs), rt = ref_type(L, rhs); - uint32_t t32 = bir_type_int(L->M, 32); - if (is_i1(L, lt)) { lhs = coerce_to(L, lhs, t32, 1); lt = t32; } - if (is_i1(L, rt)) { rhs = coerce_to(L, rhs, t32, 1); rt = t32; } + iprom(L, &lhs, <, lhs_n); + iprom(L, &rhs, &rt, rhs_n); uint32_t res_t = lt; int lf = is_float_type(L, lt), rf = is_float_type(L, rt); diff --git a/tests/trpi.c b/tests/trpi.c index ee18923..990b2c0 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6476,3 +6476,20 @@ static void rpi323(void) PASS(); } TH_REG("rpi", 323, "a deduction sees through a dereferenced cast", rpi323) + +static void rpi324(void) +{ + CHNE(scratch("rpi324.cu", + "__global__ void k(const unsigned short *x, int *o) {\n" + " int v = x[2 * threadIdx.x] << 0;\n" + " v |= x[2 * threadIdx.x + 1] << 16;\n" + " o[threadIdx.x] = v; }\n"), + NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi324.cu", obuf, (int)sizeof obuf), 0); + + CHEQ(strstr(obuf, "shl i16"), NULL); + CHEQ(strstr(obuf, "sext"), NULL); + CHNE(strstr(obuf, "shl i32"), NULL); + PASS(); +} +TH_REG("rpi", 324, "a short promotes to int before it shifts", rpi324) From cace29219e183091277f531395523efafe8e81a6 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Wed, 23 Sep 2026 01:44:13 +1200 Subject: [PATCH 32/41] bir: a launch wrapper's local that Booth cannot name is skipped, not refused --- src/ir/bir_lower.c | 3 ++- tests/trpi.c | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index bee6d40..0954866 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -13393,7 +13393,8 @@ static void vscn(lower_t *L, uint32_t vd) if (!nn || ND(L, nn)->type != AST_IDENT) return; get_text(L, nn, vn, (int)sizeof vn); if (!vn[0]) return; - t = rtype(L, n->first_child, n->d.oper.flags, n->cuda_flags); + t = resolve_type(L, n->first_child, n->d.oper.flags, n->cuda_flags); + if (L->rtbad || L->rtunk) { L->rtbad = 0; L->rtunk = 0; return; } if (t) { uint32_t aft = 0; int bad = 0; diff --git a/tests/trpi.c b/tests/trpi.c index 990b2c0..610280f 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6493,3 +6493,20 @@ static void rpi324(void) PASS(); } TH_REG("rpi", 324, "a short promotes to int before it shifts", rpi324) + +static void rpi325(void) +{ + CHNE(scratch("rpi325.cu", + "#include \n" + "__global__ void k(float *o) { o[threadIdx.x] = 1.0f; }\n" + "void go(float *o) {\n" + " constexpr std::array slow = { 1, 2 };\n" + " k<<<1, slow[1]>>>(o); }\n"), + NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi325.cu", obuf, (int)sizeof obuf), 0); + + CHEQ(strstr(obuf, "E134"), NULL); + CHNE(strstr(obuf, "func @k("), NULL); + PASS(); +} +TH_REG("rpi", 325, "a wrapper local Booth cannot name is skipped", rpi325) From 0c2e5bf220865a3bfaca5daa2d884c121a57a64d Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Wed, 23 Sep 2026 12:56:42 +1200 Subject: [PATCH 33/41] bir: a template handed out as a function pointer still gets its kernels instantiated --- src/ir/bir_lower.c | 37 +++++++++++++++++++++++++++++++++++++ tests/trpi.c | 15 +++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index 0954866..d346201 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -14325,6 +14325,42 @@ static uint32_t lbody(const lower_t *L, uint32_t lam) return body; } +static int sfval(lower_t *L, uint32_t node) +{ + uint32_t ta = ND(L, node)->first_child; + char cname[128]; + int hit = 0; + + if (!ta || ND(L, ta)->type != AST_TEMPLATE_ARGS) return 0; + if (L->fdep >= MAX_FWD) return 0; + get_text(L, node, cname, sizeof cname); + if (!find_template(L, cname)) return 0; + for (int i = 0; i < L->ntemplates; i++) { + template_def_t *t = &L->templates[i]; + binding_t *nb = L->tnb; + uint32_t fn, body, dfn = 0; + int ntp = 0, onb = L->nbindings, obs = L->nbbase; + + if (!tmhit(L, t, cname)) continue; + fn = tfunc(L, t); + body = fn ? find_func_body(L, fn) : 0; + if (!body || !hasl(L, body, 0, MAX_FWD)) continue; + if (!tdeduc(L, t->ast, node, NULL, 0, nb, &ntp, &dfn)) continue; + if (ntp > MAX_BIND - onb) continue; + for (int k = 0; k < ntp; k++) L->bindings[L->nbindings++] = nb[k]; + L->fdep++; + push_scope(L); + pscn(L, fn); + scan_launches(L, body); + pop_scope(L); + L->fdep--; + L->nbbase = obs; + L->nbindings = onb; + hit = 1; + } + return hit; +} + static int sglc(lower_t *L, uint32_t node) { uint32_t cn = ND(L, node)->first_child, lam = 0, a, body; @@ -14571,6 +14607,7 @@ static void scan_launches(lower_t *L, uint32_t node) if (n->type == AST_CALL && sglc(L, node)) return; if (n->type == AST_CALL && swrap(L, node)) return; if (n->type == AST_CALL && sfun(L, node)) return; + if (n->type == AST_IDENT && sfval(L, node)) return; if (n->type == AST_BLOCK) { int gsv = L->nglm, fsv = L->nfnal; diff --git a/tests/trpi.c b/tests/trpi.c index 610280f..5ab995b 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6510,3 +6510,18 @@ static void rpi325(void) PASS(); } TH_REG("rpi", 325, "a wrapper local Booth cannot name is skipped", rpi325) + +static void rpi326(void) +{ + CHNE(scratch("rpi326.cu", + "template __global__ void k(T *o) { o[threadIdx.x] = T(1); }\n" + "template static void go(T *o) { k<<<1, 4>>>(o); }\n" + "typedef void (*fn_t)(float *);\n" + "fn_t pick(int i) { return go; }\n"), + NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi326.cu", obuf, (int)sizeof obuf), 0); + + CHNE(strstr(obuf, "func @k(ptr"), NULL); + PASS(); +} +TH_REG("rpi", 326, "a template handed out as a pointer launches", rpi326) From ba02700299e36897f0542ef187857baf3a297eea Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Wed, 23 Sep 2026 16:13:03 +1200 Subject: [PATCH 34/41] a function pointer keeps its parameter list, so a template returned through one deduces against it --- src/fe/parser.c | 13 ++++-- src/ir/bir_lower.c | 98 ++++++++++++++++++++++++++++++++++++++++++---- tests/tphase.c | 2 +- tests/trpi.c | 17 ++++++++ 4 files changed, 119 insertions(+), 11 deletions(-) diff --git a/src/fe/parser.c b/src/fe/parser.c index 47a3fbf..c6d477a 100644 --- a/src/fe/parser.c +++ b/src/fe/parser.c @@ -1743,8 +1743,9 @@ static void skippar(parser_t *P) } } -/* T (*name)(sig) — inner stars add to *depth, and the signature is skipped - because Booth has no indirect calls to lower it to. 0 if abstract. */ +/* T (*name)(sig) — inner stars add to *depth, and the signature hangs off + the name as params, so a template handed out through the pointer can be + deduced against it. 0 if abstract. */ static uint32_t fnptr(parser_t *P, int *depth) { uint32_t name = 0; @@ -1759,7 +1760,13 @@ static uint32_t fnptr(parser_t *P, int *depth) advance(P); } expect(P, TOK_RPAREN); - if (cur_type(P) == TOK_LPAREN) skippar(P); + if (cur_type(P) == TOK_LPAREN) { + if (!name) { skippar(P); return 0; } + advance(P); + uint32_t params = parse_param_list(P); + if (params) add_child(P, name, params); + expect(P, TOK_RPAREN); + } return name; } diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index d346201..8c69b3c 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -425,6 +425,7 @@ typedef struct { int ntags; struct { char name[64]; fnc_t c[MAX_FNC]; int n; } fnal[MAX_FNAL]; int nfnal; + uint32_t scnrt; glent_t glms[MAX_GLAM]; int nglm; @@ -11892,6 +11893,31 @@ static void tdbad(lower_t *L, typedef_def_t *td) ncpy(td->snm, sizeof(td->snm), L->rtsnm); } +static uint32_t fpty(lower_t *L, uint32_t name_n, uint32_t type_n, int depth) +{ + uint32_t pv[MAX_PARM], pt[MAX_PARM], ret, t; + int np = collect_params(L, name_n, pv, MAX_PARM); + + if (np <= 0) return resolve_type(L, type_n, depth, 0); + ret = resolve_type(L, type_n, 0, 0); + if (L->rtbad || L->rtunk) { L->rtbad = 0; L->rtunk = 0; return 0; } + for (int i = 0; i < np; i++) { + const ast_node_t *pn = ND(L, pv[i]); + + if (pn->d.oper.op == PRM_VARG || pn->d.oper.op == PRM_PACK) return 0; + pt[i] = resolve_type(L, pn->first_child, pn->d.oper.flags, + pn->cuda_flags); + if (L->rtbad || L->rtunk || !pt[i]) { + L->rtbad = 0; + L->rtunk = 0; + return 0; + } + } + t = bir_type_func(L->M, ret, pt, np); + for (int i = 0; i < depth; i++) t = bir_type_ptr(L->M, t, BIR_AS_GLOBAL); + return t; +} + static void collect_typedef(lower_t *L, uint32_t node) { /* typedef TYPE NAME; @@ -11948,7 +11974,7 @@ static void collect_typedef(lower_t *L, uint32_t node) typedef_def_t *td = &L->typedefs[L->ntypedefs++]; memset(td, 0, sizeof(*td)); get_text(L, name_n, td->name, sizeof(td->name)); - td->bir_type = resolve_type(L, type_n, ND(L, node)->d.oper.flags, 0); + td->bir_type = fpty(L, name_n, type_n, ND(L, node)->d.oper.flags); tdbad(L, td); } @@ -14325,7 +14351,49 @@ static uint32_t lbody(const lower_t *L, uint32_t lam) return body; } -static int sfval(lower_t *L, uint32_t node) +static void tdtgt(lower_t *L, uint32_t fn, binding_t *nb, int ntp, uint32_t tt) +{ + const bir_type_t *ft; + uint32_t fpn[MAX_PARM]; + int nfp; + + if (tt && tt < L->M->num_types && L->M->types[tt].kind == BIR_TYPE_PTR) + tt = L->M->types[tt].inner; + if (!tt || tt >= L->M->num_types || L->M->types[tt].kind != BIR_TYPE_FUNC) + return; + ft = &L->M->types[tt]; + nfp = collect_params(L, fn, fpn, MAX_PARM); + for (int i = 0; i < nfp && i < (int)ft->num_fields; i++) { + const ast_node_t *pn = ND(L, fpn[i]); + uint32_t ts = pn->first_child, at; + char tname[64]; + + if (!ts || ND(L, ts)->type != AST_TYPE_SPEC + || ND(L, ts)->d.btype.kind != TYPE_NAME + || !ND(L, ts)->first_child) continue; + get_text(L, ND(L, ts)->first_child, tname, sizeof tname); + at = tpeel(L, L->M->type_fields[ft->count + (uint32_t)i], + pn->d.oper.flags); + if (at) tdty(L, nb, ntp, tname, at); + } +} + +static int tdfp(lower_t *L, const template_def_t *t, uint32_t cal, uint32_t tt, + binding_t *nb, int *ntpo, uint32_t *fno) +{ + int ntp = tparm(L, t->ast, nb); + + *ntpo = ntp < 0 ? 0 : ntp; + *fno = tfunc(L, t); + if (ntp < 0 || !*fno || !texpl(L, cal, nb, ntp)) return 0; + tdtgt(L, *fno, nb, ntp, tt); + for (int i = 0; i < ntp; i++) + if (nb[i].is_type && !nb[i].fixed && nb[i].type == 0 && !nb[i].dflt) + return 0; + return tdflt(L, nb, ntp); +} + +static int sfval(lower_t *L, uint32_t node, uint32_t tt) { uint32_t ta = ND(L, node)->first_child; char cname[128]; @@ -14338,14 +14406,13 @@ static int sfval(lower_t *L, uint32_t node) for (int i = 0; i < L->ntemplates; i++) { template_def_t *t = &L->templates[i]; binding_t *nb = L->tnb; - uint32_t fn, body, dfn = 0; + uint32_t fn = 0, body; int ntp = 0, onb = L->nbindings, obs = L->nbbase; if (!tmhit(L, t, cname)) continue; - fn = tfunc(L, t); - body = fn ? find_func_body(L, fn) : 0; + if (!tdfp(L, t, node, tt, nb, &ntp, &fn)) continue; + body = find_func_body(L, fn); if (!body || !hasl(L, body, 0, MAX_FWD)) continue; - if (!tdeduc(L, t->ast, node, NULL, 0, nb, &ntp, &dfn)) continue; if (ntp > MAX_BIND - onb) continue; for (int k = 0; k < ntp; k++) L->bindings[L->nbindings++] = nb[k]; L->fdep++; @@ -14361,6 +14428,18 @@ static int sfval(lower_t *L, uint32_t node) return hit; } +static uint32_t fnret(lower_t *L, uint32_t fd) +{ + uint32_t ts = ND(L, fd)->first_child, t; + + if (!ts || ND(L, ts)->type != AST_TYPE_SPEC) return 0; + t = resolve_type(L, ts, ND(L, fd)->d.oper.flags, ND(L, fd)->cuda_flags); + if (L->rtbad || L->rtunk) t = 0; + L->rtbad = 0; + L->rtunk = 0; + return t; +} + static int sglc(lower_t *L, uint32_t node) { uint32_t cn = ND(L, node)->first_child, lam = 0, a, body; @@ -14607,7 +14686,10 @@ static void scan_launches(lower_t *L, uint32_t node) if (n->type == AST_CALL && sglc(L, node)) return; if (n->type == AST_CALL && swrap(L, node)) return; if (n->type == AST_CALL && sfun(L, node)) return; - if (n->type == AST_IDENT && sfval(L, node)) return; + if (n->type == AST_IDENT && sfval(L, node, 0)) return; + if (n->type == AST_RETURN && n->first_child + && ND(L, n->first_child)->type == AST_IDENT + && sfval(L, n->first_child, L->scnrt)) return; if (n->type == AST_BLOCK) { int gsv = L->nglm, fsv = L->nfnal; @@ -15070,7 +15152,9 @@ int bir_ltu(const parser_t *P, uint32_t ast_root, bir_module_t *M, if (n->type == AST_FUNC_DEF && !(n->cuda_flags & (CUDA_GLOBAL|CUDA_DEVICE))) { /* Host function — scan for launches */ uint32_t body = find_func_body(L, c); + L->scnrt = fnret(L, c); if (body) scan_launches(L, body); + L->scnrt = 0; } if (n->type == AST_TEMPLATE_INST) tixp(L, c); } diff --git a/tests/tphase.c b/tests/tphase.c index 82b05f8..2d680ac 100644 --- a/tests/tphase.c +++ b/tests/tphase.c @@ -101,7 +101,7 @@ static void pha05(void) CHEQ(rc, 0); CHECK(strstr(obuf, "0 parse error(s)") != NULL); CHECK(strstr(obuf, "(ident cb_t)") != NULL); - CHECK(strstr(obuf, "(ident hook)") != NULL); + CHECK(strstr(obuf, "(ident hook") != NULL); CHECK(strstr(obuf, "call") == NULL); PASS(); } diff --git a/tests/trpi.c b/tests/trpi.c index 5ab995b..9b1edb6 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6525,3 +6525,20 @@ static void rpi326(void) PASS(); } TH_REG("rpi", 326, "a template handed out as a pointer launches", rpi326) + +static void rpi327(void) +{ + CHNE(scratch("rpi327.cu", + "template __global__ void k(const S *x, D *y) {\n" + " y[threadIdx.x] = (D) x[threadIdx.x]; }\n" + "template static void go(const void *x, D *y) {\n" + " k<<<1, 4>>>((const S *) x, y); }\n" + "typedef void (*to16_t)(const void *, short *);\n" + "to16_t pick(int i) { return go; }\n"), + NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi327.cu", obuf, (int)sizeof obuf), 0); + + CHNE(strstr(obuf, "func @k(ptr %0, ptr %1)"), NULL); + PASS(); +} +TH_REG("rpi", 327, "a pointer typedef lends deduction its params", rpi327) From c99112455d6799222dd112e0e803a1046c8a8739 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Wed, 23 Sep 2026 19:09:50 +1200 Subject: [PATCH 35/41] sass: P1 is the wide compares' scratch, so no value may live there --- src/nvidia/emit_sass.c | 4 ++-- tests/trpi.c | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/nvidia/emit_sass.c b/src/nvidia/emit_sass.c index ec2bd22..9b0e88c 100644 --- a/src/nvidia/emit_sass.c +++ b/src/nvidia/emit_sass.c @@ -617,7 +617,7 @@ static uint32_t sapick(uint32_t w, uint32_t v) static uint32_t sappik(uint32_t v) { - for (uint32_t r = 1u; r < SA_NPR; r++) + for (uint32_t r = 2u; r < SA_NPR; r++) if (saocc(sast.pocc[r], v, 0) == 0) return r; return SA_NPR; } @@ -3217,7 +3217,7 @@ static int sarega(void) } if (saspil() != 0) { if (sast.npr != 0u) - (void)be_fail(BC_E604, "nvptx", sast.name, (unsigned)SA_NPR - 1u); + (void)be_fail(BC_E604, "nvptx", sast.name, (unsigned)SA_NPR - 2u); else (void)be_fail(BC_E603, "nvptx", sast.name, (unsigned)(LT_MAX_NVREG - SA_RBAS)); diff --git a/tests/trpi.c b/tests/trpi.c index 9b1edb6..2658a58 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6542,3 +6542,29 @@ static void rpi327(void) PASS(); } TH_REG("rpi", 327, "a pointer typedef lends deduction its params", rpi327) + +static void rpi328(void) +{ + const char *p = rpi_sass( + "__global__ void k(const float *x, const float *g, float *o, long long n){\n" + " const bool use_g = g != nullptr; float acc = 0.0f;\n" + " for (long long i = threadIdx.x; i < n; i += 32) {\n" + " acc += x[i]; if (use_g) acc += g[i]; }\n" + " o[threadIdx.x] = acc; }\n", "rpi328"); + int seen = 0; + + CHNE(p, NULL); + for (const char *q = strstr(p, "NV_SETP_NE_U64"); q; q = strstr(q + 1, "NV_SETP_NE_U64")) { + const char *ln = q; + unsigned long long lo, hi; + + while (ln > p && ln[-1] != '\n') ln--; + CHEQ(sscanf(ln, "%*x %llx %llx", &lo, &hi), 2); + if ((lo & 0xFFFull) != 0x20Cull) continue; + CHECK(((hi >> 17) & 7ull) >= 2ull); + seen++; + } + CHECK(seen >= 2); + PASS(); +} +TH_REG("rpi", 328, "P1 is scratch for wide compares, never a value", rpi328) From ae66cb4b8106f87b67d55c2ce423a2551eb00ca9 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Thu, 24 Sep 2026 14:13:36 +1200 Subject: [PATCH 36/41] an alias template of a function pointer keeps its params too, so ggml's to_t_cuda_t deduces --- src/fe/parser.c | 12 ++++++++++-- src/ir/bir_lower.c | 18 +++++++++++------- tests/trpi.c | 18 ++++++++++++++++++ 3 files changed, 39 insertions(+), 9 deletions(-) diff --git a/src/fe/parser.c b/src/fe/parser.c index c6d477a..eb456ea 100644 --- a/src/fe/parser.c +++ b/src/fe/parser.c @@ -541,6 +541,7 @@ static uint32_t parse_stmt(parser_t *P); static uint32_t parse_type_spec(parser_t *P, uint16_t *quals, uint16_t *cuda); static uint32_t parse_decl_or_stmt(parser_t *P); static uint32_t fnptr(parser_t *P, int *depth); +static uint32_t fnpta(parser_t *P, int *depth, uint32_t owner); static int is_fnptr(parser_t *P); static uint32_t tnargs(parser_t *P); static uint32_t parse_param_list(parser_t *P); @@ -1747,6 +1748,11 @@ static void skippar(parser_t *P) the name as params, so a template handed out through the pointer can be deduced against it. 0 if abstract. */ static uint32_t fnptr(parser_t *P, int *depth) +{ + return fnpta(P, depth, 0); +} + +static uint32_t fnpta(parser_t *P, int *depth, uint32_t owner) { uint32_t name = 0; advance(P); /* ( */ @@ -1761,10 +1767,11 @@ static uint32_t fnptr(parser_t *P, int *depth) } expect(P, TOK_RPAREN); if (cur_type(P) == TOK_LPAREN) { - if (!name) { skippar(P); return 0; } + uint32_t at = name ? name : owner; + if (!at) { skippar(P); return 0; } advance(P); uint32_t params = parse_param_list(P); - if (params) add_child(P, name, params); + if (params) add_child(P, at, params); expect(P, TOK_RPAREN); } return name; @@ -2259,6 +2266,7 @@ static uint32_t parse_declaration(parser_t *P) int pd2 = 0; uint32_t alias_type = parse_type_spec(P, &q2, &c2); while (cur_type(P) == TOK_STAR) { advance(P); pd2++; } + if (is_fnptr(P)) (void)fnpta(P, &pd2, name); P->nodes[u].d.oper.flags = pd2; P->nodes[u].cuda_flags = c2; add_child(P, u, alias_type); diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index 8c69b3c..ee5ae21 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -1558,6 +1558,8 @@ static int tpdep(const lower_t *L, uint32_t n) } static int altry(lower_t *L, const char *nm, uint32_t ta, uint32_t *out); +static uint32_t fpty(lower_t *L, uint32_t name_n, uint32_t type_n, int depth, + uint16_t cuda); static int malfnd(const lower_t *L, const char *cls, const char *nm, uint32_t *ty); @@ -2220,8 +2222,9 @@ static int altry(lower_t *L, const char *nm, uint32_t ta, uint32_t *out) for (int i = 0; i < ntp; i++) L->bindings[L->nbindings++] = nb[i]; L->nbbase = onb; if (ty && ND(L, ty)->type == AST_TYPE_SPEC) - *out = resolve_type(L, ty, ND(L, al->use)->d.oper.flags, - ND(L, al->use)->cuda_flags); + *out = fpty(L, ND(L, al->use)->first_child, ty, + ND(L, al->use)->d.oper.flags, + ND(L, al->use)->cuda_flags); else ok = 0; if (ok && (L->rtbad || L->rtunk)) ok = 0; @@ -11893,12 +11896,13 @@ static void tdbad(lower_t *L, typedef_def_t *td) ncpy(td->snm, sizeof(td->snm), L->rtsnm); } -static uint32_t fpty(lower_t *L, uint32_t name_n, uint32_t type_n, int depth) +static uint32_t fpty(lower_t *L, uint32_t name_n, uint32_t type_n, int depth, + uint16_t cuda) { uint32_t pv[MAX_PARM], pt[MAX_PARM], ret, t; int np = collect_params(L, name_n, pv, MAX_PARM); - if (np <= 0) return resolve_type(L, type_n, depth, 0); + if (np <= 0) return resolve_type(L, type_n, depth, cuda); ret = resolve_type(L, type_n, 0, 0); if (L->rtbad || L->rtunk) { L->rtbad = 0; L->rtunk = 0; return 0; } for (int i = 0; i < np; i++) { @@ -11974,7 +11978,7 @@ static void collect_typedef(lower_t *L, uint32_t node) typedef_def_t *td = &L->typedefs[L->ntypedefs++]; memset(td, 0, sizeof(*td)); get_text(L, name_n, td->name, sizeof(td->name)); - td->bir_type = fpty(L, name_n, type_n, ND(L, node)->d.oper.flags); + td->bir_type = fpty(L, name_n, type_n, ND(L, node)->d.oper.flags, 0); tdbad(L, td); } @@ -11998,8 +12002,8 @@ static int ureg(lower_t *L, uint32_t node) } memset(td, 0, sizeof(*td)); ncpy(td->name, sizeof(td->name), nm); - td->bir_type = resolve_type(L, ty_n, ND(L, node)->d.oper.flags, - ND(L, node)->cuda_flags); + td->bir_type = fpty(L, nm_n, ty_n, ND(L, node)->d.oper.flags, + ND(L, node)->cuda_flags); tdbad(L, td); L->rtbad = 0; return 1; diff --git a/tests/trpi.c b/tests/trpi.c index 2658a58..485c29a 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -6568,3 +6568,21 @@ static void rpi328(void) PASS(); } TH_REG("rpi", 328, "P1 is scratch for wide compares, never a value", rpi328) + +static void rpi329(void) +{ + CHNE(scratch("rpi329.cu", + "template using fp_t = void (*)(const void *, T *, long);\n" + "typedef fp_t to16_t;\n" + "template __global__ void k(const S *x, D *y) {\n" + " y[threadIdx.x] = (D) x[threadIdx.x]; }\n" + "template static void go(const void *x, D *y, long n) {\n" + " k<<<1, 4>>>((const S *) x, y); }\n" + "to16_t pick(int i) { return go; }\n"), + NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi329.cu", obuf, (int)sizeof obuf), 0); + + CHNE(strstr(obuf, "func @k(ptr %0, ptr %1)"), NULL); + PASS(); +} +TH_REG("rpi", 329, "an alias template of a pointer keeps params", rpi329) From 3e3d85758ced55ab3c7607f639edb788810915d5 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Mon, 26 Oct 2026 17:23:59 +1300 Subject: [PATCH 37/41] the tensor cores were in there the whole time --- src/nvidia/emit_sass.c | 105 +++++++++++++++++++++++++++++++++++++++++ src/nvidia/lt_nv.h | 4 ++ src/nvidia/lt_nvi.c | 50 ++++++++++++++++++++ tests/tasm.c | 61 ++++++++++++++++++++++-- 4 files changed, 217 insertions(+), 3 deletions(-) diff --git a/src/nvidia/emit_sass.c b/src/nvidia/emit_sass.c index 9b0e88c..ca606db 100644 --- a/src/nvidia/emit_sass.c +++ b/src/nvidia/emit_sass.c @@ -17,6 +17,7 @@ #define SA_NPR 6u #define SA_NOIX 0xFFFFu #define SA_MAT 12u +#define SA_MREG 10u #define SA_STK 0x028u #define SA_NVW (SA_NV / 64u) #define SA_NIW 1024u @@ -62,6 +63,7 @@ typedef struct { uint64_t pocc[SA_NPR][SA_NIW]; uint32_t rbas[NV_RF_COUNT]; uint32_t nvr; + uint32_t mbas; uint32_t nreg; uint32_t npr; uint32_t f0; @@ -2807,6 +2809,99 @@ static void saldsm(const nv_minst_t *I, const nv_asm_t *A, uint32_t n, } } +/* ---- mma.sync: the forms ptxas output in the corpus pins down ---- */ + +typedef struct { uint8_t na, nb, nd, msz, dty, sty, imm; } samm_t; + +static int samsh(const char *t, samm_t *m) +{ + static const struct { const char *p; samm_t m; } tab[] = { + { "mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32", + { 4u, 2u, 4u, 1u, 1u, 0u, 0u } }, + { "mma.sync.aligned.m16n8k16.row.col.f16.f16.f16.f16", + { 4u, 2u, 2u, 1u, 0u, 0u, 0u } }, + { "mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32", + { 4u, 2u, 4u, 1u, 1u, 1u, 0u } }, + { "mma.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32", + { 4u, 2u, 4u, 0u, 1u, 2u, 0u } }, + { "mma.sync.aligned.m16n8k16.row.col.s32.s8.s8.s32", + { 2u, 1u, 4u, 0u, 0u, 0u, 1u } }, + { "mma.sync.aligned.m16n8k32.row.col.s32.s8.s8.s32", + { 4u, 2u, 4u, 0u, 0u, 0u, 2u } }, + }; + + for (uint32_t i = 0; i < sizeof tab / sizeof tab[0]; i++) + if (sapfx(t, tab[i].p)) { *m = tab[i].m; return 1; } + return 0; +} + +/* a frame that holds one of these needs somewhere to stage the runs, and + the block is reserved once for the whole function rather than per call. */ +static int samany(const nv_module_t *M) +{ + for (uint32_t i = 0; i < sast.fn; i++) { + const nv_minst_t *I = &M->minsts[sast.f0 + i]; + const nv_asm_t *A; + samm_t m; + + if (I->op != (uint16_t)NV_ASM) continue; + A = saaof(I); + if (A == NULL || M->bir == NULL || A->tmpl >= M->bir->string_len) + continue; + if (samsh(M->bir->strings + A->tmpl, &m)) return 1; + } + return 0; +} + +/* every operand arrives as its own value, so each run is copied into the + staging block the frame reserved, the same way the AMD host stages a + matmul before it can name one register for the run. */ +static void samcp(uint32_t d, uint32_t sr, uint32_t n) +{ + uint64_t w[2]; + + for (uint32_t k = 0; k < n; k++) { + lt_nrw_t y; + + memset(&y, 0, sizeof y); + samsr(&y.rd, sr + k, 1u); + samsr(&y.wr, d + k, 1u); + lt_nvmov(w, d + k, sr + k); + safire(w, &y, 0u); + } +} + +static void samma(const nv_minst_t *I, const nv_asm_t *A, const samm_t *m) +{ + uint32_t b = sast.mbas, ab = b, bb = b + 4u, cb = b + 6u; + uint32_t n = (uint32_t)m->na + m->nb + m->nd; + uint64_t w[2]; + lt_nrw_t x; + + if (sast.mbas == 0u || (uint32_t)A->nout != m->nd + || (uint32_t)A->nops != n) { sabad(I->op, BC_E609); return; } + for (uint32_t k = 0; k < (uint32_t)A->nops; k++) + if (A->ops[k].kind != (uint8_t)NV_MOP_REG) { sabad(I->op, BC_E609); return; } + + for (uint32_t k = 0; k < m->na; k++) + samcp(ab + k, sarg(&A->ops[m->nd + k]), 1u); + for (uint32_t k = 0; k < m->nb; k++) + samcp(bb + k, sarg(&A->ops[m->nd + m->na + k]), 1u); + for (uint32_t k = 0; k < m->nd; k++) + samcp(cb + k, sarg(&A->ops[k]), 1u); + + memset(&x, 0, sizeof x); + samsr(&x.rd, ab, m->na); + samsr(&x.rd, bb, m->nb); + samsr(&x.rd, cb, m->nd); + samsr(&x.wr, cb, m->nd); + if (m->imm != 0u) lt_nvimma(w, cb, ab, bb, cb, m->imm == 2u ? 1u : 0u); + else lt_nvhmma(w, cb, ab, bb, cb, m->msz, m->dty, m->sty); + safire(w, &x, 3u); + for (uint32_t k = 0; k < m->nd; k++) + samcp(sarg(&A->ops[k]), cb + k, 1u); +} + static void saasm(const nv_minst_t *I) { const nv_asm_t *A = saaof(I); @@ -2836,6 +2931,11 @@ static void saasm(const nv_minst_t *I) if (sapfx(t, "ldmatrix.sync.aligned.m8n8.x4.trans.b16")) { saldsm(I, A, 4u, 1u); return; } + { + samm_t m; + + if (samsh(t, &m)) { samma(I, A, &m); return; } + } (void)be_fail(BC_E541, "nvptx", saawhy(t)); sast.nbad++; } @@ -3169,6 +3269,7 @@ static int sabld(const nv_module_t *M, uint32_t fi) sast.fbas = (sast.isfn != 0u && sast.ktop > SA_RBAS) ? sast.ktop : SA_RBAS; sast.rlo = sast.fbas; + sast.mbas = 0u; if (F->num_blks == 0u || F->num_params > LT_MAX_NVPRM) { (void)be_fail(BC_E600, "nvptx", (unsigned)LT_MAX_NVKRN, 0u); return 1; @@ -3185,6 +3286,10 @@ static int sabld(const nv_module_t *M, uint32_t fi) sast.kcall = 1u; break; } + if (samany(M) != 0) { + sast.mbas = sast.rlo; + sast.rlo += SA_MREG; + } if (sast.fn >= 0xFFFFu || F->num_blks >= SA_NBB) { (void)be_fail(BC_E602, "nvptx", sast.name, (unsigned)F->num_blks, (unsigned)SA_NBB); diff --git a/src/nvidia/lt_nv.h b/src/nvidia/lt_nv.h index 8a4aa88..89b156b 100644 --- a/src/nvidia/lt_nv.h +++ b/src/nvidia/lt_nv.h @@ -328,6 +328,10 @@ void lt_nvlds(uint64_t *w, uint32_t dst, uint32_t ra, uint32_t off, uint32_t ty) void lt_nvsts(uint64_t *w, uint32_t ra, uint32_t rb, uint32_t off, uint32_t ty); void lt_nvldsm(uint64_t *w, uint32_t d, uint32_t ra, uint32_t off, uint32_t n, uint32_t tr); +void lt_nvhmma(uint64_t *w, uint32_t d, uint32_t ra, uint32_t rb, uint32_t rc, + uint32_t msz, uint32_t dty, uint32_t sty); +void lt_nvimma(uint64_t *w, uint32_t d, uint32_t ra, uint32_t rb, uint32_t rc, + uint32_t k32); void lt_nvvot(uint64_t *w, uint32_t d, uint32_t pd, uint32_t p, uint32_t nt, uint32_t vop); void lt_nvsfl(uint64_t *w, uint32_t d, uint32_t pd, uint32_t ra, uint32_t rb, diff --git a/src/nvidia/lt_nvi.c b/src/nvidia/lt_nvi.c index d640ac9..68b7ff5 100644 --- a/src/nvidia/lt_nvi.c +++ b/src/nvidia/lt_nvi.c @@ -503,6 +503,56 @@ lt_nvldsm(uint64_t *w, uint32_t d, uint32_t ra, uint32_t off, lt_nvput(w, 79u, 78u, tr); } +/* The matrix shape sits in two pieces, a low bit at 75 and the rest at 78, + which is why it reads as a field nothing records if you look in one + place. m16n8k16 is the low bit on its own. dty picks the accumulator, + f16 or f32, and sty picks the source, f16 or bf16. */ +void +lt_nvhmma(uint64_t *w, uint32_t d, uint32_t ra, uint32_t rb, uint32_t rc, + uint32_t msz, uint32_t dty, uint32_t sty) +{ + assert(w != NULL); + assert(d < 256u && ra < 256u && rb < 256u && rc < 256u); + assert(msz < 4u && dty < 2u && sty < 4u); + + /* per nak-mesa-90320e12 sm70_encode.rs, differenced against nv_isa_sm89. + msz is the shape in its two pieces, 0 for m16n8k8 and 1 for m16n8k16, + and sty names the source, 0 f16, 1 bf16, 2 tf32. */ + head(w, 0x23Cu, 0u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 31u, 24u, ra); + lt_nvput(w, 39u, 32u, rb); + lt_nvput(w, 71u, 64u, rc); + lt_nvput(w, 75u, 75u, msz & 1u); + lt_nvput(w, 76u, 76u, dty); + lt_nvput(w, 78u, 78u, (msz >> 1) & 1u); + lt_nvput(w, 83u, 82u, sty); +} + +/* imma spells its shape the same way but wider, and signs each side on its + own. Both sources signed and b transposed is the only form ptxas emits + for the s8 mma the corpus carries. */ +void +lt_nvimma(uint64_t *w, uint32_t d, uint32_t ra, uint32_t rb, uint32_t rc, + uint32_t k32) +{ + assert(w != NULL); + assert(d < 256u && ra < 256u && rb < 256u && rc < 256u); + assert(k32 < 2u); + + /* per nak-mesa-90320e12 sm70_encode.rs, differenced against nv_isa_sm89 */ + head(w, 0x237u, 0u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 31u, 24u, ra); + lt_nvput(w, 39u, 32u, rb); + lt_nvput(w, 71u, 64u, rc); + lt_nvput(w, 74u, 74u, 1u); + lt_nvput(w, 75u, 75u, k32 ? 0u : 1u); + lt_nvput(w, 76u, 76u, 1u); + lt_nvput(w, 78u, 78u, 1u); + lt_nvput(w, 86u, 85u, 2u); +} + /* ---- Lanes ---- */ void diff --git a/tests/tasm.c b/tests/tasm.c index d30b8b6..ed1f914 100644 --- a/tests/tasm.c +++ b/tests/tasm.c @@ -278,7 +278,7 @@ TH_REG("asm", 18, "ldmatrix x4 reaches SASS as LDSM", asm18) static void asm19(void) { - CHNE(acub( + CHEQ(acub( "__global__ void k(int *o) {\n" " int d0 = 0, d1 = 0, a0 = 1, a1 = 2, a2 = 3, a3 = 4;\n" " int b0 = 5, b1 = 6;\n" @@ -289,10 +289,10 @@ static void asm19(void) " \"r\"(b0), \"r\"(b1));\n" " o[threadIdx.x] = d0 + d1;\n" "}\n"), 0); - CHNE(strstr(obuf, "warp matrix multiply"), NULL); + PASS(); } -TH_REG("asm", 19, "a mma.sync template refuses by name", asm19) +TH_REG("asm", 19, "mma m16n8k16 into f16 reaches SASS as HMMA", asm19) static void asm20(void) { @@ -305,3 +305,58 @@ static void asm20(void) PASS(); } TH_REG("asm", 20, "a device printf refuses by name in SASS", asm20) + +static const char *const mmaf = + "__global__ void k(const int *a, const int *b, int *d) {\n" + " int A0=a[0],A1=a[1],A2=a[2],A3=a[3],B0=b[0],B1=b[1];\n" + " int D0=d[0],D1=d[1],D2=d[2],D3=d[3];\n" + " asm(\"mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32\"\n" + " \" {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\"\n" + " : \"+r\"(D0), \"+r\"(D1), \"+r\"(D2), \"+r\"(D3)\n" + " : \"r\"(A0),\"r\"(A1),\"r\"(A2),\"r\"(A3),\"r\"(B0),\"r\"(B1));\n" + " d[0]=D0; d[1]=D1; d[2]=D2; d[3]=D3;\n" + "}\n"; + +static const char *const mmai = + "__global__ void k(const int *a, const int *b, int *d) {\n" + " int A0=a[0],A1=a[1],B0=b[0];\n" + " int D0=d[0],D1=d[1],D2=d[2],D3=d[3];\n" + " asm(\"mma.sync.aligned.m16n8k16.row.col.s32.s8.s8.s32\"\n" + " \" {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\"\n" + " : \"+r\"(D0), \"+r\"(D1), \"+r\"(D2), \"+r\"(D3)\n" + " : \"r\"(A0),\"r\"(A1),\"r\"(B0));\n" + " d[0]=D0; d[1]=D1; d[2]=D2; d[3]=D3;\n" + "}\n"; + +static const char *const mmatf = + "__global__ void k(const int *a, const int *b, int *d) {\n" + " int A0=a[0],A1=a[1],A2=a[2],A3=a[3],B0=b[0],B1=b[1];\n" + " int D0=d[0],D1=d[1],D2=d[2],D3=d[3];\n" + " asm(\"mma.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32\"" + " \" {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\"" + " \n" + " : \"+r\"(D0), \"+r\"(D1), \"+r\"(D2), \"+r\"(D3)\n" + " : \"r\"(A0),\"r\"(A1),\"r\"(A2),\"r\"(A3),\"r\"(B0),\"r\"(B1));\n" + " d[0]=D0; d[1]=D1; d[2]=D2; d[3]=D3;\n" + "}\n"; + +static void asm21(void) +{ + CHEQ(acub(mmaf), 0); + PASS(); +} +TH_REG("asm", 21, "mma m16n8k16 f16 into f32 reaches SASS as HMMA", asm21) + +static void asm22(void) +{ + CHEQ(acub(mmai), 0); + PASS(); +} +TH_REG("asm", 22, "mma m16n8k16 s8 into s32 reaches SASS as IMMA", asm22) + +static void asm23(void) +{ + CHEQ(acub(mmatf), 0); + PASS(); +} +TH_REG("asm", 23, "m16n8k8 tf32 reaches SASS as HMMA", asm23) From a6f9603912c81b7d21352f44466869ed2e2d31de Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Mon, 26 Oct 2026 17:23:59 +1300 Subject: [PATCH 38/41] you were meant to be the chosen launcher! (Param shadowing and launcher names) --- src/ir/bir_lower.c | 15 ++++++++++++++- tests/rules.tbl | 2 +- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index ee5ae21..636079a 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -13435,10 +13435,23 @@ static void vscn(lower_t *L, uint32_t vd) } } +static int psdup(const lower_t *L, int base, const char *nm) +{ + for (int k = base; k < L->nsyms; k++) + if (strcmp(L->syms[k].name, nm) == 0) return 1; + return 0; +} + +/* A parameter shadows whatever the enclosing scan had in scope. The kernel + is instantiated from inside its launcher's own scan, so the launcher's + locals are still live here, and ggml names several of them exactly as the + kernel names its parameters at a different width. Only a repeat inside + this one parameter list is a duplicate. */ static void pscn(lower_t *L, uint32_t fd) { uint32_t pv[MAX_PARM]; int np = collect_params(L, fd, pv, MAX_PARM); + int base = L->nsyms; for (int i = 0; i < np; i++) { const ast_node_t *pn = ND(L, pv[i]); @@ -13452,7 +13465,7 @@ static void pscn(lower_t *L, uint32_t fd) get_text(L, pc, pnm, (int)sizeof pnm); break; } - if (!pnm[0] || find_sym(L, pnm)) continue; + if (!pnm[0] || psdup(L, base, pnm)) continue; t = rtype(L, pn->first_child, pn->d.oper.flags, pn->cuda_flags); if (t) add_sym(L, pnm, BIR_VAL_NONE, t, 0); } diff --git a/tests/rules.tbl b/tests/rules.tbl index 624269f..558e721 100644 --- a/tests/rules.tbl +++ b/tests/rules.tbl @@ -5,5 +5,5 @@ goto 63 goto, setjmp or longjmp alloc 99 allocation calls fnptr 25 function pointers long 148 functions over 60 lines -comment 6510 comment lines +comment 6522 comment lines snprintf 83 snprintf calls whose return is discarded From 28b01755d0addc5a7d70546d41cb87ef77bbc5b5 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Mon, 26 Oct 2026 17:29:36 +1300 Subject: [PATCH 39/41] girl I'm tired lmao (no MLIR for now will work on it later) --- .gitignore | 4 + Makefile | 54 +- docs/features.md | 2 - docs/roadmap.md | 4 - docs/usage.md | 31 +- src/exec/verbs.c | 4 +- src/main.c | 61 +- src/mlir/lower.c | 591 --- src/mlir/mlir_fe.c | 128 - src/mlir/mlir_fe.h | 29 - src/mlir/mlir_lower.h | 19 - src/mlir/vendor/LICENSE.corec | 21 - src/mlir/vendor/LICENSE.mlir | 25 - src/mlir/vendor/base/arena.c | 202 - src/mlir/vendor/base/arena.h | 143 - src/mlir/vendor/base/assert.c | 23 - src/mlir/vendor/base/assert.h | 25 - src/mlir/vendor/base/buddy.c | 530 -- src/mlir/vendor/base/buddy.h | 23 - src/mlir/vendor/base/exit.c | 11 - src/mlir/vendor/base/exit.h | 16 - src/mlir/vendor/base/format.c | 261 - src/mlir/vendor/base/format.h | 81 - src/mlir/vendor/base/hashtable.h | 95 - src/mlir/vendor/base/io.c | 159 - src/mlir/vendor/base/io.h | 55 - src/mlir/vendor/base/math.c | 77 - src/mlir/vendor/base/math.h | 51 - src/mlir/vendor/base/mem.c | 176 - src/mlir/vendor/base/mem.h | 29 - src/mlir/vendor/base/numconv.c | 382 -- src/mlir/vendor/base/numconv.h | 48 - src/mlir/vendor/base/scratch.c | 35 - src/mlir/vendor/base/scratch.h | 61 - src/mlir/vendor/base/stdarg.h | 49 - src/mlir/vendor/base/strbuf.c | 72 - src/mlir/vendor/base/strbuf.h | 63 - src/mlir/vendor/base/string.c | 94 - src/mlir/vendor/base/string.h | 41 - src/mlir/vendor/base/types.h | 132 - src/mlir/vendor/base/vector.h | 78 - src/mlir/vendor/mlir_api.h | 1104 ----- src/mlir/vendor/mlir_api_impl.c | 2688 ----------- src/mlir/vendor/mlir_classic_printer.c | 2718 ----------- src/mlir/vendor/mlir_classic_printer.h | 22 - src/mlir/vendor/mlir_codegen_buf.h | 88 - src/mlir/vendor/mlir_lift_cf_to_scf.c | 3166 ------------ src/mlir/vendor/mlir_lift_cf_to_scf.h | 60 - src/mlir/vendor/mlir_op_names.c | 284 -- src/mlir/vendor/mlir_op_names.h | 14 - src/mlir/vendor/mlir_parser.c | 1794 ------- src/mlir/vendor/mlir_parser.h | 185 - src/mlir/vendor/op_parsers.c | 4260 ----------------- src/mlir/vendor/op_parsers.h | 72 - src/mlir/vendor/platform/platform.h | 274 -- src/mlir/vendor/platform/platform_linux.c | 544 --- src/mlir/vendor/platform/platform_macos.c | 412 -- src/mlir/vendor/platform/platform_windows.c | 741 --- src/mlir/vendor/platform/syscall6.h | 86 - src/mlir/vendor/tokenizer.c | 901 ---- src/mlir/vendor/tokenizer.h | 67 - src/mlir/vendor/tokenizer.re | 157 - tests/mlir/a.mlir | 6 - tests/mlir/add1.ttir | 26 - tests/mlir/add_kernel.ttir | 35 - tests/mlir/b.mlir | 33 - tests/mlir/binops.mlir | 18 - tests/mlir/c.mlir | 30 - tests/mlir/chunked_cross_entropy_forward.ttir | 65 - tests/mlir/consts.mlir | 8 - tests/mlir/conv2d.ttir | 67 - tests/mlir/d.mlir | 48 - tests/mlir/effect.mlir | 139 - tests/mlir/floats.mlir | 9 - tests/mlir/matmul1.ttir | 166 - tests/mlir/mix.mlir | 12 - tests/mlir/reject.mlir | 7 - tests/mlir/simple.mlir | 23 - tests/mlir/sumrow.ttir | 70 - tests/mlir/t1.mlir | 18 - tests/mlir/t2.mlir | 25 - tests/mlir/t3.mlir | 28 - tests/mlir/triton_mm.ttir | 142 - tests/mutants.tbl | 10 - tests/tmain.c | 1 - tests/tmlir.c | 373 -- 86 files changed, 11 insertions(+), 24970 deletions(-) delete mode 100644 src/mlir/lower.c delete mode 100644 src/mlir/mlir_fe.c delete mode 100644 src/mlir/mlir_fe.h delete mode 100644 src/mlir/mlir_lower.h delete mode 100644 src/mlir/vendor/LICENSE.corec delete mode 100644 src/mlir/vendor/LICENSE.mlir delete mode 100644 src/mlir/vendor/base/arena.c delete mode 100644 src/mlir/vendor/base/arena.h delete mode 100644 src/mlir/vendor/base/assert.c delete mode 100644 src/mlir/vendor/base/assert.h delete mode 100644 src/mlir/vendor/base/buddy.c delete mode 100644 src/mlir/vendor/base/buddy.h delete mode 100644 src/mlir/vendor/base/exit.c delete mode 100644 src/mlir/vendor/base/exit.h delete mode 100644 src/mlir/vendor/base/format.c delete mode 100644 src/mlir/vendor/base/format.h delete mode 100644 src/mlir/vendor/base/hashtable.h delete mode 100644 src/mlir/vendor/base/io.c delete mode 100644 src/mlir/vendor/base/io.h delete mode 100644 src/mlir/vendor/base/math.c delete mode 100644 src/mlir/vendor/base/math.h delete mode 100644 src/mlir/vendor/base/mem.c delete mode 100644 src/mlir/vendor/base/mem.h delete mode 100644 src/mlir/vendor/base/numconv.c delete mode 100644 src/mlir/vendor/base/numconv.h delete mode 100644 src/mlir/vendor/base/scratch.c delete mode 100644 src/mlir/vendor/base/scratch.h delete mode 100644 src/mlir/vendor/base/stdarg.h delete mode 100644 src/mlir/vendor/base/strbuf.c delete mode 100644 src/mlir/vendor/base/strbuf.h delete mode 100644 src/mlir/vendor/base/string.c delete mode 100644 src/mlir/vendor/base/string.h delete mode 100644 src/mlir/vendor/base/types.h delete mode 100644 src/mlir/vendor/base/vector.h delete mode 100644 src/mlir/vendor/mlir_api.h delete mode 100644 src/mlir/vendor/mlir_api_impl.c delete mode 100644 src/mlir/vendor/mlir_classic_printer.c delete mode 100644 src/mlir/vendor/mlir_classic_printer.h delete mode 100644 src/mlir/vendor/mlir_codegen_buf.h delete mode 100644 src/mlir/vendor/mlir_lift_cf_to_scf.c delete mode 100644 src/mlir/vendor/mlir_lift_cf_to_scf.h delete mode 100644 src/mlir/vendor/mlir_op_names.c delete mode 100644 src/mlir/vendor/mlir_op_names.h delete mode 100644 src/mlir/vendor/mlir_parser.c delete mode 100644 src/mlir/vendor/mlir_parser.h delete mode 100644 src/mlir/vendor/op_parsers.c delete mode 100644 src/mlir/vendor/op_parsers.h delete mode 100644 src/mlir/vendor/platform/platform.h delete mode 100644 src/mlir/vendor/platform/platform_linux.c delete mode 100644 src/mlir/vendor/platform/platform_macos.c delete mode 100644 src/mlir/vendor/platform/platform_windows.c delete mode 100644 src/mlir/vendor/platform/syscall6.h delete mode 100644 src/mlir/vendor/tokenizer.c delete mode 100644 src/mlir/vendor/tokenizer.h delete mode 100644 src/mlir/vendor/tokenizer.re delete mode 100644 tests/mlir/a.mlir delete mode 100644 tests/mlir/add1.ttir delete mode 100644 tests/mlir/add_kernel.ttir delete mode 100644 tests/mlir/b.mlir delete mode 100644 tests/mlir/binops.mlir delete mode 100644 tests/mlir/c.mlir delete mode 100644 tests/mlir/chunked_cross_entropy_forward.ttir delete mode 100644 tests/mlir/consts.mlir delete mode 100644 tests/mlir/conv2d.ttir delete mode 100644 tests/mlir/d.mlir delete mode 100644 tests/mlir/effect.mlir delete mode 100644 tests/mlir/floats.mlir delete mode 100644 tests/mlir/matmul1.ttir delete mode 100644 tests/mlir/mix.mlir delete mode 100644 tests/mlir/reject.mlir delete mode 100644 tests/mlir/simple.mlir delete mode 100644 tests/mlir/sumrow.ttir delete mode 100644 tests/mlir/t1.mlir delete mode 100644 tests/mlir/t2.mlir delete mode 100644 tests/mlir/t3.mlir delete mode 100644 tests/mlir/triton_mm.ttir delete mode 100644 tests/tmlir.c diff --git a/.gitignore b/.gitignore index 5ab984a..28feadc 100644 --- a/.gitignore +++ b/.gitignore @@ -186,3 +186,7 @@ tdf_flag_out.txt # Mutation harness scratch copy. Removed on exit, but an interrupted run # can leave it behind. /.mutscratch/ + +src/mlir/ +tests/mlir/ +tests/tmlir.c diff --git a/Makefile b/Makefile index 17e0e3d..c5a2dff 100644 --- a/Makefile +++ b/Makefile @@ -76,54 +76,11 @@ SOURCES = src/main.c src/kauri_impl.c \ src/metal/emit.c src/metal/metal_be.c \ src/intel/emit.c src/intel/intel_be.c \ src/triton/lex.c src/triton/parse.c src/triton/sema.c src/triton/lower.c \ - src/mlir/mlir_fe.c src/mlir/lower.c \ src/exec/execs.c src/exec/cpu_exec.c src/exec/booth_run.c src/exec/verbs.c \ src/host/hgen.c \ runtime/host/cuda/nv_rt.c runtime/host/cuda/nv_exec.c -# Certik's pure-C MLIR reader, vendored under src/mlir/vendor. It carries his -# corec base library and a syscall shim per host, so only one of the three -# platform files is ever built. -# -# c2x rather than c99 because corec's format.h dispatches on _Generic and -# needs __VA_OPT__, and the ~100 format() call sites through it are not worth -# rewriting. -Wno-switch-enum because these switch over a 140-value op enum -# with a default label and upstream keeps adding ops. Nothing else in the -# warning set is relaxed. PLATFORM_SKIP_ENTRY leaves main to Booth, -# COREC_STDLIB_PROVIDES_MEM stops corec defining memcpy and memset when a real -# libc is already doing it. -VDIR = src/mlir/vendor -VPLAT = platform_windows.c -ifeq ($(UNAME_S),Linux) - VPLAT = platform_linux.c -endif -ifeq ($(UNAME_S),Darwin) - VPLAT = platform_macos.c -endif -VSOURCES = $(VDIR)/tokenizer.c $(VDIR)/mlir_parser.c $(VDIR)/op_parsers.c \ - $(VDIR)/mlir_api_impl.c $(VDIR)/mlir_op_names.c \ - $(VDIR)/mlir_classic_printer.c $(VDIR)/mlir_lift_cf_to_scf.c \ - $(VDIR)/base/io.c $(VDIR)/base/buddy.c $(VDIR)/base/arena.c \ - $(VDIR)/base/scratch.c $(VDIR)/base/format.c $(VDIR)/base/math.c \ - $(VDIR)/base/string.c $(VDIR)/base/strbuf.c $(VDIR)/base/mem.c \ - $(VDIR)/base/numconv.c $(VDIR)/base/assert.c $(VDIR)/base/exit.c \ - $(VDIR)/platform/$(VPLAT) -# Simply expanded, so the target-specific assignment below is a plain string -# rather than something that re-expands CFLAGS into itself. -VCFLAGS := $(subst -std=c99,-std=c2x,$(CFLAGS)) -Wno-switch-enum \ - -DPLATFORM_SKIP_ENTRY -DCOREC_STDLIB_PROVIDES_MEM -I$(VDIR) - -OBJECTS = $(SOURCES:%.c=$(OBJDIR)/%.o) $(VSOURCES:%.c=$(OBJDIR)/%.o) - -# Everything under src/mlir compiles on VCFLAGS, vendored or not. mlir_fe.c and -# lower.c are ours but they speak corec types, so they want the same flags. -# A target-specific variable rather than a pattern rule, because two patterns -# match these objects and make 3.81, which is what macOS ships, does not -# resolve that the way make 4 does. It took the generic rule and the build lost -# its include path. -MLOBJECTS = $(VSOURCES:%.c=$(OBJDIR)/%.o) \ - $(OBJDIR)/src/mlir/mlir_fe.o $(OBJDIR)/src/mlir/lower.o -$(MLOBJECTS): CFLAGS := $(VCFLAGS) +OBJECTS = $(SOURCES:%.c=$(OBJDIR)/%.o) TARGET = kath # Host programs that link a vendor driver at run time: the examples and the @@ -144,7 +101,7 @@ $(OBJDIR)/%.o: %.c # ---- Test Suite ---- TCFLAGS = -std=c99 -MMD -MP -D_POSIX_C_SOURCE=200809L -Wall -Wextra -O0 -g \ -Isrc -Isrc/fe -Isrc/ir -Isrc/tdf -Isrc/backend -Isrc/amdgpu -Isrc/tensix -Isrc/nvidia -Isrc/metal -Isrc/intel -Isrc/triton -Isrc/cpu -Isrc/build -Isrc/exec \ - -Isrc/mlir -Iruntime/include $(COVFLAGS) + -Iruntime/include $(COVFLAGS) TSRC = tests/tmain.c tests/tsmoke.c tests/tcomp.c tests/tenc.c \ tests/tasy.c \ tests/ttabs.c tests/ttypes.c tests/terrs.c tests/tphase.c \ @@ -171,7 +128,6 @@ TSRC = tests/tmain.c tests/tsmoke.c tests/tcomp.c tests/tenc.c \ tests/tbackend.c \ tests/tordr.c \ tests/trpi.c \ - tests/tmlir.c \ tests/tbir.c \ tests/tocm.c \ tests/tpack.c \ @@ -200,8 +156,7 @@ COBJS = $(OBJDIR)/src/kauri_impl.o $(OBJDIR)/src/ir/bir.o $(OBJDIR)/src/ir/bir $(OBJDIR)/src/cpu/cpu_emit.o $(OBJDIR)/src/cpu/cpu_elf.o \ $(OBJDIR)/src/cpu/rv64_emit.o $(OBJDIR)/src/cpu/rv64_elf.o \ $(OBJDIR)/src/tensix/isel.o $(OBJDIR)/src/tensix/coarsen.o $(OBJDIR)/src/tensix/datamov.o \ - $(OBJDIR)/src/metal/emit.o $(OBJDIR)/src/intel/emit.o \ - $(OBJDIR)/src/mlir/mlir_fe.o $(OBJDIR)/src/mlir/lower.o $(VSOURCES:%.c=$(OBJDIR)/%.o) + $(OBJDIR)/src/metal/emit.o $(OBJDIR)/src/intel/emit.o rules: @sh tests/rules.sh @@ -313,11 +268,8 @@ coverage: -./trunner --all @command -v gcovr >/dev/null 2>&1 || { echo "gcovr not found. pip install gcovr"; exit 1; } @mkdir -p coverage-html - @# gcovr snuffles through the object dir like a skaven after warp tokens, so vendored data has to be gone rather than filtered. - find $(COVDIR)/src/mlir \( -name '*.gcda' -o -name '*.gcno' \) -delete 2>/dev/null || true gcovr --root . --object-directory $(COVDIR) \ --filter 'src/' --filter 'runtime/' \ - --exclude 'src/mlir/vendor/' \ --exclude-unreachable-branches \ --print-summary --txt coverage.txt --html-details coverage-html/index.html rm -f $(TARGET) $(TARGET).exe trunner trunner.exe diff --git a/docs/features.md b/docs/features.md index 67ab3f2..c34bc4d 100644 --- a/docs/features.md +++ b/docs/features.md @@ -40,7 +40,6 @@ The following CUDA features compile to working GFX9/GFX10/GFX11/GFX12 machine co - Struct pass-by-value - Triton tile shape inference: rank-0/1/2 shape annotation on every expression, constexpr default propagation (`BLOCK: tl.constexpr = 256` resolves to `vec[256]`), numpy-style broadcasting, `[:, None]` / `[None, :]` reshape patterns - Triton matmul on the CPU: `tl.dot` lowers and runs via `--cpu`, with a runtime K-loop so the contraction can be any size. Rank-2 tiles materialise and unroll -- MLIR frontend (`--mlir`): `func.func`, `return`, `arith.constant`, the `arith` binops, compares and conversions lower to BIR and run through the same pipeline as CUDA and Triton. `--mlir --pp` reprints what was read - OCaml frontend: kernels are ordinary OCaml functions, type-checked by `ocamlc` against an abstract-typed `Kernel` module, lowered from the `.cmt` by `kcomp` and read back through `--bir-in`. Global and block-shared arrays of any element type, counted loops, `ref` accumulators, `if`/`else`, barriers, atomics, `let[@device]` functions, and twelve transcendentals. All six backends - BIR text frontend (`--bir-in`): a module printed by `--ir` reads back in, so a compiler outside this tree can target Booth without linking against it - x86-64 CPU backend (`--cpu`): CUDA and Triton kernels compile to a host object and run with no GPU. SIMT becomes a thread loop. Stack-everything codegen, no register allocator yet @@ -58,7 +57,6 @@ Being honest about limitations is important. Here's what's missing: - Triton `tl.dot` on the matrix cores. `mma.sync` and MFMA are in and checked against llvm-mc byte for byte, but a rank-2 tile still materialises and unrolls into scalar FMAs on every backend, which is correct and very large rather than a refusal. Reaching the matrix path from Triton is an execution-model change, not a missing encoding - Loop-carried reassignment in a Triton kernel. Rewriting a name across a `for` back-edge needs a phi at the loop head and only the counter gets one, so an accumulator refuses with E141 rather than quietly reading its pre-loop value every trip - CPU backend is correct-first: stack-everything codegen, no register allocator yet, single block per call, and `tl.load` masks aren't honoured (so keep the launch's nthreads equal to the element count). It runs; it isn't fast. -- MLIR beyond `func`, `return` and `arith`. No `memref`, `scf` or `gpu` dialect, and a function body with more than one block is refused rather than flattened. Nothing marks an MLIR function as a kernel, so it lowers as a device function: `--cpu` and `--rv64` emit real code, `--metal` counts it as a kernel, and `--amdgpu-bin` and `--nvidia-ptx` report zero kernels and write an empty container - OCaml kernels have no `while` and no early exit, no `f64`, no warp shuffles, and no atomic `min` or `max`. BIR carries one opcode for each of those two and the NVIDIA and AMD backends read it with opposite signedness, so they stay out of reach until the IR can say which is meant - `--bir-in` reads the subset the frontends emit, not all of BIR. Round-tripping the sample corpus is 45 of 103; an opcode or type it does not know is named and refused rather than skipped - Soft-float for the Tenstorrent native RV32IM path. The runtime exists and validates against host FPU; wiring it into `--rv-elf` is a sitting's work away. diff --git a/docs/roadmap.md b/docs/roadmap.md index aa9b15d..978dc41 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -47,7 +47,6 @@ Booth takes seven inputs. They all meet at BIR and go down the same pipeline. | HIP | `--hip`, or a `.hip` file | Macro layer over the CUDA path | | Triton | `--triton` | Python subset, `tl.*`, `tl.dot` on the CPU backend | | Fortran | via LFortran | `do concurrent`, elementwise, SLATEC-checked in CI | -| MLIR | `--mlir` | `func`, `return` and `arith`. No LLVM in the path | | OCaml | via `kcomp` | Kernels as typed OCaml functions | | BIR text | `--bir-in` | What `--ir` prints, read back in | @@ -55,9 +54,6 @@ What each still owes: - **Triton** — rank-2 tiles refuse on GPU targets with E099. `tl.load` masks are not honoured on the CPU backend. -- **MLIR** — no `memref`, `scf` or `gpu` dialect. A function body with more than - one block is refused rather than flattened, and nothing marks an MLIR function - as a kernel, so it lowers as a device function. - **OCaml** — no `while` and no early exit, no `f64`, no warp shuffles, and no atomic min or max until the IR question above is settled. - **Fortran** — This is more LFortran work than on Booth as Fortran already has GPU support through `do concurrent`. I'm working on the LFortran compiler at the moment to shore up some support around legacy f77 Fortran and also send a patch upstream so I can get Fortran compiling to GPUs properly rather than the limited subset. diff --git a/docs/usage.md b/docs/usage.md index 168b63a..bda6ef5 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -119,7 +119,7 @@ Hand `kath` more than one `.cu` and each is compiled on its own, then linked int Each file gets a fresh preprocessor, lexer, parser and sema, so a macro, typedef or struct in one cannot reach the next, and two files may each keep their own `static` helper of the same name without either calling the other's. Anything not marked `static` is one symbol the whole program shares, so a `__device__` function, a `__constant__` global, or an `inline` function arriving from a header several files include, all give you one copy rather than one per file. Two files defining the same non-`inline` symbol is E126 rather than a quiet decision about which one wins. -Symbols become visible in the order you list the files, so a `__device__` function has to be defined in a file earlier on the command line than the one calling it. The other way round comes back as E105, unknown function. The other frontends read one document each, so `--triton`, `--mlir` and `--bir-in` still take a single file and will say so if given more. +Symbols become visible in the order you list the files, so a `__device__` function has to be defined in a file earlier on the command line than the one calling it. The other way round comes back as E105, unknown function. The other frontends read one document each, so `--triton` and `--bir-in` still take a single file and will say so if given more. ## Runtime Launcher @@ -310,32 +310,3 @@ abstract. Both take a literal, not an expression. This is not OCaml running on a GPU. It is OCaml as the language you write the kernel in. There is no GC, no closure at runtime, no exception and no polymorphism on the device. CUDA C is not C either so it does track (gpu's are weird).. - -## MLIR - -`--mlir` reads MLIR text. The reader is Ondřej Čertík's, vendored under -`src/mlir/vendor`, and there is no LLVM in the path. - -```bash -# Lower MLIR and compile it, same as any other frontend -./kath --mlir kernel.mlir --cpu -o kernel.o -./kath --mlir kernel.mlir --rv64 -o kernel.o - -# Dump the BIR the lowering produced -./kath --mlir --ir kernel.mlir - -# Reprint what was read instead of lowering it, for telling a misreading -# from a bad file -./kath --mlir --pp kernel.mlir -``` - -Accepted today: `func.func` with named arguments, `return`, `arith.constant`, -every `arith` integer and float binop, `arith.cmpi` and `arith.cmpf`, and the -`arith` conversions. Anything else is named on stderr and the whole lowering -fails, because an op skipped quietly is a kernel that compiles and computes -something different. - -Nothing in MLIR marks a function as a kernel yet, so everything lowers as a -device function. `--cpu` and `--rv64` give you real code; the GPU backends will -take the file and then report zero kernels, which is an honest answer until -the `gpu` dialect arrives. diff --git a/src/exec/verbs.c b/src/exec/verbs.c index f335c14..8454a10 100644 --- a/src/exec/verbs.c +++ b/src/exec/verbs.c @@ -116,7 +116,7 @@ static int is_source(const char *file) { const char *e = ext_of(file); return streq(e, "cu") || streq(e, "hip") || streq(e, "py") - || streq(e, "mlir") || streq(e, "bir") || streq(e, "ml") + || streq(e, "bir") || streq(e, "ml") || streq(e, "f90"); } @@ -249,7 +249,6 @@ static int build_source(const char *file, const char *bflag, } const char *ffe = NULL; if (streq(e, "py")) ffe = "--triton"; - else if (streq(e, "mlir")) ffe = "--mlir"; else if (streq(e, "bir")) ffe = "--bir-in"; else if (streq(e, "hip")) ffe = "--hip"; return compile3(ffe, bflag, file, out, ko); @@ -391,7 +390,6 @@ static int verb_build(int argc, char **argv) if (streq(e, "f90")) { if (cvt_f90(file, conv, sizeof conv) != 0) return 1; src = conv; } else if (streq(e, "ml")) { if (cvt_ml(file, conv, sizeof conv) != 0) return 1; src = conv; ffe = "--bir-in"; } else if (streq(e, "py")) ffe = "--triton"; - else if (streq(e, "mlir")) ffe = "--mlir"; else if (streq(e, "bir")) ffe = "--bir-in"; char *av[MAXPASS + 8]; int n = 0; diff --git a/src/main.c b/src/main.c index 430f211..6ce8cb8 100644 --- a/src/main.c +++ b/src/main.c @@ -17,9 +17,7 @@ #include "metal.h" #include "intel.h" #include "triton.h" -#include "mlir/mlir_fe.h" #include "bir_parse.h" -#include "mlir/mlir_lower.h" #include "tdf.h" #include "rv_buf.h" #include "rv_elf.h" @@ -462,7 +460,6 @@ static void usage(const char *prog) " hard failure again and a build lists every gap\n" " --hip HIP frontend mode (predefines __HIPCC__ and platform macros;\n" " auto-on for .hip files; combine with --amdgpu-bin or --nvidia-ptx)\n" - " --mlir Read MLIR text. Core dialects only, anything else is refused\n" " --triton Triton frontend mode (parses Python source). Pair with a target\n" " backend (--cpu, --amdgpu-bin, --nvidia-ptx). tl.dot matmul runs.\n" " --cpu x86-64 host backend; emits a normal object you can link and run\n" @@ -502,7 +499,6 @@ int kath_compile(int argc, char *argv[], kath_out_t *out) int mode_tdf_fission = 0; int mode_hip = 0; int mode_triton = 0; /* Triton frontend: see TRITON NOTES below */ - int mode_mlir = 0; /* MLIR frontend: see MLIR NOTES below */ int mode_bir_in = 0; /* BIR text in: see BIR NOTES below */ int mode_chost = 0; const char *fat_file = NULL; @@ -559,8 +555,6 @@ int kath_compile(int argc, char *argv[], kath_out_t *out) mode_hip = 1; else if (strcmp(argv[i], "--triton") == 0) mode_triton = 1; - else if (strcmp(argv[i], "--mlir") == 0) - mode_mlir = 1; else if (strcmp(argv[i], "--tt-chip") == 0 && i + 1 < argc) { if (td_pchip(argv[++i], &tt_chip) != BC_OK) { fprintf(stderr, "unknown Tenstorrent chip: %s " @@ -662,8 +656,8 @@ int kath_compile(int argc, char *argv[], kath_out_t *out) /* Load translation file before any diagnostics fire */ if (lang_file) bc_eload(lang_file); - if (nfile > 1 && (mode_bir_in || mode_mlir || mode_triton)) { - fprintf(stderr, "only one input file for --bir-in, --mlir " + if (nfile > 1 && (mode_bir_in || mode_triton)) { + fprintf(stderr, "only one input file for --bir-in " "and --triton (%d given)\n", nfile); return 1; } @@ -707,57 +701,6 @@ int kath_compile(int argc, char *argv[], kath_out_t *out) return brc; } - /* ---- MLIR NOTES --------------------------------------------------- - * MLIR arrives already structured, so there is no lexer, parser or - * sema on this path. src/mlir/vendor/ reads the text, src/mlir/lower.c - * walks it into BIR, and from there it is the same pipeline CUDA and - * Triton use. --pp reprints what was read instead, which is the - * quickest way to tell a misreading from a bad file. */ - if (mode_mlir) { - ml_ctx_t *mc = ml_open(64u * 1024u * 1024u); - int mrc; - - if (!mc) { - fprintf(stderr, "mlir: out of memory\n"); - return 1; - } - mrc = ml_parse(mc, source_buf, src_len); - if (mrc != 0) { - ml_close(mc); - return 1; - } - if (mode_pp) { - mrc = ml_echo(mc, stdout); - ml_close(mc); - return mrc == 0 ? 0 : 1; - } - - bir_module = (bir_module_t *)malloc(sizeof(bir_module_t)); - if (!bir_module) { - fprintf(stderr, "error: failed to allocate BIR module\n"); - ml_close(mc); - return 1; - } - mrc = ml_lowr(mc, (struct bir_module *)bir_module); - ml_close(mc); - - if (mrc == 0) { - backend_cfg_t cfg = {0}; - cfg.no_mem2reg = no_mem2reg; - cfg.no_cfold = no_cfold; - cfg.no_dce = no_dce; - cfg.no_sched = no_sched; - cfg.no_sroa = no_sroa; - cfg.mode_ir = mode_ir; - cfg.mode_tdf = mode_tdf; - cfg.mode_tdf_fission = mode_tdf_fission; - cfg.output_file = output_file; - mrc = (run_bir_backends(bir_module, &cfg) == BC_OK) ? 0 : 1; - } - free(bir_module); - return mrc == 0 ? 0 : 1; - } - /* ---- TRITON NOTES ------------------------------------------------- * The Triton frontend is a parallel input path that does not share * the C99 preprocessor or lexer. When --triton is on, we route the diff --git a/src/mlir/lower.c b/src/mlir/lower.c deleted file mode 100644 index aebe03a..0000000 --- a/src/mlir/lower.c +++ /dev/null @@ -1,591 +0,0 @@ -/* MLIR to BIR. Anyone can define a dialect, so MLIR has no natural boundary - * and this one is ours. An op off the list is named and refused, never - * skipped, because a skipped op compiles and computes the wrong thing. */ - -#include - -#include - -#include "mlir_api.h" -#include "mlir_op_names.h" -#include "mlir_fe.h" -#include "mlir_lower.h" - -#include "barracuda.h" -#include "bir.h" - -/* One module at a time, and the map is 128 KB, so it does not go on a stack. */ -#define LW_MAX_VALS 4096 -#define LW_MAX_ERRS 16 -#define LW_MAX_PARAMS 64 - -typedef struct { - MLIR_ValueHandle key; - string nm; /* register name, see lw_look */ - uint32_t val; -} lw_ent_t; - -typedef struct { - bir_module_t *M; - MLIR_Context *ctx; - uint32_t cur_func; - uint32_t cur_block; - lw_ent_t map[LW_MAX_VALS]; - uint32_t nmap; - uint32_t nerr; -} lw_t; - -static lw_t lw; - -/* ---- Refusal ---- */ - -/* A file from an unsupported dialect would print a line per op, so past - * LW_MAX_ERRS we stop talking and keep counting. */ -static void -lw_no(MLIR_OpHandle op, const char *why) -{ - string n; - - if (lw.nerr < LW_MAX_ERRS) { - n = op_type_to_string(MLIR_GetOpType(op)); - if (n.size == 0) - n = MLIR_GetOpName(op); /* unregistered ops keep theirs */ - fprintf(stderr, "E120: mlir: %.*s: %s\n", (int)n.size, n.str, why); - } else if (lw.nerr == LW_MAX_ERRS) { - fprintf(stderr, "E120: mlir: further refusals not printed\n"); - } - lw.nerr++; -} - -/* ---- Value map ---- */ - -static void -lw_bind(MLIR_ValueHandle v, uint32_t bv) -{ - /* A dropped binding surfaces later as an operand with no definition, which - * lw_use refuses against the wrong op, so count it here too. */ - if (!v) - return; - if (lw.nmap >= LW_MAX_VALS) { - lw.nerr++; - return; - } - lw.map[lw.nmap].key = v; - lw.map[lw.nmap].nm = MLIR_GetValueRegisterName(v); - lw.map[lw.nmap].val = bv; - lw.nmap++; -} - -/* Handle first, name second. arith.cmpi and the conversions build a second - * value object for the same %n, so identity alone loses them. Later wins. */ -static uint32_t -lw_look(MLIR_ValueHandle v) -{ - string nm; - uint32_t i; - - for (i = lw.nmap; i > 0; i--) - if (lw.map[i - 1].key == v) - return lw.map[i - 1].val; - - nm = MLIR_GetValueRegisterName(v); - if (nm.size == 0) - return BIR_VAL_NONE; - for (i = lw.nmap; i > 0; i--) - if (lw.map[i - 1].nm.size > 0 && str_eq(lw.map[i - 1].nm, nm)) - return lw.map[i - 1].val; - return BIR_VAL_NONE; -} - -/* ---- Types ---- */ - -/* No width accessor in the reader, so the textual form is what we have. - * Anything unnamed here has no BIR equivalent and is not worth guessing at. */ -static uint32_t -lw_type(MLIR_TypeHandle t) -{ - string s; - char buf[32]; - - if (!t) - return bir_type_void(lw.M); - - s = MLIR_GetTypeString(lw.ctx, t); - if (s.size == 0 || s.size >= sizeof buf) - return 0; - memcpy(buf, s.str, (size_t)s.size); - buf[s.size] = '\0'; - - if (strcmp(buf, "i1") == 0) return bir_type_int(lw.M, 1); - if (strcmp(buf, "i8") == 0) return bir_type_int(lw.M, 8); - if (strcmp(buf, "i16") == 0) return bir_type_int(lw.M, 16); - if (strcmp(buf, "i32") == 0) return bir_type_int(lw.M, 32); - if (strcmp(buf, "i64") == 0) return bir_type_int(lw.M, 64); - if (strcmp(buf, "f16") == 0) return bir_type_float(lw.M, 16); - if (strcmp(buf, "f32") == 0) return bir_type_float(lw.M, 32); - if (strcmp(buf, "f64") == 0) return bir_type_float(lw.M, 64); - if (strcmp(buf, "bf16") == 0) return bir_type_bfloat(lw.M); - /* index is whatever the target's pointer arithmetic wants, 64 for now. */ - if (strcmp(buf, "index") == 0) return bir_type_int(lw.M, 64); - - return 0; /* type 0 is the sentinel, so this reads as "no idea" */ -} - -/* ---- Emission ---- */ - -static uint32_t -lw_emit(int op, uint32_t type, int subop) -{ - bir_module_t *M = lw.M; - uint32_t idx; - bir_inst_t *I; - int k; - - if (M->num_insts >= BIR_MAX_INSTS) { - bir_pfull(M, BIR_P_INSTS); - return BIR_VAL_NONE; - } - idx = M->num_insts++; - I = &M->insts[idx]; - I->op = (uint16_t)op; - I->num_operands = 0; - I->subop = (uint8_t)subop; - I->type = type; - for (k = 0; k < BIR_OPERANDS_INLINE; k++) - I->operands[k] = BIR_VAL_NONE; - M->blocks[lw.cur_block].num_insts++; - return BIR_MAKE_VAL(idx); -} - -static void -lw_arg(uint32_t inst, uint32_t operand) -{ - bir_inst_t *I; - uint32_t idx; - - if (inst == BIR_VAL_NONE || BIR_VAL_IS_CONST(inst)) - return; - idx = BIR_VAL_INDEX(inst); - if (idx >= lw.M->num_insts) - return; - I = &lw.M->insts[idx]; - if (I->num_operands < BIR_OPERANDS_INLINE) - I->operands[I->num_operands++] = operand; -} - -/* Named because string offset 0 is a live string, so a nameless block is - * labelled with whatever went into the table first. */ -static uint32_t -lw_block(const char *name) -{ - bir_module_t *M = lw.M; - bir_func_t *F; - uint32_t idx; - - /* Block 0 is real, so a refusal answered with it hands back someone else's - * block. Record it and let bir_pchk stop the compile. */ - if (M->num_blocks >= BIR_MAX_BLOCKS) { - bir_pfull(M, BIR_P_BLOCKS); - return 0; - } - idx = M->num_blocks++; - M->blocks[idx].name = bir_add_string(M, name, (uint32_t)strlen(name)); - M->blocks[idx].first_inst = M->num_insts; - M->blocks[idx].num_insts = 0; - F = &M->funcs[lw.cur_func]; - if (F->num_blocks == 0) - F->first_block = idx; - F->num_blocks++; - return idx; -} - -/* ---- Operands ---- */ - -/* Unbound means we refused the op that should have defined it. */ -static uint32_t -lw_use(MLIR_OpHandle op, size_t i) -{ - MLIR_ValueHandle v = MLIR_GetOpOperand(op, i); - uint32_t bv = lw_look(v); - - if (bv == BIR_VAL_NONE) - lw_no(op, "operand has no lowered definition"); - return bv; -} - -/* ---- arith ---- */ - -static int -lw_pred(string p) -{ - char buf[8]; - - if (p.size == 0 || p.size >= sizeof buf) - return -1; - memcpy(buf, p.str, (size_t)p.size); - buf[p.size] = '\0'; - - if (strcmp(buf, "eq") == 0) return BIR_ICMP_EQ; - if (strcmp(buf, "ne") == 0) return BIR_ICMP_NE; - if (strcmp(buf, "slt") == 0) return BIR_ICMP_SLT; - if (strcmp(buf, "sle") == 0) return BIR_ICMP_SLE; - if (strcmp(buf, "sgt") == 0) return BIR_ICMP_SGT; - if (strcmp(buf, "sge") == 0) return BIR_ICMP_SGE; - if (strcmp(buf, "ult") == 0) return BIR_ICMP_ULT; - if (strcmp(buf, "ule") == 0) return BIR_ICMP_ULE; - if (strcmp(buf, "ugt") == 0) return BIR_ICMP_UGT; - if (strcmp(buf, "uge") == 0) return BIR_ICMP_UGE; - return -1; -} - -static int -lw_fpred(string p) -{ - char buf[8]; - - if (p.size == 0 || p.size >= sizeof buf) - return -1; - memcpy(buf, p.str, (size_t)p.size); - buf[p.size] = '\0'; - - if (strcmp(buf, "oeq") == 0) return BIR_FCMP_OEQ; - if (strcmp(buf, "one") == 0) return BIR_FCMP_ONE; - if (strcmp(buf, "olt") == 0) return BIR_FCMP_OLT; - if (strcmp(buf, "ole") == 0) return BIR_FCMP_OLE; - if (strcmp(buf, "ogt") == 0) return BIR_FCMP_OGT; - if (strcmp(buf, "oge") == 0) return BIR_FCMP_OGE; - if (strcmp(buf, "ueq") == 0) return BIR_FCMP_UEQ; - if (strcmp(buf, "une") == 0) return BIR_FCMP_UNE; - if (strcmp(buf, "ult") == 0) return BIR_FCMP_ULT; - if (strcmp(buf, "ule") == 0) return BIR_FCMP_ULE; - if (strcmp(buf, "ugt") == 0) return BIR_FCMP_UGT; - if (strcmp(buf, "uge") == 0) return BIR_FCMP_UGE; - if (strcmp(buf, "ord") == 0) return BIR_FCMP_ORD; - if (strcmp(buf, "uno") == 0) return BIR_FCMP_UNO; - return -1; -} - -/* Two operands in, one result out, which covers every arith binop we take. */ -static uint32_t -lw_bin(MLIR_OpHandle op, int birop, uint32_t ty) -{ - uint32_t a = lw_use(op, 0); - uint32_t b = lw_use(op, 1); - uint32_t r; - - if (a == BIR_VAL_NONE || b == BIR_VAL_NONE) - return BIR_VAL_NONE; - r = lw_emit(birop, ty, 0); - lw_arg(r, a); - lw_arg(r, b); - return r; -} - -static uint32_t -lw_const(MLIR_OpHandle op, uint32_t ty) -{ - MLIR_AttributeHandle a = MLIR_GetOpAttributeByName(op, "value"); - MLIR_AttrKind k; - - if (!a) { - lw_no(op, "constant with no value attribute"); - return BIR_VAL_NONE; - } - k = MLIR_GetAttributeKind(a); - - /* The result type decides, not how the literal was written. The reader - * builds `1 : f32` as an integer attribute, and trusting that put the bits - * 0x1 where 1.0f belonged, quietly. */ - if (ty < lw.M->num_types && lw.M->types[ty].kind == BIR_TYPE_FLOAT) { - if (k == MLIR_ATTR_KIND_FLOAT) - return BIR_MAKE_CONST(bir_const_float(lw.M, ty, MLIR_GetAttributeFloat(a))); - if (k == MLIR_ATTR_KIND_INTEGER) - return BIR_MAKE_CONST(bir_const_float(lw.M, ty, - (double)MLIR_GetAttributeInteger(a))); - lw_no(op, "float constant has no numeric value"); - return BIR_VAL_NONE; - } - - if (k == MLIR_ATTR_KIND_INTEGER) - return BIR_MAKE_CONST(bir_const_int(lw.M, ty, MLIR_GetAttributeInteger(a))); - if (k == MLIR_ATTR_KIND_BOOL) - return BIR_MAKE_CONST(bir_const_int(lw.M, ty, MLIR_GetAttributeBool(a) ? 1 : 0)); - - /* A float literal on an integer type is not something to round silently. */ - lw_no(op, "constant value does not match its type"); - return BIR_VAL_NONE; -} - -/* One operand, so not lw_bin, which would refuse on the missing second. */ -static uint32_t -lw_un(MLIR_OpHandle op, int birop, uint32_t ty) -{ - uint32_t a = lw_use(op, 0); - uint32_t r; - - if (a == BIR_VAL_NONE) - return BIR_VAL_NONE; - r = lw_emit(birop, ty, 0); - lw_arg(r, a); - return r; -} - -/* ---- Operations ---- */ - -static void -lw_op(MLIR_OpHandle op) -{ - MLIR_OpType kind = MLIR_GetOpType(op); - uint32_t ty = 0; - uint32_t r = BIR_VAL_NONE; - int pred; - - if (MLIR_GetOpNumResultTypes(op) > 0) { - ty = lw_type(MLIR_GetOpResult_type(op, 0)); - if (ty == 0) { - lw_no(op, "result type has no BIR equivalent"); - return; - } - } - - switch (kind) { - case OP_TYPE_ARITH_CONSTANT: r = lw_const(op, ty); break; - - case OP_TYPE_ARITH_ADDI: r = lw_bin(op, BIR_ADD, ty); break; - case OP_TYPE_ARITH_SUBI: r = lw_bin(op, BIR_SUB, ty); break; - case OP_TYPE_ARITH_MULI: r = lw_bin(op, BIR_MUL, ty); break; - case OP_TYPE_ARITH_DIVSI: r = lw_bin(op, BIR_SDIV, ty); break; - case OP_TYPE_ARITH_DIVUI: r = lw_bin(op, BIR_UDIV, ty); break; - case OP_TYPE_ARITH_REMSI: r = lw_bin(op, BIR_SREM, ty); break; - case OP_TYPE_ARITH_REMUI: r = lw_bin(op, BIR_UREM, ty); break; - case OP_TYPE_ARITH_ADDF: r = lw_bin(op, BIR_FADD, ty); break; - case OP_TYPE_ARITH_SUBF: r = lw_bin(op, BIR_FSUB, ty); break; - case OP_TYPE_ARITH_MULF: r = lw_bin(op, BIR_FMUL, ty); break; - case OP_TYPE_ARITH_DIVF: r = lw_bin(op, BIR_FDIV, ty); break; - case OP_TYPE_ARITH_ANDI: r = lw_bin(op, BIR_AND, ty); break; - case OP_TYPE_ARITH_ORI: r = lw_bin(op, BIR_OR, ty); break; - case OP_TYPE_ARITH_XORI: r = lw_bin(op, BIR_XOR, ty); break; - case OP_TYPE_ARITH_SHLI: r = lw_bin(op, BIR_SHL, ty); break; - case OP_TYPE_ARITH_SHRUI: r = lw_bin(op, BIR_LSHR, ty); break; - case OP_TYPE_ARITH_SHRSI: r = lw_bin(op, BIR_ASHR, ty); break; - - case OP_TYPE_ARITH_CMPI: - pred = lw_pred(MLIR_GetAttributeString(MLIR_GetOpAttributeByName(op, "predicate"))); - if (pred < 0) { lw_no(op, "unknown integer compare predicate"); return; } - r = lw_bin(op, BIR_ICMP, ty); - if (r != BIR_VAL_NONE) - lw.M->insts[BIR_VAL_INDEX(r)].subop = (uint8_t)pred; - break; - - case OP_TYPE_ARITH_CMPF: - pred = lw_fpred(MLIR_GetAttributeString(MLIR_GetOpAttributeByName(op, "predicate"))); - if (pred < 0) { lw_no(op, "unknown float compare predicate"); return; } - r = lw_bin(op, BIR_FCMP, ty); - if (r != BIR_VAL_NONE) - lw.M->insts[BIR_VAL_INDEX(r)].subop = (uint8_t)pred; - break; - - case OP_TYPE_ARITH_EXTSI: r = lw_un(op, BIR_SEXT, ty); break; - case OP_TYPE_ARITH_EXTUI: r = lw_un(op, BIR_ZEXT, ty); break; - case OP_TYPE_ARITH_TRUNCI: r = lw_un(op, BIR_TRUNC, ty); break; - case OP_TYPE_ARITH_SITOFP: r = lw_un(op, BIR_SITOFP, ty); break; - case OP_TYPE_ARITH_FPTOSI: r = lw_un(op, BIR_FPTOSI, ty); break; - - case OP_TYPE_RETURN: - case OP_TYPE_FUNC_RETURN: { - uint32_t v; - - r = lw_emit(BIR_RET, bir_type_void(lw.M), 0); - if (MLIR_GetOpNumOperands(op) > 0) { - v = lw_use(op, 0); - if (v != BIR_VAL_NONE) - lw_arg(r, v); - } - return; /* a return defines nothing */ - } - - default: - lw_no(op, "op is outside the accepted subset"); - return; - } - - if (r == BIR_VAL_NONE) - return; - if (MLIR_GetOpNumResults(op) > 0) - lw_bind(MLIR_GetOpResult(op, 0), r); -} - -/* ---- Functions ---- */ - -static uint32_t -lw_rety(const bir_module_t *M, const bir_func_t *F, uint32_t dflt) -{ - uint32_t b, j; - - for (b = 0; b < F->num_blocks && F->first_block + b < M->num_blocks; b++) { - const bir_block_t *B = &M->blocks[F->first_block + b]; - - for (j = 0; j < B->num_insts && B->first_inst + j < M->num_insts; j++) { - const bir_inst_t *I = &M->insts[B->first_inst + j]; - uint32_t v; - - if (I->op != BIR_RET || I->num_operands < 1) continue; - v = I->operands[0]; - if (v == BIR_VAL_NONE) continue; - if (BIR_VAL_IS_CONST(v)) - return BIR_VAL_INDEX(v) < M->num_consts - ? M->consts[BIR_VAL_INDEX(v)].type : dflt; - return BIR_VAL_INDEX(v) < M->num_insts - ? M->insts[BIR_VAL_INDEX(v)].type : dflt; - } - } - return dflt; -} - -static void -lw_func(MLIR_OpHandle op) -{ - bir_module_t *M = lw.M; - bir_func_t *F; - MLIR_AttributeHandle nm; - MLIR_RegionHandle body; - MLIR_BlockHandle entry; - uint32_t ptypes[LW_MAX_PARAMS]; - uint32_t ret = 0; - size_t np, i, nb, j; - string s; - - if (M->num_funcs >= BIR_MAX_FUNCS) { - bir_pfull(M, BIR_P_FUNCS); - lw_no(op, "too many functions"); - return; - } - if (MLIR_GetOpNumRegions(op) == 0) { - /* A declaration with no body. Nothing to emit and nothing wrong. */ - return; - } - - lw.cur_func = M->num_funcs++; - F = &M->funcs[lw.cur_func]; - memset(F, 0, sizeof *F); - - nm = MLIR_GetOpAttributeByName(op, "sym_name"); - if (nm) { - s = MLIR_GetAttributeString(nm); - F->name = bir_add_string(M, s.str, (uint32_t)s.size); - } - - /* Never a kernel. MLIR marks those with a gpu.kernel attribute and the - * reader skips the attributes clause without recording it, so there is - * nothing to read and guessing would promote every helper. */ - F->cuda_flags = CUDA_DEVICE; - - body = MLIR_GetOpRegion(op, 0); - if (!body || MLIR_GetRegionNumBlocks(body) == 0) { - lw_no(op, "function body has no blocks"); - return; - } - entry = MLIR_GetRegionBlock(body, 0); - - /* The reader binds the header's arguments onto the entry block. */ - np = MLIR_GetBlockNumArgs(entry); - if (np > LW_MAX_PARAMS) { - lw_no(op, "too many parameters"); - return; - } - - lw.cur_block = lw_block("entry"); - - for (i = 0; i < np; i++) { - MLIR_ValueHandle a = MLIR_GetBlockArg(entry, i); - uint32_t t = lw_type(MLIR_GetValueType(a)); - uint32_t p; - - if (t == 0) { - lw_no(op, "parameter type has no BIR equivalent"); - return; - } - ptypes[i] = t; - p = lw_emit(BIR_PARAM, t, (int)i); - lw_bind(a, p); - } - F->num_params = (uint16_t)np; - - if (MLIR_GetOpNumResultTypes(op) > 0) - ret = lw_type(MLIR_GetOpResult_type(op, 0)); - if (ret == 0) - ret = bir_type_void(M); - F->type = bir_type_func(M, ret, ptypes, (int)np); - - /* Branches are not lowered yet, so more than one block is refused rather - * than run straight through. */ - nb = MLIR_GetRegionNumBlocks(body); - if (nb > 1) { - lw_no(op, "multi-block function bodies need scf or cf lowering"); - return; - } - - for (j = 0; j < MLIR_GetBlockNumOps(entry); j++) - lw_op(MLIR_GetBlockOp(entry, j)); - - /* Every block ends in a terminator, whatever the source did. */ - { - bir_block_t *B = &M->blocks[lw.cur_block]; - if (B->num_insts == 0 || - M->insts[B->first_inst + B->num_insts - 1].op != BIR_RET) - (void)lw_emit(BIR_RET, bir_type_void(M), 0); - } - F->type = bir_type_func(M, lw_rety(M, F, ret), ptypes, (int)np); - - for (j = 0; j < F->num_blocks; j++) - F->total_insts += M->blocks[F->first_block + j].num_insts; -} - -/* ---- Entry ---- */ - -int -ml_lowr(const ml_ctx_t *C, struct bir_module *Mp) -{ - bir_module_t *M = (bir_module_t *)Mp; - MLIR_OpHandle root; - MLIR_RegionHandle r; - MLIR_BlockHandle b; - size_t i; - - root = (MLIR_OpHandle)(uintptr_t)ml_root(C); - if (!root || !M) - return -1; - - memset(&lw, 0, sizeof lw); - lw.M = M; - lw.ctx = (MLIR_Context *)ml_ctx(C); - - bir_module_init(M); - - if (MLIR_GetOpType(root) != OP_TYPE_MODULE) { - lw_no(root, "top level is not a module"); - return -1; - } - if (MLIR_GetOpNumRegions(root) == 0) - return 0; /* an empty module is a module */ - - r = MLIR_GetOpRegion(root, 0); - if (!r || MLIR_GetRegionNumBlocks(r) == 0) - return 0; - b = MLIR_GetRegionBlock(r, 0); - - for (i = 0; i < MLIR_GetBlockNumOps(b); i++) { - MLIR_OpHandle op = MLIR_GetBlockOp(b, i); - - if (MLIR_GetOpType(op) == OP_TYPE_FUNC_FUNC) - lw_func(op); - else - lw_no(op, "only func.func is accepted at module level"); - } - - if (lw.nerr > 0) { - fprintf(stderr, "E120: mlir: %u op(s) refused, nothing emitted\n", lw.nerr); - return -1; - } - return bir_pchk(M, "mlir lowering") == BC_OK ? 0 : -1; -} diff --git a/src/mlir/mlir_fe.c b/src/mlir/mlir_fe.c deleted file mode 100644 index 6679b16..0000000 --- a/src/mlir/mlir_fe.c +++ /dev/null @@ -1,128 +0,0 @@ -/* MLIR frontend boundary. See mlir_fe.h. The reader normally owns _start, so - * platform_*.c is built with PLATFORM_SKIP_ENTRY and we bring corec's heap up - * ourselves the first time anyone asks for a context. */ - -#include -#include - -#include -#include -#include - -#include "mlir_api.h" -#include "mlir_parser.h" -#include "mlir_fe.h" - -struct ml_ctx { - Arena *arena; - MLIR_Context ctx; - MLIR_OpHandle root; - int dead; /* a failed parse leaves the reader mid-descent */ -}; - -/* One mmap, process-wide, so this happens once however many contexts open. */ -static int ml_up = 0; - -/* Where mlir_parse_fail lands, set only across one parse. */ -static jmp_buf ml_bail; -static int ml_catching = 0; - -void -mlir_parse_fail(void) -{ - if (ml_catching) - longjmp(ml_bail, 1); - - /* Nothing to unwind to, so the standalone behaviour is the honest one. */ - exit(1); -} - -ml_ctx_t * -ml_open(size_t arena_bytes) -{ - ml_ctx_t *C; - - if (!ml_up) { - platform_init(0, NULL, NULL); - ml_up = 1; - } - - C = (ml_ctx_t *)calloc(1, sizeof *C); - if (!C) - return NULL; - - C->arena = arena_create(arena_bytes); - if (!C->arena) { - free(C); - return NULL; - } - MLIR_SetArenaAllocator(&C->ctx, C->arena); - return C; -} - -void -ml_close(ml_ctx_t *C) -{ - if (!C) - return; - - /* The interning caches hold handles into this arena. Upstream assumes one - * context per process, we do not, and a stale one is a walk through freed - * memory on the next parse rather than anything that announces itself. */ - MLIR_ResetInternRegistry(); - arena_destroy(C->arena); - free(C); -} - -int -ml_parse(ml_ctx_t *C, const char *src, size_t len) -{ - if (!C || !src || C->dead) - return -1; - - /* Clearing the interning tables is what makes a module self-contained. - * Every type it names is interned afresh into this context's arena, so - * nothing outlives its own ml_close. The cost is cross-module dedup. */ - MLIR_ResetInternRegistry(); - - /* Unwinding abandons whatever the reader had half built, which is safe - * only because it all came from our arena. The context is done after - * that though, since the reader's statics are past saving. */ - ml_catching = 1; - if (setjmp(ml_bail)) { - ml_catching = 0; - C->dead = 1; - C->root = 0; - return -1; - } - C->root = MLIR_ParseTextClassic(&C->ctx, - str_from_cstr_len_view_const(src, len)); - ml_catching = 0; - return C->root ? 0 : -1; -} - -void * -ml_root(const ml_ctx_t *C) -{ - return (C && C->root) ? (void *)C->root : NULL; -} - -void * -ml_ctx(const ml_ctx_t *C) -{ - return C ? (void *)&C->ctx : NULL; -} - -int -ml_echo(const ml_ctx_t *C, FILE *out) -{ - string s; - - if (!C || !C->root) - return -1; - - /* Const off only because the printer allocates into the arena. */ - s = MLIR_PrintOperationClassic((MLIR_Context *)&C->ctx, C->root); - fprintf(out, "%.*s", (int)s.size, s.str); - return 0; -} diff --git a/src/mlir/mlir_fe.h b/src/mlir/mlir_fe.h deleted file mode 100644 index d76ee78..0000000 --- a/src/mlir/mlir_fe.h +++ /dev/null @@ -1,29 +0,0 @@ -/* MLIR frontend boundary. Booth is c99 and the vendored reader is not, so - * nothing of corec's or MLIR's may appear here. Opaque pointers only. */ - -#ifndef MLIR_FE_H -#define MLIR_FE_H - -#include -#include - -typedef struct ml_ctx ml_ctx_t; - -/* Parsing never allocates outside the arena, so a module that does not fit is - * a refusal rather than a crawl into swap. A parsed module owns everything it - * names, which costs ml_parse a reset and rules out calling it from threads. */ -ml_ctx_t *ml_open(size_t arena_bytes); -void ml_close(ml_ctx_t *C); - -/* Returns 0 on success. The reader reports its own syntax errors on stderr. */ -int ml_parse(ml_ctx_t *C, const char *src, size_t len); - -/* Reprints what was read, which is how you tell a misreading from a bad file. */ -int ml_echo(const ml_ctx_t *C, FILE *out); - -/* MLIR handles, for lower.c only. Opaque so nothing else is tempted, and null - * before a successful ml_parse. */ -void *ml_root(const ml_ctx_t *C); -void *ml_ctx(const ml_ctx_t *C); - -#endif diff --git a/src/mlir/mlir_lower.h b/src/mlir/mlir_lower.h deleted file mode 100644 index d17d125..0000000 --- a/src/mlir/mlir_lower.h +++ /dev/null @@ -1,19 +0,0 @@ -/* MLIR to BIR. See lower.c. - * - * Split from mlir_fe.h so a caller that only wants to read MLIR does not have - * to pull in the IR headers. - */ - -#ifndef MLIR_LOWER_H -#define MLIR_LOWER_H - -#include "mlir_fe.h" - -struct bir_module; - -/* Fills M from the module C last parsed. Returns 0 on success. Any op outside - * the accepted subset is named on stderr and the whole lowering fails; a - * partial module is worse than none. */ -int ml_lowr(const ml_ctx_t *C, struct bir_module *M); - -#endif diff --git a/src/mlir/vendor/LICENSE.corec b/src/mlir/vendor/LICENSE.corec deleted file mode 100644 index f1ebc43..0000000 --- a/src/mlir/vendor/LICENSE.corec +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Ondřej Čertík - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/src/mlir/vendor/LICENSE.mlir b/src/mlir/vendor/LICENSE.mlir deleted file mode 100644 index 1786aa9..0000000 --- a/src/mlir/vendor/LICENSE.mlir +++ /dev/null @@ -1,25 +0,0 @@ -MIT License - -Copyright (c) 2025 Ondřej Čertík - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - --------------------------------------------------------------------------------- -The files in the test_mlir/ directory were copied from public github -repositories and are licensed under their respective upstream licenses. diff --git a/src/mlir/vendor/base/arena.c b/src/mlir/vendor/base/arena.c deleted file mode 100644 index fc4e000..0000000 --- a/src/mlir/vendor/base/arena.c +++ /dev/null @@ -1,202 +0,0 @@ -#include -#include -#include -#include -#include -#include - -// All allocations will be aligned to this boundary (must be a power of two). -#define ARENA_ALIGNMENT 16 -// New chunks will be at least this large. -#define MIN_CHUNK_SIZE 4096 - -// Represents a single chunk of memory obtained from the buddy allocator. -struct arena_chunk { - struct arena_chunk *next; - // Total size of the block returned by buddy_alloc for this chunk. - size_t size; - // The data area for this chunk begins immediately after this struct. -}; - -// The main arena structure. Its definition is hidden from the public API. -struct arena_s { - struct arena_chunk *first_chunk; - struct arena_chunk *current_chunk; - char *current_ptr; - size_t remaining_in_chunk; - size_t default_chunk_size; -}; - -// Aligns a value up to the nearest multiple of ARENA_ALIGNMENT. -static inline uintptr_t align_up(uintptr_t val) { - return (val + ARENA_ALIGNMENT - 1) & ~(uintptr_t)(ARENA_ALIGNMENT - 1); -} - -Arena *arena_create(size_t initial_size) { - // Allocate the arena controller struct itself. - Arena *arena = buddy_alloc(sizeof(Arena), NULL); - if (!arena) { - FATAL_ERROR("buddy_alloc failed for Arena"); - } - - if (initial_size < MIN_CHUNK_SIZE) { - initial_size = MIN_CHUNK_SIZE; - } - arena->default_chunk_size = initial_size; - arena->first_chunk = NULL; - - // Allocate the first chunk. - // Request enough space for the chunk header, the caller's requested size, - // and any padding that might be needed to align the data pointer. - size_t requested_size = sizeof(struct arena_chunk) + initial_size + ARENA_ALIGNMENT; - size_t actual_size; - struct arena_chunk *first = buddy_alloc(requested_size, &actual_size); - if (!first) { - //buddy_free(arena); - FATAL_ERROR("buddy_alloc failed for size"); - } - first->next = NULL; - first->size = actual_size; - - // Initialize arena state to point to the start of the first chunk. - arena->first_chunk = first; - arena->current_chunk = first; - - uintptr_t data_start = align_up((uintptr_t)(first + 1)); - uintptr_t chunk_end = (uintptr_t)first + actual_size; - - arena->current_ptr = (char *)data_start; - arena->remaining_in_chunk = (data_start < chunk_end) ? (chunk_end - data_start) : 0; - - return arena; -} - -void *arena_alloc(Arena *arena, size_t size) { - assert(arena); - assert(size > 0); - - size_t aligned_size = (size + ARENA_ALIGNMENT - 1) & ~(size_t)(ARENA_ALIGNMENT - 1); - -try_alloc: - // If the current chunk has enough space, perform a simple bump allocation. - if (aligned_size <= arena->remaining_in_chunk) { - void *ptr = arena->current_ptr; - arena->current_ptr += aligned_size; - arena->remaining_in_chunk -= aligned_size; - return ptr; - } - - // Not enough space. If a next chunk already exists (from previous use), move to it. - if (arena->current_chunk && arena->current_chunk->next) { - arena->current_chunk = arena->current_chunk->next; - - struct arena_chunk* chunk = arena->current_chunk; - uintptr_t data_start = align_up((uintptr_t)(chunk + 1)); - uintptr_t chunk_end = (uintptr_t)chunk + chunk->size; - - arena->current_ptr = (char *)data_start; - arena->remaining_in_chunk = (data_start < chunk_end) ? (chunk_end - data_start) : 0; - - goto try_alloc; // Retry allocation in the next chunk. - } - - // No more reusable chunks are available, so allocate a new one. - size_t new_chunk_data_size = arena->default_chunk_size; - if (aligned_size > new_chunk_data_size) { - new_chunk_data_size = aligned_size; // Ensure the new chunk is large enough. - } - - // Request: header + data + alignment padding - // The usable data area starts at align_up(chunk + 1), so we may lose up to ARENA_ALIGNMENT bytes - size_t requested_size = sizeof(struct arena_chunk) + new_chunk_data_size + ARENA_ALIGNMENT; - - // Allocate and get the actual size buddy provides (rounded up to power-of-2) - size_t actual_size; - struct arena_chunk *new_chunk = buddy_alloc(requested_size, &actual_size); - if (!new_chunk) { - FATAL_ERROR("buddy_alloc failed"); - } - - new_chunk->next = NULL; - // Store the actual size we got from buddy, not what we requested - new_chunk->size = actual_size; - - // Link the new chunk to the end of the list. - if (arena->current_chunk) { - arena->current_chunk->next = new_chunk; - } else { - arena->first_chunk = new_chunk; - } - arena->current_chunk = new_chunk; - - // Set the allocation pointer to the start of the new chunk. - // data_start is after the arena_chunk header, aligned up - uintptr_t data_start = align_up((uintptr_t)(new_chunk + 1)); - // chunk_end is based on the actual size buddy gave us - uintptr_t chunk_end = (uintptr_t)new_chunk + actual_size; - arena->current_ptr = (char *)data_start; - arena->remaining_in_chunk = (data_start < chunk_end) ? (chunk_end - data_start) : 0; - - // Retry the allocation now that we have a new, sufficiently large chunk. - goto try_alloc; -} - -void arena_destroy(Arena *arena) { - assert(arena); - struct arena_chunk *current = arena->first_chunk; - while (current) { - struct arena_chunk *next = current->next; - buddy_free(current); - current = next; - } - buddy_free(arena); -} - -arena_pos_t arena_get_pos(Arena *arena) { - assert(arena); - return (arena_pos_t){ - .chunk = arena->current_chunk, - .ptr = arena->current_ptr - }; -} - -void arena_reset(Arena *arena, arena_pos_t pos) { - assert(arena); - assert(pos.chunk); - assert(pos.ptr); - - // Restore the state from the saved position - arena->current_chunk = pos.chunk; - arena->current_ptr = pos.ptr; - - // Recalculate the remaining size in the restored chunk - uintptr_t chunk_end = (uintptr_t)pos.chunk + pos.chunk->size; - uintptr_t current_pos = (uintptr_t)pos.ptr; - - arena->remaining_in_chunk = (current_pos < chunk_end) ? (chunk_end - current_pos) : 0; -} - -size_t arena_chunk_count(Arena *arena) { - assert(arena); - - size_t count = 0; - struct arena_chunk *chunk = arena->first_chunk; - while (chunk) { - count++; - chunk = chunk->next; - } - return count; -} - -size_t arena_current_chunk_index(Arena *arena) { - assert(arena); - assert(arena->current_chunk); - - size_t index = 0; - struct arena_chunk *chunk = arena->first_chunk; - while (chunk && chunk != arena->current_chunk) { - index++; - chunk = chunk->next; - } - return index; -} diff --git a/src/mlir/vendor/base/arena.h b/src/mlir/vendor/base/arena.h deleted file mode 100644 index 70e4726..0000000 --- a/src/mlir/vendor/base/arena.h +++ /dev/null @@ -1,143 +0,0 @@ -#pragma once - -#include - -// An opaque data type for the arena allocator. - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct arena_s Arena; - -// Forward-declare the internal chunk struct. This is needed for the arena_pos_t -// but keeps the full definition private to the .c file. -struct arena_chunk; - -/** - * @brief A handle representing a specific position within the arena. - * Use this to save the arena's state and later reset back to it. - */ -typedef struct { - struct arena_chunk *chunk; - char *ptr; -} arena_pos_t; - - -/** - * @brief Creates a new arena allocator. - * - * This function initializes an arena and allocates an initial memory chunk - * from the buddy allocator. - * @param initial_size The suggested size for the first chunk. The actual size - * may be larger to meet alignment and minimum size requirements. - * @return A pointer to the newly created arena, or NULL on failure. - */ -Arena *arena_create(size_t initial_size); - -/** - * @brief Allocates a block of memory from the arena. - * - * Memory is allocated using a bump pointer for high efficiency. If the current - * chunk is full, the arena will advance to the next chunk (if available after a - * reset) or allocate a new one from the buddy system. - * - * @param arena A pointer to the arena. - * @param size The number of bytes to allocate. - * @return A pointer to the allocated memory, aligned to 16 bytes. - * - * The returned pointer is always valid. If the allocation fails it aborts. - */ -void *arena_alloc(Arena *arena, size_t size); - -/** - * @brief Captures the current allocation position in the arena. - * - * @param arena A pointer to the arena. - * @return An arena_pos_t handle that can be used with arena_reset_to(). - */ -arena_pos_t arena_get_pos(Arena *arena); - -/** - * @brief Resets the arena's allocation pointer to a previously saved position. - * - * This invalidates all allocations made since the position was saved, - * making that memory available for new allocations. - * - * Chunks allocated after the saved position are NOT freed. They remain - * linked via the chunk list and will be reused by subsequent allocations: - * once the restored chunk fills up again, arena_alloc walks the existing - * `next` pointers and bump-allocates from those already-allocated chunks - * before requesting new memory from the buddy allocator. The chunks are - * only released when arena_destroy is called. - * - * @param arena A pointer to the arena. - * @param pos The saved position to restore. - */ -void arena_reset(Arena *arena, arena_pos_t pos); - -/** - * @brief Deallocates all memory used by the arena. - * - * This function iterates through all chunks owned by the arena, frees them - * using `buddy_free`, and finally frees the arena structure itself. - * The arena pointer is invalid after this call. - * - * @param arena A pointer to the arena. - */ -void arena_destroy(Arena *arena); - -/** - * @brief Returns the total number of chunks in the arena. - * - * This function walks the chunk linked list to count all chunks. - * Useful for testing and debugging to verify arena expansion. - * - * @param arena A pointer to the arena. - * @return The total number of chunks, or 0 if arena is NULL. - */ -size_t arena_chunk_count(Arena *arena); - -/** - * @brief Returns the index of the current chunk (0-based). - * - * This function walks from the first chunk to the current chunk, - * counting the number of steps. The first chunk has index 0, - * the second chunk has index 1, and so on. - * Useful for testing to verify which chunk allocations are in. - * - * @param arena A pointer to the arena. - * @return The index of the current chunk (0-based), or 0 if arena is NULL. - */ -size_t arena_current_chunk_index(Arena *arena); - -/** - * @brief Convenience macro to allocate a single element of `type` from the arena. - * - * Behaves like C++ `new type`: returns a pointer to one freshly allocated - * `type`, cast to `type *`. The memory is uninitialized. - * - * @param arena A pointer to the arena. - * @param type The type of the element to allocate. - * @return A pointer to the allocated element, cast to `type *`. - */ -#define arena_new(arena, type) \ - ((type *)arena_alloc((arena), sizeof(type))) - -/** - * @brief Convenience macro to allocate an array of `count` elements of `type` - * from the arena. - * - * Behaves like C++ `new type[count]`: returns a pointer to the first element - * of a freshly allocated array, cast to `type *`. The memory is uninitialized. - * - * @param arena A pointer to the arena. - * @param type The type of elements to allocate. - * @param count The number of elements to allocate. - * @return A pointer to the allocated array, cast to `type *`. - */ -#define arena_new_array(arena, type, count) \ - ((type *)arena_alloc((arena), sizeof(type) * (size_t)(count))) -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/assert.c b/src/mlir/vendor/base/assert.c deleted file mode 100644 index b107c41..0000000 --- a/src/mlir/vendor/base/assert.c +++ /dev/null @@ -1,23 +0,0 @@ -#include -#include -#include -#include -#include - -/* After proper strings and formatting, this should just be: - -void corec_assert_fail(const char *assertion, const char *file, unsigned int line, const char *function) { - printf("Assertion failed: (%s) at '%s:%u' in function '%s'\n", assertion, file, line, function); - exit(1); -} - -However, we do not want to depend on arenas working, we only want to use the -lower-level API, no other base dependencies, so that asser() can be used -anywhere in base. -*/ - -void corec_assert_fail(const char *assertion, const char *file, unsigned int line, const char *function) { - // Simple assertion failure handler using only base/ dependencies - writeln_loc(PLATFORM_STDERR_FD, assertion, file, line, function); - platform_exit(1); -} diff --git a/src/mlir/vendor/base/assert.h b/src/mlir/vendor/base/assert.h deleted file mode 100644 index 8203902..0000000 --- a/src/mlir/vendor/base/assert.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -// Base assertion facility - self-contained, no dependencies on stdio/stdlib -// Used by base/ tests and re-exported by stdlib/assert.h -// -// Named corec_assert_fail rather than __assert_fail, which is what a -// freestanding build wants but which glibc also declares and defines. Hosted, -// the declaration is redundant and the definition quietly overrides libc's for -// the whole program. - -#ifdef __cplusplus -extern "C" { -#endif - -void corec_assert_fail(const char *assertion, const char *file, unsigned int line, const char *function); - -#undef assert -#ifdef NDEBUG -#define assert(condition) ((void)0) -#else -#define assert(condition) ((condition) ? (void)0 : corec_assert_fail("Assertion failed '" #condition "'", __FILE__, __LINE__, __func__)) -#endif -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/buddy.c b/src/mlir/vendor/base/buddy.c deleted file mode 100644 index 0ff4456..0000000 --- a/src/mlir/vendor/base/buddy.c +++ /dev/null @@ -1,530 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -#define MIN_PAGE_SIZE 4096UL -#define MAX_ORDER 20 // 2^20 * 4KB = 4GB - -/* - * Header for each memory block (free or allocated). - * This header is stored "inline" at the beginning of each block of memory. - */ -struct buddy_block { - // The order of the block. Positive if free, negative if allocated. - int order; - struct buddy_block *prev; - struct buddy_block *next; -}; - -struct list_head { - struct buddy_block *first; -}; - -// free_lists[i] contains a doubly-linked list of free blocks of order i. -static struct list_head free_lists[MAX_ORDER + 1]; -static void *heap_base; - -static void list_add(struct list_head *lh, struct buddy_block *p) { - p->next = lh->first; - p->prev = NULL; - if (lh->first) { - lh->first->prev = p; - } - lh->first = p; -} - -static void list_remove(struct list_head *lh, struct buddy_block *p) { - if (p->prev) { - p->prev->next = p->next; - } else { - lh->first = p->next; - } - if (p->next) { - p->next->prev = p->prev; - } -} - -static void add_memory(void *mem, size_t bytes) { - uintptr_t start = (uintptr_t)mem; - uintptr_t end = start + bytes; - - // Align start address up to a MIN_PAGE_SIZE boundary - uintptr_t mis = start % MIN_PAGE_SIZE; - if (mis) { - start += MIN_PAGE_SIZE - mis; - } - - // Carve the memory region into the largest possible power-of-two blocks - while (start + MIN_PAGE_SIZE <= end) { - int order = 0; - size_t block_size = MIN_PAGE_SIZE; - while ((block_size << 1) <= (end - start) && (start % (block_size << 1) == 0) && order < MAX_ORDER) { - block_size <<= 1; - order++; - } - - struct buddy_block *p = (struct buddy_block *)start; - p->order = order; - list_add(&free_lists[order], p); - - start += block_size; - } -} - -void buddy_init(void) { - heap_base = platform_heap_base(); - for (int o = 0; o <= MAX_ORDER; o++) { - free_lists[o].first = NULL; - } - size_t initial_size = platform_heap_size(); - if (initial_size > 0) { - add_memory(heap_base, initial_size); - } -} - -// Helper to append a string to a buffer (simple strcat that knows buffer size) -static void str_append_safe(char *dest, const char *src, size_t dest_size) { - size_t dest_len = base_strlen(dest); - size_t src_len = base_strlen(src); - size_t space_left = dest_size - dest_len - 1; // -1 for null terminator - - if (src_len > space_left) { - src_len = space_left; - } - - base_memcpy(dest + dest_len, src, src_len); - dest[dest_len + src_len] = '\0'; -} - -void buddy_print_stats() { - int fd = PLATFORM_STDOUT_FD; - writeln(fd, ""); - writeln(fd, "=== Buddy Allocator Statistics ==="); - writeln(fd, ""); - - // Calculate total free and allocated bytes per order - size_t free_counts[MAX_ORDER + 1]; - size_t allocated_counts[MAX_ORDER + 1]; - size_t total_free_bytes = 0; - size_t total_allocated_bytes = 0; - - for (int o = 0; o <= MAX_ORDER; o++) { - free_counts[o] = 0; - allocated_counts[o] = 0; - } - - // Count free blocks - for (int o = 0; o <= MAX_ORDER; o++) { - struct buddy_block *block = free_lists[o].first; - while (block) { - size_t block_size = MIN_PAGE_SIZE << o; - total_free_bytes += block_size; - free_counts[o]++; - block = block->next; - } - } - - // Count allocated blocks by scanning all committed memory - uintptr_t heap_start = (uintptr_t)heap_base; - uintptr_t heap_end = heap_start + platform_heap_size(); - - // Scan through memory looking for allocated blocks - // This is a heuristic scan - we check each MIN_PAGE_SIZE aligned address - for (uintptr_t addr = heap_start; addr < heap_end; addr += MIN_PAGE_SIZE) { - struct buddy_block *block = (struct buddy_block *)addr; - // Check if this looks like an allocated block (negative order) - if (block->order < 0) { - int order = -block->order - 1; - if (order >= 0 && order <= MAX_ORDER) { - size_t block_size = MIN_PAGE_SIZE << order; - // Verify the block is within bounds and properly aligned - if ((addr % block_size) == 0 && addr + block_size <= heap_end) { - total_allocated_bytes += block_size; - allocated_counts[order]++; - // Skip past this allocated block - addr += block_size - MIN_PAGE_SIZE; // -MIN_PAGE_SIZE because loop adds it - } - } - } - } - - size_t committed_bytes = platform_heap_size(); - - // Helper to print size_t value with label - #define PRINT_SIZE(label, value) do { \ - char buf[32]; \ - size_t len = uint64_to_str((value), buf); \ - buf[len] = '\0'; \ - write_all(fd, (ciovec_t[]){(ciovec_t){(label), base_strlen(label)}}, 1); \ - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); \ - write_all(fd, (ciovec_t[]){(ciovec_t){buf, len}}, 1); \ - write_all(fd, (ciovec_t[]){(ciovec_t){"\n", 1}}, 1); \ - } while(0) - - // Helper to print floating point MiB with 2 decimal places - #define PRINT_MIB(label, bytes) do { \ - double mib = (double)(bytes) / (1024.0 * 1024.0); \ - char buf[32]; \ - size_t len = double_to_str(mib, buf, 2); \ - buf[len] = '\0'; \ - write_all(fd, (ciovec_t[]){(ciovec_t){(label), base_strlen(label)}}, 1); \ - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); \ - write_all(fd, (ciovec_t[]){(ciovec_t){buf, len}}, 1); \ - write_all(fd, (ciovec_t[]){(ciovec_t){"\n", 1}}, 1); \ - } while(0) - - // Print memory overview - writeln(fd, "Memory Overview:"); - PRINT_SIZE(" Committed (bytes): ", committed_bytes); - PRINT_MIB(" Committed (MiB): ", committed_bytes); - PRINT_SIZE(" Free (bytes): ", total_free_bytes); - PRINT_MIB(" Free (MiB): ", total_free_bytes); - PRINT_SIZE(" Allocated (bytes): ", total_allocated_bytes); - PRINT_MIB(" Allocated (MiB): ", total_allocated_bytes); - if (committed_bytes > 0) { - double utilization = ((double)total_allocated_bytes * 100.0) / (double)committed_bytes; - char util_buf[32]; - size_t util_len = double_to_str(utilization, util_buf, 2); - util_buf[util_len] = '\0'; - write_all(fd, (ciovec_t[]){(ciovec_t){" Utilization (%): ", 21}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){util_buf, util_len}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){"\n", 1}}, 1); - } - writeln(fd, ""); - - // Print per-order breakdown (all orders) - writeln(fd, "Per-Order Breakdown (all orders 0-20):"); - writeln(fd, " 'Free' = blocks in free list, 'Allocated' = blocks given to user"); - writeln(fd, "Order BlockSize Free Allocated FreeMiB AllocMiB"); - writeln(fd, "----- -------------- ----- --------- -------- --------"); - - int total_orders_with_free = 0; - int total_orders_with_allocated = 0; - for (int o = 0; o <= MAX_ORDER; o++) { - if (free_counts[o] > 0) total_orders_with_free++; - if (allocated_counts[o] > 0) total_orders_with_allocated++; - } - - for (int o = 0; o <= MAX_ORDER; o++) { - size_t block_size = MIN_PAGE_SIZE << o; - size_t free_bytes = free_counts[o] * block_size; - size_t alloc_bytes = allocated_counts[o] * block_size; - - // Print order (width 5, right-aligned) - char order_str[32]; - size_t order_len = int_to_str(o, order_str); - order_str[order_len] = '\0'; - for (size_t i = order_len; i < 5; i++) { - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); - } - write_all(fd, (ciovec_t[]){(ciovec_t){order_str, order_len}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 2}}, 1); - - // Print block size (width 14, right-aligned) - char size_str[32]; - size_t size_len = uint64_to_str(block_size, size_str); - size_str[size_len] = '\0'; - for (size_t i = size_len; i < 14; i++) { - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); - } - write_all(fd, (ciovec_t[]){(ciovec_t){size_str, size_len}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 2}}, 1); - - // Print free count (width 5, right-aligned) - char free_count_str[32]; - size_t free_count_len = int_to_str((int)free_counts[o], free_count_str); - free_count_str[free_count_len] = '\0'; - for (size_t i = free_count_len; i < 5; i++) { - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); - } - write_all(fd, (ciovec_t[]){(ciovec_t){free_count_str, free_count_len}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 2}}, 1); - - // Print allocated count (width 9, right-aligned) - char alloc_count_str[32]; - size_t alloc_count_len = int_to_str((int)allocated_counts[o], alloc_count_str); - alloc_count_str[alloc_count_len] = '\0'; - for (size_t i = alloc_count_len; i < 9; i++) { - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); - } - write_all(fd, (ciovec_t[]){(ciovec_t){alloc_count_str, alloc_count_len}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 2}}, 1); - - // Print free MiB (width 9, right-aligned, 2 decimal places) - char free_mib_str[32]; - double free_mib = (double)free_bytes / (1024.0 * 1024.0); - size_t free_mib_len = double_to_str(free_mib, free_mib_str, 2); - free_mib_str[free_mib_len] = '\0'; - for (size_t i = free_mib_len; i < 9; i++) { - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); - } - write_all(fd, (ciovec_t[]){(ciovec_t){free_mib_str, free_mib_len}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 2}}, 1); - - // Print alloc MiB (width 9, right-aligned, 2 decimal places) - char alloc_mib_str[32]; - double alloc_mib = (double)alloc_bytes / (1024.0 * 1024.0); - size_t alloc_mib_len = double_to_str(alloc_mib, alloc_mib_str, 2); - alloc_mib_str[alloc_mib_len] = '\0'; - for (size_t i = alloc_mib_len; i < 9; i++) { - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); - } - write_all(fd, (ciovec_t[]){(ciovec_t){alloc_mib_str, alloc_mib_len}}, 1); - - write_all(fd, (ciovec_t[]){(ciovec_t){"\n", 1}}, 1); - } - - // Print summary - writeln(fd, ""); - char summary1[128], summary2[128]; - char free_orders_str[16], alloc_orders_str[16]; - size_t free_orders_len = int_to_str(total_orders_with_free, free_orders_str); - free_orders_str[free_orders_len] = '\0'; - size_t alloc_orders_len = int_to_str(total_orders_with_allocated, alloc_orders_str); - alloc_orders_str[alloc_orders_len] = '\0'; - - base_strcpy(summary1, "Summary: "); - str_append_safe(summary1, free_orders_str, sizeof(summary1)); - str_append_safe(summary1, " orders have free blocks (buddy has memory at these sizes)", sizeof(summary1)); - writeln(fd, summary1); - - base_strcpy(summary2, " "); - str_append_safe(summary2, alloc_orders_str, sizeof(summary2)); - str_append_safe(summary2, " orders have allocated blocks (user is using these sizes)", sizeof(summary2)); - writeln(fd, summary2); - writeln(fd, ""); - - // Print alignment diagnostics for large orders - writeln(fd, "Alignment Diagnostics:"); - writeln(fd, " (Buddy allocator requires blocks to be aligned to their size)"); - uintptr_t current_top = (uintptr_t)heap_base + platform_heap_size(); - - char top_str[32]; - size_t top_len = uint64_to_str(current_top, top_str); - top_str[top_len] = '\0'; - write_all(fd, (ciovec_t[]){(ciovec_t){" Current heap top: ", 23}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){top_str, top_len}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){"\n", 1}}, 1); - - writeln(fd, ""); - writeln(fd, " Alignment status for large orders:"); - for (int o = 9; o <= 14; o++) { - size_t alignment = MIN_PAGE_SIZE << o; - uintptr_t misalignment = current_top % alignment; - size_t size_mib = alignment >> 20; - - char line[128]; - char order_str[32], size_str[32], status[64]; - size_t order_str_len = int_to_str(o, order_str); - order_str[order_str_len] = '\0'; - size_t size_str_len = int_to_str((int)size_mib, size_str); - size_str[size_str_len] = '\0'; - - if (misalignment == 0) { - base_strcpy(status, "ALIGNED"); - } else { - char mis_str[32]; - size_t mis_str_len = uint64_to_str(misalignment, mis_str); - mis_str[mis_str_len] = '\0'; - base_strcpy(status, "MISALIGNED by "); - str_append_safe(status, mis_str, sizeof(status)); - str_append_safe(status, " bytes", sizeof(status)); - } - - base_strcpy(line, " Order "); - str_append_safe(line, order_str, sizeof(line)); - str_append_safe(line, " (", sizeof(line)); - str_append_safe(line, size_str, sizeof(line)); - str_append_safe(line, " MiB): ", sizeof(line)); - str_append_safe(line, status, sizeof(line)); - - writeln(fd, line); - } - writeln(fd, ""); - - // Print warnings - writeln(fd, "DIAGNOSIS:"); - int has_warnings = 0; - for (int o = 9; o <= MAX_ORDER; o++) { - size_t alignment = MIN_PAGE_SIZE << o; - uintptr_t misalignment = current_top % alignment; - if (misalignment != 0 && free_counts[o] == 0) { - if (!has_warnings) { - writeln(fd, " *** ALIGNMENT BUG DETECTED ***"); - writeln(fd, " Cannot allocate large blocks because heap top is misaligned."); - writeln(fd, " Even though memory is available, add_memory() cannot create"); - writeln(fd, " properly aligned blocks at these orders:"); - writeln(fd, ""); - has_warnings = 1; - } - char msg[128]; - char order_str[32], size_str[32], padding_str[32]; - size_t order_str_len = int_to_str(o, order_str); - order_str[order_str_len] = '\0'; - size_t size_str_len = int_to_str((int)(alignment >> 20), size_str); - size_str[size_str_len] = '\0'; - - // Calculate padding needed to align - size_t padding_needed = (alignment - misalignment) % alignment; - size_t padding_len = uint64_to_str(padding_needed, padding_str); - padding_str[padding_len] = '\0'; - - base_strcpy(msg, " Order "); - str_append_safe(msg, order_str, sizeof(msg)); - str_append_safe(msg, " (", sizeof(msg)); - str_append_safe(msg, size_str, sizeof(msg)); - str_append_safe(msg, " MiB): needs ", sizeof(msg)); - str_append_safe(msg, padding_str, sizeof(msg)); - str_append_safe(msg, " bytes padding", sizeof(msg)); - writeln(fd, msg); - } - } - - if (!has_warnings) { - writeln(fd, " No alignment issues detected."); - } - writeln(fd, ""); - writeln(fd, "=== End Statistics ==="); - writeln(fd, ""); - - #undef PRINT_SIZE - #undef PRINT_MIB -} - -static void *buddy_alloc_order(int order) { - assert(order >= 0 && order <= MAX_ORDER); - - // Find the smallest available block that is large enough - int current_order; - for (current_order = order; current_order <= MAX_ORDER; current_order++) { - if (free_lists[current_order].first) { - break; // Found a suitable block - } - } - - // If no block is available, grow the heap - if (current_order > MAX_ORDER) { - size_t required_size = MIN_PAGE_SIZE << order; - size_t alignment = MIN_PAGE_SIZE << order; - - // Calculate current heap top and alignment padding needed - uintptr_t current_top = (uintptr_t)heap_base + platform_heap_size(); - uintptr_t aligned_top = (current_top + alignment - 1) / alignment * alignment; - size_t padding = aligned_top - current_top; - - // Total bytes to grow: padding + required_size - size_t total_grow = padding + required_size; - - // Round up to PLATFORM_WASM_PAGE_SIZE boundary - size_t grow_by = ((total_grow + PLATFORM_WASM_PAGE_SIZE - 1) / PLATFORM_WASM_PAGE_SIZE) * PLATFORM_WASM_PAGE_SIZE; - - void *new_mem = platform_heap_grow(grow_by); - if (!new_mem) { - buddy_print_stats(); - writeln_int(PLATFORM_STDERR_FD, "order =", order); - writeln_int(PLATFORM_STDERR_FD, "required_size =", (int)required_size); - writeln_int(PLATFORM_STDERR_FD, "grow_by =", (int)grow_by); - writeln_int(PLATFORM_STDERR_FD, "padding =", (int)padding); - writeln_int(PLATFORM_STDERR_FD, "current_top % alignment =", (int)(current_top % alignment)); - FATAL_ERROR("platform_heap_grow(grow_by) failed"); - } - add_memory(new_mem, grow_by); - return buddy_alloc_order(order); // Retry allocation - } - - // We have a block of order 'current_order'. Remove it from its free list. - struct buddy_block *p = free_lists[current_order].first; - list_remove(&free_lists[current_order], p); - - // Split the block until it's the desired size - while (current_order > order) { - current_order--; - size_t half_size = MIN_PAGE_SIZE << current_order; - struct buddy_block *buddy = (struct buddy_block *)((uintptr_t)p + half_size); - buddy->order = current_order; - list_add(&free_lists[current_order], buddy); - } - - // Mark the block as allocated by making its order negative - p->order = -(order + 1); - - // Return the pointer to the memory *after* our inline header - return (void *)(p + 1); -} - -void *buddy_alloc(size_t size, size_t *actual_size) { - assert(size > 0); - - // Add space for our header to the requested size - size_t size_with_header = size + sizeof(struct buddy_block); - - // Calculate the order required for the allocation - int order = 0; - size_t block_size = MIN_PAGE_SIZE; - while (block_size < size_with_header) { - block_size <<= 1; - order++; - if (order > MAX_ORDER) { - return NULL; // Request is too large - } - } - - // If caller wants to know the actual size, calculate it - if (actual_size) { - *actual_size = block_size - sizeof(struct buddy_block); - } - - return buddy_alloc_order(order); -} - -void buddy_free(void *ptr) { - assert(ptr); - - // Get the block header from the user-provided pointer - struct buddy_block *p = ((struct buddy_block *)ptr) - 1; - - // Retrieve the original order and mark the block as free - int order = -p->order - 1; - if (order < 0 || order > MAX_ORDER) { - return; // Invalid pointer or heap corruption - } - - uintptr_t heap_end = (uintptr_t)heap_base + platform_heap_size(); - - // Coalesce with buddy if possible - while (order < MAX_ORDER) { - size_t block_size = MIN_PAGE_SIZE << order; - uintptr_t p_addr = (uintptr_t)p; - uintptr_t buddy_addr = p_addr ^ block_size; - - // Ensure the buddy is within the heap bounds before accessing it - if (buddy_addr < (uintptr_t)heap_base || buddy_addr >= heap_end) { - break; - } - - struct buddy_block *buddy = (struct buddy_block *)buddy_addr; - - if (buddy->order != order) { - break; // Buddy is not free or not the same size - } - - // Buddy is free and of the same order, so merge them. - list_remove(&free_lists[order], buddy); - - // The merged block starts at the lower of the two addresses - if (buddy_addr < p_addr) { - p = buddy; - } - - order++; - } - - p->order = order; - list_add(&free_lists[order], p); -} diff --git a/src/mlir/vendor/base/buddy.h b/src/mlir/vendor/base/buddy.h deleted file mode 100644 index 0691505..0000000 --- a/src/mlir/vendor/base/buddy.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -void buddy_init(void); - -// Allocate memory from the buddy allocator. -// Returns NULL on allocation failure. -// If actual_size is not NULL, stores the actual usable size allocated (which may be -// larger than requested due to power-of-2 rounding). -void *buddy_alloc(size_t size, size_t *actual_size); - -void buddy_free(void *ptr); - -// Print detailed statistics about the buddy allocator state -void buddy_print_stats(); -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/exit.c b/src/mlir/vendor/base/exit.c deleted file mode 100644 index 55479fe..0000000 --- a/src/mlir/vendor/base/exit.c +++ /dev/null @@ -1,11 +0,0 @@ -#include -#include - -void base_exit(int status) { - platform_exit(status); -} - -void base_abort(void) { - PRINT_ERR("Aborting..."); - base_exit(1); -} diff --git a/src/mlir/vendor/base/exit.h b/src/mlir/vendor/base/exit.h deleted file mode 100644 index 2559281..0000000 --- a/src/mlir/vendor/base/exit.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define FATAL_ERROR(x) do { PRINT_ERR(x); base_abort(); } while (0) - -// Process exit for base/ -void base_exit(int status); -void base_abort(void); -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/format.c b/src/mlir/vendor/base/format.c deleted file mode 100644 index 2fa69ec..0000000 --- a/src/mlir/vendor/base/format.c +++ /dev/null @@ -1,261 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -// Inline implementation of isdigit -static inline int fmt_isdigit(int c) { - return c >= '0' && c <= '9'; -} - - -typedef struct { - char alignment; // '<', '>', '^', or '\0' - int width; // -1 if not specified - int precision; // -1 if not specified -} FormatSpec; - -// Parse format specifier -static FormatSpec parse_format_spec(string spec) { - FormatSpec fs = {.alignment = '\0', .width = -1, .precision = -1}; - const char *p = spec.str; - const char *end = spec.str + spec.size; - if (p < end) { - if (*p == '<' || *p == '>' || *p == '^') { - fs.alignment = *p++; - } - } - if (p < end && fmt_isdigit(*p)) { - fs.width = 0; - while (p < end && fmt_isdigit(*p)) { - fs.width = fs.width * 10 + (*p++ - '0'); - } - } - if (p < end && *p == '.') { - p++; - if (p < end && fmt_isdigit(*p)) { - fs.precision = 0; - while (p < end && fmt_isdigit(*p)) { - fs.precision = fs.precision * 10 + (*p++ - '0'); - } - } - } - return fs; -} - -// Core formatting function with variadic arguments -string format_explicit_varg(Arena *arena, string fmt, size_t arg_count, - va_list ap) { - Scratch scratch = scratch_begin_avoid_conflict(arena); - strbuf result = strbuf_make_cap(scratch.arena, fmt.size + 16); - const char *p = fmt.str; - const char *end = fmt.str + fmt.size; - size_t arg_index = 0; - while (p < end) { - const char *open_brace = base_memchr(p, '{', (size_t)(end - p)); - if (open_brace == NULL) { - string remaining = {.str = (char*)p, .size = (uint64_t)(end - p)}; - strbuf_append(scratch.arena, &result, remaining); - break; - } - if (open_brace > p) { - string part = {.str = (char*)p, .size = (uint64_t)(open_brace - p)}; - strbuf_append(scratch.arena, &result, part); - } - p = open_brace + 1; - if (p >= end) { - strbuf_append_char(scratch.arena, &result, '{'); - break; - } - if (*p == '{') { - strbuf_append_char(scratch.arena, &result, '{'); - p++; - continue; - } - const char *close_brace = base_memchr(p, '}', (size_t)(end - p)); - if (close_brace == NULL) { - string error = str_lit("Error: missing closing brace"); - strbuf_append(scratch.arena, &result, error); - break; - } - const char *colon = base_memchr(p, ':', (size_t)(close_brace - p)); - FormatSpec spec; - if (colon) { - string spec_str = {.str = (char*)colon + 1, .size = (uint64_t)(close_brace - (colon + 1))}; - spec = parse_format_spec(spec_str); - } else { - if (p != close_brace) { - string error = str_lit("Error: invalid format specifier"); - strbuf_append(scratch.arena, &result, error); - p = close_brace + 1; - continue; - } - spec = (FormatSpec){.alignment = '\0', .width = -1, .precision = -1}; - } - if (arg_index >= arg_count) { - FATAL_ERROR("Missing argument"); - } - ArgType type = (ArgType)va_arg(ap, int); - string s; - switch (type) { - case ARG_INT8: { - int8_t value = (int8_t)va_arg(ap, int); - s = int_to_string(scratch.arena, value); - break; - } - case ARG_UINT8: { - uint8_t value = (uint8_t)va_arg(ap, int); - s = uint_to_string(scratch.arena, value); - break; - } - case ARG_INT16: { - int16_t value = (int16_t)va_arg(ap, int); - s = int_to_string(scratch.arena, value); - break; - } - case ARG_UINT16: { - uint16_t value = (uint16_t)va_arg(ap, int); - s = uint_to_string(scratch.arena, value); - break; - } - case ARG_INT32: { - int32_t value = va_arg(ap, int32_t); - s = int_to_string(scratch.arena, value); - break; - } - case ARG_UINT32: { - uint32_t value = va_arg(ap, uint32_t); - s = uint_to_string(scratch.arena, value); - break; - } - case ARG_INT64: { - int64_t value = va_arg(ap, int64_t); - s = int_to_string(scratch.arena, value); - break; - } - case ARG_UINT64: { - uint64_t value = va_arg(ap, uint64_t); - s = uint_to_string(scratch.arena, value); - break; - } - case ARG_DOUBLE: { - double value = va_arg(ap, double); - s = double_to_string(scratch.arena, value, spec.precision); - break; - } - case ARG_STRING: { - char* value = va_arg(ap, char*); - s = str_from_cstr_view(value); - if (spec.precision >= 0 && (uint64_t)spec.precision < s.size) { - s.size = (uint64_t)spec.precision; - } - break; - } - case ARG_STRING2: { -#if defined(_WIN64) - // On Windows x64, structs > 8 bytes are passed by reference in varargs - string value = *va_arg(ap, string*); -#else - string value = va_arg(ap, string); -#endif - s = value; - if (spec.precision >= 0 && (uint64_t)spec.precision < s.size) { - s.size = (uint64_t)spec.precision; - } - break; - } - case ARG_POINTER: { - void* value = va_arg(ap, void*); - s = uint_to_string(scratch.arena, (uint64_t)value); - break; - } - case ARG_VECTOR_INT64: { -#if defined(_WIN64) - // On Windows x64, structs > 8 bytes are passed by reference in varargs - vector_i64 value = *va_arg(ap, vector_i64*); -#else - vector_i64 value = va_arg(ap, vector_i64); -#endif - strbuf vec_buf = strbuf_make_cap(scratch.arena, 32); - strbuf_append_char(scratch.arena, &vec_buf, '{'); - for (size_t i=0; i= 0 && (uint64_t)spec.precision < s.size) { - s.size = (uint64_t)spec.precision; - } - break; - } - default: - s = str_lit("Unknown type"); - } - arg_index++; - // Apply width and alignment - if (spec.alignment == '\0') { - // Right-align numeric types, left-align everything else - if (type == ARG_INT8 || type == ARG_UINT8 || - type == ARG_INT16 || type == ARG_UINT16 || - type == ARG_INT32 || type == ARG_UINT32 || - type == ARG_INT64 || type == ARG_UINT64 || - type == ARG_DOUBLE) { - spec.alignment = '>'; - } else { - spec.alignment = '<'; - } - } - if (spec.width > 0 && s.size < (uint64_t)spec.width) { - size_t pad_size = (size_t)spec.width - s.size; - char pad_char = ' '; - if (spec.alignment == '<') { - strbuf_append(scratch.arena, &result, s); - for (size_t k = 0; k < pad_size; k++) { - strbuf_append_char(scratch.arena, &result, pad_char); - } - } else if (spec.alignment == '^') { - size_t left_pad = pad_size / 2; - size_t right_pad = pad_size - left_pad; - for (size_t k = 0; k < left_pad; k++) { - strbuf_append_char(scratch.arena, &result, pad_char); - } - strbuf_append(scratch.arena, &result, s); - for (size_t k = 0; k < right_pad; k++) { - strbuf_append_char(scratch.arena, &result, pad_char); - } - } else { // '>' or default - for (size_t k = 0; k < pad_size; k++) { - strbuf_append_char(scratch.arena, &result, pad_char); - } - strbuf_append(scratch.arena, &result, s); - } - } else { - strbuf_append(scratch.arena, &result, s); - } - p = close_brace + 1; - } - if (arg_index != arg_count) { - FATAL_ERROR("Arguments do not match the format string"); - } - - // Copy final result to the supplied arena - string final_result = str_copy(arena, strbuf_to_string(result)); - scratch_end(scratch); - return final_result; -} - -string format_explicit(Arena *arena, string fmt, size_t arg_count, ...) { - va_list ap; - va_start(ap, arg_count); - string result = format_explicit_varg(arena, fmt, arg_count, ap); - va_end(ap); - return result; -} diff --git a/src/mlir/vendor/base/format.h b/src/mlir/vendor/base/format.h deleted file mode 100644 index c8794d0..0000000 --- a/src/mlir/vendor/base/format.h +++ /dev/null @@ -1,81 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum { - ARG_INT8, - ARG_UINT8, - ARG_INT16, - ARG_UINT16, - ARG_INT32, - ARG_UINT32, - ARG_INT64, - ARG_UINT64, - ARG_DOUBLE, - ARG_STRING, - ARG_STRING2, - ARG_POINTER, - ARG_VECTOR_INT64 -} ArgType; - -string format_explicit_varg(Arena *arena, string fmt, size_t arg_count, - va_list ap); -string format_explicit(Arena *arena, string fmt, size_t arg_count, ...); - -#define GET_ARG_COUNT(_0, _1, _2, _3, _4, _5, _6, _7, _8, N, ...) N -#define COUNT_ARGS(...) GET_ARG_COUNT(0 __VA_OPT__(,) __VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1, 0) - -// Map all types to explicit ArgType enum values -// Using fixed-width types for consistency across platforms -#define A(x) _Generic((x), \ - char*: ARG_STRING, \ - string: ARG_STRING2, \ - double: ARG_DOUBLE, \ - int8_t: ARG_INT8, \ - uint8_t: ARG_UINT8, \ - int16_t: ARG_INT16, \ - uint16_t: ARG_UINT16, \ - int32_t: ARG_INT32, \ - uint32_t: ARG_UINT32, \ - int64_t: ARG_INT64, \ - uint64_t: ARG_UINT64, \ - void*: ARG_POINTER, \ - Arena*: ARG_POINTER, \ - vector_i64: ARG_VECTOR_INT64 \ - ), (x) - -#define APPLY_A0() -#define APPLY_A1(a) A(a) -#define APPLY_A2(a, b) A(a), A(b) -#define APPLY_A3(a, b, c) A(a), A(b), A(c) -#define APPLY_A4(a, b, c, d) A(a), A(b), A(c), A(d) -#define APPLY_A5(a, b, c, d, e) A(a), A(b), A(c), A(d), A(e) -#define APPLY_A6(a, b, c, d, e, f) A(a), A(b), A(c), A(d), A(e), A(f) -#define APPLY_A7(a, b, c, d, e, f, g) A(a), A(b), A(c), A(d), A(e), A(f), A(g) -#define APPLY_A8(a, b, c, d, e, f, g, h) A(a), A(b), A(c), A(d), A(e), A(f), A(g), A(h) - -#define APPLY_A_FOR_COUNT_0 APPLY_A0 -#define APPLY_A_FOR_COUNT_1 APPLY_A1 -#define APPLY_A_FOR_COUNT_2 APPLY_A2 -#define APPLY_A_FOR_COUNT_3 APPLY_A3 -#define APPLY_A_FOR_COUNT_4 APPLY_A4 -#define APPLY_A_FOR_COUNT_5 APPLY_A5 -#define APPLY_A_FOR_COUNT_6 APPLY_A6 -#define APPLY_A_FOR_COUNT_7 APPLY_A7 -#define APPLY_A_FOR_COUNT_8 APPLY_A8 - -#define CONCAT_AFTER_EXPAND(prefix, count) prefix ## count -#define APPLY_WITH_COUNT(count, ...) CONCAT_AFTER_EXPAND(APPLY_A_FOR_COUNT_, count)(__VA_ARGS__) - -#define format(arena, fmt, ...) \ - format_explicit(arena, fmt, COUNT_ARGS(__VA_ARGS__) __VA_OPT__(,) APPLY_WITH_COUNT(COUNT_ARGS(__VA_ARGS__) __VA_OPT__(,) __VA_ARGS__)) -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/hashtable.h b/src/mlir/vendor/base/hashtable.h deleted file mode 100644 index 9dc7c02..0000000 --- a/src/mlir/vendor/base/hashtable.h +++ /dev/null @@ -1,95 +0,0 @@ -#pragma once - -#include -#include - -// Helper Macros (internal use) - -#ifdef __cplusplus -extern "C" { -#endif - -#define _GV_CONCAT_IMPL(a, b) a##b -#define _GV_CONCAT(a, b) _GV_CONCAT_IMPL(a, b) - -#define _GV_CONCAT3_IMPL(a, b, c) a##b##c -#define _GV_CONCAT3(a, b, c) _GV_CONCAT3_IMPL(a, b, c) - -// Hashtable Definition Macro with Inlined Hash and Equality -#define DEFINE_HASHTABLE_FOR_TYPES(KEY_TYPE, VALUE_TYPE, NAME) \ - typedef struct _GV_CONCAT3(NAME, _, Entry) { \ - KEY_TYPE key; \ - VALUE_TYPE value; \ - int occupied; \ - } _GV_CONCAT3(NAME, _, Entry); \ - \ - typedef struct NAME { \ - _GV_CONCAT3(NAME, _, Entry) *buckets; \ - size_t num_buckets; \ - size_t size; \ - } NAME; \ - \ - static inline void _GV_CONCAT3(NAME, _, init)(Arena *arena, NAME *ht, size_t initial_buckets) { \ - ht->num_buckets = initial_buckets; \ - ht->size = 0; \ - ht->buckets = arena_new_array(arena, _GV_CONCAT3(NAME, _, Entry), initial_buckets); \ - for (size_t i = 0; i < initial_buckets; i++) { \ - ht->buckets[i].occupied = 0; \ - } \ - } \ - \ - static inline void _GV_CONCAT3(NAME, _, insert)(Arena *arena, NAME *ht, KEY_TYPE key, VALUE_TYPE value) { \ - if ((double)ht->size >= 0.75 * (double)ht->num_buckets) { \ - size_t new_num_buckets = ht->num_buckets * 2; \ - _GV_CONCAT3(NAME, _, Entry) *new_buckets = arena_new_array(arena, _GV_CONCAT3(NAME, _, Entry), new_num_buckets); \ - for (size_t i = 0; i < new_num_buckets; i++) { \ - new_buckets[i].occupied = 0; \ - } \ - for (size_t i = 0; i < ht->num_buckets; i++) { \ - if (ht->buckets[i].occupied) { \ - KEY_TYPE existing_key = ht->buckets[i].key; \ - VALUE_TYPE existing_value = ht->buckets[i].value; \ - size_t hash_value = _GV_CONCAT3(NAME, _, HASH)(existing_key); \ - size_t index = hash_value % new_num_buckets; \ - while (new_buckets[index].occupied) { \ - index = (index + 1) % new_num_buckets; \ - } \ - new_buckets[index].key = existing_key; \ - new_buckets[index].value = existing_value; \ - new_buckets[index].occupied = 1; \ - } \ - } \ - ht->buckets = new_buckets; \ - ht->num_buckets = new_num_buckets; \ - } \ - size_t hash_value = _GV_CONCAT3(NAME, _, HASH)(key); \ - size_t index = hash_value % ht->num_buckets; \ - while (ht->buckets[index].occupied) { \ - if (_GV_CONCAT3(NAME, _, EQUAL)(ht->buckets[index].key, key)) { \ - ht->buckets[index].value = value; \ - return; \ - } \ - index = (index + 1) % ht->num_buckets; \ - } \ - ht->buckets[index].key = key; \ - ht->buckets[index].value = value; \ - ht->buckets[index].occupied = 1; \ - ht->size++; \ - } \ - \ - static inline VALUE_TYPE* _GV_CONCAT3(NAME, _, get)(NAME *ht, KEY_TYPE key) { \ - size_t hash_value = _GV_CONCAT3(NAME, _, HASH)(key); \ - size_t index = hash_value % ht->num_buckets; \ - size_t start_index = index; \ - while (ht->buckets[index].occupied) { \ - if (_GV_CONCAT3(NAME, _, EQUAL)(ht->buckets[index].key, key)) { \ - return &ht->buckets[index].value; \ - } \ - index = (index + 1) % ht->num_buckets; \ - if (index == start_index) break; \ - } \ - return NULL; \ - } -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/io.c b/src/mlir/vendor/base/io.c deleted file mode 100644 index 1527219..0000000 --- a/src/mlir/vendor/base/io.c +++ /dev/null @@ -1,159 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -uint32_t write_all(int fd, ciovec_t* iovs, size_t iovs_len) { - size_t i; - size_t nwritten; - uint32_t ret; - - for (i = 0; i < iovs_len; ) { - ret = platform_fd_write(fd, &iovs[i], iovs_len - i, &nwritten); - if (ret != 0) { - return ret; // Return error code - } - - // Advance through the iovecs based on how much was written - while (nwritten > 0 && i < iovs_len) { - if (nwritten >= iovs[i].buf_len) { - nwritten -= iovs[i].buf_len; - i++; - } else { - iovs[i].buf = (const uint8_t*)iovs[i].buf + nwritten; - iovs[i].buf_len -= nwritten; - nwritten = 0; - } - } - } - return 0; // Success -} - -void writeln(int fd, const char* text) { - const char *msg1 = text; - const char *msg2 = "\n"; - - ciovec_t iovs[2]; - iovs[0].buf = msg1; - iovs[0].buf_len = base_strlen(msg1); - iovs[1].buf = msg2; - iovs[1].buf_len = base_strlen(msg2); - - write_all(fd, iovs, 2); -} - -void writeln_int(int fd, const char* text, int n) { - (void)fd; /* upstream writes to stderr regardless. Left alone deliberately. */ - const char *msg1 = text; - const char *msg2 = " "; - char p[32]; size_t p_len = int_to_str(n, p); p[p_len] = '\0'; - const char *msg3 = "\n"; - - ciovec_t iovs[4]; - iovs[0].buf = msg1; - iovs[0].buf_len = base_strlen(msg1); - iovs[1].buf = msg2; - iovs[1].buf_len = base_strlen(msg2); - iovs[2].buf = p; - iovs[2].buf_len = base_strlen(p); - iovs[3].buf = msg3; - iovs[3].buf_len = base_strlen(msg3); - - write_all(PLATFORM_STDERR_FD, iovs, 4); -} - -void writeln_loc(int fd, const char *text, const char *file, unsigned int line, const char *function) { - char line_str[32]; size_t p_len = int_to_str((int)line, line_str); - line_str[p_len] = '\0'; - - const char *msg[] = {file, ":", line_str, " in ", - function, "(): ", text, "\n"}; - - ciovec_t iovs[array_size(msg)]; - for (size_t i=0; istr = bytes; - text->size = filesize+1; - scratch_end(scratch); - return true; -} - - -string read_file_ok(Arena *arena, const string filename) { - string text; - if (read_file(arena, filename, &text)) { - return text; - } else { - FATAL_ERROR("File cannot be opened."); - return text; - } -} - -void println_explicit(string fmt, size_t arg_count, ...) { - Scratch scratch = scratch_begin(); - va_list varg; - va_start(varg, arg_count); - - string text = format_explicit_varg(scratch.arena, fmt, arg_count, varg); - va_end(varg); - text = str_concat(scratch.arena, text, str_lit("\n")); - ciovec_t iov = {.buf = text.str, .buf_len = text.size}; - write_all(PLATFORM_STDOUT_FD, &iov, 1); - - scratch_end(scratch); -} diff --git a/src/mlir/vendor/base/io.h b/src/mlir/vendor/base/io.h deleted file mode 100644 index eeafabe..0000000 --- a/src/mlir/vendor/base/io.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -// The functions below this comment do not allocate memory (no arenas), so they -// are safe to use anywhere, including in arena / buddy allocator code, or in -// asserts. - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @brief Writes all data from the iovecs to the specified file descriptor. - * - * This function repeatedly calls fd_write until all data is written or an error occurs. - * It updates the iovecs to skip already-written data. - * - * @param fd The file descriptor to write to. - * @param iovs Array of ciovec_t structures containing the data to write. - * @param iovs_len Number of iovecs in the array. - * @return 0 on success, or an error code if fd_write fails. - */ -uint32_t write_all(int fd, ciovec_t* iovs, size_t iovs_len); - -// Prints a single line, appends `\n` -void writeln(int fd, const char* text); - -// Prints: text + ' ' + int + '\n' -void writeln_int(int fd, const char* text, int n); - -// Prints text with location information, appends '\n' -void writeln_loc(int fd, const char *text, const char *file, unsigned int line, const char *function); - -#define PRINT_ERR(x) writeln_loc(PLATFORM_STDERR_FD, (x), __FILE__, __LINE__, __func__) - -// The functions below allocate via arenas/scratch and depend on more of base/. - -// Returns the file contents as a null-terminated string in `text`. -// Returns `true` on success, otherwise `false`. -bool read_file(Arena *arena, const string filename, string *text); -string read_file_ok(Arena *arena, const string filename); - -void println_explicit(string fmt, size_t arg_count, ...); - -#define println(fmt, ...) \ - println_explicit(fmt, COUNT_ARGS(__VA_ARGS__) __VA_OPT__(,) APPLY_WITH_COUNT(COUNT_ARGS(__VA_ARGS__) __VA_OPT__(,) __VA_ARGS__)) - -#define PRINT_LOG(x) println(str_lit("{}:{} in {}(): {}"), str_lit(__FILE__), __LINE__, str_lit(__func__), str_lit(x)) -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/math.c b/src/mlir/vendor/base/math.c deleted file mode 100644 index 29f9473..0000000 --- a/src/mlir/vendor/base/math.c +++ /dev/null @@ -1,77 +0,0 @@ -#include -#include - -static const float S6 = -0.01445205f; -static const float S5 = 0.09838380f; -static const float S4 = -0.01243614f; -static const float S3 = -0.64157278f; -static const float S2 = -0.00077364f; -static const float S1 = 1.5708527f; -static const float S0 = -0.000000992f; - -static const double DPI_D = 6.28318530717958647692; -static const double PI_D = 3.14159265358979323846; -static const float PI2_F = 1.57079632679f; -static const float PI_F = 3.14159265f; - -static inline float poly_sincos(float z) { - float p = S6 * z + S5; - p = p * z + S4; - p = p * z + S3; - p = p * z + S2; - p = p * z + S1; - p = p * z + S0; - return p; -} - -static inline void reduce_to_quarter(float x, float* y, float* sin_sign, float* cos_sign) { - double xd = (double)x; - double q = xd / DPI_D; - double k = base_round(q); - double rd = xd - k * DPI_D; - if (rd > PI_D) { - rd -= DPI_D; - } else if (rd < -PI_D) { - rd += DPI_D; - } - float r = (float)rd; - bool flip_sin = (r < 0.0f); - if (flip_sin) { - r = -r; - } - *sin_sign = flip_sin ? -1.0f : 1.0f; - *cos_sign = 1.0f; - if (r > PI2_F) { - *y = PI_F - r; - *cos_sign = -1.0f; - } else { - *y = r; - } -} - -float fast_sinf(float x) { - if (x == 0.0f) return 0.0f; - float y, sin_s, cos_s; - reduce_to_quarter(x, &y, &sin_s, &cos_s); - float z = y / PI2_F; - float sy = poly_sincos(z); - return sin_s * sy; -} - -float fast_cosf(float x) { - if (x == 0.0f) return 1.0f; - float y, sin_s, cos_s; - reduce_to_quarter(x, &y, &sin_s, &cos_s); - float z = y / PI2_F; - float cy = poly_sincos(1.0f - z); - return cos_s * cy; -} - -float fast_tanf(float x) { - float s = fast_sinf(x); - float c = fast_cosf(x); - if (c == 0.0f) { - return (s < 0.0f ? -INFINITY : INFINITY); - } - return s / c; -} diff --git a/src/mlir/vendor/base/math.h b/src/mlir/vendor/base/math.h deleted file mode 100644 index 3de843c..0000000 --- a/src/mlir/vendor/base/math.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once - -#include - -// We build with -nostdinc / /X, so is not available. Define the -// usual C99 floating-point macros ourselves. The expression -// `(float)(1e308 * 1e308)` overflows to +inf at compile time on every -// conforming compiler (Clang, GCC, MSVC), so no compiler-specific spelling -// is needed. - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef INFINITY -#define INFINITY ((float)(1e308 * 1e308)) -#endif - -#ifndef NAN -#define NAN ((float)(INFINITY * 0.0f)) -#endif - -#ifndef HUGE_VAL -#define HUGE_VAL ((double)INFINITY) -#endif - -static inline double base_fabs(double x) { - return x < 0 ? -x : x; -} - -static inline float base_fabsf(float x) { - return x < 0 ? -x : x; -} - -// Simple round implementation. Note: Overflows for values outside [INT64_MIN, INT64_MAX]. -static inline double base_round(double x) { - return (x >= 0.0) ? (double)(int64_t)(x + 0.5) : (double)(int64_t)(x - 0.5); -} - -// Fast single-precision trigonometric functions -float fast_sinf(float x); -float fast_cosf(float x); -float fast_tanf(float x); - -// Fast square-root functions (declared in platform.h, repeated here for -// discoverability alongside the other math primitives). -double fast_sqrt(double x); -float fast_sqrtf(float x); -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/mem.c b/src/mlir/vendor/base/mem.c deleted file mode 100644 index 569236e..0000000 --- a/src/mlir/vendor/base/mem.c +++ /dev/null @@ -1,176 +0,0 @@ -#include - -size_t base_strlen(const char* str) { - const char* s; - for (s = str; *s; ++s); - return (size_t)(s - str); -} - -char* base_strcpy(char* dest, const char* src) { - char* d = dest; - while ((*d++ = *src++) != '\0'); - return dest; -} - -int base_strcmp(const char* s1, const char* s2) { - while (*s1 && (*s1 == *s2)) { - s1++; - s2++; - } - return *(const unsigned char*)s1 - *(const unsigned char*)s2; -} - -void* base_memcpy(void* dest, const void* src, size_t n) { - unsigned char* d = (unsigned char*)dest; - const unsigned char* s = (const unsigned char*)src; - for (size_t i = 0; i < n; i++) { - d[i] = s[i]; - } - return dest; -} - -void* base_memmove(void* dest, const void* src, size_t n) { - unsigned char* d = (unsigned char*)dest; - const unsigned char* s = (const unsigned char*)src; - - if (d == s || n == 0) { - return dest; - } - - // Copy forward when regions do not overlap or destination is before source - if (d < s || d >= s + n) { - for (size_t i = 0; i < n; i++) { - d[i] = s[i]; - } - return dest; - } - - // Copy backward to handle overlapping regions safely - for (size_t i = n; i != 0; i--) { - d[i - 1] = s[i - 1]; - } - return dest; -} - -int base_memcmp(const void* s1, const void* s2, size_t n) { - const unsigned char* p1 = (const unsigned char*)s1; - const unsigned char* p2 = (const unsigned char*)s2; - for (size_t i = 0; i < n; i++) { - if (p1[i] != p2[i]) { - return p1[i] - p2[i]; - } - } - return 0; -} - -void* base_memset(void* s, int c, size_t n) { - unsigned char* p = (unsigned char*)s; - for (size_t i = 0; i < n; i++) { - p[i] = (unsigned char)c; - } - return s; -} - -void* base_memchr(const void* s, int c, size_t n) { - const unsigned char* p = (const unsigned char*)s; - for (size_t i = 0; i < n; i++) { - if (p[i] == (unsigned char)c) { - return (void*)(p + i); - } - } - return (void*)0; -} - -char* base_strchr(const char* s, int c) { - while (*s) { - if (*s == (char)c) { - return (char*)s; - } - s++; - } - // Check for null terminator match - if ((char)c == '\0') { - return (char*)s; - } - return (void*)0; -} - -char* base_strrchr(const char* s, int c) { - const char* last = (void*)0; - while (*s) { - if (*s == (char)c) { - last = s; - } - s++; - } - // Check for null terminator match - if ((char)c == '\0') { - return (char*)s; - } - return (char*)last; -} - -char* base_strncpy(char* dest, const char* src, size_t n) { - size_t i; - for (i = 0; i < n && src[i] != '\0'; i++) { - dest[i] = src[i]; - } - // Pad with null bytes if src is shorter than n - for (; i < n; i++) { - dest[i] = '\0'; - } - return dest; -} - -size_t base_strcspn(const char* s, const char* reject) { - const char* p; - const char* r; - size_t count = 0; - - for (p = s; *p != '\0'; p++) { - for (r = reject; *r != '\0'; r++) { - if (*p == *r) { - return count; - } - } - count++; - } - return count; -} - -int base_strncmp(const char* s1, const char* s2, size_t n) { - if (n == 0) { - return 0; - } - for (size_t i = 0; i < n; i++) { - if (s1[i] != s2[i]) { - return (unsigned char)s1[i] - (unsigned char)s2[i]; - } - if (s1[i] == '\0') { - return 0; - } - } - return 0; -} - -char* base_strstr(const char* haystack, const char* needle) { - if (*needle == '\0') { - return (char*)haystack; - } - - for (; *haystack != '\0'; haystack++) { - const char* h = haystack; - const char* n = needle; - - while (*h != '\0' && *n != '\0' && *h == *n) { - h++; - n++; - } - - if (*n == '\0') { - return (char*)haystack; - } - } - - return (void*)0; -} diff --git a/src/mlir/vendor/base/mem.h b/src/mlir/vendor/base/mem.h deleted file mode 100644 index a94ca22..0000000 --- a/src/mlir/vendor/base/mem.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Memory and string manipulation functions for base/ -// Self-contained implementations with no external dependencies -// Prefixed with base_ to avoid conflicts with system headers - -#ifdef __cplusplus -extern "C" { -#endif - -size_t base_strlen(const char *str); -char *base_strcpy(char *dest, const char *src); -int base_strcmp(const char *s1, const char *s2); -void *base_memcpy(void *dest, const void *src, size_t n); -void *base_memmove(void *dest, const void *src, size_t n); -int base_memcmp(const void *s1, const void *s2, size_t n); -void *base_memset(void *s, int c, size_t n); -void *base_memchr(const void *s, int c, size_t n); -char *base_strchr(const char *s, int c); -char *base_strrchr(const char *s, int c); -char *base_strncpy(char *dest, const char *src, size_t n); -size_t base_strcspn(const char *s, const char *reject); -int base_strncmp(const char *s1, const char *s2, size_t n); -char *base_strstr(const char *haystack, const char *needle); -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/numconv.c b/src/mlir/vendor/base/numconv.c deleted file mode 100644 index 932ce7b..0000000 --- a/src/mlir/vendor/base/numconv.c +++ /dev/null @@ -1,382 +0,0 @@ -#include -#include - -size_t uint64_to_str(uint64_t val, char* buf) { - if (val == 0) { - buf[0] = '0'; - return 1; - } - - size_t len = 0; - // Convert digits in reverse order - while (val > 0) { - buf[len++] = (char)('0' + (val % 10)); - val /= 10; - } - // Reverse - for (size_t i = 0; i < len / 2; i++) { - char t = buf[i]; - buf[i] = buf[len - 1 - i]; - buf[len - 1 - i] = t; - } - return len; -} - -size_t int64_to_str(int64_t val, char* buf) { - if (val < 0) { - buf[0] = '-'; - size_t len = uint64_to_str((uint64_t)(-val), buf + 1); - return len + 1; - } else { - return uint64_to_str((uint64_t)val, buf); - } -} - -size_t int_to_str(int val, char* buf) { - return int64_to_str((int64_t)val, buf); -} - -size_t double_to_str(double val, char* buf, int precision) { - // Simple implementation: handle sign, integer part, decimal point, fractional part - size_t pos = 0; - - if (val < 0) { - buf[pos++] = '-'; - val = -val; - } - - // Integer part - int64_t int_part = (int64_t)val; - pos += int64_to_str(int_part, buf + pos); - - // Default precision is 6 if not specified - if (precision < 0) precision = 6; - - if (precision > 0) { - buf[pos++] = '.'; - - // Fractional part - double frac_part = val - (double)int_part; - for (int i = 0; i < precision; i++) { - frac_part *= 10; - int digit = (int)frac_part; - buf[pos++] = (char)('0' + digit); - frac_part -= digit; - } - } - - return pos; -} - -static size_t double_to_str_g(double val, char* buf, int precision) { - if (precision < 0) precision = 6; - size_t len = double_to_str(val, buf, precision); - while (len > 0 && buf[len - 1] == '0') len--; - if (len > 0 && buf[len - 1] == '.') len--; - if (len == 0) buf[len++] = '0'; - return len; -} - -// Format `val` as `[-]d.ddde[+-]NN` (C's "%e"), with `precision` fractional -// digits in the mantissa. Always at least two exponent digits. -size_t double_to_str_e(double val, char* buf, int precision) { - size_t pos = 0; - - int neg = 0; - if (val < 0) { neg = 1; val = -val; } - if (precision < 0) precision = 6; - // Clamp precision so the integer mantissa fits in int64_t. - if (precision > 17) precision = 17; - - // Normalize to [1, 10) and compute the decimal exponent. - int exp = 0; - if (val != 0.0) { - while (val >= 10.0) { val /= 10.0; exp++; } - while (val < 1.0) { val *= 10.0; exp--; } - } - - // Compute the integer mantissa with `precision+1` digits, rounded. - double scale = 1.0; - for (int i = 0; i < precision; i++) scale *= 10.0; - int64_t mantissa = (int64_t)(val * scale + 0.5); - int64_t cutoff = 10; - for (int i = 0; i < precision; i++) cutoff *= 10; - if (mantissa >= cutoff) { mantissa /= 10; exp++; } - - if (neg) buf[pos++] = '-'; - - // First digit (integer part). - int64_t scale_i = (int64_t)scale; - int first = (int)(mantissa / scale_i); - int64_t frac = mantissa % scale_i; - if (first > 9) first = 9; - buf[pos++] = (char)('0' + first); - - if (precision > 0) { - buf[pos++] = '.'; - char digbuf[32]; - int n = 0; - int64_t r = frac; - while (r > 0) { digbuf[n++] = (char)('0' + (r % 10)); r /= 10; } - while (n < precision) digbuf[n++] = '0'; - while (n > 0) buf[pos++] = digbuf[--n]; - } - - buf[pos++] = 'e'; - if (exp < 0) { buf[pos++] = '-'; exp = -exp; } - else { buf[pos++] = '+'; } - - char digits[8]; - int n = 0; - if (exp == 0) digits[n++] = '0'; - while (exp > 0) { digits[n++] = (char)('0' + (exp % 10)); exp /= 10; } - while (n < 2) digits[n++] = '0'; - while (n > 0) buf[pos++] = digits[--n]; - - return pos; -} - -size_t uint64_to_hex_str(uint64_t val, char* buf, int uppercase) { - if (val == 0) { - buf[0] = '0'; - return 1; - } - - const char* digits = uppercase ? "0123456789ABCDEF" : "0123456789abcdef"; - size_t len = 0; - - // Convert digits in reverse order - while (val > 0) { - buf[len++] = digits[val & 0xF]; - val >>= 4; - } - - // Reverse - for (size_t i = 0; i < len / 2; i++) { - char t = buf[i]; - buf[i] = buf[len - 1 - i]; - buf[len - 1 - i] = t; - } - return len; -} - -// vsnprintf/snprintf implementations (only for nostdlib builds) -int base_vsnprintf(char *str, size_t size, const char *format, va_list args) { - if (size == 0) return 0; - - size_t pos = 0; - const char* p = format; - char temp_buf[32]; - - while (*p && pos < size - 1) { - if (*p == '%' && *(p + 1)) { - p++; - - // Check for length modifiers: l, ll, z - int is_long = 0; - int is_long_long = 0; - int is_size_t = 0; - - if (*p == 'l') { - p++; - is_long = 1; - if (*p == 'l') { - p++; - is_long_long = 1; - is_long = 0; - } - } else if (*p == 'z') { - p++; - is_size_t = 1; - } - - // Check for precision specifier (e.g., %.2f, %.*s) - int precision = -1; - if (*p == '.') { - p++; - if (*p == '*') { - // %.*X form: precision read from a preceding int arg. - precision = va_arg(args, int); - if (precision < 0) precision = 0; - p++; - } else { - precision = 0; - while (*p >= '0' && *p <= '9') { - precision = precision * 10 + (*p - '0'); - p++; - } - } - } - - switch (*p) { - case 'd': - case 'i': { - if (is_long_long) { - int64_t val = va_arg(args, int64_t); - size_t len = int64_to_str(val, temp_buf); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } else if (is_long) { - long val = va_arg(args, long); - size_t len = int64_to_str((int64_t)val, temp_buf); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } else { - int val = va_arg(args, int); - size_t len = int_to_str(val, temp_buf); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } - break; - } - case 'u': { - if (is_long_long) { - uint64_t val = va_arg(args, uint64_t); - size_t len = uint64_to_str(val, temp_buf); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } else if (is_long || is_size_t) { - unsigned long val = va_arg(args, unsigned long); - size_t len = uint64_to_str((uint64_t)val, temp_buf); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } else { - unsigned int val = va_arg(args, unsigned int); - size_t len = uint64_to_str((uint64_t)val, temp_buf); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } - break; - } - case 'x': - case 'X': { - if (is_long_long) { - uint64_t val = va_arg(args, uint64_t); - size_t len = uint64_to_hex_str(val, temp_buf, *p == 'X'); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } else if (is_long || is_size_t) { - unsigned long val = va_arg(args, unsigned long); - size_t len = uint64_to_hex_str((uint64_t)val, temp_buf, *p == 'X'); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } else { - unsigned int val = va_arg(args, unsigned int); - size_t len = uint64_to_hex_str(val, temp_buf, *p == 'X'); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } - break; - } - case 'p': { - void* ptr = va_arg(args, void*); - if (pos < size - 2) { - str[pos++] = '0'; - str[pos++] = 'x'; - } - size_t len = uint64_to_hex_str((uint64_t)(uintptr_t)ptr, temp_buf, 0); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - break; - } - case 'f': { - double val = va_arg(args, double); - if (precision < 0) precision = 6; - size_t len = double_to_str(val, temp_buf, precision); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - break; - } - case 'g': { - double val = va_arg(args, double); - size_t len = double_to_str_g(val, temp_buf, precision); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - break; - } - case 'e': { - double val = va_arg(args, double); - if (precision < 0) precision = 6; - size_t len = double_to_str_e(val, temp_buf, precision); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - break; - } - case 's': { - const char* s = va_arg(args, char*); - if (s == NULL) s = "(null)"; - if (precision >= 0) { - // %.*s / %.Ns: emit at most `precision` chars (do not - // require NUL termination — needed for slice-style - // strings like the corec `string` { ptr, size } view). - int n = 0; - while (n < precision && pos < size - 1) { - str[pos++] = s[n++]; - } - } else { - while (*s && pos < size - 1) { - str[pos++] = *s++; - } - } - break; - } - case 'c': { - char c = (char)va_arg(args, int); - if (pos < size - 1) { - str[pos++] = c; - } - break; - } - case '%': { - str[pos++] = '%'; - break; - } - default: - // Unknown format specifier, just skip it - break; - } - p++; - } else { - str[pos++] = *p++; - } - } - - str[pos] = '\0'; - return (int)pos; -} - -// Simple snprintf implementation for base/ -// Supports: %d, %u, %f, %.Nf, %s -int base_snprintf(char *str, size_t size, const char *format, ...) { - va_list args; - va_start(args, format); - int result = base_vsnprintf(str, size, format, args); - va_end(args); - return result; -} diff --git a/src/mlir/vendor/base/numconv.h b/src/mlir/vendor/base/numconv.h deleted file mode 100644 index 27071da..0000000 --- a/src/mlir/vendor/base/numconv.h +++ /dev/null @@ -1,48 +0,0 @@ -#pragma once - -#include -#include - -// Number to string conversion functions for base/ -// Self-contained implementations with no external dependencies - -// Convert unsigned 64-bit integer to string -// Returns length of string written (not including null terminator) - -#ifdef __cplusplus -extern "C" { -#endif - -size_t uint64_to_str(uint64_t val, char* buf); - -// Convert signed 64-bit integer to string -// Returns length of string written (not including null terminator) -size_t int64_to_str(int64_t val, char* buf); - -// Convert int to string (calls int64_to_str) -// Returns length of string written (not including null terminator) -size_t int_to_str(int val, char* buf); - -// Convert double to string with specified precision -// Returns length of string written (not including null terminator) -// precision: number of decimal places (-1 for default of 6) -size_t double_to_str(double val, char* buf, int precision); -size_t double_to_str_e(double val, char* buf, int precision); - -// Convert unsigned 64-bit integer to hexadecimal string -// Returns length of string written (not including null terminator) -// uppercase: 0 for lowercase (a-f), non-zero for uppercase (A-F) -size_t uint64_to_hex_str(uint64_t val, char* buf, int uppercase); - -// Simple vsnprintf/snprintf implementations for base/ (only for nostdlib builds) -// Supports: %d, %i, %u, %ld, %li, %lu, %lld, %lli, %llu, %zu, %x, %X, %lx, %lX, %llx, %llX, %p, %c, %s, %f, %g, %.Nf, %% -// Returns number of characters written (not including null terminator) -int base_vsnprintf(char *str, size_t size, const char *format, va_list args); - -// Simple snprintf implementation for base/ -// Supports: %d, %i, %u, %ld, %li, %lu, %lld, %lli, %llu, %zu, %x, %X, %lx, %lX, %llx, %llX, %p, %c, %s, %f, %g, %.Nf, %% -// Returns number of characters written (not including null terminator) -int base_snprintf(char *str, size_t size, const char *format, ...); -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/scratch.c b/src/mlir/vendor/base/scratch.c deleted file mode 100644 index 717ecee..0000000 --- a/src/mlir/vendor/base/scratch.c +++ /dev/null @@ -1,35 +0,0 @@ -#include -#include -#include - -Scratch scratch_begin_from_arena(Arena *arena) { - return (Scratch){.arena=arena, .saved_pos=arena_get_pos(arena)}; -} - -Scratch scratch_begin() { - return scratch_begin_avoid_conflict(NULL); -} - -Arena* scratch_arenas[2] = {NULL, NULL}; - -static void init_scratch_arenas(void) { - scratch_arenas[0] = arena_create(1024); - scratch_arenas[1] = arena_create(1024); -} - -Scratch scratch_begin_avoid_conflict(Arena *conflict) { - if (scratch_arenas[0] == NULL) { - init_scratch_arenas(); - } - for (int i = 0; i < 2; i++) { - if (scratch_arenas[i] != conflict) { - return scratch_begin_from_arena(scratch_arenas[i]); - } - } - FATAL_ERROR("Cannot find conflict-free arena."); - return (Scratch){NULL,{0}}; -} - -void scratch_end(Scratch scratch) { - arena_reset(scratch.arena, scratch.saved_pos); -} diff --git a/src/mlir/vendor/base/scratch.h b/src/mlir/vendor/base/scratch.h deleted file mode 100644 index a2f9344..0000000 --- a/src/mlir/vendor/base/scratch.h +++ /dev/null @@ -1,61 +0,0 @@ -#pragma once - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - Arena *arena; - arena_pos_t saved_pos; -} Scratch; - -// Internally there are 2 scratch arenas. You can use a scratch in the -// region marked by scratch_begin*() and scratch_end(). - -// Use if there are no other arenas that you allocate from in the scratch region. -// Always returns the first scratch arena. -Scratch scratch_begin(); - -// Use if there is another arena that you allocate from in the scratch region. -// Pass the other arena as an argument `conflict`. -// Returns a scratch arena that does not conflict with `conflict`. -/* -The example below shows the case when you need to call -scratch_begin_avoid_conflict(). The inner_fn() is returning result to the caller -using the `outer_arena`, which was allocated using scratch_begin() by the caller -in `outer_fn`. The inner arena must be allocated using -scratch_begin_avoid_conflict() otherwise both the outer_temp and outer_temp2 -will point to the same memory and we get a conflict (the result of outer_temp -will be lost). - - char* inner_fn(Arena *outer_arena) { - Scratch inner = scratch_begin_avoid_conflict(outer_arena); - char *result = arena_alloc(outer_arena, 50); - ... - scratch_end(inner); - return result; - } - - void outer_fn() { - Scratch outer = scratch_begin(); - char *outer_temp = inner_fn(outer.arena); - char *outer_temp2 = arena_alloc(outer.arena, 50); - ... - scratch_end(outer); - } -*/ -Scratch scratch_begin_avoid_conflict(Arena *conflict); - -// Use if there is another arena available in the region but you do not push -// into it in the scratch region. The scratch will be created in `arena`. -Scratch scratch_begin_from_arena(Arena *arena); - -// Marks the end of the scratch region. Resets the arena that was used to -// create the scratch to the position before the scratch. -void scratch_end(Scratch scratch); -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/stdarg.h b/src/mlir/vendor/base/stdarg.h deleted file mode 100644 index 5c40c91..0000000 --- a/src/mlir/vendor/base/stdarg.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -// Variadic arguments support -// This provides cross-platform variadic argument macros using compiler -// builtins. The typedefs use the same underlying types as the system -// on each platform (clang/gcc both implement 's -// va_list as `__builtin_va_list`; on MSVC va_list is `char*`), so they can -// safely coexist with the system header in a hosted TU. - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(_MSC_VER) -// MSVC varargs implementation -// x86: 4-byte alignment, x64/ARM64: 8-byte alignment -typedef char* va_list; - -#if defined(_M_X64) || defined(_M_ARM64) -#define _VA_ALIGN 8 -#else -#define _VA_ALIGN 4 -#endif - -#define _VA_ROUNDED_SIZE(t) ((sizeof(t) + _VA_ALIGN - 1) & ~(_VA_ALIGN - 1)) - -#ifndef va_start -#define va_start(ap, v) ((void)((ap) = (va_list)((char*)(&(v)) + _VA_ROUNDED_SIZE(v)))) -#define va_arg(ap, t) (*(t*)((ap += _VA_ROUNDED_SIZE(t)) - _VA_ROUNDED_SIZE(t))) -#define va_end(ap) ((void)((ap) = (va_list)0)) -#define va_copy(dest, src) ((dest) = (src)) -#endif - -#else -// Use compiler builtins for Clang/GCC -typedef __builtin_va_list va_list; - -#ifndef va_start -#define va_start(ap, last) __builtin_va_start((ap), (last)) -#define va_arg(ap, type) __builtin_va_arg((ap), type) -#define va_end(ap) __builtin_va_end((ap)) -#define va_copy(dest, src) __builtin_va_copy((dest), (src)) -#endif - -#endif - -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/strbuf.c b/src/mlir/vendor/base/strbuf.c deleted file mode 100644 index 6d645c0..0000000 --- a/src/mlir/vendor/base/strbuf.c +++ /dev/null @@ -1,72 +0,0 @@ -#include -#include -#include - -// Initial capacity granted on the first append when the buffer was created -// with capacity zero. Large enough that short strings never grow, small -// enough that we don't waste arena space on buffers that stay tiny. -#define STRBUF_MIN_CAP 64 - -strbuf strbuf_make(void) { - return (strbuf){NULL, 0, 0}; -} - -strbuf strbuf_make_cap(Arena *arena, uint64_t cap) { - strbuf b = (strbuf){NULL, 0, 0}; - if (cap > 0) { - b.str = arena_new_array(arena, char, cap); - b.cap = cap; - } - return b; -} - -// Grow the buffer so that at least `min_cap` total bytes are available. -// Doubling strategy: `new_cap = max(cap * 2, min_cap, STRBUF_MIN_CAP)`. -static void strbuf_grow(Arena *arena, strbuf *b, uint64_t min_cap) { - if (min_cap <= b->cap) return; - uint64_t new_cap = b->cap ? b->cap : STRBUF_MIN_CAP; - while (new_cap < min_cap) { - new_cap *= 2; - } - char *new_buf = arena_new_array(arena, char, new_cap); - if (b->size > 0) { - base_memcpy(new_buf, b->str, b->size); - } - b->str = new_buf; - b->cap = new_cap; -} - -void strbuf_reserve(Arena *arena, strbuf *b, uint64_t min_cap) { - assert(arena); - assert(b); - strbuf_grow(arena, b, min_cap); -} - -void strbuf_append_bytes(Arena *arena, strbuf *b, const void *p, uint64_t n) { - assert(arena); - assert(b); - if (n == 0) return; - strbuf_grow(arena, b, b->size + n); - base_memcpy(b->str + b->size, p, n); - b->size += n; -} - -void strbuf_append(Arena *arena, strbuf *b, string s) { - strbuf_append_bytes(arena, b, s.str, s.size); -} - -void strbuf_append_char(Arena *arena, strbuf *b, char c) { - assert(arena); - assert(b); - strbuf_grow(arena, b, b->size + 1); - b->str[b->size++] = c; -} - -void strbuf_append_cstr(Arena *arena, strbuf *b, const char *s) { - assert(s); - strbuf_append_bytes(arena, b, s, base_strlen(s)); -} - -string strbuf_to_string(strbuf b) { - return (string){b.str, b.size}; -} diff --git a/src/mlir/vendor/base/strbuf.h b/src/mlir/vendor/base/strbuf.h deleted file mode 100644 index 69960d8..0000000 --- a/src/mlir/vendor/base/strbuf.h +++ /dev/null @@ -1,63 +0,0 @@ -#pragma once - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -// Growable byte buffer with explicit capacity. -// -// `strbuf` exists for the "build up a string by appending to it" workload, -// where the read-only `string` (pointer + length view) type is the wrong -// abstraction — there is no capacity to track and every `str_concat` would -// have to copy the accumulator. -// -// The arena that owns the backing memory is NOT stored inside `strbuf`; -// callers pass it to every mutating call. This lets a caller: -// - build a temporary buffer in a scratch arena, copy the final view -// into a long-lived arena, then `scratch_end`; or -// - build directly in a long-lived arena when the result must outlive -// the call. -// -// On growth, `strbuf` allocates a fresh buffer (capacity doubled) from the -// arena and memcpys the existing contents. The old buffer is left as -// arena slack — bounded at ≤2× the final size geometrically. Use -// `strbuf_make_cap()` with a reasonable initial capacity to avoid early -// reallocations in hot loops. - -typedef struct { - char *str; // mutable buffer (NOT NUL-terminated; same convention as `string`) - uint64_t size; // current length - uint64_t cap; // allocated capacity -} strbuf; - -// Initialise to an empty, unallocated buffer (size=0, cap=0). -// Equivalent to a zero-initialised struct literal `(strbuf){0}`. -strbuf strbuf_make(void); - -// Initialise with at least `cap` bytes of capacity pre-reserved. Useful -// for hot loops and large outputs to avoid repeated doublings. If -// `cap == 0` no allocation is performed; the first append will allocate. -strbuf strbuf_make_cap(Arena *arena, uint64_t cap); - -// Append bytes. Grows by doubling when needed. -void strbuf_append(Arena *arena, strbuf *b, string s); -void strbuf_append_char(Arena *arena, strbuf *b, char c); -void strbuf_append_cstr(Arena *arena, strbuf *b, const char *s); -void strbuf_append_bytes(Arena *arena, strbuf *b, const void *p, uint64_t n); - -// Ensure the buffer has at least `min_cap` bytes of total capacity. No-op -// if already sufficient. -void strbuf_reserve(Arena *arena, strbuf *b, uint64_t min_cap); - -// View the current contents as an immutable `string` (no copy). -// Subsequent mutating calls may invalidate the returned view if growth -// moves the underlying buffer. -string strbuf_to_string(strbuf b); - -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/string.c b/src/mlir/vendor/base/string.c deleted file mode 100644 index a4a87d5..0000000 --- a/src/mlir/vendor/base/string.c +++ /dev/null @@ -1,94 +0,0 @@ -#include -#include -#include -#include - -string str_from_cstr_view(char *cstr) { - return (string){cstr, base_strlen(cstr)}; -} - -string str_from_cstr_len_view(char *cstr, uint64_t size) { - return (string){cstr, size}; -} - -string str_from_cstr_len_view_const(const char *cstr, uint64_t size) { - return (string){(char*)cstr, size}; -} - -char *str_to_cstr_copy(Arena *arena, string str) { - char *cstr = arena_new_array(arena, char, str.size+1); - base_memcpy(cstr, str.str, str.size); - cstr[str.size] = '\0'; - return cstr; -} - -bool str_eq(string a, string b) { - if (a.size == b.size) { - return (base_memcmp(a.str, b.str, a.size) == 0); - } else { - return false; - } -} - -string str_substr(string str, uint64_t min, uint64_t size) { - return (string){str.str+min, size}; -} - -string int_to_string(Arena *arena, int64_t value) { - char buf[32]; - size_t len = int64_to_str(value, buf); - char *str = arena_new_array(arena, char, len); - base_memcpy(str, buf, len); - return (string){str, len}; -} - -string uint_to_string(Arena *arena, uint64_t value) { - char buf[32]; - size_t len = uint64_to_str(value, buf); - char *str = arena_new_array(arena, char, len); - base_memcpy(str, buf, len); - return (string){str, len}; -} - -string double_to_string(Arena *arena, double value, int precision) { - char buf[32]; - size_t len = double_to_str(value, buf, precision); - char *str = arena_new_array(arena, char, len); - base_memcpy(str, buf, len); - return (string){str, len}; -} - -string char_to_string(Arena *arena, char c) { - char *buf = arena_new_array(arena, char, 1); - *buf = c; - return (string){buf, 1}; -} - -string str_concat(Arena *arena, string a, string b) { - if (b.size == 0) return a; - if (a.size == 0) return str_copy(arena, b); - size_t total = a.size + b.size; - char *str = arena_new_array(arena, char, total); - base_memcpy(str, a.str, a.size); - base_memcpy(str + a.size, b.str, b.size); - return (string){str, total}; -} - -string str_copy(Arena *arena, string a) { - char *str = NULL; - if (a.size > 0) { - str = arena_new_array(arena, char, a.size); - base_memcpy(str, a.str, a.size); - } - return (string){str, a.size}; -} - -uint32_t str_hash(string str) { - // FNV-1a hash - uint32_t hash = 2166136261u; - for (size_t i = 0; i < str.size; i++) { - hash ^= (uint32_t)(unsigned char)str.str[i]; - hash *= 16777619u; - } - return hash; -} diff --git a/src/mlir/vendor/base/string.h b/src/mlir/vendor/base/string.h deleted file mode 100644 index 5b1d5ee..0000000 --- a/src/mlir/vendor/base/string.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -// Non-null-terminated string, represented by a pointer and a length. - -// The string is typically owned by the Arena, so `string` can be seen as a -// "view" of the string. - -typedef struct { - char *str; - uint64_t size; -} string; - -#define str_lit(S) str_from_cstr_len_view_const(S, sizeof(S)-1) - -string str_from_cstr_view(char *cstr); -string str_from_cstr_len_view(char *cstr, uint64_t size); -string str_from_cstr_len_view_const(const char *cstr, uint64_t size); -char *str_to_cstr_copy(Arena *arena, string str); -bool str_eq(string a, string b); -string str_substr(string str, uint64_t min, uint64_t max); - -string int_to_string(Arena *arena, int64_t value); -string uint_to_string(Arena *arena, uint64_t value); -string double_to_string(Arena *arena, double value, int precision); -string char_to_string(Arena *arena, char c); -string str_concat(Arena *arena, string a, string b); -string str_copy(Arena *arena, string a); -uint32_t str_hash(string str); - - - -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/types.h b/src/mlir/vendor/base/types.h deleted file mode 100644 index d146276..0000000 --- a/src/mlir/vendor/base/types.h +++ /dev/null @@ -1,132 +0,0 @@ -#pragma once - -// Basic integer types and a few macros. -// -// corec defines its own size_t/uint8_t/int64_t/etc. typedefs and integer -// limit macros. These typedefs use the same underlying primitive types as -// every libc we target (size_t = unsigned long on 64-bit Unix and -// uint64_t/Windows; int64_t = long long; uint8_t = unsigned char; ...). -// C11 and C++ both permit redundant identical typedef redeclarations, so -// these definitions can coexist with system // -// in the same TU. -// -// Macros (NULL, SIZE_MAX, INT*_MAX, FLT_MAX, true/false) are guarded with -// #ifndef so they don't clash with the system definitions if those happen -// to be included first (e.g. via libc++ headers in a hosted C++ TU). -// -// The result: corec headers never include any system or libc header, while -// remaining safe to include in hosted C/C++ TUs (e.g. when bridging the -// mlir C API to upstream LLVM/MLIR). - -#ifdef __cplusplus -extern "C" { -#endif - -typedef unsigned char uint8_t; -typedef unsigned short uint16_t; -typedef unsigned int uint32_t; - -// On Linux x86_64, long is 64 bits, so use unsigned long for uint64_t -// On other platforms (especially Windows), long is 32 bits, so use unsigned long long -#if defined(__linux__) && defined(__x86_64__) -typedef unsigned long uint64_t; -#else -typedef unsigned long long uint64_t; -#endif - -typedef signed char int8_t; -typedef signed short int16_t; -typedef signed int int32_t; - -#if defined(__linux__) && defined(__x86_64__) -typedef long int64_t; -#else -typedef signed long long int64_t; -#endif - -// Pointer-sized integer type and size types - -#if defined(_WIN32) && defined(_WIN64) - // For 64 bit Windows the long is 4 bytes, but pointer is 8 bytes - typedef uint64_t uintptr_t; - typedef int64_t ptrdiff_t; -#else - // For 32 bit platforms and wasm64 the long and a pointer is 4 bytes, for - // 64 bit macOS/Linux the long and pointer is 8 bytes - typedef unsigned long uintptr_t; - typedef long ptrdiff_t; -#endif - -#if defined(_WIN32) && defined(_WIN64) - // 64 bit Windows has 8 byte size_t (but 4 byte long) - typedef uint64_t size_t; - typedef int64_t ssize_t; -#else - // All other platforms have long and size_t the same number of bytes (4 or - // 8) - typedef unsigned long size_t; - typedef signed long ssize_t; -#endif - -#ifndef NULL -# ifdef __cplusplus -# define NULL nullptr -# else -# define NULL ((void*)0) -# endif -#endif - -#ifndef __cplusplus -// In C, bool is provided by (a macro for _Bool). Mirror that. -# ifndef bool -# define bool _Bool -# endif -# ifndef true -# define true 1 -# endif -# ifndef false -# define false 0 -# endif -#endif - -#ifndef SIZE_MAX -#define SIZE_MAX ((size_t)-1) -#endif - -#ifndef INT8_C -#define INT8_C(value) value -#define UINT8_C(value) value##u -#define INT16_C(value) value -#define UINT16_C(value) value##u -#define INT32_C(value) value -#define UINT32_C(value) value##u -#define INT64_C(value) value##ll -#define UINT64_C(value) value##ull -#define INTMAX_C(value) INT64_C(value) -#define UINTMAX_C(value) UINT64_C(value) -#endif - -#ifndef UINT16_MAX -#define UINT16_MAX ((uint16_t)0xFFFFu) -#endif -#ifndef INT32_MAX -#define INT32_MAX ((int32_t)0x7FFFFFFF) -#endif -#ifndef UINT32_MAX -#define UINT32_MAX ((uint32_t)0xFFFFFFFFu) -#endif -#ifndef INT64_MAX -#define INT64_MAX ((int64_t)0x7FFFFFFFFFFFFFFFll) -#endif -#ifndef UINT64_MAX -#define UINT64_MAX ((uint64_t)0xFFFFFFFFFFFFFFFFull) -#endif -#ifndef FLT_MAX -#define FLT_MAX 3.402823466e+38F -#endif - -#define array_size(a) (sizeof(a) / sizeof((a)[0])) - -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/vector.h b/src/mlir/vendor/base/vector.h deleted file mode 100644 index 332d1dd..0000000 --- a/src/mlir/vendor/base/vector.h +++ /dev/null @@ -1,78 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -// --- Helper Macros (internal use) --- - -#ifdef __cplusplus -extern "C" { -#endif - -#define _GV_CONCAT_IMPL(a, b) a##b -#define _GV_CONCAT(a, b) _GV_CONCAT_IMPL(a, b) - -#define _GV_CONCAT3_IMPL(a, b, c) a##b##c -#define _GV_CONCAT3(a, b, c) _GV_CONCAT3_IMPL(a, b, c) - -// --- Conditional Compilation Helper for WITH_BASE_ASSERT --- -#if defined(WITH_BASE_ASSERT) - #define IF_GENERIC_VECTOR_WITH_BASE_ASSERT(code) code - // This constant is used for assertion checks. - // Declared static const for internal linkage, avoiding multiple definition errors. - static const int GV_INTERNAL_RESERVE_CALLED_MAGIC = 0xDEADBEEF; -#else - #define IF_GENERIC_VECTOR_WITH_BASE_ASSERT(code) -#endif - -// --- Main Macro to Define a Vector Type and its Functions --- -// TYPE: The data type to be stored (e.g., int, MyStructA). -// NAME: A prefix for the generated struct and function names (e.g., IntVec, MyStructAVec). -// - Struct type will be: NAME -// - Functions will be: NAME_init, NAME_reserve, NAME_push_back. -#define DEFINE_VECTOR_FOR_TYPE(TYPE, NAME) \ - \ - /* Vector Struct Definition */ \ - typedef struct NAME { \ - TYPE *data; \ - size_t size; \ - size_t max; \ - /* This field is conditionally compiled based on WITH_BASE_ASSERT */ \ - IF_GENERIC_VECTOR_WITH_BASE_ASSERT(int reserve_called_flag;) \ - } NAME; \ - \ - /* Reserves memory for at least 'new_max_capacity' elements. */ \ - /* Resets size to 0. Old data is not preserved. */ \ - static inline void _GV_CONCAT3(NAME, _, reserve)(Arena *arena, NAME *vec, size_t new_max_capacity) { \ - vec->size = 0; \ - if (new_max_capacity <= 0) new_max_capacity = 1; /* Minimum capacity of 1 */ \ - vec->data = arena_new_array(arena, TYPE, new_max_capacity); \ - vec->max = new_max_capacity; \ - IF_GENERIC_VECTOR_WITH_BASE_ASSERT(vec->reserve_called_flag = GV_INTERNAL_RESERVE_CALLED_MAGIC;) \ - } \ - \ - /* Adds an element to the end of the vector, resizing if necessary. */ \ - static inline void _GV_CONCAT3(NAME, _, push_back)(Arena *arena, NAME *vec, TYPE value) { \ - IF_GENERIC_VECTOR_WITH_BASE_ASSERT( \ - assert(vec->reserve_called_flag == GV_INTERNAL_RESERVE_CALLED_MAGIC && \ - "Vector reserve() not called before push_back()."); \ - ) \ - if (vec->size == vec->max) { \ - size_t new_max_capacity = 2 * vec->max; \ - TYPE* new_data = arena_new_array(arena, TYPE, new_max_capacity); \ - base_memcpy(new_data, vec->data, sizeof(TYPE) * vec->size); \ - vec->data = new_data; \ - vec->max = new_max_capacity; \ - } \ - vec->data[vec->size] = value; \ - vec->size++; \ - } - - - -DEFINE_VECTOR_FOR_TYPE(int64_t, vector_i64) -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/mlir_api.h b/src/mlir/vendor/mlir_api.h deleted file mode 100644 index 9b13578..0000000 --- a/src/mlir/vendor/mlir_api.h +++ /dev/null @@ -1,1104 +0,0 @@ -// Public MLIR C API declarations without exposing internal data structures. -// Implementations can back these APIs with different MLIR representations. - -#pragma once - -#include -#include - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -// ----------------------------------------------------------------------------- -// Handle types - opaque integer handles replacing raw pointers -// ----------------------------------------------------------------------------- - -typedef uintptr_t MLIR_OpHandle; -typedef uintptr_t MLIR_RegionHandle; -typedef uintptr_t MLIR_BlockHandle; -typedef uintptr_t MLIR_ValueHandle; -typedef uintptr_t MLIR_TypeHandle; -typedef uintptr_t MLIR_AttributeHandle; -typedef uintptr_t MLIR_LocationHandle; - -#define MLIR_INVALID_HANDLE 0 - -typedef struct MLIR_Context { - Arena *arena; - // When true, MLIR_CreateOp* skips building the per-operand def-use - // chains (UseNode allocations + the parallel operand_uses / - // successor_operand_uses arrays). The def-use machinery is only needed - // by the cf->scf and lower-to-LLVM passes; the wasm -> wasmstack -> - // wasmssa -> llvm -> aarch64 -> macho pipeline never queries uses, so - // disabling it there removes a large per-op memory overhead. Defaults - // to false (tracking on) so all existing callers are unaffected. - bool no_def_use_tracking; - // When non-NULL, the process-wide type/struct intern registry allocates - // its IR_Type objects AND its handle arrays into this arena instead of - // `arena`. The streaming llvm->aarch64->macho backend lowers each function - // into a throwaway temp arena (swapping `arena`) but must keep interned - // types — which are cached in the global registry across functions — in a - // persistent arena so cached handles never dangle after a temp arena is - // released. Defaults to NULL (= use `arena`, no behaviour change). - Arena *type_arena; -} MLIR_Context; - -typedef struct MLIR_LocationMap { - void *impl; -} MLIR_LocationMap; - -size_t MLIR_GetLocationMapSize(const MLIR_LocationMap *location_map); -size_t MLIR_CollectLocationMap(const MLIR_LocationMap *location_map, string *out_keys, MLIR_LocationHandle *out_locs, size_t max); - -// Vector helpers used by the parser implementation -DEFINE_VECTOR_FOR_TYPE(MLIR_OpHandle, VecOp) -DEFINE_VECTOR_FOR_TYPE(MLIR_ValueHandle, VecValue) -DEFINE_VECTOR_FOR_TYPE(MLIR_BlockHandle, VecBlock) -DEFINE_VECTOR_FOR_TYPE(MLIR_AttributeHandle, VecAttribute) - -// ----------------------------------------------------------------------------- -// Operation kinds -// ----------------------------------------------------------------------------- - -typedef enum { - // Core ops - OP_TYPE_UNREGISTERED = 0, - OP_TYPE_MODULE, - - // Arithmetic dialect - OP_TYPE_ARITH_ADDI, - OP_TYPE_ARITH_SUBI, - OP_TYPE_ARITH_MULI, - OP_TYPE_ARITH_DIVI, - OP_TYPE_ARITH_ADDF, - OP_TYPE_ARITH_SUBF, - OP_TYPE_ARITH_MULF, - OP_TYPE_ARITH_DIVF, - OP_TYPE_ARITH_CONSTANT, - OP_TYPE_ARITH_CMPI, - OP_TYPE_ARITH_CMPF, - OP_TYPE_ARITH_SELECT, - OP_TYPE_ARITH_BITCAST, - OP_TYPE_ARITH_SITOFP, - OP_TYPE_ARITH_FPTOSI, - OP_TYPE_ARITH_INDEX_CAST, - OP_TYPE_ARITH_EXTSI, - OP_TYPE_ARITH_TRUNCI, - OP_TYPE_ARITH_EXTF, - OP_TYPE_ARITH_TRUNCF, - OP_TYPE_ARITH_EXTUI, - OP_TYPE_ARITH_MAXF, - OP_TYPE_ARITH_DIVSI, - OP_TYPE_ARITH_REMSI, - OP_TYPE_ARITH_DIVUI, - OP_TYPE_ARITH_REMUI, - OP_TYPE_ARITH_SHRUI, - OP_TYPE_ARITH_ORI, - OP_TYPE_ARITH_MINSI, - OP_TYPE_ARITH_ANDI, - - // Math dialect - OP_TYPE_MATH_EXP, - OP_TYPE_MATH_LOG, - - // Memory dialect - OP_TYPE_MEMREF_LOAD, - OP_TYPE_MEMREF_STORE, - OP_TYPE_MEMREF_ALLOC, - OP_TYPE_MEMREF_DEALLOC, - - // Control flow - OP_TYPE_CF_BR, - OP_TYPE_CF_COND_BR, - OP_TYPE_CF_SWITCH, - - // Function dialect - OP_TYPE_FUNC_FUNC, - OP_TYPE_FUNC_RETURN, - OP_TYPE_FUNC_CALL, - OP_TYPE_FUNC_CALL_INDIRECT, - OP_TYPE_FUNC_CONSTANT, - OP_TYPE_UNREALIZED_CONVERSION_CAST, - - // SCF dialect - OP_TYPE_SCF_FOR, - OP_TYPE_SCF_WHILE, - OP_TYPE_SCF_IF, - OP_TYPE_SCF_YIELD, - OP_TYPE_SCF_CONDITION, - OP_TYPE_SCF_INDEX_SWITCH, - - // Triton dialect - OP_TYPE_TT_GET_PROGRAM_ID, - OP_TYPE_TT_LOAD, - OP_TYPE_TT_STORE, - OP_TYPE_TT_MAKE_RANGE, - OP_TYPE_TT_SPLAT, - OP_TYPE_TT_ADDPTR, - OP_TYPE_TT_RETURN, - OP_TYPE_TT_FUNC, - OP_TYPE_TT_CALL, - OP_TYPE_TT_REDUCE, - OP_TYPE_TT_BROADCAST, - OP_TYPE_TT_EXPAND_DIMS, - OP_TYPE_TT_DOT, - OP_TYPE_TT_PURE_EXTERN_ELEMENTWISE, - - // GPU dialect - OP_TYPE_GPU_LAUNCH, - - // Affine dialect - OP_TYPE_AFFINE_FOR, - OP_TYPE_AFFINE_LOAD, - - // Vector dialect - OP_TYPE_VECTOR_PRINT, - - // Standard dialect - OP_TYPE_STD_CONSTANT, - OP_TYPE_STD_RETURN, - - // Tensor dialect - OP_TYPE_TENSOR_EXTRACT, - OP_TYPE_TENSOR_SPLAT, - OP_TYPE_TENSOR_COLLAPSE_SHAPE, - - // Linalg dialect - OP_TYPE_LINALG_FILL, - OP_TYPE_LINALG_COPY, - - // Index dialect - OP_TYPE_INDEX_CONSTANT, - - // LLVM dialect - OP_TYPE_LLVM_MLIR_UNDEF, - OP_TYPE_LLVM_ALLOCA, - OP_TYPE_LLVM_LOAD, - OP_TYPE_LLVM_STORE, - OP_TYPE_LLVM_GEP, - OP_TYPE_LLVM_MLIR_ZERO, - OP_TYPE_LLVM_MLIR_CONSTANT, - OP_TYPE_LLVM_ICMP, - OP_TYPE_LLVM_MLIR_ADDRESSOF, - OP_TYPE_LLVM_MLIR_GLOBAL, - OP_TYPE_LLVM_RETURN, - OP_TYPE_LLVM_PTRTOINT, - OP_TYPE_LLVM_FUNC, - OP_TYPE_LLVM_CALL, - OP_TYPE_LLVM_SEXT, - OP_TYPE_LLVM_ADD, - OP_TYPE_LLVM_SUB, - OP_TYPE_LLVM_MUL, - OP_TYPE_LLVM_SDIV, - OP_TYPE_LLVM_UDIV, - OP_TYPE_LLVM_SREM, - OP_TYPE_LLVM_UREM, - OP_TYPE_LLVM_AND, - OP_TYPE_LLVM_OR, - OP_TYPE_LLVM_XOR, - OP_TYPE_LLVM_SHL, - OP_TYPE_LLVM_LSHR, - OP_TYPE_LLVM_ASHR, - OP_TYPE_LLVM_TRUNC, - OP_TYPE_LLVM_ZEXT, - OP_TYPE_ARITH_XORI, - OP_TYPE_ARITH_SHLI, - OP_TYPE_ARITH_SHRSI, - - // Return operations - OP_TYPE_RETURN, - OP_TYPE_TT_REDUCE_RETURN, - - // ------------------------------------------------------------------------- - // wasmssa dialect — high-level SSA-form WebAssembly ops. Produced by - // the LLVM-dialect -> wasmssa lowering pass and consumed by the - // wasmssa -> wasmstack stackification pass. All values are SSA; - // there are no explicit local.get / local.set / local.tee here. - // - // Op operand-order convention (non-commutative ops): - // sub: %r = wasmssa.sub %lhs, %rhs ; emits "lhs rhs i32.sub" - // load: %r = wasmssa.load %addr ; offset/align as attrs - // store: wasmssa.store %addr, %val - // ------------------------------------------------------------------------- - OP_TYPE_WASMSSA_FUNC, - OP_TYPE_WASMSSA_IMPORT_FUNC, - OP_TYPE_WASMSSA_IMPORT_GLOBAL, - OP_TYPE_WASMSSA_CONST, - OP_TYPE_WASMSSA_ADD, - OP_TYPE_WASMSSA_SUB, - OP_TYPE_WASMSSA_BINOP, - OP_TYPE_WASMSSA_UNOP, - OP_TYPE_WASMSSA_LOAD, - OP_TYPE_WASMSSA_STORE, - OP_TYPE_WASMSSA_GLOBAL_GET, - OP_TYPE_WASMSSA_GLOBAL_SET, - OP_TYPE_WASMSSA_EXTEND_I32_S, - OP_TYPE_WASMSSA_RETURN, - OP_TYPE_WASMSSA_CALL, - // Region-bearing structured control flow. Cross-CF value passing is - // modelled via MLIR block arguments on the region's entry block (for - // loops) and via the variadic operands of block_return / br (for all - // three op kinds). Results of the region-bearing op carry the values - // that flow out via fall-through or `br` to its label. - // - // %r:R* = wasmssa.block () : (R*) { ... } - // %r:R* = wasmssa.loop (init:T*) : (R*) { ^entry(a:T*): ... } - // %r:R* = wasmssa.if (%cond:i32) : (R*) { then } else { else } - // - // Region terminators: block_return | br | br_if (non-terminator) | - // unreachable | return. - OP_TYPE_WASMSSA_BLOCK, - OP_TYPE_WASMSSA_LOOP, - OP_TYPE_WASMSSA_IF, - // Region terminator carrying the values that flow out of the enclosing - // wasmssa.block / wasmssa.loop / wasmssa.if via fall-through. - OP_TYPE_WASMSSA_BLOCK_RETURN, - // Terminator emitting wasm `unreachable` (0x00). Used after wasmssa.loop - // when the loop never falls through (every back-edge `br 0` or outward - // `br N` exits the loop's own end). - OP_TYPE_WASMSSA_UNREACHABLE, - // Branch carrying variadic values matching the target label's signature - // (depth-relative). Terminator. - OP_TYPE_WASMSSA_BR, - // Conditional branch carrying only the condition; no value operands. - // For value-carrying conditional branches we use `wasmssa.if %cond { br N (vals) }`. - OP_TYPE_WASMSSA_BR_IF, - OP_TYPE_WASMSSA_SELECT, - OP_TYPE_WASMSSA_EQZ, - OP_TYPE_WASMSSA_ADDRESSOF, - // Function-pointer support: FUNC_ADDR pushes the table-index of a - // named function (lowered via R_WASM_TABLE_INDEX_SLEB); CALL_INDIRECT - // pops args + table-index and dispatches via wasm `call_indirect`. - OP_TYPE_WASMSSA_FUNC_ADDR, - OP_TYPE_WASMSSA_CALL_INDIRECT, - // Wasm function-locals access. Each function has a fixed set of - // typed locals (params + declared locals). LOCAL_GET reads slot - // `local_idx`, LOCAL_SET writes it. Locals are NEVER address-taken - // in wasm semantics, so they live in a native (non-linmem) stack - // frame that the llvm->aarch64 backend allocates. The lifter used - // to spill them into linmem cells (8 bytes each), which inflated - // the wasm stack by ~20x and forced unrealistic stack-size grows. - // attrs: valtype (i32 byte: i32|i64|f32|f64), local_idx (i32). - OP_TYPE_WASMSSA_LOCAL_GET, - OP_TYPE_WASMSSA_LOCAL_SET, - // WebAssembly memory instructions: `memory.size` (0x3F 0x00) and - // `memory.grow` (0x40 0x00). MEMORY_SIZE has no operands and an i32 - // result (size in pages). MEMORY_GROW takes one i32 operand (pages - // to grow by) and returns the previous size in pages (or -1 on - // failure) as i32. Both carry a trailing single-byte immediate - // identifying the memory index (always 0 for the default memory). - OP_TYPE_WASMSSA_MEMORY_SIZE, - OP_TYPE_WASMSSA_MEMORY_GROW, - - // ------------------------------------------------------------------------- - // wasmstack dialect — low-level stack-machine WebAssembly ops. 1:1 - // with the wasm bytecode opcodes. Produced by the wasmssa -> wasmstack - // stackification pass and consumed by the binary emitter. - // ------------------------------------------------------------------------- - OP_TYPE_WASMSTACK_FUNC, - OP_TYPE_WASMSTACK_IMPORT_FUNC, - OP_TYPE_WASMSTACK_IMPORT_GLOBAL, - OP_TYPE_WASMSTACK_LOCAL_GET, - OP_TYPE_WASMSTACK_LOCAL_SET, - OP_TYPE_WASMSTACK_LOCAL_TEE, - OP_TYPE_WASMSTACK_CONST, - OP_TYPE_WASMSTACK_ADD, - OP_TYPE_WASMSTACK_SUB, - OP_TYPE_WASMSTACK_BINOP, - OP_TYPE_WASMSTACK_UNOP, - OP_TYPE_WASMSTACK_LOAD, - OP_TYPE_WASMSTACK_STORE, - OP_TYPE_WASMSTACK_GLOBAL_GET, - OP_TYPE_WASMSTACK_GLOBAL_SET, - OP_TYPE_WASMSTACK_EXTEND_I32_S, - OP_TYPE_WASMSTACK_RETURN, - OP_TYPE_WASMSTACK_CALL, - // Structured-CF + select. - OP_TYPE_WASMSTACK_BLOCK, - OP_TYPE_WASMSTACK_LOOP, - OP_TYPE_WASMSTACK_IF, - OP_TYPE_WASMSTACK_ELSE, - OP_TYPE_WASMSTACK_END, - OP_TYPE_WASMSTACK_BR, - OP_TYPE_WASMSTACK_BR_IF, - // Terminator emitting wasm `unreachable` (0x00). - OP_TYPE_WASMSTACK_UNREACHABLE, - OP_TYPE_WASMSTACK_SELECT, - OP_TYPE_WASMSTACK_EQZ, - OP_TYPE_WASMSTACK_ADDRESSOF, - OP_TYPE_WASMSTACK_FUNC_ADDR, - OP_TYPE_WASMSTACK_CALL_INDIRECT, - // 1:1 wasmstack mirrors of OP_TYPE_WASMSSA_MEMORY_{SIZE,GROW}. - OP_TYPE_WASMSTACK_MEMORY_SIZE, - OP_TYPE_WASMSTACK_MEMORY_GROW, - // `drop` (wasm 0x1a): pop one stack value, no result. Only used by - // the wasm -> wasmstack lifter; the C-frontend wasmssa pipeline - // never emits this op. - OP_TYPE_WASMSTACK_DROP, - // `br_table`: emitted by clang for switch dispatch in linked - // runtime objects. Carries a comma-separated list of target depths - // plus a default depth. - OP_TYPE_WASMSTACK_BR_TABLE, - // Module-level data segment lifted from a wasm DATA section. The - // wasmstack -> wasmssa pass converts this into a wasmssa.import_global - // sized appropriately. - OP_TYPE_WASMSTACK_DATA_SEGMENT, - // Module-level global declaration with an initial value. Lifted - // from the wasm GLOBAL section. The backend allocates a static - // i64 slot per global; only the initial value matters. - OP_TYPE_WASMSTACK_GLOBAL_DECL, - - // Module-level table entry lifted from a wasm ELEM section. Carries - // (slot, target) — i.e. table_slot_index N now contains a reference - // to function `target`. The wasmstack -> wasmssa pass collects these - // and emits a synthetic wasmssa.func "_tinyc_fnptr_init" containing - // one wasmssa.func_addr per entry, so the lifter pre-pass sees them. - OP_TYPE_WASMSTACK_FUNC_ADDR_DECL, - - // ------------------------------------------------------------------------- - // aarch64 dialect — 1:1 with the AArch64 instruction encoding. The - // `aarch64 → Mach-O` backend is a "dumb" byte emitter; all isel / - // register-allocation knowledge lives in the `llvm → aarch64` lowering. - // First-light slice: just enough to run `int main() { return 42; }` - // and have its return value become the process exit code via a - // direct `svc #0x80` Mach syscall (no `proc_exit` shim required). - // ------------------------------------------------------------------------- - OP_TYPE_AARCH64_FUNC, - OP_TYPE_AARCH64_MOVZ, // movz Wd|Xd, #imm16, LSL #(hw*16) - OP_TYPE_AARCH64_MOVK, // movk Wd|Xd, #imm16, LSL #(hw*16) - OP_TYPE_AARCH64_MOV_X, // mov Xd, Xn (register move; X-form) - OP_TYPE_AARCH64_BL, // bl (branch-and-link, PC-relative) - OP_TYPE_AARCH64_BLR, // blr Xn (indirect branch-and-link via register) - OP_TYPE_AARCH64_SVC, // svc #imm16 - OP_TYPE_AARCH64_RET, // ret (== ret x30) - - // Arithmetic + memory + stack-frame ops added in the arith slice. - OP_TYPE_AARCH64_ADD_IMM, // add Wd|Xd, Wn|Xn, #imm12 (LSL 0) - OP_TYPE_AARCH64_SUB_IMM, // sub Wd|Xd, Wn|Xn, #imm12 (LSL 0) - OP_TYPE_AARCH64_ADD_REG, // add Wd|Xd, Wn|Xn, Wm|Xm - OP_TYPE_AARCH64_SUB_REG, // sub Wd|Xd, Wn|Xn, Wm|Xm - OP_TYPE_AARCH64_MUL, // mul Wd|Xd, Wn|Xn, Wm|Xm (== madd ..., xzr) - OP_TYPE_AARCH64_SDIV, // sdiv Wd|Xd, Wn|Xn, Wm|Xm - OP_TYPE_AARCH64_UDIV, // udiv Wd|Xd, Wn|Xn, Wm|Xm - OP_TYPE_AARCH64_MSUB, // msub Wd, Wn, Wm, Wa (used for srem/urem) - OP_TYPE_AARCH64_AND_REG, // and Wd|Xd, Wn|Xn, Wm|Xm - OP_TYPE_AARCH64_AND_IMM, // and Wd|Xd, Wn|Xn, #(1<) - OP_TYPE_AARCH64_ADD_DATA_LO, // add Xd, Xn, #lo12() - // Function prologue/epilogue (modeled as an op pair so the dumb - // backend can emit the exact instruction sequence; details of - // sp/fp/lr handling baked into the encoder). - OP_TYPE_AARCH64_PROLOGUE, - OP_TYPE_AARCH64_EPILOGUE, - // Comparison + condition-set. Used to materialise i32 booleans for - // `llvm.icmp` and eqz results. - OP_TYPE_AARCH64_CMP_REG, // cmp Wn, Wm (== subs Wzr, Wn, Wm) - OP_TYPE_AARCH64_CMP_IMM, // cmp Wn, #imm12 (== subs Wzr, Wn, #imm12) - OP_TYPE_AARCH64_CSET, // cset Wd, COND (== csinc Wd, Wzr, Wzr, invert(COND)) - // Conditional select. `csel Wd, Wn, Wm, COND`. Used for llvm.select. - OP_TYPE_AARCH64_CSEL, - // Control-flow ops. `target` attribute is the symbolic label name. - // The macho backend tracks all `aarch64.label` positions inside a - // function and patches the branch immediates after layout. - OP_TYPE_AARCH64_B, // b