From 81bef7cfe02481f385f04004c5a7043d7252240f Mon Sep 17 00:00:00 2001 From: Alex Cameron Date: Mon, 9 Nov 2026 03:59:07 +0000 Subject: [PATCH 1/8] feat(pipeline): inline Forth words before lowering the stack The Forth dialect registered no inliner interface, so the inliner refused any word that still held a Forth op after memref lowering. A word that reads TID-X or calls BARRIER reached PTX as a .visible .func. Compile-time stack flattening needs every word inlined into its kernel before the stack is lowered, so the inliner moves ahead of that stage. Its canonicalizer then deletes Forth code whose result is never stored. optimization.forth and source-locations.forth inspected such code, so they store their values. --- lib/Conversion/Passes.cpp | 15 ++++++++------- lib/Dialect/Forth/ForthDialect.cpp | 16 +++++++++++++++- test/Pipeline/inline-gpu-words.forth | 17 +++++++++++++++++ test/Pipeline/optimization.forth | 3 +-- test/Pipeline/source-locations.forth | 7 ++++--- 5 files changed, 45 insertions(+), 13 deletions(-) create mode 100644 test/Pipeline/inline-gpu-words.forth diff --git a/lib/Conversion/Passes.cpp b/lib/Conversion/Passes.cpp index 32e99eb..239b2c5 100644 --- a/lib/Conversion/Passes.cpp +++ b/lib/Conversion/Passes.cpp @@ -89,15 +89,16 @@ static StringRef getBinaryFormat(gpu::CompilationTarget target) { void buildWarpForthLoweringPipeline(OpPassManager &pm, const WarpForthPipelineOptions &options) { - // Stage 1: Lower Forth to MemRef (CF ops pass through as-is) - pm.addPass(createConvertForthToMemRefPass()); - - // Stage 2: Inline user words while both callers and callees are func.func. - // MLIR's GPU inliner does not support inlining a func.func region into a - // gpu.func region, so this must precede GPU conversion. + // Stage 1: Inline user words while they are still Forth, so the kernel is the + // whole program when its stack is lowered. MLIR's GPU inliner does not + // support inlining a func.func region into a gpu.func region, so this must + // precede GPU conversion. pm.addPass(createInlinerPass()); - // Stage 3: Convert to GPU dialect (includes private address space annotation) + // Stage 2: Lower Forth to MemRef (CF ops pass through as-is) + pm.addPass(createConvertForthToMemRefPass()); + + // Stage 3: Convert to GPU dialect pm.addPass(createConvertForthToGPUPass()); // Stage 4: Optimize the materialized stack and memory IR in the kernel. diff --git a/lib/Dialect/Forth/ForthDialect.cpp b/lib/Dialect/Forth/ForthDialect.cpp index aa410a3..162c1cd 100644 --- a/lib/Dialect/Forth/ForthDialect.cpp +++ b/lib/Dialect/Forth/ForthDialect.cpp @@ -7,7 +7,8 @@ #include "warpforth/Dialect/Forth/ForthDialect.h" #include "mlir/IR/Builders.h" // IWYU pragma: keep #include "mlir/IR/DialectImplementation.h" // IWYU pragma: keep -#include "llvm/ADT/TypeSwitch.h" // IWYU pragma: keep +#include "mlir/Transforms/InliningUtils.h" +#include "llvm/ADT/TypeSwitch.h" // IWYU pragma: keep using namespace mlir; using namespace mlir::forth; @@ -20,6 +21,18 @@ using namespace mlir::forth; #define GET_OP_CLASSES #include "warpforth/Dialect/Forth/ForthOps.cpp.inc" +namespace { +/// Forth ops hold no state tied to their enclosing word, so every word can be +/// inlined into its caller before the stack is lowered. +struct ForthInlinerInterface : public DialectInlinerInterface { + using DialectInlinerInterface::DialectInlinerInterface; + + bool isLegalToInline(Operation *, Region *, bool, IRMapping &) const final { + return true; + } +}; +} // namespace + //===----------------------------------------------------------------------===// // Forth dialect. //===----------------------------------------------------------------------===// @@ -33,4 +46,5 @@ void ForthDialect::initialize() { #define GET_OP_LIST #include "warpforth/Dialect/Forth/ForthOps.cpp.inc" >(); + addInterfaces(); } diff --git a/test/Pipeline/inline-gpu-words.forth b/test/Pipeline/inline-gpu-words.forth new file mode 100644 index 0000000..8fbdb28 --- /dev/null +++ b/test/Pipeline/inline-gpu-words.forth @@ -0,0 +1,17 @@ +\ RUN: %warpforthc %s -o %t.ptx +\ RUN: %FileCheck %s < %t.ptx + +\ Words that read a GPU index or synchronize are inlined like any other word, +\ so they do not survive as device functions. +\ CHECK-NOT: .func +\ CHECK: .entry main( +\ CHECK: %tid.x +\ CHECK: bar.sync +\ CHECK: st.global +\ CHECK-NOT: .func + +\! kernel main +\! param DATA i64[256] +: MYID TID-X ; +: SYNC BARRIER ; +MYID SYNC MYID CELLS DATA + ! diff --git a/test/Pipeline/optimization.forth b/test/Pipeline/optimization.forth index 0b8c8a3..d800c25 100644 --- a/test/Pipeline/optimization.forth +++ b/test/Pipeline/optimization.forth @@ -17,5 +17,4 @@ \! kernel main \! param DATA i64[4] : DOUBLE DUP + ; -5 DOUBLE DROP -DATA DROP DATA DROP +5 DOUBLE DATA @ + DATA ! diff --git a/test/Pipeline/source-locations.forth b/test/Pipeline/source-locations.forth index 1df9860..00b64c0 100644 --- a/test/Pipeline/source-locations.forth +++ b/test/Pipeline/source-locations.forth @@ -2,11 +2,12 @@ \ RUN: %warpforthc --mlir-print-ir-after=convert-forth-to-memref --mlir-print-debuginfo --mlir-disable-threading %s -o %t.ptx 2>&1 | %FileCheck %s --check-prefix=LOWERED \! kernel main -42 +\! param OUT i64[1] +42 OUT ! \ FORTH: forth.constant %{{.*}}(42 : i64) {{.*}} loc([[FORTH_LOC:#loc[0-9]+]]) -\ FORTH: [[FORTH_LOC]] = loc("{{.*}}source-locations.forth":5:1) +\ FORTH: [[FORTH_LOC]] = loc("{{.*}}source-locations.forth":6:1) \ LOWERED: IR Dump After ConvertForthToMemRef (convert-forth-to-memref) \ LOWERED: arith.constant 42 : i64 loc([[LOWERED_LOC:#loc[0-9]+]]) -\ LOWERED: [[LOWERED_LOC]] = loc("{{.*}}source-locations.forth":5:1) +\ LOWERED: [[LOWERED_LOC]] = loc("{{.*}}source-locations.forth":6:1) From 23828bb3b9070ba196935c4ec3953a30d4abfd34 Mon Sep 17 00:00:00 2001 From: Alex Cameron Date: Mon, 9 Nov 2026 04:15:38 +0000 Subject: [PATCH 2/8] feat(conversion): lower straight-line Forth stacks to SSA values The memref stack turns every cell into a store and a load through a 256-cell local buffer, even where the compiler knows the depth of every cell. Once words are inlined, a straight-line kernel's stack is fully known, so its cells can be plain i64 values. lower-forth-stack does that for constants, parameter references, integer arithmetic, and the global store. The stack-word table in StackWords.cpp declares each word's stack effect and its compute, and the pass alone decides where cells live. A function that uses any other word, has more than one block, or pops below its known depth is left for convert-forth-to-memref, which still runs after it until every word has a row. --- .../Conversion/ForthStack/LowerForthStack.h | 24 +++ include/warpforth/Conversion/Passes.td | 19 ++ lib/Conversion/CMakeLists.txt | 2 + lib/Conversion/ForthStack/CMakeLists.txt | 18 ++ lib/Conversion/ForthStack/LowerForthStack.cpp | 196 ++++++++++++++++++ lib/Conversion/ForthStack/StackWords.cpp | 183 ++++++++++++++++ lib/Conversion/ForthStack/StackWords.h | 60 ++++++ lib/Conversion/Passes.cpp | 7 +- test/Conversion/ForthStack/straight-line.mlir | 66 ++++++ .../ForthStack/word-not-inlined-error.mlir | 18 ++ test/Pipeline/source-locations.forth | 4 +- test/Pipeline/stack-promotion.forth | 22 ++ 12 files changed, 616 insertions(+), 3 deletions(-) create mode 100644 include/warpforth/Conversion/ForthStack/LowerForthStack.h create mode 100644 lib/Conversion/ForthStack/CMakeLists.txt create mode 100644 lib/Conversion/ForthStack/LowerForthStack.cpp create mode 100644 lib/Conversion/ForthStack/StackWords.cpp create mode 100644 lib/Conversion/ForthStack/StackWords.h create mode 100644 test/Conversion/ForthStack/straight-line.mlir create mode 100644 test/Conversion/ForthStack/word-not-inlined-error.mlir create mode 100644 test/Pipeline/stack-promotion.forth diff --git a/include/warpforth/Conversion/ForthStack/LowerForthStack.h b/include/warpforth/Conversion/ForthStack/LowerForthStack.h new file mode 100644 index 0000000..67a4374 --- /dev/null +++ b/include/warpforth/Conversion/ForthStack/LowerForthStack.h @@ -0,0 +1,24 @@ +//===- LowerForthStack.h - Lower the Forth stack ----------------*- C++ -*-===// +// +// This file declares the pass that lowers the Forth data stack. +// +//===----------------------------------------------------------------------===// + +#ifndef WARPFORTH_CONVERSION_FORTHSTACK_LOWERFORTHSTACK_H +#define WARPFORTH_CONVERSION_FORTHSTACK_LOWERFORTHSTACK_H + +#include "mlir/Pass/Pass.h" +#include + +namespace mlir { +namespace warpforth { + +/// Creates the pass that lowers every !forth.stack value. Every user word must +/// already be inlined. A cell whose depth and slot are known at compile time +/// becomes an i64 SSA value. +std::unique_ptr createLowerForthStackPass(); + +} // namespace warpforth +} // namespace mlir + +#endif diff --git a/include/warpforth/Conversion/Passes.td b/include/warpforth/Conversion/Passes.td index be86499..9ea3b95 100644 --- a/include/warpforth/Conversion/Passes.td +++ b/include/warpforth/Conversion/Passes.td @@ -32,6 +32,25 @@ def ConvertForthToMemRef "mlir::math::MathDialect"]; } +def LowerForthStack : Pass<"lower-forth-stack", "mlir::ModuleOp"> { + let summary = "Lower the Forth stack to i64 SSA values"; + let description = [{ + Lowers every `!forth.stack` value. Every user word must already be + inlined, so run `--inline` first. A cell whose depth and slot are known at + compile time becomes an `i64` SSA value, and each word becomes the `arith`, + `memref`, or `llvm` ops that compute its result. + + A function whose words this pass does not lower yet is left unchanged for + `convert-forth-to-memref`. + }]; + + let constructor = "mlir::warpforth::createLowerForthStackPass()"; + + let dependentDialects = ["mlir::arith::ArithDialect", + "mlir::LLVM::LLVMDialect", + "mlir::memref::MemRefDialect"]; +} + def ConvertForthToGPU : Pass<"convert-forth-to-gpu", "mlir::ModuleOp"> { let summary = "Convert Forth functions to GPU dialect"; let description = [{ diff --git a/lib/Conversion/CMakeLists.txt b/lib/Conversion/CMakeLists.txt index 6393a67..3dce691 100644 --- a/lib/Conversion/CMakeLists.txt +++ b/lib/Conversion/CMakeLists.txt @@ -6,6 +6,7 @@ add_mlir_library(MLIRConversionPasses LINK_LIBS PUBLIC MLIRPass + MLIRForthStackConversion MLIRForthToMemRefConversion MLIRForthToGPUConversion MLIRGPUDialect @@ -21,5 +22,6 @@ target_compile_definitions(obj.MLIRConversionPasses PRIVATE WARPFORTH_LIBDEVICE_PATH="${WARPFORTH_LIBDEVICE_PATH}" ) +add_subdirectory(ForthStack) add_subdirectory(ForthToMemRef) add_subdirectory(ForthToGPU) diff --git a/lib/Conversion/ForthStack/CMakeLists.txt b/lib/Conversion/ForthStack/CMakeLists.txt new file mode 100644 index 0000000..5f4e758 --- /dev/null +++ b/lib/Conversion/ForthStack/CMakeLists.txt @@ -0,0 +1,18 @@ +add_mlir_conversion_library(MLIRForthStackConversion + LowerForthStack.cpp + StackWords.cpp + + DEPENDS + MLIRConversionPassIncGen + MLIRForth + + LINK_LIBS PUBLIC + MLIRIR + MLIRPass + MLIRArithDialect + MLIRFuncDialect + MLIRLLVMDialect + MLIRMemRefDialect + MLIRNVVMDialect + MLIRForth +) diff --git a/lib/Conversion/ForthStack/LowerForthStack.cpp b/lib/Conversion/ForthStack/LowerForthStack.cpp new file mode 100644 index 0000000..d2fc894 --- /dev/null +++ b/lib/Conversion/ForthStack/LowerForthStack.cpp @@ -0,0 +1,196 @@ +//===- LowerForthStack.cpp - Lower the Forth stack --------------*- C++ -*-===// +// +// This file implements the pass that lowers every !forth.stack value. The +// stack-word table says what each word computes. This file decides where each +// cell lives: a cell whose depth and slot are known is an i64 SSA value. +// +//===----------------------------------------------------------------------===// + +#include "warpforth/Conversion/ForthStack/LowerForthStack.h" +#include "StackWords.h" +#include "mlir/Dialect/Arith/IR/Arith.h" // IWYU pragma: keep +#include "mlir/Dialect/Func/IR/FuncOps.h" +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" // IWYU pragma: keep +#include "mlir/Dialect/MemRef/IR/MemRef.h" // IWYU pragma: keep +#include "mlir/IR/Builders.h" +#include "mlir/IR/BuiltinOps.h" +#include "mlir/IR/BuiltinTypes.h" +#include "mlir/Pass/Pass.h" +#include "warpforth/Dialect/Forth/ForthDialect.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/STLExtras.h" +#include + +namespace mlir { +namespace warpforth { + +#define GEN_PASS_DEF_LOWERFORTHSTACK +#include "warpforth/Conversion/Passes.h.inc" + +namespace { + +using stack::StackEffect; +using stack::StackWord; +using stack::WordContext; + +bool isStack(Type type) { return isa(type); } + +/// Compile-time shape of one !forth.stack value. A static stack holds exactly +/// `cells` cells, all in registers. A residual stack keeps its top `cells` +/// cells in registers above an unknown number of cells in memory. +struct StaticShape { + unsigned cells; +}; +struct ResidualShape { + unsigned cells; +}; +using StackShape = std::variant; + +unsigned registerCells(StackShape shape) { + return std::visit([](auto s) { return s.cells; }, shape); +} + +/// The shape after an op with `effect`. A static stack that cannot supply the +/// pops reads below its known cells, so the result is residual. +StackShape transfer(StackShape in, StackEffect effect) { + unsigned cells = registerCells(in); + if (std::holds_alternative(in) && effect.pops <= cells) + return StaticShape{cells - effect.pops + effect.pushes}; + unsigned kept = cells > effect.pops ? cells - effect.pops : 0; + return ResidualShape{kept + effect.pushes}; +} + +/// Where the cells of one !forth.stack value live while the pass rewrites it. +/// `cells` are i64 values, deepest first. A residual stack also holds `depth`, +/// the index of its top cell in memory. +struct StaticState { + SmallVector cells; +}; +struct ResidualState { + SmallVector cells; + Value depth; +}; +using StackState = std::variant; + +SmallVector &cellsOf(StackState &state) { + return std::visit([](auto &s) -> SmallVector & { return s.cells; }, + state); +} + +/// A word keeps the stack in its signature until the inliner removes it, and +/// this pass gives words no calling convention. +LogicalResult verifyWordsInlined(ModuleOp module) { + for (auto fn : module.getOps()) { + FunctionType type = fn.getFunctionType(); + if (llvm::any_of(type.getInputs(), isStack) || + llvm::any_of(type.getResults(), isStack)) + return fn.emitError() + << "Forth word @" << fn.getSymName() + << " was not inlined; run --inline before --lower-forth-stack"; + } + return success(); +} + +/// Whether this pass lowers `fn` yet: it is straight-line code, every stack op +/// has a row, and no pop reaches below the static depth. +bool isLowerable(func::FuncOp fn) { + if (!fn.getBody().hasOneBlock()) + return false; + DenseMap shapes; + WalkResult walk = fn.walk([&](Operation *op) { + if (isa(op)) { + shapes.try_emplace(op->getResult(0), StaticShape{0}); + return WalkResult::advance(); + } + if (llvm::none_of(op->getOperandTypes(), isStack)) + return WalkResult::advance(); + const StackWord *word = stack::lookupStackWord(op); + if (!word) + return WalkResult::interrupt(); + StackShape shape = transfer(shapes.at(op->getOperand(0)), word->effect); + if (!std::holds_alternative(shape)) + return WalkResult::interrupt(); + shapes.try_emplace(op->getResult(0), shape); + return WalkResult::advance(); + }); + return !walk.wasInterrupted(); +} + +/// Rewrites one function. Rows reach the cells only through WordContext. +class StackSimulator final : public WordContext { +public: + explicit StackSimulator(func::FuncOp fn) : fn(fn), b(fn.getContext()) {} + + /// Lowers every stack word in `fn`, then erases the Forth stack ops. + void run(); + + OpBuilder &builder() override { return b; } + Value popped(unsigned i) override { return poppedCells[i]; } + void push(Value cell) override { pushedCells.push_back(cell); } + +private: + void lowerWord(Operation *op, const StackWord &word); + + func::FuncOp fn; + OpBuilder b; + /// Keyed by the original !forth.stack value. + DenseMap states; + SmallVector lowered; + + // Scratch for the op being lowered. + StackState working; + SmallVector poppedCells; + SmallVector pushedCells; +}; + +void StackSimulator::run() { + for (Operation &op : fn.getBody().front()) { + if (isa(op)) { + states[op.getResult(0)] = StaticState{}; + lowered.push_back(&op); + } else if (const StackWord *word = stack::lookupStackWord(&op)) { + lowerWord(&op, *word); + } + } + for (Operation *op : lowered) + op->dropAllReferences(); + for (Operation *op : lowered) + op->erase(); +} + +void StackSimulator::lowerWord(Operation *op, const StackWord &word) { + working = states.at(op->getOperand(0)); + SmallVector &cells = cellsOf(working); + poppedCells.clear(); + for (unsigned i = 0; i < word.effect.pops; ++i) + poppedCells.push_back(cells.pop_back_val()); + pushedCells.clear(); + b.setInsertionPoint(op); + word.lower(op, *this); + assert(pushedCells.size() == word.effect.pushes && + "a row pushes exactly the cells its effect declares"); + llvm::append_range(cellsOf(working), pushedCells); + states[op->getResult(0)] = std::move(working); + lowered.push_back(op); +} + +struct LowerForthStackPass + : public impl::LowerForthStackBase { + void runOnOperation() override { + ModuleOp module = getOperation(); + if (failed(verifyWordsInlined(module))) + return signalPassFailure(); + for (auto fn : module.getOps()) + if (!fn.isExternal() && isLowerable(fn)) + StackSimulator(fn).run(); + } +}; + +} // namespace + +std::unique_ptr createLowerForthStackPass() { + return std::make_unique(); +} + +} // namespace warpforth +} // namespace mlir diff --git a/lib/Conversion/ForthStack/StackWords.cpp b/lib/Conversion/ForthStack/StackWords.cpp new file mode 100644 index 0000000..1e803ea --- /dev/null +++ b/lib/Conversion/ForthStack/StackWords.cpp @@ -0,0 +1,183 @@ +//===- StackWords.cpp - Stack effects of Forth words ------------*- C++ -*-===// +// +// This file implements the stack-word table: one row per Forth op that takes +// a !forth.stack operand. +// +//===----------------------------------------------------------------------===// + +#include "StackWords.h" +#include "mlir/Dialect/Arith/IR/Arith.h" +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" +#include "mlir/Dialect/LLVMIR/NVVMDialect.h" +#include "mlir/Dialect/MemRef/IR/MemRef.h" +#include "mlir/IR/BuiltinTypes.h" +#include "warpforth/Dialect/Forth/ForthDialect.h" +#include "llvm/ADT/DenseMap.h" + +namespace mlir { +namespace warpforth { +namespace stack { + +WordContext::~WordContext() = default; + +namespace { + +// Global addresses are numerically equal to their generic addresses, so +// inttoptr into this space is valid and lets NVPTX emit ld.global/st.global +// after address arithmetic. +constexpr unsigned kGlobalAddressSpace = + static_cast(NVVM::kGlobalMemorySpace); + +/// Element type of a memory access. Cells are i64; a narrower integer is +/// sign-extended and a float is carried as the bits of an f64. +enum class MemType { I64, F64, I8, I16, I32, F16, BF16, F32 }; + +Type memElementType(MLIRContext *ctx, MemType type) { + switch (type) { + case MemType::I64: + return IntegerType::get(ctx, 64); + case MemType::I32: + return IntegerType::get(ctx, 32); + case MemType::I16: + return IntegerType::get(ctx, 16); + case MemType::I8: + return IntegerType::get(ctx, 8); + case MemType::F64: + return Float64Type::get(ctx); + case MemType::F32: + return Float32Type::get(ctx); + case MemType::F16: + return Float16Type::get(ctx); + case MemType::BF16: + return BFloat16Type::get(ctx); + } + llvm_unreachable("unhandled MemType"); +} + +/// The cell as a value of the memory element type. +Value narrow(OpBuilder &b, Location loc, Value cell, MemType type) { + Type elementType = memElementType(b.getContext(), type); + switch (type) { + case MemType::I64: + return cell; + case MemType::I8: + case MemType::I16: + case MemType::I32: + return b.create(loc, elementType, cell); + case MemType::F64: + return b.create(loc, elementType, cell); + case MemType::F16: + case MemType::BF16: + case MemType::F32: { + Value f64 = b.create(loc, b.getF64Type(), cell); + return b.create(loc, elementType, f64); + } + } + llvm_unreachable("unhandled MemType"); +} + +struct StackWordRow { + TypeID op; + StackWord word; +}; + +/// A row built by a family helper, which carries its own effect. +template StackWordRow row(StackWord word) { + return {TypeID::get(), std::move(word)}; +} + +/// A row whose lowering reads the typed op. +template +StackWordRow row(StackEffect effect, void (*lower)(OpT, WordContext &)) { + return {TypeID::get(), + {effect, [lower](Operation *op, WordContext &ctx) { + lower(cast(op), ctx); + }}}; +} + +/// ( a b -- a op b ) +template StackWord intBinary() { + return {{2, 1}, [](Operation *op, WordContext &ctx) { + ctx.push(ctx.builder().create(op->getLoc(), ctx.popped(1), + ctx.popped(0))); + }}; +} + +/// ( x addr -- ) +StackWord store(MemType type, unsigned addressSpace) { + return {{2, 0}, [type, addressSpace](Operation *op, WordContext &ctx) { + OpBuilder &b = ctx.builder(); + Location loc = op->getLoc(); + auto pointerType = + LLVM::LLVMPointerType::get(b.getContext(), addressSpace); + Value pointer = + b.create(loc, pointerType, ctx.popped(0)); + b.create(loc, narrow(b, loc, ctx.popped(1), type), + pointer); + }}; +} + +ArrayRef stackWordRows() { + static const StackWordRow rows[] = { + row({0, 1}, + [](forth::ConstantOp op, WordContext &ctx) { + OpBuilder &b = ctx.builder(); + auto value = cast(op.getValueAttr()); + if (isa(value)) { + Value f64 = b.create( + op.getLoc(), b.getF64Type(), value); + ctx.push(b.create( + op.getLoc(), b.getI64Type(), f64)); + return; + } + ctx.push(b.create( + op.getLoc(), b.getI64Type(), value)); + }), + row( + {0, 1}, + [](forth::ParamRefOp op, WordContext &ctx) { + OpBuilder &b = ctx.builder(); + Location loc = op.getLoc(); + Value parameter = op.getParameter(); + if (isa(parameter.getType())) { + Value pointer = b.create( + loc, parameter); + ctx.push( + b.create(loc, b.getI64Type(), pointer)); + return; + } + if (parameter.getType().isF64()) { + ctx.push( + b.create(loc, b.getI64Type(), parameter)); + return; + } + ctx.push(parameter); + }), + row(intBinary()), + row(intBinary()), + row(intBinary()), + row(intBinary()), + row(intBinary()), + row(store(MemType::I64, kGlobalAddressSpace)), + }; + return rows; +} + +} // namespace + +const StackWord *lookupStackWord(Operation *op) { + static const DenseMap words = [] { + DenseMap words; + for (const StackWordRow &row : stackWordRows()) { + bool inserted = words.try_emplace(row.op, &row.word).second; + assert(inserted && "duplicate stack-word row"); + (void)inserted; + } + return words; + }(); + return words.lookup(op->getName().getTypeID()); +} + +} // namespace stack +} // namespace warpforth +} // namespace mlir diff --git a/lib/Conversion/ForthStack/StackWords.h b/lib/Conversion/ForthStack/StackWords.h new file mode 100644 index 0000000..8acbe28 --- /dev/null +++ b/lib/Conversion/ForthStack/StackWords.h @@ -0,0 +1,60 @@ +//===- StackWords.h - Stack effects of Forth words --------------*- C++ -*-===// +// +// This file declares the stack-word table. Each row gives one Forth op its +// stack effect and lowers the op's compute on i64 cells. Where the cells live +// is decided by LowerForthStack.cpp alone. +// +//===----------------------------------------------------------------------===// + +#ifndef WARPFORTH_LIB_CONVERSION_FORTHSTACK_STACKWORDS_H +#define WARPFORTH_LIB_CONVERSION_FORTHSTACK_STACKWORDS_H + +#include "mlir/IR/Builders.h" +#include "mlir/IR/Operation.h" +#include "mlir/IR/Value.h" +#include + +namespace mlir { +namespace warpforth { +namespace stack { + +/// How many cells a word pops, then pushes. The table is the only place that +/// declares a stack effect. +struct StackEffect { + unsigned pops = 0; + unsigned pushes = 0; +}; + +/// What a row may do while it lowers one op. Every cell is an i64 value, and a +/// row never learns where a cell lives. +class WordContext { +public: + virtual ~WordContext(); + + /// Positioned immediately before the op being lowered. + virtual OpBuilder &builder() = 0; + + /// Popped cell `i`, where 0 is the old top. Requires `i < effect.pops`. + virtual Value popped(unsigned i) = 0; + + /// Pushes one cell. A row pushes exactly `effect.pushes` cells, deepest + /// first. + virtual void push(Value cell) = 0; +}; + +using LowerFn = std::function; + +/// One row of the stack-word table. +struct StackWord { + StackEffect effect; + LowerFn lower; +}; + +/// The row for `op`, or null when the table has none. +const StackWord *lookupStackWord(Operation *op); + +} // namespace stack +} // namespace warpforth +} // namespace mlir + +#endif diff --git a/lib/Conversion/Passes.cpp b/lib/Conversion/Passes.cpp index 239b2c5..2c4b527 100644 --- a/lib/Conversion/Passes.cpp +++ b/lib/Conversion/Passes.cpp @@ -13,6 +13,7 @@ #include "mlir/Dialect/GPU/Transforms/Passes.h" #include "mlir/Pass/PassManager.h" #include "mlir/Transforms/Passes.h" +#include "warpforth/Conversion/ForthStack/LowerForthStack.h" #include "warpforth/Conversion/ForthToGPU/ForthToGPU.h" #include "warpforth/Conversion/ForthToMemRef/ForthToMemRef.h" #include "llvm/ADT/STLExtras.h" @@ -95,7 +96,9 @@ void buildWarpForthLoweringPipeline(OpPassManager &pm, // precede GPU conversion. pm.addPass(createInlinerPass()); - // Stage 2: Lower Forth to MemRef (CF ops pass through as-is) + // Stage 2: Lower the stack. A function the stack lowering cannot take yet + // keeps its Forth ops and falls through to the memref stack. + pm.addPass(createLowerForthStackPass()); pm.addPass(createConvertForthToMemRefPass()); // Stage 3: Convert to GPU dialect @@ -151,6 +154,8 @@ void buildWarpForthPipeline(OpPassManager &pm) { } void registerConversionPasses() { + registerPass( + []() -> std::unique_ptr { return createLowerForthStackPass(); }); registerPass([]() -> std::unique_ptr { return createConvertForthToMemRefPass(); }); diff --git a/test/Conversion/ForthStack/straight-line.mlir b/test/Conversion/ForthStack/straight-line.mlir new file mode 100644 index 0000000..ad206b0 --- /dev/null +++ b/test/Conversion/ForthStack/straight-line.mlir @@ -0,0 +1,66 @@ +// RUN: %warpforth-opt --lower-forth-stack %s | %FileCheck %s + +// The stored value is the sum itself, with no stack buffer in between. +// CHECK-LABEL: func.func @add_then_store( +// CHECK-SAME: %[[OUT:[^:]*]]: memref<1xi64> +// CHECK-NOT: memref.alloca +// CHECK: %[[TWO:.*]] = arith.constant 2 : i64 +// CHECK: %[[THREE:.*]] = arith.constant 3 : i64 +// CHECK: %[[SUM:.*]] = arith.addi %[[TWO]], %[[THREE]] : i64 +// CHECK: %[[BASE:.*]] = memref.extract_aligned_pointer_as_index %[[OUT]] +// CHECK: %[[ADDRESS:.*]] = arith.index_cast %[[BASE]] : index to i64 +// CHECK: %[[POINTER:.*]] = llvm.inttoptr %[[ADDRESS]] : i64 to !llvm.ptr<1> +// CHECK: llvm.store %[[SUM]], %[[POINTER]] : i64, !llvm.ptr<1> +// CHECK-NEXT: return +func.func @add_then_store(%out: memref<1xi64>) { + %0 = forth.stack !forth.stack + %1 = forth.constant %0(2 : i64) : !forth.stack -> !forth.stack + %2 = forth.constant %1(3 : i64) : !forth.stack -> !forth.stack + %3 = forth.addi %2 : !forth.stack -> !forth.stack + %4 = forth.param_ref %3 %out : !forth.stack, memref<1xi64> -> !forth.stack + %5 = forth.storei %4 : !forth.stack -> !forth.stack + return +} + +// A binary word takes the deeper cell as its left operand, so `A B -` is A - B. +// CHECK-LABEL: func.func @operand_order( +// CHECK-SAME: %[[A:[^:]*]]: i64, %[[B:[^:]*]]: i64 +// CHECK: %[[DIFF:.*]] = arith.subi %[[A]], %[[B]] : i64 +// CHECK: %[[QUOT:.*]] = arith.divsi %[[DIFF]], %[[B]] : i64 +// CHECK: %[[REM:.*]] = arith.remsi %[[QUOT]], %[[A]] : i64 +// CHECK: %[[PROD:.*]] = arith.muli %[[REM]], %[[B]] : i64 +// CHECK: llvm.store %[[PROD]], %{{.*}} : i64, !llvm.ptr<1> +func.func @operand_order(%a: i64, %b: i64, %out: memref<1xi64>) { + %0 = forth.stack !forth.stack + %1 = forth.param_ref %0 %a : !forth.stack, i64 -> !forth.stack + %2 = forth.param_ref %1 %b : !forth.stack, i64 -> !forth.stack + %3 = forth.subi %2 : !forth.stack -> !forth.stack + %4 = forth.param_ref %3 %b : !forth.stack, i64 -> !forth.stack + %5 = forth.divi %4 : !forth.stack -> !forth.stack + %6 = forth.param_ref %5 %a : !forth.stack, i64 -> !forth.stack + %7 = forth.mod %6 : !forth.stack -> !forth.stack + %8 = forth.param_ref %7 %b : !forth.stack, i64 -> !forth.stack + %9 = forth.muli %8 : !forth.stack -> !forth.stack + %10 = forth.param_ref %9 %out : !forth.stack, memref<1xi64> -> !forth.stack + %11 = forth.storei %10 : !forth.stack -> !forth.stack + return +} + +// A float literal and an f64 parameter are cells holding their f64 bits. +// CHECK-LABEL: func.func @float_cells( +// CHECK-SAME: %[[SCALE:[^:]*]]: f64 +// CHECK: %[[LITERAL:.*]] = arith.constant 1.500000e+00 : f64 +// CHECK: %[[LITERAL_BITS:.*]] = arith.bitcast %[[LITERAL]] : f64 to i64 +// CHECK: llvm.store %[[LITERAL_BITS]], %{{.*}} : i64, !llvm.ptr<1> +// CHECK: %[[SCALE_BITS:.*]] = arith.bitcast %[[SCALE]] : f64 to i64 +// CHECK: llvm.store %[[SCALE_BITS]], %{{.*}} : i64, !llvm.ptr<1> +func.func @float_cells(%scale: f64, %out: memref<1xi64>) { + %0 = forth.stack !forth.stack + %1 = forth.constant %0(1.500000e+00 : f64) : !forth.stack -> !forth.stack + %2 = forth.param_ref %1 %out : !forth.stack, memref<1xi64> -> !forth.stack + %3 = forth.storei %2 : !forth.stack -> !forth.stack + %4 = forth.param_ref %3 %scale : !forth.stack, f64 -> !forth.stack + %5 = forth.param_ref %4 %out : !forth.stack, memref<1xi64> -> !forth.stack + %6 = forth.storei %5 : !forth.stack -> !forth.stack + return +} diff --git a/test/Conversion/ForthStack/word-not-inlined-error.mlir b/test/Conversion/ForthStack/word-not-inlined-error.mlir new file mode 100644 index 0000000..8dc34a5 --- /dev/null +++ b/test/Conversion/ForthStack/word-not-inlined-error.mlir @@ -0,0 +1,18 @@ +// RUN: %not %warpforth-opt --lower-forth-stack %s 2>&1 | %FileCheck %s + +// The lowered stack has no calling convention, so every word must be inlined +// before the stack is lowered. +// CHECK: error: Forth word @double was not inlined; run --inline before --lower-forth-stack + +func.func private @double(%s: !forth.stack) -> !forth.stack { + %0 = forth.dup %s : !forth.stack -> !forth.stack + %1 = forth.addi %0 : !forth.stack -> !forth.stack + return %1 : !forth.stack +} + +func.func @main() attributes {forth.kernel} { + %0 = forth.stack !forth.stack + %1 = forth.constant %0(5 : i64) : !forth.stack -> !forth.stack + %2 = call @double(%1) : (!forth.stack) -> !forth.stack + return +} diff --git a/test/Pipeline/source-locations.forth b/test/Pipeline/source-locations.forth index 00b64c0..b5c03db 100644 --- a/test/Pipeline/source-locations.forth +++ b/test/Pipeline/source-locations.forth @@ -1,5 +1,5 @@ \ RUN: %warpforth-translate --forth-to-mlir --mlir-print-debuginfo %s | %FileCheck %s --check-prefix=FORTH -\ RUN: %warpforthc --mlir-print-ir-after=convert-forth-to-memref --mlir-print-debuginfo --mlir-disable-threading %s -o %t.ptx 2>&1 | %FileCheck %s --check-prefix=LOWERED +\ RUN: %warpforthc --mlir-print-ir-after=lower-forth-stack --mlir-print-debuginfo --mlir-disable-threading %s -o %t.ptx 2>&1 | %FileCheck %s --check-prefix=LOWERED \! kernel main \! param OUT i64[1] @@ -8,6 +8,6 @@ \ FORTH: forth.constant %{{.*}}(42 : i64) {{.*}} loc([[FORTH_LOC:#loc[0-9]+]]) \ FORTH: [[FORTH_LOC]] = loc("{{.*}}source-locations.forth":6:1) -\ LOWERED: IR Dump After ConvertForthToMemRef (convert-forth-to-memref) +\ LOWERED: IR Dump After LowerForthStack (lower-forth-stack) \ LOWERED: arith.constant 42 : i64 loc([[LOWERED_LOC:#loc[0-9]+]]) \ LOWERED: [[LOWERED_LOC]] = loc("{{.*}}source-locations.forth":6:1) diff --git a/test/Pipeline/stack-promotion.forth b/test/Pipeline/stack-promotion.forth new file mode 100644 index 0000000..04108c9 --- /dev/null +++ b/test/Pipeline/stack-promotion.forth @@ -0,0 +1,22 @@ +\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --inline --lower-forth-stack | %FileCheck %s --check-prefix=MID +\ RUN: %warpforthc -O0 %s -o %t.ptx +\ RUN: %FileCheck %s --check-prefix=PTX < %t.ptx + +\ Every cell's depth is known at compile time, so the sum is stored straight +\ from a register. Even without optimization the kernel reserves no local +\ memory for a data stack. + +\! kernel main +\! param OUT i64[1] +2 3 + OUT ! + +\ MID-LABEL: func.func @main( +\ MID-NOT: memref.alloca +\ MID: %[[SUM:.*]] = arith.addi +\ MID-NOT: memref.alloca +\ MID: llvm.store %[[SUM]], %{{.*}} : i64, !llvm.ptr<1> +\ MID-NEXT: return + +\ PTX-LABEL: .entry main( +\ PTX-NOT: __local_depot +\ PTX: st.global.u64 From 17093016c554621772d816b4c4786f655cbf199d Mon Sep 17 00:00:00 2001 From: Alex Cameron Date: Mon, 9 Nov 2026 04:25:01 +0000 Subject: [PATCH 3/8] feat(conversion): carry Forth stack cells across branches and loops IF/ELSE and DO loops pass the stack between blocks as a block argument, so the straight-line lowering stopped at the first branch. When every path into a block agrees on the stack depth, the block can take the cells themselves. Shape inference now runs to a fixpoint over the blocks in reverse post-order. A stack block argument whose incoming shapes agree becomes one i64 argument per cell, and each branch forwards the cells. pop, pop_flag, and push_value get rows, so the DO bounds, IF flags, and loop index read cells directly. The DO counter stays in its memref<1xi64>. A join whose incoming depths differ still goes to convert-forth-to-memref. --- lib/Conversion/ForthStack/LowerForthStack.cpp | 192 +++++++++++++++--- lib/Conversion/ForthStack/StackWords.cpp | 16 ++ lib/Conversion/ForthStack/StackWords.h | 4 + test/Conversion/ForthStack/control-flow.mlir | 88 ++++++++ test/Pipeline/stack-promotion-loop.forth | 14 ++ 5 files changed, 285 insertions(+), 29 deletions(-) create mode 100644 test/Conversion/ForthStack/control-flow.mlir create mode 100644 test/Pipeline/stack-promotion-loop.forth diff --git a/lib/Conversion/ForthStack/LowerForthStack.cpp b/lib/Conversion/ForthStack/LowerForthStack.cpp index d2fc894..91a97d1 100644 --- a/lib/Conversion/ForthStack/LowerForthStack.cpp +++ b/lib/Conversion/ForthStack/LowerForthStack.cpp @@ -15,10 +15,17 @@ #include "mlir/IR/Builders.h" #include "mlir/IR/BuiltinOps.h" #include "mlir/IR/BuiltinTypes.h" +#include "mlir/IR/PatternMatch.h" +#include "mlir/IR/RegionGraphTraits.h" // IWYU pragma: keep +#include "mlir/Interfaces/ControlFlowInterfaces.h" #include "mlir/Pass/Pass.h" +#include "mlir/Transforms/RegionUtils.h" #include "warpforth/Dialect/Forth/ForthDialect.h" #include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/PostOrderIterator.h" #include "llvm/ADT/STLExtras.h" +#include +#include #include namespace mlir { @@ -40,9 +47,15 @@ bool isStack(Type type) { return isa(type); } /// cells in registers above an unknown number of cells in memory. struct StaticShape { unsigned cells; + bool operator==(const StaticShape &other) const { + return cells == other.cells; + } }; struct ResidualShape { unsigned cells; + bool operator==(const ResidualShape &other) const { + return cells == other.cells; + } }; using StackShape = std::variant; @@ -60,6 +73,15 @@ StackShape transfer(StackShape in, StackEffect effect) { return ResidualShape{kept + effect.pushes}; } +/// The shape where stacks of shapes `a` and `b` meet. Equal shapes are kept. +/// Otherwise the join keeps in registers only the top cells that both sides +/// hold there, and the cells below move to memory. +StackShape join(StackShape a, StackShape b) { + if (a == b) + return a; + return ResidualShape{std::min(registerCells(a), registerCells(b))}; +} + /// Where the cells of one !forth.stack value live while the pass rewrites it. /// `cells` are i64 values, deepest first. A residual stack also holds `depth`, /// the index of its top cell in memory. @@ -91,35 +113,80 @@ LogicalResult verifyWordsInlined(ModuleOp module) { return success(); } -/// Whether this pass lowers `fn` yet: it is straight-line code, every stack op -/// has a row, and no pop reaches below the static depth. -bool isLowerable(func::FuncOp fn) { - if (!fn.getBody().hasOneBlock()) - return false; - DenseMap shapes; - WalkResult walk = fn.walk([&](Operation *op) { - if (isa(op)) { - shapes.try_emplace(op->getResult(0), StaticShape{0}); - return WalkResult::advance(); - } - if (llvm::none_of(op->getOperandTypes(), isStack)) - return WalkResult::advance(); - const StackWord *word = stack::lookupStackWord(op); - if (!word) - return WalkResult::interrupt(); - StackShape shape = transfer(shapes.at(op->getOperand(0)), word->effect); - if (!std::holds_alternative(shape)) +/// Whether every op in `body` that takes a stack either has a row or branches. +bool hasRowsFor(Region &body) { + WalkResult walk = body.walk([](Operation *op) { + if (llvm::any_of(op->getOperandTypes(), isStack) && + !isa(op) && !stack::lookupStackWord(op)) return WalkResult::interrupt(); - shapes.try_emplace(op->getResult(0), shape); return WalkResult::advance(); }); return !walk.wasInterrupted(); } +/// Joins the shapes that the predecessors seen so far pass to the stack +/// argument `arg`. +std::optional +joinIncoming(BlockArgument arg, const DenseMap &shapes) { + std::optional joined; + Block *block = arg.getOwner(); + for (auto it = block->pred_begin(), e = block->pred_end(); it != e; ++it) { + auto branch = cast((*it)->getTerminator()); + Value incoming = + branch.getSuccessorOperands(it.getSuccessorIndex())[arg.getArgNumber()]; + auto shape = shapes.find(incoming); + if (shape == shapes.end()) + continue; + joined = joined ? join(*joined, shape->second) : shape->second; + } + return joined; +} + +/// The shape of every !forth.stack value in `body`, iterated to a fixpoint in +/// reverse post-order. Requires that every block is reachable and that every +/// op that takes a stack has a row or branches. +/// +/// Shapes only move from static to residual or toward fewer register cells, so +/// the iteration ends. +DenseMap inferShapes(Region &body) { + llvm::ReversePostOrderTraversal order(&body.front()); + DenseMap shapes; + bool changed = true; + while (changed) { + changed = false; + for (Block *block : order) { + for (BlockArgument arg : block->getArguments()) { + if (!isStack(arg.getType())) + continue; + std::optional joined = joinIncoming(arg, shapes); + assert(joined && "reverse post-order visits a predecessor first"); + auto [it, inserted] = shapes.try_emplace(arg, *joined); + if (inserted || !(it->second == *joined)) { + it->second = *joined; + changed = true; + } + } + for (Operation &op : *block) { + if (isa(op)) { + shapes[op.getResult(0)] = StaticShape{0}; + continue; + } + const StackWord *word = stack::lookupStackWord(&op); + if (!word) + continue; + shapes[op.getResult(0)] = + transfer(shapes.at(op.getOperand(0)), word->effect); + } + } + } + return shapes; +} + /// Rewrites one function. Rows reach the cells only through WordContext. class StackSimulator final : public WordContext { public: - explicit StackSimulator(func::FuncOp fn) : fn(fn), b(fn.getContext()) {} + StackSimulator(func::FuncOp fn, DenseMap shapes) + : fn(fn), b(fn.getContext()), shapes(std::move(shapes)) {} /// Lowers every stack word in `fn`, then erases the Forth stack ops. void run(); @@ -127,38 +194,73 @@ class StackSimulator final : public WordContext { OpBuilder &builder() override { return b; } Value popped(unsigned i) override { return poppedCells[i]; } void push(Value cell) override { pushedCells.push_back(cell); } + void replaceValueResult(Value value) override { + current->getResult(1).replaceAllUsesWith(value); + } private: + void expandArguments(Block &block); void lowerWord(Operation *op, const StackWord &word); + void forwardCells(BranchOpInterface branch); func::FuncOp fn; OpBuilder b; + DenseMap shapes; /// Keyed by the original !forth.stack value. DenseMap states; SmallVector lowered; + SmallVector replacedArguments; // Scratch for the op being lowered. + Operation *current = nullptr; StackState working; SmallVector poppedCells; SmallVector pushedCells; }; void StackSimulator::run() { - for (Operation &op : fn.getBody().front()) { - if (isa(op)) { - states[op.getResult(0)] = StaticState{}; - lowered.push_back(&op); - } else if (const StackWord *word = stack::lookupStackWord(&op)) { - lowerWord(&op, *word); + Region &body = fn.getBody(); + for (Block &block : body) + expandArguments(block); + for (Block *block : llvm::ReversePostOrderTraversal(&body.front())) { + for (Operation &op : *block) { + if (isa(op)) { + states[op.getResult(0)] = StaticState{}; + lowered.push_back(&op); + } else if (const StackWord *word = stack::lookupStackWord(&op)) { + lowerWord(&op, *word); + } else if (auto branch = dyn_cast(op)) { + forwardCells(branch); + } } } for (Operation *op : lowered) op->dropAllReferences(); for (Operation *op : lowered) op->erase(); + for (BlockArgument arg : replacedArguments) + arg.getOwner()->eraseArgument(arg.getArgNumber()); +} + +/// Gives each stack argument of `block` one i64 argument per cell, placed +/// after it. The stack argument is erased once nothing uses it. +void StackSimulator::expandArguments(Block &block) { + for (unsigned i = 0; i < block.getNumArguments(); ++i) { + BlockArgument arg = block.getArgument(i); + if (!isStack(arg.getType())) + continue; + StaticState state; + for (unsigned cell = 0, e = registerCells(shapes.at(arg)); cell < e; ++cell) + state.cells.push_back( + block.insertArgument(i + 1 + cell, b.getI64Type(), arg.getLoc())); + i += state.cells.size(); + states[arg] = std::move(state); + replacedArguments.push_back(arg); + } } void StackSimulator::lowerWord(Operation *op, const StackWord &word) { + current = op; working = states.at(op->getOperand(0)); SmallVector &cells = cellsOf(working); poppedCells.clear(); @@ -174,15 +276,47 @@ void StackSimulator::lowerWord(Operation *op, const StackWord &word) { lowered.push_back(op); } +/// Passes each forwarded stack to its successor as the stack's cells. +void StackSimulator::forwardCells(BranchOpInterface branch) { + for (unsigned i = 0, e = branch->getNumSuccessors(); i < e; ++i) { + SuccessorOperands operands = branch.getSuccessorOperands(i); + if (llvm::none_of(operands.getForwardedOperands().getTypes(), isStack)) + continue; + SmallVector forwarded; + for (Value value : operands.getForwardedOperands()) { + if (!isStack(value.getType())) { + forwarded.push_back(value); + continue; + } + StackState state = states.at(value); + llvm::append_range(forwarded, cellsOf(state)); + } + operands.getMutableForwardedOperands().assign(forwarded); + } +} + struct LowerForthStackPass : public impl::LowerForthStackBase { void runOnOperation() override { ModuleOp module = getOperation(); if (failed(verifyWordsInlined(module))) return signalPassFailure(); - for (auto fn : module.getOps()) - if (!fn.isExternal() && isLowerable(fn)) - StackSimulator(fn).run(); + IRRewriter rewriter(&getContext()); + for (auto fn : module.getOps()) { + if (fn.isExternal()) + continue; + (void)eraseUnreachableBlocks(rewriter, fn->getRegions()); + // A function this pass cannot lower yet is left whole for + // convert-forth-to-memref. + if (!hasRowsFor(fn.getBody())) + continue; + DenseMap shapes = inferShapes(fn.getBody()); + if (llvm::any_of(shapes, [](const auto &entry) { + return !std::holds_alternative(entry.second); + })) + continue; + StackSimulator(fn, std::move(shapes)).run(); + } } }; diff --git a/lib/Conversion/ForthStack/StackWords.cpp b/lib/Conversion/ForthStack/StackWords.cpp index 1e803ea..90ce0d0 100644 --- a/lib/Conversion/ForthStack/StackWords.cpp +++ b/lib/Conversion/ForthStack/StackWords.cpp @@ -153,6 +153,22 @@ ArrayRef stackWordRows() { } ctx.push(parameter); }), + row({0, 1}, + [](forth::PushValueOp op, WordContext &ctx) { + ctx.push(op.getValue()); + }), + row({1, 0}, + [](forth::PopOp, WordContext &ctx) { + ctx.replaceValueResult(ctx.popped(0)); + }), + row( + {1, 0}, + [](forth::PopFlagOp op, WordContext &ctx) { + OpBuilder &b = ctx.builder(); + Value zero = b.create(op.getLoc(), 0, 64); + ctx.replaceValueResult(b.create( + op.getLoc(), arith::CmpIPredicate::ne, ctx.popped(0), zero)); + }), row(intBinary()), row(intBinary()), row(intBinary()), diff --git a/lib/Conversion/ForthStack/StackWords.h b/lib/Conversion/ForthStack/StackWords.h index 8acbe28..bdf8848 100644 --- a/lib/Conversion/ForthStack/StackWords.h +++ b/lib/Conversion/ForthStack/StackWords.h @@ -40,6 +40,10 @@ class WordContext { /// Pushes one cell. A row pushes exactly `effect.pushes` cells, deepest /// first. virtual void push(Value cell) = 0; + + /// Replaces every use of the op's non-stack result, such as the i1 of + /// forth.pop_flag, with `value`. + virtual void replaceValueResult(Value value) = 0; }; using LowerFn = std::function; diff --git a/test/Conversion/ForthStack/control-flow.mlir b/test/Conversion/ForthStack/control-flow.mlir new file mode 100644 index 0000000..8223336 --- /dev/null +++ b/test/Conversion/ForthStack/control-flow.mlir @@ -0,0 +1,88 @@ +// RUN: %warpforth-opt --lower-forth-stack %s | %FileCheck %s +// RUN: %warpforth-opt --lower-forth-stack --canonicalize %s | %FileCheck %s --check-prefix=FOLD + +// `1 IF 42 ELSE 99 THEN OUT !`: each arm leaves one cell, so the join takes +// that cell as one i64 argument and stores it. The arms take no arguments +// because popping the flag left the stack empty. +// CHECK-LABEL: func.func @if_else( +// CHECK: %[[FLAG:.*]] = arith.cmpi ne, %{{.*}}, %{{.*}} : i64 +// CHECK: cf.cond_br %[[FLAG]], ^[[THEN:bb[0-9]+]], ^[[ELSE:bb[0-9]+]] +// CHECK: ^[[THEN]]: +// CHECK: %[[C42:.*]] = arith.constant 42 : i64 +// CHECK: cf.br ^[[JOIN:bb[0-9]+]](%[[C42]] : i64) +// CHECK: ^[[ELSE]]: +// CHECK: %[[C99:.*]] = arith.constant 99 : i64 +// CHECK: cf.br ^[[JOIN]](%[[C99]] : i64) +// CHECK: ^[[JOIN]](%[[RESULT:.*]]: i64): +// CHECK: llvm.store %[[RESULT]], %{{.*}} : i64, !llvm.ptr<1> + +// A true flag takes the IF arm. +// FOLD-LABEL: func.func @if_else( +// FOLD: %[[C42:.*]] = arith.constant 42 : i64 +// FOLD: llvm.store %[[C42]], %{{.*}} : i64, !llvm.ptr<1> +func.func @if_else(%out: memref<1xi64>) { + %0 = forth.stack !forth.stack + %1 = forth.constant %0(1 : i64) : !forth.stack -> !forth.stack + %output_stack, %flag = forth.pop_flag %1 : !forth.stack -> !forth.stack, i1 + cf.cond_br %flag, ^bb1(%output_stack : !forth.stack), ^bb2(%output_stack : !forth.stack) +^bb1(%2: !forth.stack): + %3 = forth.constant %2(42 : i64) : !forth.stack -> !forth.stack + cf.br ^bb3(%3 : !forth.stack) +^bb2(%4: !forth.stack): + %5 = forth.constant %4(99 : i64) : !forth.stack -> !forth.stack + cf.br ^bb3(%5 : !forth.stack) +^bb3(%6: !forth.stack): + %7 = forth.param_ref %6 %out : !forth.stack, memref<1xi64> -> !forth.stack + %8 = forth.storei %7 : !forth.stack -> !forth.stack + return +} + +// `5 10 2 DO I + LOOP OUT !`: the body pushes I and adds it, so every +// iteration starts and ends with one cell. The loop header carries that cell +// as an i64 argument, and the loop counter stays in memory. +// CHECK-LABEL: func.func @do_loop_sum( +// CHECK: %[[INITIAL:.*]] = arith.constant 5 : i64 +// CHECK: %[[LIMIT:.*]] = arith.constant 10 : i64 +// CHECK: %[[START:.*]] = arith.constant 2 : i64 +// CHECK: %[[COUNTER:.*]] = memref.alloca() : memref<1xi64> +// CHECK: memref.store %[[START]], %[[COUNTER]] +// CHECK: cf.br ^[[HEADER:bb[0-9]+]](%[[INITIAL]] : i64) +// CHECK: ^[[HEADER]](%[[ACC:.*]]: i64): +// CHECK: %[[I:.*]] = memref.load %[[COUNTER]] +// CHECK: %[[SUM:.*]] = arith.addi %[[ACC]], %[[I]] : i64 +// CHECK: arith.subi %{{.*}}, %[[LIMIT]] : i64 +// CHECK: cf.cond_br %{{.*}}, ^[[EXIT:bb[0-9]+]](%[[SUM]] : i64), ^[[HEADER]](%[[SUM]] : i64) +// CHECK: ^[[EXIT]](%[[TOTAL:.*]]: i64): +// CHECK: llvm.store %[[TOTAL]], %{{.*}} : i64, !llvm.ptr<1> +func.func @do_loop_sum(%out: memref<1xi64>) { + %0 = forth.stack !forth.stack + %1 = forth.constant %0(5 : i64) : !forth.stack -> !forth.stack + %2 = forth.constant %1(10 : i64) : !forth.stack -> !forth.stack + %3 = forth.constant %2(2 : i64) : !forth.stack -> !forth.stack + %output_stack, %value = forth.pop %3 : !forth.stack -> !forth.stack, i64 + %output_stack_0, %value_1 = forth.pop %output_stack : !forth.stack -> !forth.stack, i64 + %alloca = memref.alloca() : memref<1xi64> + %c0 = arith.constant 0 : index + memref.store %value, %alloca[%c0] : memref<1xi64> + cf.br ^bb1(%output_stack_0 : !forth.stack) +^bb1(%4: !forth.stack): + %c0_2 = arith.constant 0 : index + %5 = memref.load %alloca[%c0_2] : memref<1xi64> + %6 = forth.push_value %4, %5 : !forth.stack, i64 -> !forth.stack + %7 = forth.addi %6 : !forth.stack -> !forth.stack + %c1_i64 = arith.constant 1 : i64 + %c0_3 = arith.constant 0 : index + %8 = memref.load %alloca[%c0_3] : memref<1xi64> + %9 = arith.addi %8, %c1_i64 : i64 + memref.store %9, %alloca[%c0_3] : memref<1xi64> + %10 = arith.subi %8, %value_1 : i64 + %11 = arith.subi %9, %value_1 : i64 + %12 = arith.xori %10, %11 : i64 + %c0_i64 = arith.constant 0 : i64 + %13 = arith.cmpi slt, %12, %c0_i64 : i64 + cf.cond_br %13, ^bb2(%7 : !forth.stack), ^bb1(%7 : !forth.stack) +^bb2(%14: !forth.stack): + %15 = forth.param_ref %14 %out : !forth.stack, memref<1xi64> -> !forth.stack + %16 = forth.storei %15 : !forth.stack -> !forth.stack + return +} diff --git a/test/Pipeline/stack-promotion-loop.forth b/test/Pipeline/stack-promotion-loop.forth new file mode 100644 index 0000000..98d3ebd --- /dev/null +++ b/test/Pipeline/stack-promotion-loop.forth @@ -0,0 +1,14 @@ +\ RUN: %warpforthc -O0 %s -o %t.ptx +\ RUN: %FileCheck %s < %t.ptx + +\ The loop carries its one cell in a register. Only the DO counter lives in +\ local memory, so even without optimization the local depot holds 8 bytes, +\ not a 2048-byte stack. + +\! kernel main +\! param OUT i64[1] +5 10 2 DO I + LOOP OUT ! + +\ CHECK-LABEL: .entry main( +\ CHECK: .local .align 8 .b8 __local_depot0[8]; +\ CHECK: st.global.u64 From e3bbede35c2460a3b9e78c3bab1879597eb57e0f Mon Sep 17 00:00:00 2001 From: Alex Cameron Date: Mon, 9 Nov 2026 04:35:38 +0000 Subject: [PATCH 4/8] feat(conversion): keep PICK and ROLL cells in registers when the slot is known A literal PICK or ROLL index names a register cell, so the word is just another use of that value or a reordering of the cells. Only a runtime index, a pop below the known depth, or a join of unequal depths needs cells that can be addressed in memory. Those cases now use a per-thread memref<256xi64> created on first use, with the memref stack's layout: index 0 is empty, a push stores at depth + 1, and there is no overflow check or address space. A dynamic PICK stores the live cells only as the image for its load and keeps them in registers. A dynamic ROLL stores them, runs the same shift loop as before, and reloads them. A pop the static depth cannot cover widens the stack to the buffer and loads index 0, as before, so every program that compiled still compiles. A join of unequal depths keeps the top cells that every edge holds and takes the memory depth as an index block argument. --- include/warpforth/Conversion/Passes.td | 5 + lib/Conversion/ForthStack/CMakeLists.txt | 4 + lib/Conversion/ForthStack/LowerForthStack.cpp | 249 +++++++++++++++--- lib/Conversion/ForthStack/StackWords.cpp | 8 + lib/Conversion/ForthStack/StackWords.h | 8 + test/Conversion/ForthStack/pick-roll.mlir | 132 ++++++++++ test/Conversion/ForthStack/residual.mlir | 53 ++++ test/Pipeline/stack-residual.forth | 24 ++ 8 files changed, 451 insertions(+), 32 deletions(-) create mode 100644 test/Conversion/ForthStack/pick-roll.mlir create mode 100644 test/Conversion/ForthStack/residual.mlir create mode 100644 test/Pipeline/stack-residual.forth diff --git a/include/warpforth/Conversion/Passes.td b/include/warpforth/Conversion/Passes.td index 9ea3b95..0b6d162 100644 --- a/include/warpforth/Conversion/Passes.td +++ b/include/warpforth/Conversion/Passes.td @@ -40,6 +40,10 @@ def LowerForthStack : Pass<"lower-forth-stack", "mlir::ModuleOp"> { compile time becomes an `i64` SSA value, and each word becomes the `arith`, `memref`, or `llvm` ops that compute its result. + A cell below the known depth, or one that a runtime `PICK` or `ROLL` index + addresses, lives in a per-thread `memref<256xi64>` with the memref stack's + layout: index 0 is empty and a push stores at depth + 1. + A function whose words this pass does not lower yet is left unchanged for `convert-forth-to-memref`. }]; @@ -47,6 +51,7 @@ def LowerForthStack : Pass<"lower-forth-stack", "mlir::ModuleOp"> { let constructor = "mlir::warpforth::createLowerForthStackPass()"; let dependentDialects = ["mlir::arith::ArithDialect", + "mlir::cf::ControlFlowDialect", "mlir::LLVM::LLVMDialect", "mlir::memref::MemRefDialect"]; } diff --git a/lib/Conversion/ForthStack/CMakeLists.txt b/lib/Conversion/ForthStack/CMakeLists.txt index 5f4e758..e094a9c 100644 --- a/lib/Conversion/ForthStack/CMakeLists.txt +++ b/lib/Conversion/ForthStack/CMakeLists.txt @@ -10,9 +10,13 @@ add_mlir_conversion_library(MLIRForthStackConversion MLIRIR MLIRPass MLIRArithDialect + MLIRControlFlowDialect + MLIRControlFlowInterfaces + MLIRDialectUtils MLIRFuncDialect MLIRLLVMDialect MLIRMemRefDialect MLIRNVVMDialect + MLIRTransformUtils MLIRForth ) diff --git a/lib/Conversion/ForthStack/LowerForthStack.cpp b/lib/Conversion/ForthStack/LowerForthStack.cpp index 91a97d1..4bdc92d 100644 --- a/lib/Conversion/ForthStack/LowerForthStack.cpp +++ b/lib/Conversion/ForthStack/LowerForthStack.cpp @@ -2,16 +2,19 @@ // // This file implements the pass that lowers every !forth.stack value. The // stack-word table says what each word computes. This file decides where each -// cell lives: a cell whose depth and slot are known is an i64 SSA value. +// cell lives: a cell whose depth and slot are known is an i64 SSA value, and +// the rest live in a per-thread buffer laid out like the memref stack. // //===----------------------------------------------------------------------===// #include "warpforth/Conversion/ForthStack/LowerForthStack.h" #include "StackWords.h" -#include "mlir/Dialect/Arith/IR/Arith.h" // IWYU pragma: keep +#include "mlir/Dialect/Arith/IR/Arith.h" +#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" #include "mlir/Dialect/Func/IR/FuncOps.h" #include "mlir/Dialect/LLVMIR/LLVMDialect.h" // IWYU pragma: keep -#include "mlir/Dialect/MemRef/IR/MemRef.h" // IWYU pragma: keep +#include "mlir/Dialect/MemRef/IR/MemRef.h" +#include "mlir/Dialect/Utils/StaticValueUtils.h" #include "mlir/IR/Builders.h" #include "mlir/IR/BuiltinOps.h" #include "mlir/IR/BuiltinTypes.h" @@ -40,6 +43,10 @@ using stack::StackEffect; using stack::StackWord; using stack::WordContext; +/// Cells in the residual buffer. Index 0 is never written by a push, so an +/// empty buffer has depth 0. +constexpr int64_t kResidualCells = 256; + bool isStack(Type type) { return isa(type); } /// Compile-time shape of one !forth.stack value. A static stack holds exactly @@ -82,6 +89,15 @@ StackShape join(StackShape a, StackShape b) { return ResidualShape{std::min(registerCells(a), registerCells(b))}; } +/// The block arguments that carry a stack of `shape`: one i64 per register +/// cell, deepest first, then the memory depth of a residual stack. +SmallVector argumentTypes(StackShape shape, Builder &b) { + SmallVector types(registerCells(shape), b.getI64Type()); + if (std::holds_alternative(shape)) + types.push_back(b.getIndexType()); + return types; +} + /// Where the cells of one !forth.stack value live while the pass rewrites it. /// `cells` are i64 values, deepest first. A residual stack also holds `depth`, /// the index of its top cell in memory. @@ -99,6 +115,11 @@ SmallVector &cellsOf(StackState &state) { state); } +ArrayRef cellsOf(const StackState &state) { + return std::visit([](const auto &s) -> ArrayRef { return s.cells; }, + state); +} + /// A word keeps the stack in its signature until the inliner removes it, and /// this pass gives words no calling convention. LogicalResult verifyWordsInlined(ModuleOp module) { @@ -186,7 +207,8 @@ DenseMap inferShapes(Region &body) { class StackSimulator final : public WordContext { public: StackSimulator(func::FuncOp fn, DenseMap shapes) - : fn(fn), b(fn.getContext()), shapes(std::move(shapes)) {} + : fn(fn), b(fn.getContext()), loc(fn.getLoc()), + shapes(std::move(shapes)) {} /// Lowers every stack word in `fn`, then erases the Forth stack ops. void run(); @@ -194,6 +216,8 @@ class StackSimulator final : public WordContext { OpBuilder &builder() override { return b; } Value popped(unsigned i) override { return poppedCells[i]; } void push(Value cell) override { pushedCells.push_back(cell); } + Value peek(Value n) override; + void rollToTop(Value n) override; void replaceValueResult(Value value) override { current->getResult(1).replaceAllUsesWith(value); } @@ -201,15 +225,31 @@ class StackSimulator final : public WordContext { private: void expandArguments(Block &block); void lowerWord(Operation *op, const StackWord &word); + Value popCell(); void forwardCells(BranchOpInterface branch); + void appendEdgeOperands(const StackState &state, StackShape target, + SmallVectorImpl &operands); + + Value residualBuffer(); + Value memoryDepth(const StackState &state); + Value storeCells(ArrayRef cells, Value depth); + Value indexConstant(int64_t value); + static std::optional registerSlot(Value n, size_t cells); func::FuncOp fn; OpBuilder b; + /// Location of the op or branch being lowered. + Location loc; DenseMap shapes; /// Keyed by the original !forth.stack value. DenseMap states; + /// Each block's arguments before stack arguments were expanded. + DenseMap> originalArguments; SmallVector lowered; SmallVector replacedArguments; + /// Allocated on first use, so a function whose cells all have static slots + /// has no buffer. + Value buffer; // Scratch for the op being lowered. Operation *current = nullptr; @@ -223,15 +263,20 @@ void StackSimulator::run() { for (Block &block : body) expandArguments(block); for (Block *block : llvm::ReversePostOrderTraversal(&body.front())) { - for (Operation &op : *block) { + // A dynamic ROLL moves the ops after it into a new block, so follow each + // op's next op rather than iterating the block. + Operation *op = &block->front(); + while (op) { + Operation *next = op->getNextNode(); if (isa(op)) { - states[op.getResult(0)] = StaticState{}; - lowered.push_back(&op); - } else if (const StackWord *word = stack::lookupStackWord(&op)) { - lowerWord(&op, *word); + states[op->getResult(0)] = StaticState{}; + lowered.push_back(op); + } else if (const StackWord *word = stack::lookupStackWord(op)) { + lowerWord(op, *word); } else if (auto branch = dyn_cast(op)) { forwardCells(branch); } + op = next; } } for (Operation *op : lowered) @@ -242,32 +287,38 @@ void StackSimulator::run() { arg.getOwner()->eraseArgument(arg.getArgNumber()); } -/// Gives each stack argument of `block` one i64 argument per cell, placed +/// Gives each stack argument of `block` the arguments its shape needs, placed /// after it. The stack argument is erased once nothing uses it. void StackSimulator::expandArguments(Block &block) { - for (unsigned i = 0; i < block.getNumArguments(); ++i) { - BlockArgument arg = block.getArgument(i); + SmallVector &original = originalArguments[&block]; + original = llvm::to_vector(block.getArguments()); + for (BlockArgument arg : original) { if (!isStack(arg.getType())) continue; - StaticState state; - for (unsigned cell = 0, e = registerCells(shapes.at(arg)); cell < e; ++cell) - state.cells.push_back( - block.insertArgument(i + 1 + cell, b.getI64Type(), arg.getLoc())); - i += state.cells.size(); - states[arg] = std::move(state); + StackShape shape = shapes.at(arg); + unsigned position = arg.getArgNumber(); + SmallVector values; + for (Type type : argumentTypes(shape, b)) + values.push_back(block.insertArgument(++position, type, arg.getLoc())); + if (std::holds_alternative(shape)) { + states[arg] = StaticState{std::move(values)}; + } else { + Value depth = values.pop_back_val(); + states[arg] = ResidualState{std::move(values), depth}; + } replacedArguments.push_back(arg); } } void StackSimulator::lowerWord(Operation *op, const StackWord &word) { current = op; + loc = op->getLoc(); + b.setInsertionPoint(op); working = states.at(op->getOperand(0)); - SmallVector &cells = cellsOf(working); poppedCells.clear(); for (unsigned i = 0; i < word.effect.pops; ++i) - poppedCells.push_back(cells.pop_back_val()); + poppedCells.push_back(popCell()); pushedCells.clear(); - b.setInsertionPoint(op); word.lower(op, *this); assert(pushedCells.size() == word.effect.pushes && "a row pushes exactly the cells its effect declares"); @@ -276,25 +327,164 @@ void StackSimulator::lowerWord(Operation *op, const StackWord &word) { lowered.push_back(op); } -/// Passes each forwarded stack to its successor as the stack's cells. +/// Pops the top cell of the working stack. Below the register cells the cell +/// is loaded from memory. A static stack has nothing below its cells, so it +/// widens to an empty residual stack and the load reads index 0, as the memref +/// stack did. +Value StackSimulator::popCell() { + SmallVector &cells = cellsOf(working); + if (!cells.empty()) + return cells.pop_back_val(); + if (std::holds_alternative(working)) + working = ResidualState{{}, indexConstant(0)}; + auto &residual = std::get(working); + Value cell = b.create(loc, residualBuffer(), residual.depth); + residual.depth = + b.create(loc, residual.depth, indexConstant(1)); + return cell; +} + +/// The register slot that the constant `n` names, counted from the top of +/// `cells` register cells, or none when `n` is not such a constant. +std::optional StackSimulator::registerSlot(Value n, size_t cells) { + std::optional slot = getConstantIntValue(n); + if (!slot || *slot < 0 || static_cast(*slot) >= cells) + return std::nullopt; + return static_cast(cells - 1 - static_cast(*slot)); +} + +Value StackSimulator::peek(Value n) { + SmallVector &cells = cellsOf(working); + if (std::optional slot = registerSlot(n, cells.size())) + return cells[*slot]; + // The register cells are written only as the image this load addresses, and + // they stay the live stack. + Value top = storeCells(cells, memoryDepth(working)); + Value offset = b.create(loc, b.getIndexType(), n); + Value index = b.create(loc, top, offset); + return b.create(loc, residualBuffer(), index); +} + +void StackSimulator::rollToTop(Value n) { + SmallVector &cells = cellsOf(working); + if (std::optional slot = registerSlot(n, cells.size())) { + std::rotate(cells.begin() + *slot, cells.begin() + *slot + 1, cells.end()); + return; + } + Value depth = memoryDepth(working); + Value top = storeCells(cells, depth); + Value offset = b.create(loc, b.getIndexType(), n); + Value rolledIndex = b.create(loc, top, offset); + Value rolled = b.create(loc, residualBuffer(), rolledIndex); + + // for (iv = rolledIndex; iv < top; ++iv) buffer[iv] = buffer[iv + 1] + Block *before = b.getInsertionBlock(); + Block *after = before->splitBlock(b.getInsertionPoint()); + Type indexType = b.getIndexType(); + Block *header = b.createBlock(after, indexType, loc); + Block *body = b.createBlock(after, indexType, loc); + + b.setInsertionPointToEnd(before); + b.create(loc, header, rolledIndex); + + b.setInsertionPointToStart(header); + Value iv = header->getArgument(0); + Value shifting = + b.create(loc, arith::CmpIPredicate::slt, iv, top); + b.create(loc, shifting, body, iv, after, ValueRange{}); + + b.setInsertionPointToStart(body); + Value slot = body->getArgument(0); + Value next = b.create(loc, slot, indexConstant(1)); + Value shifted = b.create(loc, residualBuffer(), next); + b.create(loc, shifted, residualBuffer(), slot); + b.create(loc, header, next); + + b.setInsertionPointToStart(after); + b.create(loc, rolled, residualBuffer(), top); + Value index = depth; + for (Value &cell : cells) { + index = b.create(loc, index, indexConstant(1)); + cell = b.create(loc, residualBuffer(), index); + } +} + +/// Passes each forwarded stack to its successor in the successor's shape. void StackSimulator::forwardCells(BranchOpInterface branch) { + loc = branch->getLoc(); + b.setInsertionPoint(branch); for (unsigned i = 0, e = branch->getNumSuccessors(); i < e; ++i) { SuccessorOperands operands = branch.getSuccessorOperands(i); if (llvm::none_of(operands.getForwardedOperands().getTypes(), isStack)) continue; + ArrayRef targets = + originalArguments.find(branch->getSuccessor(i))->second; + unsigned first = operands.getProducedOperandCount(); SmallVector forwarded; - for (Value value : operands.getForwardedOperands()) { + for (auto [j, value] : llvm::enumerate(operands.getForwardedOperands())) { if (!isStack(value.getType())) { forwarded.push_back(value); continue; } - StackState state = states.at(value); - llvm::append_range(forwarded, cellsOf(state)); + appendEdgeOperands(states.at(value), shapes.at(targets[first + j]), + forwarded); } operands.getMutableForwardedOperands().assign(forwarded); } } +/// Appends the operands that pass a stack in `state` to an argument of shape +/// `target`. The cells below the target's register cells are stored to memory +/// first. Every edge into a join stores a cell at the same index, so the +/// stores agree whichever edge runs. +void StackSimulator::appendEdgeOperands(const StackState &state, + StackShape target, + SmallVectorImpl &operands) { + ArrayRef cells = cellsOf(state); + unsigned kept = registerCells(target); + assert(kept <= cells.size() && "a join keeps cells that every edge holds"); + if (std::holds_alternative(target)) { + assert(std::holds_alternative(state) && kept == cells.size() && + "a static join has equal static edges"); + llvm::append_range(operands, cells); + return; + } + Value depth = storeCells(cells.drop_back(kept), memoryDepth(state)); + llvm::append_range(operands, cells.take_back(kept)); + operands.push_back(depth); +} + +Value StackSimulator::residualBuffer() { + if (!buffer) { + OpBuilder::InsertionGuard guard(b); + b.setInsertionPointToStart(&fn.getBody().front()); + buffer = b.create( + loc, MemRefType::get({kResidualCells}, b.getI64Type())); + } + return buffer; +} + +/// The index of the top memory cell under `state`'s register cells. +Value StackSimulator::memoryDepth(const StackState &state) { + if (const auto *residual = std::get_if(&state)) + return residual->depth; + return indexConstant(0); +} + +/// Pushes `cells` to memory above `depth`, deepest first, and returns the new +/// depth. +Value StackSimulator::storeCells(ArrayRef cells, Value depth) { + for (Value cell : cells) { + depth = b.create(loc, depth, indexConstant(1)); + b.create(loc, cell, residualBuffer(), depth); + } + return depth; +} + +Value StackSimulator::indexConstant(int64_t value) { + return b.create(loc, value); +} + struct LowerForthStackPass : public impl::LowerForthStackBase { void runOnOperation() override { @@ -306,16 +496,11 @@ struct LowerForthStackPass if (fn.isExternal()) continue; (void)eraseUnreachableBlocks(rewriter, fn->getRegions()); - // A function this pass cannot lower yet is left whole for + // A function that uses a word with no row yet is left whole for // convert-forth-to-memref. if (!hasRowsFor(fn.getBody())) continue; - DenseMap shapes = inferShapes(fn.getBody()); - if (llvm::any_of(shapes, [](const auto &entry) { - return !std::holds_alternative(entry.second); - })) - continue; - StackSimulator(fn, std::move(shapes)).run(); + StackSimulator(fn, inferShapes(fn.getBody())).run(); } } }; diff --git a/lib/Conversion/ForthStack/StackWords.cpp b/lib/Conversion/ForthStack/StackWords.cpp index 90ce0d0..ce431d6 100644 --- a/lib/Conversion/ForthStack/StackWords.cpp +++ b/lib/Conversion/ForthStack/StackWords.cpp @@ -153,6 +153,14 @@ ArrayRef stackWordRows() { } ctx.push(parameter); }), + row({1, 1}, + [](forth::PickOp, WordContext &ctx) { + ctx.push(ctx.peek(ctx.popped(0))); + }), + row({1, 0}, + [](forth::RollOp, WordContext &ctx) { + ctx.rollToTop(ctx.popped(0)); + }), row({0, 1}, [](forth::PushValueOp op, WordContext &ctx) { ctx.push(op.getValue()); diff --git a/lib/Conversion/ForthStack/StackWords.h b/lib/Conversion/ForthStack/StackWords.h index bdf8848..0d4fa53 100644 --- a/lib/Conversion/ForthStack/StackWords.h +++ b/lib/Conversion/ForthStack/StackWords.h @@ -41,6 +41,14 @@ class WordContext { /// first. virtual void push(Value cell) = 0; + /// The cell `n` places below the top of the stack left after the pops, + /// where 0 is the top. `n` is an i64 cell and need not be a constant. + virtual Value peek(Value n) = 0; + + /// Moves the cell `n` places below the top of the stack left after the pops + /// to the top, shifting the cells above it down by one. + virtual void rollToTop(Value n) = 0; + /// Replaces every use of the op's non-stack result, such as the i1 of /// forth.pop_flag, with `value`. virtual void replaceValueResult(Value value) = 0; diff --git a/test/Conversion/ForthStack/pick-roll.mlir b/test/Conversion/ForthStack/pick-roll.mlir new file mode 100644 index 0000000..e105d90 --- /dev/null +++ b/test/Conversion/ForthStack/pick-roll.mlir @@ -0,0 +1,132 @@ +// RUN: %warpforth-opt --lower-forth-stack %s | %FileCheck %s + +// `10 20 30 2 PICK A !`: a literal index names a register cell, so PICK is +// another use of that cell's value. +// CHECK-LABEL: func.func @literal_pick( +// CHECK-NOT: memref.alloca +// CHECK: %[[TEN:.*]] = arith.constant 10 : i64 +// CHECK-NOT: memref.alloca +// CHECK: llvm.store %[[TEN]], %{{.*}} : i64, !llvm.ptr<1> +// CHECK-NEXT: return +func.func @literal_pick(%a: memref<1xi64>) { + %0 = forth.stack !forth.stack + %1 = forth.constant %0(10 : i64) : !forth.stack -> !forth.stack + %2 = forth.constant %1(20 : i64) : !forth.stack -> !forth.stack + %3 = forth.constant %2(30 : i64) : !forth.stack -> !forth.stack + %4 = forth.constant %3(2 : i64) : !forth.stack -> !forth.stack + %5 = forth.pick %4 : !forth.stack -> !forth.stack + %6 = forth.param_ref %5 %a : !forth.stack, memref<1xi64> -> !forth.stack + %7 = forth.storei %6 : !forth.stack -> !forth.stack + return +} + +// `10 20 30 2 ROLL A ! B ! C !`: a literal ROLL reorders register cells, so +// the stack becomes 20 30 10 with no memory traffic. +// CHECK-LABEL: func.func @literal_roll( +// CHECK-NOT: memref.alloca +// CHECK: %[[TEN:.*]] = arith.constant 10 : i64 +// CHECK: %[[TWENTY:.*]] = arith.constant 20 : i64 +// CHECK: %[[THIRTY:.*]] = arith.constant 30 : i64 +// CHECK-NOT: memref.alloca +// CHECK: llvm.store %[[TEN]], %{{.*}} : i64, !llvm.ptr<1> +// CHECK: llvm.store %[[THIRTY]], %{{.*}} : i64, !llvm.ptr<1> +// CHECK: llvm.store %[[TWENTY]], %{{.*}} : i64, !llvm.ptr<1> +// CHECK-NEXT: return +func.func @literal_roll(%a: memref<1xi64>, %b: memref<1xi64>, %c: memref<1xi64>) { + %0 = forth.stack !forth.stack + %1 = forth.constant %0(10 : i64) : !forth.stack -> !forth.stack + %2 = forth.constant %1(20 : i64) : !forth.stack -> !forth.stack + %3 = forth.constant %2(30 : i64) : !forth.stack -> !forth.stack + %4 = forth.constant %3(2 : i64) : !forth.stack -> !forth.stack + %5 = forth.roll %4 : !forth.stack -> !forth.stack + %6 = forth.param_ref %5 %a : !forth.stack, memref<1xi64> -> !forth.stack + %7 = forth.storei %6 : !forth.stack -> !forth.stack + %8 = forth.param_ref %7 %b : !forth.stack, memref<1xi64> -> !forth.stack + %9 = forth.storei %8 : !forth.stack -> !forth.stack + %10 = forth.param_ref %9 %c : !forth.stack, memref<1xi64> -> !forth.stack + %11 = forth.storei %10 : !forth.stack -> !forth.stack + return +} + +// `10 20 30 N PICK A ! B !`: a runtime index needs addressable cells, so the +// three cells are stored at indices 1 to 3 as the image for one load at +// 3 - N. The cells stay in registers, so B receives 30 directly. +// CHECK-LABEL: func.func @dynamic_pick( +// CHECK-SAME: %[[N:[^:]*]]: i64 +// CHECK: %[[BUFFER:.*]] = memref.alloca() : memref<256xi64> +// CHECK: %[[TEN:.*]] = arith.constant 10 : i64 +// CHECK: %[[TWENTY:.*]] = arith.constant 20 : i64 +// CHECK: %[[THIRTY:.*]] = arith.constant 30 : i64 +// CHECK: %[[EMPTY:.*]] = arith.constant 0 : index +// CHECK: %[[SLOT1:.*]] = arith.addi %[[EMPTY]], %{{.*}} : index +// CHECK: memref.store %[[TEN]], %[[BUFFER]][%[[SLOT1]]] +// CHECK: %[[SLOT2:.*]] = arith.addi %[[SLOT1]], %{{.*}} : index +// CHECK: memref.store %[[TWENTY]], %[[BUFFER]][%[[SLOT2]]] +// CHECK: %[[SLOT3:.*]] = arith.addi %[[SLOT2]], %{{.*}} : index +// CHECK: memref.store %[[THIRTY]], %[[BUFFER]][%[[SLOT3]]] +// CHECK: %[[OFFSET:.*]] = arith.index_cast %[[N]] : i64 to index +// CHECK: %[[INDEX:.*]] = arith.subi %[[SLOT3]], %[[OFFSET]] : index +// CHECK: %[[PICKED:.*]] = memref.load %[[BUFFER]][%[[INDEX]]] +// CHECK: llvm.store %[[PICKED]], %{{.*}} : i64, !llvm.ptr<1> +// CHECK: llvm.store %[[THIRTY]], %{{.*}} : i64, !llvm.ptr<1> +func.func @dynamic_pick(%n: i64, %a: memref<1xi64>, %b: memref<1xi64>) { + %0 = forth.stack !forth.stack + %1 = forth.constant %0(10 : i64) : !forth.stack -> !forth.stack + %2 = forth.constant %1(20 : i64) : !forth.stack -> !forth.stack + %3 = forth.constant %2(30 : i64) : !forth.stack -> !forth.stack + %4 = forth.param_ref %3 %n : !forth.stack, i64 -> !forth.stack + %5 = forth.pick %4 : !forth.stack -> !forth.stack + %6 = forth.param_ref %5 %a : !forth.stack, memref<1xi64> -> !forth.stack + %7 = forth.storei %6 : !forth.stack -> !forth.stack + %8 = forth.param_ref %7 %b : !forth.stack, memref<1xi64> -> !forth.stack + %9 = forth.storei %8 : !forth.stack -> !forth.stack + return +} + +// `10 20 30 N ROLL A ! B ! C !`: a runtime ROLL stores the cells, saves the +// cell at 3 - N, shifts the cells above it down, stores the saved cell on top, +// and reloads the three cells. +// CHECK-LABEL: func.func @dynamic_roll( +// CHECK-SAME: %[[N:[^:]*]]: i64 +// CHECK: %[[BUFFER:.*]] = memref.alloca() : memref<256xi64> +// CHECK: %[[EMPTY:.*]] = arith.constant 0 : index +// CHECK: memref.store +// CHECK: memref.store +// CHECK: %[[TOP:.*]] = arith.addi %{{.*}}, %{{.*}} : index +// CHECK: memref.store %{{.*}}, %[[BUFFER]][%[[TOP]]] +// CHECK: %[[OFFSET:.*]] = arith.index_cast %[[N]] : i64 to index +// CHECK: %[[FROM:.*]] = arith.subi %[[TOP]], %[[OFFSET]] : index +// CHECK: %[[ROLLED:.*]] = memref.load %[[BUFFER]][%[[FROM]]] +// CHECK: cf.br ^[[HEADER:bb[0-9]+]](%[[FROM]] : index) +// CHECK: ^[[HEADER]](%[[IV:.*]]: index): +// CHECK: %[[MORE:.*]] = arith.cmpi slt, %[[IV]], %[[TOP]] : index +// CHECK: cf.cond_br %[[MORE]], ^[[BODY:bb[0-9]+]](%[[IV]] : index), ^[[DONE:bb[0-9]+]] +// CHECK: ^[[BODY]](%[[SLOT:.*]]: index): +// CHECK: %[[NEXT:.*]] = arith.addi %[[SLOT]], %{{.*}} : index +// CHECK: %[[SHIFTED:.*]] = memref.load %[[BUFFER]][%[[NEXT]]] +// CHECK: memref.store %[[SHIFTED]], %[[BUFFER]][%[[SLOT]]] +// CHECK: cf.br ^[[HEADER]](%[[NEXT]] : index) +// CHECK: ^[[DONE]]: +// CHECK: memref.store %[[ROLLED]], %[[BUFFER]][%[[TOP]]] +// CHECK: %[[RELOAD1:.*]] = arith.addi %[[EMPTY]], %{{.*}} : index +// CHECK: %[[BOTTOM:.*]] = memref.load %[[BUFFER]][%[[RELOAD1]]] +// CHECK: %[[MIDDLE:.*]] = memref.load +// CHECK: %[[NEWTOP:.*]] = memref.load +// CHECK: llvm.store %[[NEWTOP]], %{{.*}} : i64, !llvm.ptr<1> +// CHECK: llvm.store %[[MIDDLE]], %{{.*}} : i64, !llvm.ptr<1> +// CHECK: llvm.store %[[BOTTOM]], %{{.*}} : i64, !llvm.ptr<1> +func.func @dynamic_roll(%n: i64, %a: memref<1xi64>, %b: memref<1xi64>, %c: memref<1xi64>) { + %0 = forth.stack !forth.stack + %1 = forth.constant %0(10 : i64) : !forth.stack -> !forth.stack + %2 = forth.constant %1(20 : i64) : !forth.stack -> !forth.stack + %3 = forth.constant %2(30 : i64) : !forth.stack -> !forth.stack + %4 = forth.param_ref %3 %n : !forth.stack, i64 -> !forth.stack + %5 = forth.roll %4 : !forth.stack -> !forth.stack + %6 = forth.param_ref %5 %a : !forth.stack, memref<1xi64> -> !forth.stack + %7 = forth.storei %6 : !forth.stack -> !forth.stack + %8 = forth.param_ref %7 %b : !forth.stack, memref<1xi64> -> !forth.stack + %9 = forth.storei %8 : !forth.stack -> !forth.stack + %10 = forth.param_ref %9 %c : !forth.stack, memref<1xi64> -> !forth.stack + %11 = forth.storei %10 : !forth.stack -> !forth.stack + return +} diff --git a/test/Conversion/ForthStack/residual.mlir b/test/Conversion/ForthStack/residual.mlir new file mode 100644 index 0000000..bf160a0 --- /dev/null +++ b/test/Conversion/ForthStack/residual.mlir @@ -0,0 +1,53 @@ +// RUN: %warpforth-opt --lower-forth-stack %s | %FileCheck %s + +// `5 + A !`: + needs a second cell that the stack does not have. The pop +// widens the stack to the residual buffer and loads index 0, as the memref +// stack did, instead of failing to compile. +// CHECK-LABEL: func.func @underflow( +// CHECK: %[[BUFFER:.*]] = memref.alloca() : memref<256xi64> +// CHECK: %[[FIVE:.*]] = arith.constant 5 : i64 +// CHECK: %[[EMPTY:.*]] = arith.constant 0 : index +// CHECK: %[[BELOW:.*]] = memref.load %[[BUFFER]][%[[EMPTY]]] +// CHECK: %[[SUM:.*]] = arith.addi %[[BELOW]], %[[FIVE]] : i64 +// CHECK: llvm.store %[[SUM]], %{{.*}} : i64, !llvm.ptr<1> +func.func @underflow(%a: memref<1xi64>) { + %0 = forth.stack !forth.stack + %1 = forth.constant %0(5 : i64) : !forth.stack -> !forth.stack + %2 = forth.addi %1 : !forth.stack -> !forth.stack + %3 = forth.param_ref %2 %a : !forth.stack, memref<1xi64> -> !forth.stack + %4 = forth.storei %3 : !forth.stack -> !forth.stack + return +} + +// `7 FLAG IF 1 THEN + A !`: the arms reach THEN with two cells and with one, +// so the join keeps the one top cell both share in a register and takes the +// memory depth as an index. The arm with two cells stores 7 at index 1. +// CHECK-LABEL: func.func @unequal_join( +// CHECK: %[[BUFFER:.*]] = memref.alloca() : memref<256xi64> +// CHECK: %[[SEVEN:.*]] = arith.constant 7 : i64 +// CHECK: %[[EMPTY:.*]] = arith.constant 0 : index +// CHECK: cf.cond_br %{{.*}}, ^[[THEN:bb[0-9]+]](%[[SEVEN]] : i64), ^[[JOIN:bb[0-9]+]](%[[SEVEN]], %[[EMPTY]] : i64, index) +// CHECK: ^[[THEN]](%[[KEPT:.*]]: i64): +// CHECK: %[[ONE:.*]] = arith.constant 1 : i64 +// CHECK: %[[SLOT:.*]] = arith.addi %{{.*}}, %{{.*}} : index +// CHECK: memref.store %[[KEPT]], %[[BUFFER]][%[[SLOT]]] +// CHECK: cf.br ^[[JOIN]](%[[ONE]], %[[SLOT]] : i64, index) +// CHECK: ^[[JOIN]](%[[TOP:.*]]: i64, %[[DEPTH:.*]]: index): +// CHECK: %[[BELOW:.*]] = memref.load %[[BUFFER]][%[[DEPTH]]] +// CHECK: %[[SUM:.*]] = arith.addi %[[BELOW]], %[[TOP]] : i64 +// CHECK: llvm.store %[[SUM]], %{{.*}} : i64, !llvm.ptr<1> +func.func @unequal_join(%flag: i64, %a: memref<1xi64>) { + %0 = forth.stack !forth.stack + %1 = forth.constant %0(7 : i64) : !forth.stack -> !forth.stack + %2 = forth.param_ref %1 %flag : !forth.stack, i64 -> !forth.stack + %output_stack, %cond = forth.pop_flag %2 : !forth.stack -> !forth.stack, i1 + cf.cond_br %cond, ^bb1(%output_stack : !forth.stack), ^bb2(%output_stack : !forth.stack) +^bb1(%3: !forth.stack): + %4 = forth.constant %3(1 : i64) : !forth.stack -> !forth.stack + cf.br ^bb2(%4 : !forth.stack) +^bb2(%5: !forth.stack): + %6 = forth.addi %5 : !forth.stack -> !forth.stack + %7 = forth.param_ref %6 %a : !forth.stack, memref<1xi64> -> !forth.stack + %8 = forth.storei %7 : !forth.stack -> !forth.stack + return +} diff --git a/test/Pipeline/stack-residual.forth b/test/Pipeline/stack-residual.forth new file mode 100644 index 0000000..60145b9 --- /dev/null +++ b/test/Pipeline/stack-residual.forth @@ -0,0 +1,24 @@ +\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --inline --lower-forth-stack --canonicalize | %FileCheck %s + +\ The PICK index `1 1 +` is not a constant while the stack is lowered, so the +\ three cells are stored at indices 1 to 3 of the residual buffer and one load +\ reads index 3 - n. After folding, the load reads index 1, where 10 was +\ stored, so OUT receives 10. + +\! kernel main +\! param OUT i64[1] +10 20 30 1 1 + PICK OUT ! + +\ CHECK-LABEL: func.func @main( +\ CHECK-DAG: %[[INDEX1:.*]] = arith.constant 1 : index +\ CHECK-DAG: %[[INDEX2:.*]] = arith.constant 2 : index +\ CHECK-DAG: %[[INDEX3:.*]] = arith.constant 3 : index +\ CHECK-DAG: %[[TEN:.*]] = arith.constant 10 : i64 +\ CHECK-DAG: %[[TWENTY:.*]] = arith.constant 20 : i64 +\ CHECK-DAG: %[[THIRTY:.*]] = arith.constant 30 : i64 +\ CHECK: %[[BUFFER:.*]] = memref.alloca() : memref<256xi64> +\ CHECK-NEXT: memref.store %[[TEN]], %[[BUFFER]][%[[INDEX1]]] +\ CHECK-NEXT: memref.store %[[TWENTY]], %[[BUFFER]][%[[INDEX2]]] +\ CHECK-NEXT: memref.store %[[THIRTY]], %[[BUFFER]][%[[INDEX3]]] +\ CHECK-NEXT: %[[PICKED:.*]] = memref.load %[[BUFFER]][%[[INDEX1]]] +\ CHECK: llvm.store %[[PICKED]], %{{.*}} : i64, !llvm.ptr<1> From c333345507d150b0cf0ad7c847a43518c89419a2 Mon Sep 17 00:00:00 2001 From: Alex Cameron Date: Mon, 9 Nov 2026 04:55:20 +0000 Subject: [PATCH 5/8] feat(conversion): give every Forth word a stack-word row Stack shuffles, float and bitwise arithmetic, comparisons, conversions, loads and stores of every width, and the GPU index words now lower through the stack-word table. Every kernel the parser emits takes the new path and keeps its cells in registers wherever the depth is known, and a shuffle becomes a reordering of SSA values with no ops at all. The pass checks at initialization that every Forth op that takes a stack has a row, so an op added to the dialect without one fails every run instead of falling back to the memref stack. The new tests reuse the inputs of the ForthToMemRef tests and check the stored values, operand order, element and pointer types, and the block argument types that loops carry. --- include/warpforth/Conversion/Passes.td | 2 + lib/Conversion/ForthStack/CMakeLists.txt | 1 + lib/Conversion/ForthStack/LowerForthStack.cpp | 5 + lib/Conversion/ForthStack/StackWords.cpp | 330 ++++++++++++++++-- lib/Conversion/ForthStack/StackWords.h | 4 + test/Conversion/ForthStack/bitwise.mlir | 52 +++ test/Conversion/ForthStack/comparison.mlir | 67 ++++ test/Conversion/ForthStack/control-flow.mlir | 121 +++++++ test/Conversion/ForthStack/float.mlir | 180 ++++++++++ test/Conversion/ForthStack/gpu-indexing.mlir | 91 +++++ test/Conversion/ForthStack/memory.mlir | 135 +++++++ .../ForthStack/stack-manipulation.mlir | 183 ++++++++++ 12 files changed, 1145 insertions(+), 26 deletions(-) create mode 100644 test/Conversion/ForthStack/bitwise.mlir create mode 100644 test/Conversion/ForthStack/comparison.mlir create mode 100644 test/Conversion/ForthStack/float.mlir create mode 100644 test/Conversion/ForthStack/gpu-indexing.mlir create mode 100644 test/Conversion/ForthStack/memory.mlir create mode 100644 test/Conversion/ForthStack/stack-manipulation.mlir diff --git a/include/warpforth/Conversion/Passes.td b/include/warpforth/Conversion/Passes.td index 0b6d162..ac0ba12 100644 --- a/include/warpforth/Conversion/Passes.td +++ b/include/warpforth/Conversion/Passes.td @@ -52,7 +52,9 @@ def LowerForthStack : Pass<"lower-forth-stack", "mlir::ModuleOp"> { let dependentDialects = ["mlir::arith::ArithDialect", "mlir::cf::ControlFlowDialect", + "mlir::forth::ForthDialect", "mlir::LLVM::LLVMDialect", + "mlir::math::MathDialect", "mlir::memref::MemRefDialect"]; } diff --git a/lib/Conversion/ForthStack/CMakeLists.txt b/lib/Conversion/ForthStack/CMakeLists.txt index e094a9c..0f2692d 100644 --- a/lib/Conversion/ForthStack/CMakeLists.txt +++ b/lib/Conversion/ForthStack/CMakeLists.txt @@ -15,6 +15,7 @@ add_mlir_conversion_library(MLIRForthStackConversion MLIRDialectUtils MLIRFuncDialect MLIRLLVMDialect + MLIRMathDialect MLIRMemRefDialect MLIRNVVMDialect MLIRTransformUtils diff --git a/lib/Conversion/ForthStack/LowerForthStack.cpp b/lib/Conversion/ForthStack/LowerForthStack.cpp index 4bdc92d..2687df4 100644 --- a/lib/Conversion/ForthStack/LowerForthStack.cpp +++ b/lib/Conversion/ForthStack/LowerForthStack.cpp @@ -13,6 +13,7 @@ #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" #include "mlir/Dialect/Func/IR/FuncOps.h" #include "mlir/Dialect/LLVMIR/LLVMDialect.h" // IWYU pragma: keep +#include "mlir/Dialect/Math/IR/Math.h" // IWYU pragma: keep #include "mlir/Dialect/MemRef/IR/MemRef.h" #include "mlir/Dialect/Utils/StaticValueUtils.h" #include "mlir/IR/Builders.h" @@ -487,6 +488,10 @@ Value StackSimulator::indexConstant(int64_t value) { struct LowerForthStackPass : public impl::LowerForthStackBase { + LogicalResult initialize(MLIRContext *context) override { + return stack::verifyStackWordTableCoversDialect(context); + } + void runOnOperation() override { ModuleOp module = getOperation(); if (failed(verifyWordsInlined(module))) diff --git a/lib/Conversion/ForthStack/StackWords.cpp b/lib/Conversion/ForthStack/StackWords.cpp index ce431d6..35ab0f3 100644 --- a/lib/Conversion/ForthStack/StackWords.cpp +++ b/lib/Conversion/ForthStack/StackWords.cpp @@ -9,8 +9,10 @@ #include "mlir/Dialect/Arith/IR/Arith.h" #include "mlir/Dialect/LLVMIR/LLVMDialect.h" #include "mlir/Dialect/LLVMIR/NVVMDialect.h" +#include "mlir/Dialect/Math/IR/Math.h" #include "mlir/Dialect/MemRef/IR/MemRef.h" #include "mlir/IR/BuiltinTypes.h" +#include "mlir/IR/Diagnostics.h" #include "warpforth/Dialect/Forth/ForthDialect.h" #include "llvm/ADT/DenseMap.h" @@ -27,6 +29,8 @@ namespace { // after address arithmetic. constexpr unsigned kGlobalAddressSpace = static_cast(NVVM::kGlobalMemorySpace); +constexpr unsigned kSharedAddressSpace = + static_cast(NVVM::kSharedMemorySpace); /// Element type of a memory access. Cells are i64; a narrower integer is /// sign-extended and a float is carried as the bits of an f64. @@ -76,6 +80,51 @@ Value narrow(OpBuilder &b, Location loc, Value cell, MemType type) { llvm_unreachable("unhandled MemType"); } +/// The loaded memory element as a cell. +Value widen(OpBuilder &b, Location loc, Value element, MemType type) { + switch (type) { + case MemType::I64: + return element; + case MemType::I8: + case MemType::I16: + case MemType::I32: + return b.create(loc, b.getI64Type(), element); + case MemType::F64: + return b.create(loc, b.getI64Type(), element); + case MemType::F16: + case MemType::BF16: + case MemType::F32: { + Value f64 = b.create(loc, b.getF64Type(), element); + return b.create(loc, b.getI64Type(), f64); + } + } + llvm_unreachable("unhandled MemType"); +} + +Value pointerTo(OpBuilder &b, Location loc, Value address, + unsigned addressSpace) { + auto pointerType = LLVM::LLVMPointerType::get(b.getContext(), addressSpace); + return b.create(loc, pointerType, address); +} + +Value toF64(OpBuilder &b, Location loc, Value cell) { + return b.create(loc, b.getF64Type(), cell); +} + +Value toCell(OpBuilder &b, Location loc, Value f64) { + return b.create(loc, b.getI64Type(), f64); +} + +/// A Forth flag: true is -1, false is 0. +Value flagCell(OpBuilder &b, Location loc, Value bit) { + return b.create(loc, b.getI64Type(), bit); +} + +Value gpuIndex(OpBuilder &b, Location loc, StringRef intrinsic) { + return b.create(loc, b.getIndexType(), + b.getStringAttr(intrinsic)); +} + struct StackWordRow { TypeID op; StackWord word; @@ -95,6 +144,17 @@ StackWordRow row(StackEffect effect, void (*lower)(OpT, WordContext &)) { }}}; } +/// A word that only reorders cells. It pushes popped(i) for each i in +/// `order`, deepest first. +StackWord shuffle(unsigned pops, std::initializer_list order) { + SmallVector pushed(order); + auto pushes = static_cast(pushed.size()); + return {{pops, pushes}, [pushed](Operation *, WordContext &ctx) { + for (unsigned i : pushed) + ctx.push(ctx.popped(i)); + }}; +} + /// ( a b -- a op b ) template StackWord intBinary() { return {{2, 1}, [](Operation *op, WordContext &ctx) { @@ -103,21 +163,86 @@ template StackWord intBinary() { }}; } +/// ( a b -- a op b ) on the f64 bits of each cell. +template StackWord floatBinary() { + return {{2, 1}, [](Operation *op, WordContext &ctx) { + OpBuilder &b = ctx.builder(); + Location loc = op->getLoc(); + Value lhs = toF64(b, loc, ctx.popped(1)); + Value rhs = toF64(b, loc, ctx.popped(0)); + ctx.push(toCell(b, loc, b.create(loc, lhs, rhs))); + }}; +} + +/// ( x -- op x ) on the f64 bits of the cell. +template StackWord floatUnary() { + return {{1, 1}, [](Operation *op, WordContext &ctx) { + OpBuilder &b = ctx.builder(); + Location loc = op->getLoc(); + Value x = toF64(b, loc, ctx.popped(0)); + ctx.push(toCell(b, loc, b.create(loc, x))); + }}; +} + +/// ( a b -- flag ) +StackWord intCompare(arith::CmpIPredicate predicate) { + return {{2, 1}, [predicate](Operation *op, WordContext &ctx) { + OpBuilder &b = ctx.builder(); + Location loc = op->getLoc(); + Value bit = b.create(loc, predicate, ctx.popped(1), + ctx.popped(0)); + ctx.push(flagCell(b, loc, bit)); + }}; +} + +/// ( a b -- flag ) on the f64 bits of each cell. +StackWord floatCompare(arith::CmpFPredicate predicate) { + return {{2, 1}, [predicate](Operation *op, WordContext &ctx) { + OpBuilder &b = ctx.builder(); + Location loc = op->getLoc(); + Value lhs = toF64(b, loc, ctx.popped(1)); + Value rhs = toF64(b, loc, ctx.popped(0)); + Value bit = b.create(loc, predicate, lhs, rhs); + ctx.push(flagCell(b, loc, bit)); + }}; +} + +/// ( addr -- x ) +StackWord load(MemType type, unsigned addressSpace) { + return {{1, 1}, [type, addressSpace](Operation *op, WordContext &ctx) { + OpBuilder &b = ctx.builder(); + Location loc = op->getLoc(); + Value pointer = pointerTo(b, loc, ctx.popped(0), addressSpace); + Value element = b.create( + loc, memElementType(b.getContext(), type), pointer); + ctx.push(widen(b, loc, element, type)); + }}; +} + /// ( x addr -- ) StackWord store(MemType type, unsigned addressSpace) { return {{2, 0}, [type, addressSpace](Operation *op, WordContext &ctx) { OpBuilder &b = ctx.builder(); Location loc = op->getLoc(); - auto pointerType = - LLVM::LLVMPointerType::get(b.getContext(), addressSpace); - Value pointer = - b.create(loc, pointerType, ctx.popped(0)); + Value pointer = pointerTo(b, loc, ctx.popped(0), addressSpace); b.create(loc, narrow(b, loc, ctx.popped(1), type), pointer); }}; } +/// ( -- x ), where `intrinsic` names a GPU index such as "tid-x". +StackWord gpuIndexWord(StringRef intrinsic) { + return {{0, 1}, [intrinsic](Operation *op, WordContext &ctx) { + OpBuilder &b = ctx.builder(); + Value index = gpuIndex(b, op->getLoc(), intrinsic); + ctx.push(b.create(op->getLoc(), b.getI64Type(), + index)); + }}; +} + ArrayRef stackWordRows() { + using arith::CmpFPredicate; + using arith::CmpIPredicate; static const StackWordRow rows[] = { row({0, 1}, [](forth::ConstantOp op, WordContext &ctx) { @@ -126,8 +251,7 @@ ArrayRef stackWordRows() { if (isa(value)) { Value f64 = b.create( op.getLoc(), b.getF64Type(), value); - ctx.push(b.create( - op.getLoc(), b.getI64Type(), f64)); + ctx.push(toCell(b, op.getLoc(), f64)); return; } ctx.push(b.create( @@ -147,12 +271,19 @@ ArrayRef stackWordRows() { return; } if (parameter.getType().isF64()) { - ctx.push( - b.create(loc, b.getI64Type(), parameter)); + ctx.push(toCell(b, loc, parameter)); return; } ctx.push(parameter); }), + + row(shuffle(1, {0, 0})), // ( a -- a a ) + row(shuffle(1, {})), // ( a -- ) + row(shuffle(2, {0, 1})), // ( a b -- b a ) + row(shuffle(2, {1, 0, 1})), // ( a b -- a b a ) + row(shuffle(3, {1, 0, 2})), // ( a b c -- b c a ) + row(shuffle(2, {0})), // ( a b -- b ) + row(shuffle(2, {0, 1, 0})), // ( a b -- b a b ) row({1, 1}, [](forth::PickOp, WordContext &ctx) { ctx.push(ctx.peek(ctx.popped(0))); @@ -161,6 +292,136 @@ ArrayRef stackWordRows() { [](forth::RollOp, WordContext &ctx) { ctx.rollToTop(ctx.popped(0)); }), + + row(intBinary()), + row(intBinary()), + row(intBinary()), + row(intBinary()), + row(intBinary()), + row(intBinary()), + row(intBinary()), + row(intBinary()), + row(intBinary()), + row(intBinary()), + row({1, 1}, + [](forth::NotOp op, WordContext &ctx) { + OpBuilder &b = ctx.builder(); + Value allOnes = b.create( + op.getLoc(), -1, 64); + ctx.push(b.create( + op.getLoc(), ctx.popped(0), allOnes)); + }), + + row(floatBinary()), + row(floatBinary()), + row(floatBinary()), + row(floatBinary()), + row(floatBinary()), + row(floatBinary()), + row(floatUnary()), + row(floatUnary()), + row(floatUnary()), + row(floatUnary()), + row(floatUnary()), + + row(intCompare(CmpIPredicate::eq)), + row(intCompare(CmpIPredicate::slt)), + row(intCompare(CmpIPredicate::sgt)), + row(intCompare(CmpIPredicate::ne)), + row(intCompare(CmpIPredicate::sle)), + row(intCompare(CmpIPredicate::sge)), + row(floatCompare(CmpFPredicate::OEQ)), + row(floatCompare(CmpFPredicate::OLT)), + row(floatCompare(CmpFPredicate::OGT)), + row(floatCompare(CmpFPredicate::ONE)), + row(floatCompare(CmpFPredicate::OLE)), + row(floatCompare(CmpFPredicate::OGE)), + row({1, 1}, + [](forth::ZeroEqOp op, WordContext &ctx) { + OpBuilder &b = ctx.builder(); + Value zero = b.create( + op.getLoc(), 0, 64); + Value bit = b.create( + op.getLoc(), CmpIPredicate::eq, ctx.popped(0), + zero); + ctx.push(flagCell(b, op.getLoc(), bit)); + }), + + row({1, 1}, + [](forth::IToFOp op, WordContext &ctx) { + OpBuilder &b = ctx.builder(); + Value f64 = b.create( + op.getLoc(), b.getF64Type(), ctx.popped(0)); + ctx.push(toCell(b, op.getLoc(), f64)); + }), + row({1, 1}, + [](forth::FToIOp op, WordContext &ctx) { + OpBuilder &b = ctx.builder(); + Value f64 = toF64(b, op.getLoc(), ctx.popped(0)); + ctx.push(b.create( + op.getLoc(), b.getI64Type(), f64)); + }), + + row(load(MemType::I64, kGlobalAddressSpace)), + row(store(MemType::I64, kGlobalAddressSpace)), + row(load(MemType::F64, kGlobalAddressSpace)), + row(store(MemType::F64, kGlobalAddressSpace)), + row(load(MemType::I8, kGlobalAddressSpace)), + row(store(MemType::I8, kGlobalAddressSpace)), + row(load(MemType::I16, kGlobalAddressSpace)), + row(store(MemType::I16, kGlobalAddressSpace)), + row(load(MemType::I32, kGlobalAddressSpace)), + row(store(MemType::I32, kGlobalAddressSpace)), + row(load(MemType::F16, kGlobalAddressSpace)), + row(store(MemType::F16, kGlobalAddressSpace)), + row(load(MemType::BF16, kGlobalAddressSpace)), + row(store(MemType::BF16, kGlobalAddressSpace)), + row(load(MemType::F32, kGlobalAddressSpace)), + row(store(MemType::F32, kGlobalAddressSpace)), + row(load(MemType::I64, kSharedAddressSpace)), + row(store(MemType::I64, kSharedAddressSpace)), + row(load(MemType::F64, kSharedAddressSpace)), + row(store(MemType::F64, kSharedAddressSpace)), + row(load(MemType::I8, kSharedAddressSpace)), + row(store(MemType::I8, kSharedAddressSpace)), + row(load(MemType::I16, kSharedAddressSpace)), + row(store(MemType::I16, kSharedAddressSpace)), + row(load(MemType::I32, kSharedAddressSpace)), + row(store(MemType::I32, kSharedAddressSpace)), + row(load(MemType::F16, kSharedAddressSpace)), + row(store(MemType::F16, kSharedAddressSpace)), + row(load(MemType::BF16, kSharedAddressSpace)), + row(store(MemType::BF16, kSharedAddressSpace)), + row(load(MemType::F32, kSharedAddressSpace)), + row(store(MemType::F32, kSharedAddressSpace)), + + row(gpuIndexWord("tid-x")), + row(gpuIndexWord("tid-y")), + row(gpuIndexWord("tid-z")), + row(gpuIndexWord("bid-x")), + row(gpuIndexWord("bid-y")), + row(gpuIndexWord("bid-z")), + row(gpuIndexWord("bdim-x")), + row(gpuIndexWord("bdim-y")), + row(gpuIndexWord("bdim-z")), + row(gpuIndexWord("gdim-x")), + row(gpuIndexWord("gdim-y")), + row(gpuIndexWord("gdim-z")), + row({0, 1}, + [](forth::GlobalIdOp op, WordContext &ctx) { + OpBuilder &b = ctx.builder(); + Location loc = op.getLoc(); + Value blockId = gpuIndex(b, loc, "bid-x"); + Value blockDim = gpuIndex(b, loc, "bdim-x"); + Value threadId = gpuIndex(b, loc, "tid-x"); + Value product = b.create( + loc, blockId, blockDim); + Value globalId = b.create( + loc, product, threadId); + ctx.push(b.create( + loc, b.getI64Type(), globalId)); + }), + row({0, 1}, [](forth::PushValueOp op, WordContext &ctx) { ctx.push(op.getValue()); @@ -169,27 +430,20 @@ ArrayRef stackWordRows() { [](forth::PopOp, WordContext &ctx) { ctx.replaceValueResult(ctx.popped(0)); }), - row( - {1, 0}, - [](forth::PopFlagOp op, WordContext &ctx) { - OpBuilder &b = ctx.builder(); - Value zero = b.create(op.getLoc(), 0, 64); - ctx.replaceValueResult(b.create( - op.getLoc(), arith::CmpIPredicate::ne, ctx.popped(0), zero)); - }), - row(intBinary()), - row(intBinary()), - row(intBinary()), - row(intBinary()), - row(intBinary()), - row(store(MemType::I64, kGlobalAddressSpace)), + row({1, 0}, + [](forth::PopFlagOp op, WordContext &ctx) { + OpBuilder &b = ctx.builder(); + Value zero = b.create( + op.getLoc(), 0, 64); + ctx.replaceValueResult(b.create( + op.getLoc(), CmpIPredicate::ne, ctx.popped(0), + zero)); + }), }; return rows; } -} // namespace - -const StackWord *lookupStackWord(Operation *op) { +const DenseMap &stackWords() { static const DenseMap words = [] { DenseMap words; for (const StackWordRow &row : stackWordRows()) { @@ -199,7 +453,31 @@ const StackWord *lookupStackWord(Operation *op) { } return words; }(); - return words.lookup(op->getName().getTypeID()); + return words; +} + +} // namespace + +const StackWord *lookupStackWord(Operation *op) { + return stackWords().lookup(op->getName().getTypeID()); +} + +LogicalResult verifyStackWordTableCoversDialect(MLIRContext *context) { + LogicalResult result = success(); + for (RegisteredOperationName name : context->getRegisteredOperationsByDialect( + forth::ForthDialect::getDialectNamespace())) { + // The only Forth ops without a !forth.stack operand. + if (name.getTypeID() == TypeID::get() || + name.getTypeID() == TypeID::get() || + name.getTypeID() == TypeID::get()) + continue; + if (stackWords().contains(name.getTypeID())) + continue; + result = emitError(UnknownLoc::get(context)) + << "'" << name.getStringRef() + << "' takes a !forth.stack but has no row in the stack-word table"; + } + return result; } } // namespace stack diff --git a/lib/Conversion/ForthStack/StackWords.h b/lib/Conversion/ForthStack/StackWords.h index 0d4fa53..debcfbc 100644 --- a/lib/Conversion/ForthStack/StackWords.h +++ b/lib/Conversion/ForthStack/StackWords.h @@ -65,6 +65,10 @@ struct StackWord { /// The row for `op`, or null when the table has none. const StackWord *lookupStackWord(Operation *op); +/// Fails, with an error for each one, when a Forth op that takes a +/// !forth.stack has no row. The Forth dialect must be loaded. +LogicalResult verifyStackWordTableCoversDialect(MLIRContext *context); + } // namespace stack } // namespace warpforth } // namespace mlir diff --git a/test/Conversion/ForthStack/bitwise.mlir b/test/Conversion/ForthStack/bitwise.mlir new file mode 100644 index 0000000..6443074 --- /dev/null +++ b/test/Conversion/ForthStack/bitwise.mlir @@ -0,0 +1,52 @@ +// RUN: %warpforth-opt --lower-forth-stack %s | %FileCheck %s + +// `A B op OUT !` for each binary bitwise word: the deeper cell is the left +// operand, and RSHIFT is a logical shift. `A NOT` flips every bit of A. +// CHECK-LABEL: func.func @bitwise( +// CHECK-SAME: %[[A:[^:]*]]: i64, %[[B:[^:]*]]: i64 +// CHECK: %[[AND:.*]] = arith.andi %[[A]], %[[B]] : i64 +// CHECK: llvm.store %[[AND]], +// CHECK: %[[OR:.*]] = arith.ori %[[A]], %[[B]] : i64 +// CHECK: llvm.store %[[OR]], +// CHECK: %[[XOR:.*]] = arith.xori %[[A]], %[[B]] : i64 +// CHECK: llvm.store %[[XOR]], +// CHECK: %[[SHL:.*]] = arith.shli %[[A]], %[[B]] : i64 +// CHECK: llvm.store %[[SHL]], +// CHECK: %[[SHR:.*]] = arith.shrui %[[A]], %[[B]] : i64 +// CHECK: llvm.store %[[SHR]], +// CHECK: %[[ONES:.*]] = arith.constant -1 : i64 +// CHECK: %[[NOT:.*]] = arith.xori %[[A]], %[[ONES]] : i64 +// CHECK: llvm.store %[[NOT]], +func.func @bitwise(%a: i64, %b: i64, %out: memref<1xi64>) { + %s0 = forth.stack !forth.stack + %s1 = forth.param_ref %s0 %a : !forth.stack, i64 -> !forth.stack + %s2 = forth.param_ref %s1 %b : !forth.stack, i64 -> !forth.stack + %s3 = forth.and %s2 : !forth.stack -> !forth.stack + %s4 = forth.param_ref %s3 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s5 = forth.storei %s4 : !forth.stack -> !forth.stack + %s6 = forth.param_ref %s5 %a : !forth.stack, i64 -> !forth.stack + %s7 = forth.param_ref %s6 %b : !forth.stack, i64 -> !forth.stack + %s8 = forth.or %s7 : !forth.stack -> !forth.stack + %s9 = forth.param_ref %s8 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s10 = forth.storei %s9 : !forth.stack -> !forth.stack + %s11 = forth.param_ref %s10 %a : !forth.stack, i64 -> !forth.stack + %s12 = forth.param_ref %s11 %b : !forth.stack, i64 -> !forth.stack + %s13 = forth.xor %s12 : !forth.stack -> !forth.stack + %s14 = forth.param_ref %s13 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s15 = forth.storei %s14 : !forth.stack -> !forth.stack + %s16 = forth.param_ref %s15 %a : !forth.stack, i64 -> !forth.stack + %s17 = forth.param_ref %s16 %b : !forth.stack, i64 -> !forth.stack + %s18 = forth.lshift %s17 : !forth.stack -> !forth.stack + %s19 = forth.param_ref %s18 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s20 = forth.storei %s19 : !forth.stack -> !forth.stack + %s21 = forth.param_ref %s20 %a : !forth.stack, i64 -> !forth.stack + %s22 = forth.param_ref %s21 %b : !forth.stack, i64 -> !forth.stack + %s23 = forth.rshift %s22 : !forth.stack -> !forth.stack + %s24 = forth.param_ref %s23 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s25 = forth.storei %s24 : !forth.stack -> !forth.stack + %s26 = forth.param_ref %s25 %a : !forth.stack, i64 -> !forth.stack + %s27 = forth.not %s26 : !forth.stack -> !forth.stack + %s28 = forth.param_ref %s27 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s29 = forth.storei %s28 : !forth.stack -> !forth.stack + return +} diff --git a/test/Conversion/ForthStack/comparison.mlir b/test/Conversion/ForthStack/comparison.mlir new file mode 100644 index 0000000..12d6b35 --- /dev/null +++ b/test/Conversion/ForthStack/comparison.mlir @@ -0,0 +1,67 @@ +// RUN: %warpforth-opt --lower-forth-stack %s | %FileCheck %s + +// `A B op OUT !` for each integer comparison. The deeper cell is the left +// operand, and the flag is the sign-extended i1, so true is -1. +// CHECK-LABEL: func.func @int_comparisons( +// CHECK-SAME: %[[A:[^:]*]]: i64, %[[B:[^:]*]]: i64 +// CHECK: %[[EQ:.*]] = arith.cmpi eq, %[[A]], %[[B]] : i64 +// CHECK: %[[EQ_FLAG:.*]] = arith.extsi %[[EQ]] : i1 to i64 +// CHECK: llvm.store %[[EQ_FLAG]], +// CHECK: %[[LT:.*]] = arith.cmpi slt, %[[A]], %[[B]] : i64 +// CHECK: %[[LT_FLAG:.*]] = arith.extsi %[[LT]] : i1 to i64 +// CHECK: llvm.store %[[LT_FLAG]], +// CHECK: %[[GT:.*]] = arith.cmpi sgt, %[[A]], %[[B]] : i64 +// CHECK: %[[GT_FLAG:.*]] = arith.extsi %[[GT]] : i1 to i64 +// CHECK: llvm.store %[[GT_FLAG]], +// CHECK: %[[NE:.*]] = arith.cmpi ne, %[[A]], %[[B]] : i64 +// CHECK: %[[NE_FLAG:.*]] = arith.extsi %[[NE]] : i1 to i64 +// CHECK: llvm.store %[[NE_FLAG]], +// CHECK: %[[LE:.*]] = arith.cmpi sle, %[[A]], %[[B]] : i64 +// CHECK: %[[LE_FLAG:.*]] = arith.extsi %[[LE]] : i1 to i64 +// CHECK: llvm.store %[[LE_FLAG]], +// CHECK: %[[GE:.*]] = arith.cmpi sge, %[[A]], %[[B]] : i64 +// CHECK: %[[GE_FLAG:.*]] = arith.extsi %[[GE]] : i1 to i64 +// CHECK: llvm.store %[[GE_FLAG]], +// `A 0= OUT !` compares A with zero. +// CHECK: %[[ZERO:.*]] = arith.constant 0 : i64 +// CHECK: %[[IS_ZERO:.*]] = arith.cmpi eq, %[[A]], %[[ZERO]] : i64 +// CHECK: %[[ZERO_FLAG:.*]] = arith.extsi %[[IS_ZERO]] : i1 to i64 +// CHECK: llvm.store %[[ZERO_FLAG]], +func.func @int_comparisons(%a: i64, %b: i64, %out: memref<1xi64>) { + %s0 = forth.stack !forth.stack + %s1 = forth.param_ref %s0 %a : !forth.stack, i64 -> !forth.stack + %s2 = forth.param_ref %s1 %b : !forth.stack, i64 -> !forth.stack + %s3 = forth.eqi %s2 : !forth.stack -> !forth.stack + %s4 = forth.param_ref %s3 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s5 = forth.storei %s4 : !forth.stack -> !forth.stack + %s6 = forth.param_ref %s5 %a : !forth.stack, i64 -> !forth.stack + %s7 = forth.param_ref %s6 %b : !forth.stack, i64 -> !forth.stack + %s8 = forth.lti %s7 : !forth.stack -> !forth.stack + %s9 = forth.param_ref %s8 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s10 = forth.storei %s9 : !forth.stack -> !forth.stack + %s11 = forth.param_ref %s10 %a : !forth.stack, i64 -> !forth.stack + %s12 = forth.param_ref %s11 %b : !forth.stack, i64 -> !forth.stack + %s13 = forth.gti %s12 : !forth.stack -> !forth.stack + %s14 = forth.param_ref %s13 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s15 = forth.storei %s14 : !forth.stack -> !forth.stack + %s16 = forth.param_ref %s15 %a : !forth.stack, i64 -> !forth.stack + %s17 = forth.param_ref %s16 %b : !forth.stack, i64 -> !forth.stack + %s18 = forth.nei %s17 : !forth.stack -> !forth.stack + %s19 = forth.param_ref %s18 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s20 = forth.storei %s19 : !forth.stack -> !forth.stack + %s21 = forth.param_ref %s20 %a : !forth.stack, i64 -> !forth.stack + %s22 = forth.param_ref %s21 %b : !forth.stack, i64 -> !forth.stack + %s23 = forth.lei %s22 : !forth.stack -> !forth.stack + %s24 = forth.param_ref %s23 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s25 = forth.storei %s24 : !forth.stack -> !forth.stack + %s26 = forth.param_ref %s25 %a : !forth.stack, i64 -> !forth.stack + %s27 = forth.param_ref %s26 %b : !forth.stack, i64 -> !forth.stack + %s28 = forth.gei %s27 : !forth.stack -> !forth.stack + %s29 = forth.param_ref %s28 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s30 = forth.storei %s29 : !forth.stack -> !forth.stack + %s31 = forth.param_ref %s30 %a : !forth.stack, i64 -> !forth.stack + %s32 = forth.zero_eq %s31 : !forth.stack -> !forth.stack + %s33 = forth.param_ref %s32 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s34 = forth.storei %s33 : !forth.stack -> !forth.stack + return +} diff --git a/test/Conversion/ForthStack/control-flow.mlir b/test/Conversion/ForthStack/control-flow.mlir index 8223336..910ad22 100644 --- a/test/Conversion/ForthStack/control-flow.mlir +++ b/test/Conversion/ForthStack/control-flow.mlir @@ -86,3 +86,124 @@ func.func @do_loop_sum(%out: memref<1xi64>) { %16 = forth.storei %15 : !forth.stack -> !forth.stack return } + +// `10 BEGIN 1 - DUP 0= UNTIL OUT !`: DUP copies a register, so the loop +// carries one i64 and the flag reads the decremented cell directly. +// CHECK-LABEL: func.func @begin_until( +// CHECK: %[[TEN:.*]] = arith.constant 10 : i64 +// CHECK: cf.br ^[[LOOP:bb[0-9]+]](%[[TEN]] : i64) +// CHECK: ^[[LOOP]](%[[N:.*]]: i64): +// CHECK: %[[NEXT:.*]] = arith.subi %[[N]], %{{.*}} : i64 +// CHECK: %[[IS_ZERO:.*]] = arith.cmpi eq, %[[NEXT]], %{{.*}} : i64 +// CHECK: %[[FLAG:.*]] = arith.extsi %[[IS_ZERO]] : i1 to i64 +// CHECK: %[[DONE:.*]] = arith.cmpi ne, %[[FLAG]], %{{.*}} : i64 +// CHECK: cf.cond_br %[[DONE]], ^[[EXIT:bb[0-9]+]](%[[NEXT]] : i64), ^[[LOOP]](%[[NEXT]] : i64) +// CHECK: ^[[EXIT]](%[[LAST:.*]]: i64): +// CHECK: llvm.store %[[LAST]], %{{.*}} : i64, !llvm.ptr<1> +func.func @begin_until(%out: memref<1xi64>) { + %0 = forth.stack !forth.stack + %1 = forth.constant %0(10 : i64) : !forth.stack -> !forth.stack + cf.br ^bb1(%1 : !forth.stack) +^bb1(%2: !forth.stack): + %3 = forth.constant %2(1 : i64) : !forth.stack -> !forth.stack + %4 = forth.subi %3 : !forth.stack -> !forth.stack + %5 = forth.dup %4 : !forth.stack -> !forth.stack + %6 = forth.zero_eq %5 : !forth.stack -> !forth.stack + %output_stack, %flag = forth.pop_flag %6 : !forth.stack -> !forth.stack, i1 + cf.cond_br %flag, ^bb2(%output_stack : !forth.stack), ^bb1(%output_stack : !forth.stack) +^bb2(%7: !forth.stack): + %8 = forth.param_ref %7 %out : !forth.stack, memref<1xi64> -> !forth.stack + %9 = forth.storei %8 : !forth.stack -> !forth.stack + return +} + +// `10 BEGIN DUP 0 > WHILE 1 - REPEAT OUT !`: the test, the body, and the exit +// each take the one cell as an i64 argument. +// CHECK-LABEL: func.func @begin_while_repeat( +// CHECK: cf.br ^[[TEST:bb[0-9]+]](%{{.*}} : i64) +// CHECK: ^[[TEST]](%[[N:.*]]: i64): +// CHECK: arith.cmpi sgt, %[[N]], %{{.*}} : i64 +// CHECK: cf.cond_br %{{.*}}, ^[[BODY:bb[0-9]+]](%[[N]] : i64), ^[[EXIT:bb[0-9]+]](%[[N]] : i64) +// CHECK: ^[[BODY]](%[[M:.*]]: i64): +// CHECK: %[[DECREMENTED:.*]] = arith.subi %[[M]], %{{.*}} : i64 +// CHECK: cf.br ^[[TEST]](%[[DECREMENTED]] : i64) +// CHECK: ^[[EXIT]](%[[LAST:.*]]: i64): +// CHECK: llvm.store %[[LAST]], %{{.*}} : i64, !llvm.ptr<1> +func.func @begin_while_repeat(%out: memref<1xi64>) { + %0 = forth.stack !forth.stack + %1 = forth.constant %0(10 : i64) : !forth.stack -> !forth.stack + cf.br ^bb1(%1 : !forth.stack) +^bb1(%2: !forth.stack): + %3 = forth.dup %2 : !forth.stack -> !forth.stack + %4 = forth.constant %3(0 : i64) : !forth.stack -> !forth.stack + %5 = forth.gti %4 : !forth.stack -> !forth.stack + %output_stack, %flag = forth.pop_flag %5 : !forth.stack -> !forth.stack, i1 + cf.cond_br %flag, ^bb2(%output_stack : !forth.stack), ^bb3(%output_stack : !forth.stack) +^bb2(%6: !forth.stack): + %7 = forth.constant %6(1 : i64) : !forth.stack -> !forth.stack + %8 = forth.subi %7 : !forth.stack -> !forth.stack + cf.br ^bb1(%8 : !forth.stack) +^bb3(%9: !forth.stack): + %10 = forth.param_ref %9 %out : !forth.stack, memref<1xi64> -> !forth.stack + %11 = forth.storei %10 : !forth.stack -> !forth.stack + return +} + +// `0 10 0 DO I + I 3 = IF LEAVE THEN LOOP OUT !`: LEAVE and the loop's own +// exit both reach the store with the running sum as one i64. +// CHECK-LABEL: func.func @leave( +// CHECK: cf.br ^[[BODY:bb[0-9]+]](%{{.*}} : i64) +// CHECK: ^[[BODY]](%[[ACC:.*]]: i64): +// CHECK: %[[SUM:.*]] = arith.addi %[[ACC]], %{{.*}} : i64 +// CHECK: cf.cond_br %{{.*}}, ^[[LEAVE:bb[0-9]+]](%[[SUM]] : i64), ^[[NEXT:bb[0-9]+]](%[[SUM]] : i64) +// CHECK: ^[[EXIT:bb[0-9]+]](%[[TOTAL:.*]]: i64): +// CHECK: llvm.store %[[TOTAL]], %{{.*}} : i64, !llvm.ptr<1> +// CHECK: ^[[LEAVE]](%[[LEFT:.*]]: i64): +// CHECK-NEXT: cf.br ^[[EXIT]](%[[LEFT]] : i64) +// CHECK: ^[[NEXT]](%[[CARRIED:.*]]: i64): +// CHECK: cf.cond_br %{{.*}}, ^[[EXIT]](%[[CARRIED]] : i64), ^[[BODY]](%[[CARRIED]] : i64) +func.func @leave(%out: memref<1xi64>) { + %0 = forth.stack !forth.stack + %1 = forth.constant %0(0 : i64) : !forth.stack -> !forth.stack + %2 = forth.constant %1(10 : i64) : !forth.stack -> !forth.stack + %3 = forth.constant %2(0 : i64) : !forth.stack -> !forth.stack + %output_stack, %value = forth.pop %3 : !forth.stack -> !forth.stack, i64 + %output_stack_0, %value_1 = forth.pop %output_stack : !forth.stack -> !forth.stack, i64 + %alloca = memref.alloca() : memref<1xi64> + %c0 = arith.constant 0 : index + memref.store %value, %alloca[%c0] : memref<1xi64> + cf.br ^bb1(%output_stack_0 : !forth.stack) +^bb1(%4: !forth.stack): + %c0_2 = arith.constant 0 : index + %5 = memref.load %alloca[%c0_2] : memref<1xi64> + %6 = forth.push_value %4, %5 : !forth.stack, i64 -> !forth.stack + %7 = forth.addi %6 : !forth.stack -> !forth.stack + %c0_3 = arith.constant 0 : index + %8 = memref.load %alloca[%c0_3] : memref<1xi64> + %9 = forth.push_value %7, %8 : !forth.stack, i64 -> !forth.stack + %10 = forth.constant %9(3 : i64) : !forth.stack -> !forth.stack + %11 = forth.eqi %10 : !forth.stack -> !forth.stack + %output_stack_4, %flag = forth.pop_flag %11 : !forth.stack -> !forth.stack, i1 + cf.cond_br %flag, ^bb3(%output_stack_4 : !forth.stack), ^bb4(%output_stack_4 : !forth.stack) +^bb2(%12: !forth.stack): + %13 = forth.param_ref %12 %out : !forth.stack, memref<1xi64> -> !forth.stack + %14 = forth.storei %13 : !forth.stack -> !forth.stack + return +^bb3(%15: !forth.stack): + cf.br ^bb2(%15 : !forth.stack) +^bb4(%16: !forth.stack): + %c1_i64 = arith.constant 1 : i64 + %c0_5 = arith.constant 0 : index + %17 = memref.load %alloca[%c0_5] : memref<1xi64> + %18 = arith.addi %17, %c1_i64 : i64 + memref.store %18, %alloca[%c0_5] : memref<1xi64> + %19 = arith.subi %17, %value_1 : i64 + %20 = arith.subi %18, %value_1 : i64 + %21 = arith.xori %19, %20 : i64 + %c0_i64 = arith.constant 0 : i64 + %22 = arith.cmpi slt, %21, %c0_i64 : i64 + cf.cond_br %22, ^bb2(%16 : !forth.stack), ^bb1(%16 : !forth.stack) +^bb5: + %23 = forth.stack !forth.stack + cf.br ^bb4(%23 : !forth.stack) +} diff --git a/test/Conversion/ForthStack/float.mlir b/test/Conversion/ForthStack/float.mlir new file mode 100644 index 0000000..2995d62 --- /dev/null +++ b/test/Conversion/ForthStack/float.mlir @@ -0,0 +1,180 @@ +// RUN: %warpforth-opt --lower-forth-stack --canonicalize %s | %FileCheck %s + +// A float cell holds f64 bits. Every float word bitcasts its cells to f64 and +// its result back to i64, so after canonicalization the round trips are gone +// and each word applies to the f64 parameters directly. + +// `X Y op OUT !`: the deeper cell is the left operand. +// CHECK-LABEL: func.func @float_arithmetic( +// CHECK-SAME: %[[X:[^:]*]]: f64, %[[Y:[^:]*]]: f64 +// CHECK: %[[SUM:.*]] = arith.addf %[[X]], %[[Y]] : f64 +// CHECK: %[[SUM_BITS:.*]] = arith.bitcast %[[SUM]] : f64 to i64 +// CHECK: llvm.store %[[SUM_BITS]], +// CHECK: %[[DIFF:.*]] = arith.subf %[[X]], %[[Y]] : f64 +// CHECK: %[[DIFF_BITS:.*]] = arith.bitcast %[[DIFF]] : f64 to i64 +// CHECK: llvm.store %[[DIFF_BITS]], +// CHECK: %[[PROD:.*]] = arith.mulf %[[X]], %[[Y]] : f64 +// CHECK: %[[PROD_BITS:.*]] = arith.bitcast %[[PROD]] : f64 to i64 +// CHECK: llvm.store %[[PROD_BITS]], +// CHECK: %[[QUOT:.*]] = arith.divf %[[X]], %[[Y]] : f64 +// CHECK: %[[QUOT_BITS:.*]] = arith.bitcast %[[QUOT]] : f64 to i64 +// CHECK: llvm.store %[[QUOT_BITS]], +// CHECK: %[[MAX:.*]] = arith.maximumf %[[X]], %[[Y]] : f64 +// CHECK: %[[MAX_BITS:.*]] = arith.bitcast %[[MAX]] : f64 to i64 +// CHECK: llvm.store %[[MAX_BITS]], +// CHECK: %[[MIN:.*]] = arith.minimumf %[[X]], %[[Y]] : f64 +// CHECK: %[[MIN_BITS:.*]] = arith.bitcast %[[MIN]] : f64 to i64 +// CHECK: llvm.store %[[MIN_BITS]], +func.func @float_arithmetic(%x: f64, %y: f64, %out: memref<1xi64>) { + %s0 = forth.stack !forth.stack + %s1 = forth.param_ref %s0 %x : !forth.stack, f64 -> !forth.stack + %s2 = forth.param_ref %s1 %y : !forth.stack, f64 -> !forth.stack + %s3 = forth.addf %s2 : !forth.stack -> !forth.stack + %s4 = forth.param_ref %s3 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s5 = forth.storei %s4 : !forth.stack -> !forth.stack + %s6 = forth.param_ref %s5 %x : !forth.stack, f64 -> !forth.stack + %s7 = forth.param_ref %s6 %y : !forth.stack, f64 -> !forth.stack + %s8 = forth.subf %s7 : !forth.stack -> !forth.stack + %s9 = forth.param_ref %s8 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s10 = forth.storei %s9 : !forth.stack -> !forth.stack + %s11 = forth.param_ref %s10 %x : !forth.stack, f64 -> !forth.stack + %s12 = forth.param_ref %s11 %y : !forth.stack, f64 -> !forth.stack + %s13 = forth.mulf %s12 : !forth.stack -> !forth.stack + %s14 = forth.param_ref %s13 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s15 = forth.storei %s14 : !forth.stack -> !forth.stack + %s16 = forth.param_ref %s15 %x : !forth.stack, f64 -> !forth.stack + %s17 = forth.param_ref %s16 %y : !forth.stack, f64 -> !forth.stack + %s18 = forth.divf %s17 : !forth.stack -> !forth.stack + %s19 = forth.param_ref %s18 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s20 = forth.storei %s19 : !forth.stack -> !forth.stack + %s21 = forth.param_ref %s20 %x : !forth.stack, f64 -> !forth.stack + %s22 = forth.param_ref %s21 %y : !forth.stack, f64 -> !forth.stack + %s23 = forth.maxf %s22 : !forth.stack -> !forth.stack + %s24 = forth.param_ref %s23 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s25 = forth.storei %s24 : !forth.stack -> !forth.stack + %s26 = forth.param_ref %s25 %x : !forth.stack, f64 -> !forth.stack + %s27 = forth.param_ref %s26 %y : !forth.stack, f64 -> !forth.stack + %s28 = forth.minf %s27 : !forth.stack -> !forth.stack + %s29 = forth.param_ref %s28 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s30 = forth.storei %s29 : !forth.stack -> !forth.stack + return +} + +// CHECK-LABEL: func.func @float_math( +// CHECK-SAME: %[[X:[^:]*]]: f64 +// CHECK: %[[EXP:.*]] = math.exp %[[X]] : f64 +// CHECK: %[[EXP_BITS:.*]] = arith.bitcast %[[EXP]] : f64 to i64 +// CHECK: llvm.store %[[EXP_BITS]], +// CHECK: %[[SQRT:.*]] = math.sqrt %[[X]] : f64 +// CHECK: %[[SQRT_BITS:.*]] = arith.bitcast %[[SQRT]] : f64 to i64 +// CHECK: llvm.store %[[SQRT_BITS]], +// CHECK: %[[LOG:.*]] = math.log %[[X]] : f64 +// CHECK: %[[LOG_BITS:.*]] = arith.bitcast %[[LOG]] : f64 to i64 +// CHECK: llvm.store %[[LOG_BITS]], +// CHECK: %[[ABS:.*]] = math.absf %[[X]] : f64 +// CHECK: %[[ABS_BITS:.*]] = arith.bitcast %[[ABS]] : f64 to i64 +// CHECK: llvm.store %[[ABS_BITS]], +// CHECK: %[[NEG:.*]] = arith.negf %[[X]] : f64 +// CHECK: %[[NEG_BITS:.*]] = arith.bitcast %[[NEG]] : f64 to i64 +// CHECK: llvm.store %[[NEG_BITS]], +func.func @float_math(%x: f64, %out: memref<1xi64>) { + %s0 = forth.stack !forth.stack + %s1 = forth.param_ref %s0 %x : !forth.stack, f64 -> !forth.stack + %s2 = forth.expf %s1 : !forth.stack -> !forth.stack + %s3 = forth.param_ref %s2 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s4 = forth.storei %s3 : !forth.stack -> !forth.stack + %s5 = forth.param_ref %s4 %x : !forth.stack, f64 -> !forth.stack + %s6 = forth.sqrtf %s5 : !forth.stack -> !forth.stack + %s7 = forth.param_ref %s6 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s8 = forth.storei %s7 : !forth.stack -> !forth.stack + %s9 = forth.param_ref %s8 %x : !forth.stack, f64 -> !forth.stack + %s10 = forth.logf %s9 : !forth.stack -> !forth.stack + %s11 = forth.param_ref %s10 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s12 = forth.storei %s11 : !forth.stack -> !forth.stack + %s13 = forth.param_ref %s12 %x : !forth.stack, f64 -> !forth.stack + %s14 = forth.absf %s13 : !forth.stack -> !forth.stack + %s15 = forth.param_ref %s14 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s16 = forth.storei %s15 : !forth.stack -> !forth.stack + %s17 = forth.param_ref %s16 %x : !forth.stack, f64 -> !forth.stack + %s18 = forth.negf %s17 : !forth.stack -> !forth.stack + %s19 = forth.param_ref %s18 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s20 = forth.storei %s19 : !forth.stack -> !forth.stack + return +} + +// Float comparisons are ordered, and the flag is the sign-extended i1. +// CHECK-LABEL: func.func @float_comparisons( +// CHECK-SAME: %[[X:[^:]*]]: f64, %[[Y:[^:]*]]: f64 +// CHECK: %[[EQ:.*]] = arith.cmpf oeq, %[[X]], %[[Y]] : f64 +// CHECK: %[[EQ_FLAG:.*]] = arith.extsi %[[EQ]] : i1 to i64 +// CHECK: llvm.store %[[EQ_FLAG]], +// CHECK: %[[LT:.*]] = arith.cmpf olt, %[[X]], %[[Y]] : f64 +// CHECK: %[[LT_FLAG:.*]] = arith.extsi %[[LT]] : i1 to i64 +// CHECK: llvm.store %[[LT_FLAG]], +// CHECK: %[[GT:.*]] = arith.cmpf ogt, %[[X]], %[[Y]] : f64 +// CHECK: %[[GT_FLAG:.*]] = arith.extsi %[[GT]] : i1 to i64 +// CHECK: llvm.store %[[GT_FLAG]], +// CHECK: %[[NE:.*]] = arith.cmpf one, %[[X]], %[[Y]] : f64 +// CHECK: %[[NE_FLAG:.*]] = arith.extsi %[[NE]] : i1 to i64 +// CHECK: llvm.store %[[NE_FLAG]], +// CHECK: %[[LE:.*]] = arith.cmpf ole, %[[X]], %[[Y]] : f64 +// CHECK: %[[LE_FLAG:.*]] = arith.extsi %[[LE]] : i1 to i64 +// CHECK: llvm.store %[[LE_FLAG]], +// CHECK: %[[GE:.*]] = arith.cmpf oge, %[[X]], %[[Y]] : f64 +// CHECK: %[[GE_FLAG:.*]] = arith.extsi %[[GE]] : i1 to i64 +// CHECK: llvm.store %[[GE_FLAG]], +func.func @float_comparisons(%x: f64, %y: f64, %out: memref<1xi64>) { + %s0 = forth.stack !forth.stack + %s1 = forth.param_ref %s0 %x : !forth.stack, f64 -> !forth.stack + %s2 = forth.param_ref %s1 %y : !forth.stack, f64 -> !forth.stack + %s3 = forth.eqf %s2 : !forth.stack -> !forth.stack + %s4 = forth.param_ref %s3 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s5 = forth.storei %s4 : !forth.stack -> !forth.stack + %s6 = forth.param_ref %s5 %x : !forth.stack, f64 -> !forth.stack + %s7 = forth.param_ref %s6 %y : !forth.stack, f64 -> !forth.stack + %s8 = forth.ltf %s7 : !forth.stack -> !forth.stack + %s9 = forth.param_ref %s8 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s10 = forth.storei %s9 : !forth.stack -> !forth.stack + %s11 = forth.param_ref %s10 %x : !forth.stack, f64 -> !forth.stack + %s12 = forth.param_ref %s11 %y : !forth.stack, f64 -> !forth.stack + %s13 = forth.gtf %s12 : !forth.stack -> !forth.stack + %s14 = forth.param_ref %s13 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s15 = forth.storei %s14 : !forth.stack -> !forth.stack + %s16 = forth.param_ref %s15 %x : !forth.stack, f64 -> !forth.stack + %s17 = forth.param_ref %s16 %y : !forth.stack, f64 -> !forth.stack + %s18 = forth.nef %s17 : !forth.stack -> !forth.stack + %s19 = forth.param_ref %s18 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s20 = forth.storei %s19 : !forth.stack -> !forth.stack + %s21 = forth.param_ref %s20 %x : !forth.stack, f64 -> !forth.stack + %s22 = forth.param_ref %s21 %y : !forth.stack, f64 -> !forth.stack + %s23 = forth.lef %s22 : !forth.stack -> !forth.stack + %s24 = forth.param_ref %s23 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s25 = forth.storei %s24 : !forth.stack -> !forth.stack + %s26 = forth.param_ref %s25 %x : !forth.stack, f64 -> !forth.stack + %s27 = forth.param_ref %s26 %y : !forth.stack, f64 -> !forth.stack + %s28 = forth.gef %s27 : !forth.stack -> !forth.stack + %s29 = forth.param_ref %s28 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s30 = forth.storei %s29 : !forth.stack -> !forth.stack + return +} + +// `A S>F OUT !` then `X F>S OUT !`. +// CHECK-LABEL: func.func @conversions( +// CHECK-SAME: %[[A:[^:]*]]: i64, %[[X:[^:]*]]: f64 +// CHECK: %[[A_FLOAT:.*]] = arith.sitofp %[[A]] : i64 to f64 +// CHECK: %[[A_BITS:.*]] = arith.bitcast %[[A_FLOAT]] : f64 to i64 +// CHECK: llvm.store %[[A_BITS]], +// CHECK: %[[X_INT:.*]] = arith.fptosi %[[X]] : f64 to i64 +// CHECK: llvm.store %[[X_INT]], +func.func @conversions(%a: i64, %x: f64, %out: memref<1xi64>) { + %s0 = forth.stack !forth.stack + %s1 = forth.param_ref %s0 %a : !forth.stack, i64 -> !forth.stack + %s2 = forth.itof %s1 : !forth.stack -> !forth.stack + %s3 = forth.param_ref %s2 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s4 = forth.storei %s3 : !forth.stack -> !forth.stack + %s5 = forth.param_ref %s4 %x : !forth.stack, f64 -> !forth.stack + %s6 = forth.ftoi %s5 : !forth.stack -> !forth.stack + %s7 = forth.param_ref %s6 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s8 = forth.storei %s7 : !forth.stack -> !forth.stack + return +} diff --git a/test/Conversion/ForthStack/gpu-indexing.mlir b/test/Conversion/ForthStack/gpu-indexing.mlir new file mode 100644 index 0000000..ab7abd9 --- /dev/null +++ b/test/Conversion/ForthStack/gpu-indexing.mlir @@ -0,0 +1,91 @@ +// RUN: %warpforth-opt --lower-forth-stack %s | %FileCheck %s + +// Each GPU index word pushes its forth.intrinsic as an i64 cell, and +// GLOBAL-ID is BID-X * BDIM-X + TID-X. ForthToGPU lowers the intrinsics. +// CHECK-LABEL: func.func @gpu_indices( +// CHECK: %[[TID_X:.*]] = forth.intrinsic "tid-x" : index +// CHECK: %[[TID_X_CELL:.*]] = arith.index_cast %[[TID_X]] : index to i64 +// CHECK: llvm.store %[[TID_X_CELL]], +// CHECK: %[[TID_Y:.*]] = forth.intrinsic "tid-y" : index +// CHECK: %[[TID_Y_CELL:.*]] = arith.index_cast %[[TID_Y]] : index to i64 +// CHECK: llvm.store %[[TID_Y_CELL]], +// CHECK: %[[TID_Z:.*]] = forth.intrinsic "tid-z" : index +// CHECK: %[[TID_Z_CELL:.*]] = arith.index_cast %[[TID_Z]] : index to i64 +// CHECK: llvm.store %[[TID_Z_CELL]], +// CHECK: %[[BID_X:.*]] = forth.intrinsic "bid-x" : index +// CHECK: %[[BID_X_CELL:.*]] = arith.index_cast %[[BID_X]] : index to i64 +// CHECK: llvm.store %[[BID_X_CELL]], +// CHECK: %[[BID_Y:.*]] = forth.intrinsic "bid-y" : index +// CHECK: %[[BID_Y_CELL:.*]] = arith.index_cast %[[BID_Y]] : index to i64 +// CHECK: llvm.store %[[BID_Y_CELL]], +// CHECK: %[[BID_Z:.*]] = forth.intrinsic "bid-z" : index +// CHECK: %[[BID_Z_CELL:.*]] = arith.index_cast %[[BID_Z]] : index to i64 +// CHECK: llvm.store %[[BID_Z_CELL]], +// CHECK: %[[BDIM_X:.*]] = forth.intrinsic "bdim-x" : index +// CHECK: %[[BDIM_X_CELL:.*]] = arith.index_cast %[[BDIM_X]] : index to i64 +// CHECK: llvm.store %[[BDIM_X_CELL]], +// CHECK: %[[BDIM_Y:.*]] = forth.intrinsic "bdim-y" : index +// CHECK: %[[BDIM_Y_CELL:.*]] = arith.index_cast %[[BDIM_Y]] : index to i64 +// CHECK: llvm.store %[[BDIM_Y_CELL]], +// CHECK: %[[BDIM_Z:.*]] = forth.intrinsic "bdim-z" : index +// CHECK: %[[BDIM_Z_CELL:.*]] = arith.index_cast %[[BDIM_Z]] : index to i64 +// CHECK: llvm.store %[[BDIM_Z_CELL]], +// CHECK: %[[GDIM_X:.*]] = forth.intrinsic "gdim-x" : index +// CHECK: %[[GDIM_X_CELL:.*]] = arith.index_cast %[[GDIM_X]] : index to i64 +// CHECK: llvm.store %[[GDIM_X_CELL]], +// CHECK: %[[GDIM_Y:.*]] = forth.intrinsic "gdim-y" : index +// CHECK: %[[GDIM_Y_CELL:.*]] = arith.index_cast %[[GDIM_Y]] : index to i64 +// CHECK: llvm.store %[[GDIM_Y_CELL]], +// CHECK: %[[GDIM_Z:.*]] = forth.intrinsic "gdim-z" : index +// CHECK: %[[GDIM_Z_CELL:.*]] = arith.index_cast %[[GDIM_Z]] : index to i64 +// CHECK: llvm.store %[[GDIM_Z_CELL]], +// CHECK: %[[BLOCK:.*]] = forth.intrinsic "bid-x" : index +// CHECK: %[[DIM:.*]] = forth.intrinsic "bdim-x" : index +// CHECK: %[[THREAD:.*]] = forth.intrinsic "tid-x" : index +// CHECK: %[[OFFSET:.*]] = arith.muli %[[BLOCK]], %[[DIM]] : index +// CHECK: %[[GLOBAL:.*]] = arith.addi %[[OFFSET]], %[[THREAD]] : index +// CHECK: %[[GLOBAL_CELL:.*]] = arith.index_cast %[[GLOBAL]] : index to i64 +// CHECK: llvm.store %[[GLOBAL_CELL]], +func.func @gpu_indices(%out: memref<1xi64>) { + %s0 = forth.stack !forth.stack + %s1 = forth.thread_id_x %s0 : !forth.stack -> !forth.stack + %s2 = forth.param_ref %s1 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s3 = forth.storei %s2 : !forth.stack -> !forth.stack + %s4 = forth.thread_id_y %s3 : !forth.stack -> !forth.stack + %s5 = forth.param_ref %s4 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s6 = forth.storei %s5 : !forth.stack -> !forth.stack + %s7 = forth.thread_id_z %s6 : !forth.stack -> !forth.stack + %s8 = forth.param_ref %s7 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s9 = forth.storei %s8 : !forth.stack -> !forth.stack + %s10 = forth.block_id_x %s9 : !forth.stack -> !forth.stack + %s11 = forth.param_ref %s10 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s12 = forth.storei %s11 : !forth.stack -> !forth.stack + %s13 = forth.block_id_y %s12 : !forth.stack -> !forth.stack + %s14 = forth.param_ref %s13 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s15 = forth.storei %s14 : !forth.stack -> !forth.stack + %s16 = forth.block_id_z %s15 : !forth.stack -> !forth.stack + %s17 = forth.param_ref %s16 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s18 = forth.storei %s17 : !forth.stack -> !forth.stack + %s19 = forth.block_dim_x %s18 : !forth.stack -> !forth.stack + %s20 = forth.param_ref %s19 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s21 = forth.storei %s20 : !forth.stack -> !forth.stack + %s22 = forth.block_dim_y %s21 : !forth.stack -> !forth.stack + %s23 = forth.param_ref %s22 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s24 = forth.storei %s23 : !forth.stack -> !forth.stack + %s25 = forth.block_dim_z %s24 : !forth.stack -> !forth.stack + %s26 = forth.param_ref %s25 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s27 = forth.storei %s26 : !forth.stack -> !forth.stack + %s28 = forth.grid_dim_x %s27 : !forth.stack -> !forth.stack + %s29 = forth.param_ref %s28 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s30 = forth.storei %s29 : !forth.stack -> !forth.stack + %s31 = forth.grid_dim_y %s30 : !forth.stack -> !forth.stack + %s32 = forth.param_ref %s31 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s33 = forth.storei %s32 : !forth.stack -> !forth.stack + %s34 = forth.grid_dim_z %s33 : !forth.stack -> !forth.stack + %s35 = forth.param_ref %s34 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s36 = forth.storei %s35 : !forth.stack -> !forth.stack + %s37 = forth.global_id %s36 : !forth.stack -> !forth.stack + %s38 = forth.param_ref %s37 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s39 = forth.storei %s38 : !forth.stack -> !forth.stack + return +} diff --git a/test/Conversion/ForthStack/memory.mlir b/test/Conversion/ForthStack/memory.mlir new file mode 100644 index 0000000..5e63aa0 --- /dev/null +++ b/test/Conversion/ForthStack/memory.mlir @@ -0,0 +1,135 @@ +// RUN: %warpforth-opt --lower-forth-stack %s | %FileCheck %s + +// `ADDR load ADDR store` for each width. A load widens the element to a cell: +// an integer sign-extends, and a float extends to f64 and travels as bits. A +// store narrows the cell back. Global words address !llvm.ptr<1>. +// CHECK-LABEL: func.func @global_memory( +// CHECK-SAME: %[[ADDR:[^:]*]]: i64 +// CHECK: %[[I64_PTR:.*]] = llvm.inttoptr %[[ADDR]] : i64 to !llvm.ptr<1> +// CHECK: %[[I64:.*]] = llvm.load %[[I64_PTR]] : !llvm.ptr<1> -> i64 +// CHECK: llvm.store %[[I64]], %{{.*}} : i64, !llvm.ptr<1> +// CHECK: %[[F64:.*]] = llvm.load %{{.*}} : !llvm.ptr<1> -> f64 +// CHECK: %[[F64_CELL:.*]] = arith.bitcast %[[F64]] : f64 to i64 +// CHECK: %[[F64_BACK:.*]] = arith.bitcast %[[F64_CELL]] : i64 to f64 +// CHECK: llvm.store %[[F64_BACK]], %{{.*}} : f64, !llvm.ptr<1> +// CHECK: %[[I8:.*]] = llvm.load %{{.*}} : !llvm.ptr<1> -> i8 +// CHECK: %[[I8_CELL:.*]] = arith.extsi %[[I8]] : i8 to i64 +// CHECK: %[[I8_BACK:.*]] = arith.trunci %[[I8_CELL]] : i64 to i8 +// CHECK: llvm.store %[[I8_BACK]], %{{.*}} : i8, !llvm.ptr<1> +// CHECK: %[[I16:.*]] = llvm.load %{{.*}} : !llvm.ptr<1> -> i16 +// CHECK: %[[I16_CELL:.*]] = arith.extsi %[[I16]] : i16 to i64 +// CHECK: %[[I16_BACK:.*]] = arith.trunci %[[I16_CELL]] : i64 to i16 +// CHECK: llvm.store %[[I16_BACK]], %{{.*}} : i16, !llvm.ptr<1> +// CHECK: %[[I32:.*]] = llvm.load %{{.*}} : !llvm.ptr<1> -> i32 +// CHECK: %[[I32_CELL:.*]] = arith.extsi %[[I32]] : i32 to i64 +// CHECK: %[[I32_BACK:.*]] = arith.trunci %[[I32_CELL]] : i64 to i32 +// CHECK: llvm.store %[[I32_BACK]], %{{.*}} : i32, !llvm.ptr<1> +// CHECK: %[[F16:.*]] = llvm.load %{{.*}} : !llvm.ptr<1> -> f16 +// CHECK: %[[F16_WIDE:.*]] = arith.extf %[[F16]] : f16 to f64 +// CHECK: %[[F16_CELL:.*]] = arith.bitcast %[[F16_WIDE]] : f64 to i64 +// CHECK: %[[F16_F64:.*]] = arith.bitcast %[[F16_CELL]] : i64 to f64 +// CHECK: %[[F16_BACK:.*]] = arith.truncf %[[F16_F64]] : f64 to f16 +// CHECK: llvm.store %[[F16_BACK]], %{{.*}} : f16, !llvm.ptr<1> +// CHECK: %[[BF16:.*]] = llvm.load %{{.*}} : !llvm.ptr<1> -> bf16 +// CHECK: %[[BF16_WIDE:.*]] = arith.extf %[[BF16]] : bf16 to f64 +// CHECK: %[[BF16_CELL:.*]] = arith.bitcast %[[BF16_WIDE]] : f64 to i64 +// CHECK: %[[BF16_F64:.*]] = arith.bitcast %[[BF16_CELL]] : i64 to f64 +// CHECK: %[[BF16_BACK:.*]] = arith.truncf %[[BF16_F64]] : f64 to bf16 +// CHECK: llvm.store %[[BF16_BACK]], %{{.*}} : bf16, !llvm.ptr<1> +// CHECK: %[[F32:.*]] = llvm.load %{{.*}} : !llvm.ptr<1> -> f32 +// CHECK: %[[F32_WIDE:.*]] = arith.extf %[[F32]] : f32 to f64 +// CHECK: %[[F32_CELL:.*]] = arith.bitcast %[[F32_WIDE]] : f64 to i64 +// CHECK: %[[F32_F64:.*]] = arith.bitcast %[[F32_CELL]] : i64 to f64 +// CHECK: %[[F32_BACK:.*]] = arith.truncf %[[F32_F64]] : f64 to f32 +// CHECK: llvm.store %[[F32_BACK]], %{{.*}} : f32, !llvm.ptr<1> +func.func @global_memory(%addr: i64) { + %s0 = forth.stack !forth.stack + %s1 = forth.param_ref %s0 %addr : !forth.stack, i64 -> !forth.stack + %s2 = forth.loadi %s1 : !forth.stack -> !forth.stack + %s3 = forth.param_ref %s2 %addr : !forth.stack, i64 -> !forth.stack + %s4 = forth.storei %s3 : !forth.stack -> !forth.stack + %s5 = forth.param_ref %s4 %addr : !forth.stack, i64 -> !forth.stack + %s6 = forth.loadf %s5 : !forth.stack -> !forth.stack + %s7 = forth.param_ref %s6 %addr : !forth.stack, i64 -> !forth.stack + %s8 = forth.storef %s7 : !forth.stack -> !forth.stack + %s9 = forth.param_ref %s8 %addr : !forth.stack, i64 -> !forth.stack + %s10 = forth.load_i8 %s9 : !forth.stack -> !forth.stack + %s11 = forth.param_ref %s10 %addr : !forth.stack, i64 -> !forth.stack + %s12 = forth.store_i8 %s11 : !forth.stack -> !forth.stack + %s13 = forth.param_ref %s12 %addr : !forth.stack, i64 -> !forth.stack + %s14 = forth.load_i16 %s13 : !forth.stack -> !forth.stack + %s15 = forth.param_ref %s14 %addr : !forth.stack, i64 -> !forth.stack + %s16 = forth.store_i16 %s15 : !forth.stack -> !forth.stack + %s17 = forth.param_ref %s16 %addr : !forth.stack, i64 -> !forth.stack + %s18 = forth.load_i32 %s17 : !forth.stack -> !forth.stack + %s19 = forth.param_ref %s18 %addr : !forth.stack, i64 -> !forth.stack + %s20 = forth.store_i32 %s19 : !forth.stack -> !forth.stack + %s21 = forth.param_ref %s20 %addr : !forth.stack, i64 -> !forth.stack + %s22 = forth.load_f16 %s21 : !forth.stack -> !forth.stack + %s23 = forth.param_ref %s22 %addr : !forth.stack, i64 -> !forth.stack + %s24 = forth.store_f16 %s23 : !forth.stack -> !forth.stack + %s25 = forth.param_ref %s24 %addr : !forth.stack, i64 -> !forth.stack + %s26 = forth.load_bf16 %s25 : !forth.stack -> !forth.stack + %s27 = forth.param_ref %s26 %addr : !forth.stack, i64 -> !forth.stack + %s28 = forth.store_bf16 %s27 : !forth.stack -> !forth.stack + %s29 = forth.param_ref %s28 %addr : !forth.stack, i64 -> !forth.stack + %s30 = forth.load_f32 %s29 : !forth.stack -> !forth.stack + %s31 = forth.param_ref %s30 %addr : !forth.stack, i64 -> !forth.stack + %s32 = forth.store_f32 %s31 : !forth.stack -> !forth.stack + return +} + +// Shared words address !llvm.ptr<3> and convert cells like the global ones. +// CHECK-LABEL: func.func @shared_memory( +// CHECK: llvm.load %{{.*}} : !llvm.ptr<3> -> i64 +// CHECK: llvm.store %{{.*}}, %{{.*}} : i64, !llvm.ptr<3> +// CHECK: llvm.load %{{.*}} : !llvm.ptr<3> -> f64 +// CHECK: llvm.store %{{.*}}, %{{.*}} : f64, !llvm.ptr<3> +// CHECK: llvm.load %{{.*}} : !llvm.ptr<3> -> i8 +// CHECK: llvm.store %{{.*}}, %{{.*}} : i8, !llvm.ptr<3> +// CHECK: llvm.load %{{.*}} : !llvm.ptr<3> -> i16 +// CHECK: llvm.store %{{.*}}, %{{.*}} : i16, !llvm.ptr<3> +// CHECK: llvm.load %{{.*}} : !llvm.ptr<3> -> i32 +// CHECK: llvm.store %{{.*}}, %{{.*}} : i32, !llvm.ptr<3> +// CHECK: llvm.load %{{.*}} : !llvm.ptr<3> -> f16 +// CHECK: llvm.store %{{.*}}, %{{.*}} : f16, !llvm.ptr<3> +// CHECK: llvm.load %{{.*}} : !llvm.ptr<3> -> bf16 +// CHECK: llvm.store %{{.*}}, %{{.*}} : bf16, !llvm.ptr<3> +// CHECK: llvm.load %{{.*}} : !llvm.ptr<3> -> f32 +// CHECK: llvm.store %{{.*}}, %{{.*}} : f32, !llvm.ptr<3> +func.func @shared_memory(%addr: i64) { + %s0 = forth.stack !forth.stack + %s1 = forth.param_ref %s0 %addr : !forth.stack, i64 -> !forth.stack + %s2 = forth.shared_loadi %s1 : !forth.stack -> !forth.stack + %s3 = forth.param_ref %s2 %addr : !forth.stack, i64 -> !forth.stack + %s4 = forth.shared_storei %s3 : !forth.stack -> !forth.stack + %s5 = forth.param_ref %s4 %addr : !forth.stack, i64 -> !forth.stack + %s6 = forth.shared_loadf %s5 : !forth.stack -> !forth.stack + %s7 = forth.param_ref %s6 %addr : !forth.stack, i64 -> !forth.stack + %s8 = forth.shared_storef %s7 : !forth.stack -> !forth.stack + %s9 = forth.param_ref %s8 %addr : !forth.stack, i64 -> !forth.stack + %s10 = forth.shared_load_i8 %s9 : !forth.stack -> !forth.stack + %s11 = forth.param_ref %s10 %addr : !forth.stack, i64 -> !forth.stack + %s12 = forth.shared_store_i8 %s11 : !forth.stack -> !forth.stack + %s13 = forth.param_ref %s12 %addr : !forth.stack, i64 -> !forth.stack + %s14 = forth.shared_load_i16 %s13 : !forth.stack -> !forth.stack + %s15 = forth.param_ref %s14 %addr : !forth.stack, i64 -> !forth.stack + %s16 = forth.shared_store_i16 %s15 : !forth.stack -> !forth.stack + %s17 = forth.param_ref %s16 %addr : !forth.stack, i64 -> !forth.stack + %s18 = forth.shared_load_i32 %s17 : !forth.stack -> !forth.stack + %s19 = forth.param_ref %s18 %addr : !forth.stack, i64 -> !forth.stack + %s20 = forth.shared_store_i32 %s19 : !forth.stack -> !forth.stack + %s21 = forth.param_ref %s20 %addr : !forth.stack, i64 -> !forth.stack + %s22 = forth.shared_load_f16 %s21 : !forth.stack -> !forth.stack + %s23 = forth.param_ref %s22 %addr : !forth.stack, i64 -> !forth.stack + %s24 = forth.shared_store_f16 %s23 : !forth.stack -> !forth.stack + %s25 = forth.param_ref %s24 %addr : !forth.stack, i64 -> !forth.stack + %s26 = forth.shared_load_bf16 %s25 : !forth.stack -> !forth.stack + %s27 = forth.param_ref %s26 %addr : !forth.stack, i64 -> !forth.stack + %s28 = forth.shared_store_bf16 %s27 : !forth.stack -> !forth.stack + %s29 = forth.param_ref %s28 %addr : !forth.stack, i64 -> !forth.stack + %s30 = forth.shared_load_f32 %s29 : !forth.stack -> !forth.stack + %s31 = forth.param_ref %s30 %addr : !forth.stack, i64 -> !forth.stack + %s32 = forth.shared_store_f32 %s31 : !forth.stack -> !forth.stack + return +} diff --git a/test/Conversion/ForthStack/stack-manipulation.mlir b/test/Conversion/ForthStack/stack-manipulation.mlir new file mode 100644 index 0000000..9f58b55 --- /dev/null +++ b/test/Conversion/ForthStack/stack-manipulation.mlir @@ -0,0 +1,183 @@ +// RUN: %warpforth-opt --lower-forth-stack %s | %FileCheck %s + +// Each function pushes 1 2 3, runs one stack word, and stores the cells that +// remain, top first. The stores read the literals themselves: the word only +// reorders SSA values, so no stack buffer exists. + +// ( 1 2 3 -- 1 2 3 3 ) +// CHECK-LABEL: func.func @dup( +// CHECK-NOT: memref.alloca +// CHECK: %[[ONE:.*]] = arith.constant 1 : i64 +// CHECK: %[[TWO:.*]] = arith.constant 2 : i64 +// CHECK: %[[THREE:.*]] = arith.constant 3 : i64 +// CHECK: llvm.store %[[THREE]], +// CHECK: llvm.store %[[THREE]], +// CHECK: llvm.store %[[TWO]], +// CHECK: llvm.store %[[ONE]], +// CHECK-NEXT: return +func.func @dup(%out: memref<1xi64>) { + %s0 = forth.stack !forth.stack + %s1 = forth.constant %s0(1 : i64) : !forth.stack -> !forth.stack + %s2 = forth.constant %s1(2 : i64) : !forth.stack -> !forth.stack + %s3 = forth.constant %s2(3 : i64) : !forth.stack -> !forth.stack + %s4 = forth.dup %s3 : !forth.stack -> !forth.stack + %s5 = forth.param_ref %s4 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s6 = forth.storei %s5 : !forth.stack -> !forth.stack + %s7 = forth.param_ref %s6 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s8 = forth.storei %s7 : !forth.stack -> !forth.stack + %s9 = forth.param_ref %s8 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s10 = forth.storei %s9 : !forth.stack -> !forth.stack + %s11 = forth.param_ref %s10 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s12 = forth.storei %s11 : !forth.stack -> !forth.stack + return +} + +// ( 1 2 3 -- 1 2 ) +// CHECK-LABEL: func.func @drop( +// CHECK-NOT: memref.alloca +// CHECK: %[[ONE:.*]] = arith.constant 1 : i64 +// CHECK: %[[TWO:.*]] = arith.constant 2 : i64 +// CHECK: %[[THREE:.*]] = arith.constant 3 : i64 +// CHECK: llvm.store %[[TWO]], +// CHECK: llvm.store %[[ONE]], +// CHECK-NEXT: return +func.func @drop(%out: memref<1xi64>) { + %s0 = forth.stack !forth.stack + %s1 = forth.constant %s0(1 : i64) : !forth.stack -> !forth.stack + %s2 = forth.constant %s1(2 : i64) : !forth.stack -> !forth.stack + %s3 = forth.constant %s2(3 : i64) : !forth.stack -> !forth.stack + %s4 = forth.drop %s3 : !forth.stack -> !forth.stack + %s5 = forth.param_ref %s4 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s6 = forth.storei %s5 : !forth.stack -> !forth.stack + %s7 = forth.param_ref %s6 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s8 = forth.storei %s7 : !forth.stack -> !forth.stack + return +} + +// ( 1 2 3 -- 1 3 2 ) +// CHECK-LABEL: func.func @swap( +// CHECK-NOT: memref.alloca +// CHECK: %[[ONE:.*]] = arith.constant 1 : i64 +// CHECK: %[[TWO:.*]] = arith.constant 2 : i64 +// CHECK: %[[THREE:.*]] = arith.constant 3 : i64 +// CHECK: llvm.store %[[TWO]], +// CHECK: llvm.store %[[THREE]], +// CHECK: llvm.store %[[ONE]], +// CHECK-NEXT: return +func.func @swap(%out: memref<1xi64>) { + %s0 = forth.stack !forth.stack + %s1 = forth.constant %s0(1 : i64) : !forth.stack -> !forth.stack + %s2 = forth.constant %s1(2 : i64) : !forth.stack -> !forth.stack + %s3 = forth.constant %s2(3 : i64) : !forth.stack -> !forth.stack + %s4 = forth.swap %s3 : !forth.stack -> !forth.stack + %s5 = forth.param_ref %s4 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s6 = forth.storei %s5 : !forth.stack -> !forth.stack + %s7 = forth.param_ref %s6 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s8 = forth.storei %s7 : !forth.stack -> !forth.stack + %s9 = forth.param_ref %s8 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s10 = forth.storei %s9 : !forth.stack -> !forth.stack + return +} + +// ( 1 2 3 -- 1 2 3 2 ) +// CHECK-LABEL: func.func @over( +// CHECK-NOT: memref.alloca +// CHECK: %[[ONE:.*]] = arith.constant 1 : i64 +// CHECK: %[[TWO:.*]] = arith.constant 2 : i64 +// CHECK: %[[THREE:.*]] = arith.constant 3 : i64 +// CHECK: llvm.store %[[TWO]], +// CHECK: llvm.store %[[THREE]], +// CHECK: llvm.store %[[TWO]], +// CHECK: llvm.store %[[ONE]], +// CHECK-NEXT: return +func.func @over(%out: memref<1xi64>) { + %s0 = forth.stack !forth.stack + %s1 = forth.constant %s0(1 : i64) : !forth.stack -> !forth.stack + %s2 = forth.constant %s1(2 : i64) : !forth.stack -> !forth.stack + %s3 = forth.constant %s2(3 : i64) : !forth.stack -> !forth.stack + %s4 = forth.over %s3 : !forth.stack -> !forth.stack + %s5 = forth.param_ref %s4 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s6 = forth.storei %s5 : !forth.stack -> !forth.stack + %s7 = forth.param_ref %s6 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s8 = forth.storei %s7 : !forth.stack -> !forth.stack + %s9 = forth.param_ref %s8 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s10 = forth.storei %s9 : !forth.stack -> !forth.stack + %s11 = forth.param_ref %s10 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s12 = forth.storei %s11 : !forth.stack -> !forth.stack + return +} + +// ( 1 2 3 -- 2 3 1 ) +// CHECK-LABEL: func.func @rot( +// CHECK-NOT: memref.alloca +// CHECK: %[[ONE:.*]] = arith.constant 1 : i64 +// CHECK: %[[TWO:.*]] = arith.constant 2 : i64 +// CHECK: %[[THREE:.*]] = arith.constant 3 : i64 +// CHECK: llvm.store %[[ONE]], +// CHECK: llvm.store %[[THREE]], +// CHECK: llvm.store %[[TWO]], +// CHECK-NEXT: return +func.func @rot(%out: memref<1xi64>) { + %s0 = forth.stack !forth.stack + %s1 = forth.constant %s0(1 : i64) : !forth.stack -> !forth.stack + %s2 = forth.constant %s1(2 : i64) : !forth.stack -> !forth.stack + %s3 = forth.constant %s2(3 : i64) : !forth.stack -> !forth.stack + %s4 = forth.rot %s3 : !forth.stack -> !forth.stack + %s5 = forth.param_ref %s4 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s6 = forth.storei %s5 : !forth.stack -> !forth.stack + %s7 = forth.param_ref %s6 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s8 = forth.storei %s7 : !forth.stack -> !forth.stack + %s9 = forth.param_ref %s8 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s10 = forth.storei %s9 : !forth.stack -> !forth.stack + return +} + +// ( 1 2 3 -- 1 3 ) +// CHECK-LABEL: func.func @nip( +// CHECK-NOT: memref.alloca +// CHECK: %[[ONE:.*]] = arith.constant 1 : i64 +// CHECK: %[[TWO:.*]] = arith.constant 2 : i64 +// CHECK: %[[THREE:.*]] = arith.constant 3 : i64 +// CHECK: llvm.store %[[THREE]], +// CHECK: llvm.store %[[ONE]], +// CHECK-NEXT: return +func.func @nip(%out: memref<1xi64>) { + %s0 = forth.stack !forth.stack + %s1 = forth.constant %s0(1 : i64) : !forth.stack -> !forth.stack + %s2 = forth.constant %s1(2 : i64) : !forth.stack -> !forth.stack + %s3 = forth.constant %s2(3 : i64) : !forth.stack -> !forth.stack + %s4 = forth.nip %s3 : !forth.stack -> !forth.stack + %s5 = forth.param_ref %s4 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s6 = forth.storei %s5 : !forth.stack -> !forth.stack + %s7 = forth.param_ref %s6 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s8 = forth.storei %s7 : !forth.stack -> !forth.stack + return +} + +// ( 1 2 3 -- 1 3 2 3 ) +// CHECK-LABEL: func.func @tuck( +// CHECK-NOT: memref.alloca +// CHECK: %[[ONE:.*]] = arith.constant 1 : i64 +// CHECK: %[[TWO:.*]] = arith.constant 2 : i64 +// CHECK: %[[THREE:.*]] = arith.constant 3 : i64 +// CHECK: llvm.store %[[THREE]], +// CHECK: llvm.store %[[TWO]], +// CHECK: llvm.store %[[THREE]], +// CHECK: llvm.store %[[ONE]], +// CHECK-NEXT: return +func.func @tuck(%out: memref<1xi64>) { + %s0 = forth.stack !forth.stack + %s1 = forth.constant %s0(1 : i64) : !forth.stack -> !forth.stack + %s2 = forth.constant %s1(2 : i64) : !forth.stack -> !forth.stack + %s3 = forth.constant %s2(3 : i64) : !forth.stack -> !forth.stack + %s4 = forth.tuck %s3 : !forth.stack -> !forth.stack + %s5 = forth.param_ref %s4 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s6 = forth.storei %s5 : !forth.stack -> !forth.stack + %s7 = forth.param_ref %s6 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s8 = forth.storei %s7 : !forth.stack -> !forth.stack + %s9 = forth.param_ref %s8 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s10 = forth.storei %s9 : !forth.stack -> !forth.stack + %s11 = forth.param_ref %s10 %out : !forth.stack, memref<1xi64> -> !forth.stack + %s12 = forth.storei %s11 : !forth.stack -> !forth.stack + return +} From 199e6633a9a6465e676eb04dfebf3742ca868479 Mon Sep 17 00:00:00 2001 From: Alex Cameron Date: Mon, 9 Nov 2026 05:03:22 +0000 Subject: [PATCH 6/8] refactor(conversion): delete the memref stack lowering Every Forth word now has a stack-word row, so no function falls through to convert-forth-to-memref and that pass has no caller left. Deleting it leaves --lower-forth-stack as the one place that decides where a cell lives, and its fallback becomes an error for any op that uses a stack without a row. Inlining leaves the kernel as the only function, so ForthToGPU drops the branch that moved word functions into the gpu.module and reports any other function instead. The pipeline tests run --lower-forth-stack, with --inline only where the program defines words, and the docs describe the new stages. --- .../features/staged-pipeline.md | 4 +- AGENTS.md | 13 +- README.md | 5 +- .../Conversion/ForthToMemRef/ForthToMemRef.h | 26 - include/warpforth/Conversion/Passes.td | 37 +- lib/Conversion/CMakeLists.txt | 2 - lib/Conversion/ForthStack/LowerForthStack.cpp | 26 +- lib/Conversion/ForthToGPU/ForthToGPU.cpp | 29 +- lib/Conversion/ForthToMemRef/CMakeLists.txt | 19 - .../ForthToMemRef/ForthToMemRef.cpp | 1338 ----------------- lib/Conversion/Passes.cpp | 8 +- .../ForthStack/unknown-stack-user-error.mlir | 10 + .../ForthToGPU/non-kernel-function-error.mlir | 14 + .../ForthToGPU/private-functions.mlir | 22 - test/Conversion/ForthToMemRef/arithmetic.mlir | 52 - test/Conversion/ForthToMemRef/barrier.mlir | 9 - .../Conversion/ForthToMemRef/begin-until.mlir | 46 - .../ForthToMemRef/begin-while-repeat.mlir | 56 - test/Conversion/ForthToMemRef/bitwise.mlir | 64 - test/Conversion/ForthToMemRef/comparison.mlir | 80 - .../ForthToMemRef/control-flow.mlir | 70 - test/Conversion/ForthToMemRef/do-loop.mlir | 71 - .../ForthToMemRef/float-arithmetic.mlir | 44 - .../ForthToMemRef/float-math-intrinsics.mlir | 70 - .../ForthToMemRef/float-memory.mlir | 29 - test/Conversion/ForthToMemRef/leave.mlir | 43 - test/Conversion/ForthToMemRef/literal.mlir | 17 - test/Conversion/ForthToMemRef/memory-ops.mlir | 41 - .../ForthToMemRef/nested-control-flow.mlir | 290 ---- test/Conversion/ForthToMemRef/param-ref.mlir | 37 - .../ForthToMemRef/reduced-width-memory.mlir | 118 -- test/Conversion/ForthToMemRef/stack-init.mlir | 12 - .../ForthToMemRef/stack-manipulation.mlir | 95 -- .../ForthToMemRef/user-defined-words.mlir | 26 - test/Pipeline/barrier.forth | 2 +- test/Pipeline/begin-until.forth | 2 +- test/Pipeline/begin-while-repeat.forth | 2 +- test/Pipeline/control-flow.forth | 8 +- test/Pipeline/do-loop.forth | 2 +- test/Pipeline/exit.forth | 13 +- test/Pipeline/float-pipeline.forth | 12 +- test/Pipeline/full-pipeline.forth | 13 +- test/Pipeline/interleaved-control-flow.forth | 11 +- test/Pipeline/leave.forth | 2 +- test/Pipeline/matmul-naive.forth | 2 +- test/Pipeline/multi-param.forth | 2 +- test/Pipeline/nested-control-flow.forth | 2 +- test/Pipeline/scalar-param.forth | 2 +- test/Pipeline/shared-memory.forth | 2 +- tools/warpforth-opt/CMakeLists.txt | 1 - 50 files changed, 115 insertions(+), 2786 deletions(-) delete mode 100644 include/warpforth/Conversion/ForthToMemRef/ForthToMemRef.h delete mode 100644 lib/Conversion/ForthToMemRef/CMakeLists.txt delete mode 100644 lib/Conversion/ForthToMemRef/ForthToMemRef.cpp create mode 100644 test/Conversion/ForthStack/unknown-stack-user-error.mlir create mode 100644 test/Conversion/ForthToGPU/non-kernel-function-error.mlir delete mode 100644 test/Conversion/ForthToGPU/private-functions.mlir delete mode 100644 test/Conversion/ForthToMemRef/arithmetic.mlir delete mode 100644 test/Conversion/ForthToMemRef/barrier.mlir delete mode 100644 test/Conversion/ForthToMemRef/begin-until.mlir delete mode 100644 test/Conversion/ForthToMemRef/begin-while-repeat.mlir delete mode 100644 test/Conversion/ForthToMemRef/bitwise.mlir delete mode 100644 test/Conversion/ForthToMemRef/comparison.mlir delete mode 100644 test/Conversion/ForthToMemRef/control-flow.mlir delete mode 100644 test/Conversion/ForthToMemRef/do-loop.mlir delete mode 100644 test/Conversion/ForthToMemRef/float-arithmetic.mlir delete mode 100644 test/Conversion/ForthToMemRef/float-math-intrinsics.mlir delete mode 100644 test/Conversion/ForthToMemRef/float-memory.mlir delete mode 100644 test/Conversion/ForthToMemRef/leave.mlir delete mode 100644 test/Conversion/ForthToMemRef/literal.mlir delete mode 100644 test/Conversion/ForthToMemRef/memory-ops.mlir delete mode 100644 test/Conversion/ForthToMemRef/nested-control-flow.mlir delete mode 100644 test/Conversion/ForthToMemRef/param-ref.mlir delete mode 100644 test/Conversion/ForthToMemRef/reduced-width-memory.mlir delete mode 100644 test/Conversion/ForthToMemRef/stack-init.mlir delete mode 100644 test/Conversion/ForthToMemRef/stack-manipulation.mlir delete mode 100644 test/Conversion/ForthToMemRef/user-defined-words.mlir diff --git a/.claude/skills/verify-warpforth/features/staged-pipeline.md b/.claude/skills/verify-warpforth/features/staged-pipeline.md index d8df585..5d0e19b 100644 --- a/.claude/skills/verify-warpforth/features/staged-pipeline.md +++ b/.claude/skills/verify-warpforth/features/staged-pipeline.md @@ -5,7 +5,7 @@ A user debugging a kernel runs the compiler in stages: Forth to `forth`-dialect ## Sub-features - `stage-translate` `warpforth-translate --forth-to-mlir` emits `forth` dialect ops. -- `stage-passes` `warpforth-opt --convert-forth-to-memref` and `--convert-forth-to-gpu` run single lowerings. +- `stage-passes` `warpforth-opt --inline --lower-forth-stack` and `--convert-forth-to-gpu` run single lowerings. - `stage-pipeline` `warpforth-opt --warpforth-pipeline` lowers to a `gpu.binary`. - `stage-options` pipeline options `chip`, `features`, `opt-level` (0-3), `compilation-target` (`llvm|isa|bin|fatbin`). - `stage-ptx` `warpforth-translate --mlir-to-ptx` turns pipeline output into PTX. @@ -22,7 +22,7 @@ Preconditions: - Baseline preconditions hold. `K=.claude/skills/verify-warpforth/fixtures/smoke/matmul.forth`. - **Translate.** Run `build/bin/warpforth-translate --forth-to-mlir $K`. Output contains `forth.` ops and a `func.func` for `main`; exit 0. -- **Single pass.** Pipe that into `build/bin/warpforth-opt --convert-forth-to-memref`. Output has `memref<256xi64>` and no `!forth.stack`. +- **Single pass.** Pipe that into `build/bin/warpforth-opt --inline --lower-forth-stack`. Output has no `!forth.stack` and no `memref<256xi64>` stack buffer; the loop header block takes its stack cells as `i64` arguments. - **Full pipeline to PTX.** Run the three-tool pipe above. PTX on stdout with `.visible .entry main(`; compare with `build/bin/warpforthc $K` output (should match for the same arch). - **Target options.** Run the `--pass-pipeline` form with `chip=sm_80`. The `gpu.binary` attribute shows `chip = "sm_80"` and `O = 3`; its embedded assembly has `.target sm_80`. - **Evidence.** `$S/compile.sh $K sm_80` stores `kernel.mlir` and `lowered.mlir` for the same journey. diff --git a/AGENTS.md b/AGENTS.md index e102e8e..bc63461 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,7 +31,8 @@ CMake. - `include/warpforth/Dialect/Forth/ForthDialect.td` - Type definitions **Implementation:** -- `lib/Conversion/ForthToMemRef/ForthToMemRef.cpp` - Stack to MemRef conversion patterns +- `lib/Conversion/ForthStack/StackWords.cpp` - Stack-word table: the stack effect and lowering of every Forth op that takes a stack +- `lib/Conversion/ForthStack/LowerForthStack.cpp` - Stack lowering to i64 SSA cells and a residual buffer - `lib/Conversion/ForthToGPU/ForthToGPU.cpp` - GPU conversion logic - `lib/Translation/ForthToMLIR/ForthToMLIR.cpp` - Forth parser and translator @@ -50,7 +51,7 @@ request per line on stdin and writes one JSON response per line on stdout. ./build/bin/warpforth-translate --forth-to-mlir test/example.forth # Run conversion passes -./build/bin/warpforth-opt --convert-forth-to-memref input.mlir +./build/bin/warpforth-opt --inline --lower-forth-stack input.mlir ./build/bin/warpforth-opt --convert-forth-to-gpu input.mlir # Full pipeline to PTX @@ -78,7 +79,7 @@ def Forth_NewOp : Forth_Op<"opname", [Pure]> { } ``` -Add corresponding conversion pattern in `lib/Conversion/ForthToMemRef/ForthToMemRef.cpp`. +Add a row for it in `lib/Conversion/ForthStack/StackWords.cpp` that declares its stack effect and lowers it on i64 cells. Until the row exists, `--lower-forth-stack` fails on every input. ## GPU Tests @@ -102,10 +103,10 @@ uv run ruff format gpu_test/ - **Kernel Parameters**: Declared in the `\!` header. `\! kernel ` is required and must appear first. `\! param i64[]` becomes a `memref` argument; `\! param i64` becomes an `i64` argument. `\! param f64[]` becomes a `memref` argument; `\! param f64` becomes an `f64` argument (bitcast to i64 when pushed to stack). Using a param name in code emits `forth.param_ref` (arrays push address; scalars push value). - **Shared Memory**: `\! shared i64[]` or `\! shared f64[]` declares GPU shared (workgroup) memory. Emits a tagged `memref.alloca` at kernel entry; ForthToGPU converts it to a `gpu.func` workgroup attribution. Using the shared name in code pushes its base address onto the stack. Use `S@`/`S!` for i64 or `SF@`/`SF!` for f64 shared accesses. Cannot be referenced inside word definitions. - **Reduced-Width Memory**: `I8@ I16@ I32@` load a narrow integer, sign-extend to i64. `I8! I16! I32!` truncate i64 to narrow integer, store. `HF@ BF@ F32@` load a narrow float, extend to f64, bitcast to i64. `HF! BF! F32!` bitcast i64 to f64, truncate to narrow float, store. `S`-prefixed variants (`SI8@`, `SHF!`, etc.) use shared memory (address space 3). -- **Conversion**: `!forth.stack` → `memref<256xi64>` with explicit stack pointer -- **GPU**: Functions wrapped in `gpu.module`, `main` gets `gpu.kernel` attribute, configured with bare pointers for NVVM conversion +- **Stack Lowering**: After inlining, `--lower-forth-stack` turns each cell whose depth and slot are known at compile time into an i64 SSA value, and block arguments carry cells across branches and loops. A cell below the known depth, or one that a runtime `PICK`/`ROLL` index addresses, lives in a per-thread `memref<256xi64>` residual buffer. +- **GPU**: The kernel is wrapped in `gpu.module` and gets the `gpu.kernel` attribute, configured with bare pointers for NVVM conversion - **Local Variables**: `{ a b c -- }` at the start of a word definition binds read-only locals. Pops values from the stack in reverse name order (c, b, a) using `forth.pop`, stores SSA values. Referencing a local emits `forth.push_value`. SSA values from the entry block dominate all control flow, so locals work across IF/ELSE/THEN, loops, etc. On GPU, locals map directly to registers. -- **User-defined Words**: Modeled as `func.func` with signature `(!forth.stack) -> !forth.stack`, called via `func.call` +- **User-defined Words**: Modeled as `func.func` with signature `(!forth.stack) -> !forth.stack`, called via `func.call`, and inlined into the kernel before the stack is lowered ## Conventions diff --git a/README.md b/README.md index b6299c8..e61b987 100644 --- a/README.md +++ b/README.md @@ -110,8 +110,9 @@ WarpForth compiles Forth through a series of MLIR dialect lowerings, each replac | Stage | Pass | Description | |-------|-------------|-------------| | **Parsing** | `warpforth-translate --forth-to-mlir` | Parses Forth source into the `forth` dialect. The kernel is represented as a series of stack ops on an abstract `!forth.stack` type. | -| **Stack lowering** | `warpforth-opt --convert-forth-to-memref` | The abstract `!forth.stack` type is materialized as a `memref<256xi64>` buffer and `index` pair. Stack ops become explicit loads, stores, and pointer arithmetic. | -| **GPU wrapping** | `warpforth-opt --convert-forth-to-gpu` | Functions are wrapped in a `gpu.module`, the kernel entry point is marked as a `gpu.kernel` and GPU intrinsic words are lowered to `gpu` ops. | +| **Inlining** | `warpforth-opt --inline` | User-defined words are inlined into the kernel, so the kernel is the whole program when its stack is lowered. | +| **Stack lowering** | `warpforth-opt --lower-forth-stack` | Each stack cell whose depth and slot are known at compile time becomes an `i64` SSA value, and block arguments carry cells across branches and loops. A cell below the known depth, or one that a runtime `PICK` or `ROLL` index addresses, lives in a per-thread `memref<256xi64>` buffer. | +| **GPU wrapping** | `warpforth-opt --convert-forth-to-gpu` | The kernel is moved into a `gpu.module` and marked as a `gpu.kernel`, and GPU intrinsic words are lowered to `gpu` ops. | | **NVVM/LLVM lowering** | Standard MLIR passes | GPU→NVVM, math→LLVM intrinsics and NVVM→LLVM. | | **Code generation** | `warpforth-translate --mlir-to-ptx` | The GPU module is serialized to PTX assembly via LLVM's NVPTX backend. | diff --git a/include/warpforth/Conversion/ForthToMemRef/ForthToMemRef.h b/include/warpforth/Conversion/ForthToMemRef/ForthToMemRef.h deleted file mode 100644 index d6b8cc8..0000000 --- a/include/warpforth/Conversion/ForthToMemRef/ForthToMemRef.h +++ /dev/null @@ -1,26 +0,0 @@ -//===- ForthToMemRef.h - Forth to MemRef conversion ------------*- C++ -*-===// -// -// This file declares the pass for converting Forth dialect operations to -// MemRef dialect operations. -// -//===----------------------------------------------------------------------===// - -#ifndef WARPFORTH_CONVERSION_FORTHTOMEMREF_FORTHTOMEMREF_H -#define WARPFORTH_CONVERSION_FORTHTOMEMREF_FORTHTOMEMREF_H - -#include "mlir/Pass/Pass.h" -#include - -namespace mlir { -namespace warpforth { - -/// Creates a pass that converts Forth dialect operations to MemRef dialect. -/// This pass lowers the abstract Forth stack type to a concrete memref<256xi64> -/// representation with an explicit stack pointer (index type) threaded through -/// operations. -std::unique_ptr createConvertForthToMemRefPass(); - -} // namespace warpforth -} // namespace mlir - -#endif diff --git a/include/warpforth/Conversion/Passes.td b/include/warpforth/Conversion/Passes.td index ac0ba12..a964e25 100644 --- a/include/warpforth/Conversion/Passes.td +++ b/include/warpforth/Conversion/Passes.td @@ -9,29 +9,6 @@ include "mlir/Pass/PassBase.td" -def ConvertForthToMemRef - : Pass<"convert-forth-to-memref", "mlir::ModuleOp"> { - let summary = "Convert Forth dialect to MemRef dialect"; - let description = [{ - This pass converts Forth dialect operations to MemRef dialect operations. - - The abstract `!forth.stack` type is lowered to a concrete representation: - - Stack buffer: `memref<256xi64>` (fixed-size 256-element array) - - Stack pointer: `index` type (current top of stack position) - - Forth operations are converted to corresponding memref load/store operations - with explicit stack pointer arithmetic. - }]; - - let constructor = "mlir::warpforth::createConvertForthToMemRefPass()"; - - let dependentDialects = ["mlir::memref::MemRefDialect", - "mlir::arith::ArithDialect", - "mlir::LLVM::LLVMDialect", - "mlir::cf::ControlFlowDialect", - "mlir::math::MathDialect"]; -} - def LowerForthStack : Pass<"lower-forth-stack", "mlir::ModuleOp"> { let summary = "Lower the Forth stack to i64 SSA values"; let description = [{ @@ -41,11 +18,8 @@ def LowerForthStack : Pass<"lower-forth-stack", "mlir::ModuleOp"> { `memref`, or `llvm` ops that compute its result. A cell below the known depth, or one that a runtime `PICK` or `ROLL` index - addresses, lives in a per-thread `memref<256xi64>` with the memref stack's - layout: index 0 is empty and a push stores at depth + 1. - - A function whose words this pass does not lower yet is left unchanged for - `convert-forth-to-memref`. + addresses, lives in a per-thread `memref<256xi64>`. Index 0 of that buffer + is empty, and a push stores at depth + 1. }]; let constructor = "mlir::warpforth::createLowerForthStackPass()"; @@ -64,9 +38,10 @@ def ConvertForthToGPU : Pass<"convert-forth-to-gpu", "mlir::ModuleOp"> { This pass converts Forth functions to the GPU dialect to prepare them for GPU execution. - The pass wraps func.func operations in a gpu.module and converts them to - gpu.func operations. Functions named "main" receive the gpu.kernel - attribute, making them launchable from host code. + The pass moves the kernel, the func.func marked `forth.kernel`, into a + gpu.module as a gpu.func with the gpu.kernel attribute, making it + launchable from host code. Every Forth word must already be inlined, so + any other func.func is an error. Additionally, the pass lowers forth.intrinsic operations to corresponding GPU dialect operations (gpu.thread_id, gpu.block_id, gpu.block_dim, diff --git a/lib/Conversion/CMakeLists.txt b/lib/Conversion/CMakeLists.txt index 3dce691..e76e845 100644 --- a/lib/Conversion/CMakeLists.txt +++ b/lib/Conversion/CMakeLists.txt @@ -7,7 +7,6 @@ add_mlir_library(MLIRConversionPasses LINK_LIBS PUBLIC MLIRPass MLIRForthStackConversion - MLIRForthToMemRefConversion MLIRForthToGPUConversion MLIRGPUDialect MLIRGPUToNVVMTransforms @@ -23,5 +22,4 @@ target_compile_definitions(obj.MLIRConversionPasses PRIVATE ) add_subdirectory(ForthStack) -add_subdirectory(ForthToMemRef) add_subdirectory(ForthToGPU) diff --git a/lib/Conversion/ForthStack/LowerForthStack.cpp b/lib/Conversion/ForthStack/LowerForthStack.cpp index 2687df4..896905c 100644 --- a/lib/Conversion/ForthStack/LowerForthStack.cpp +++ b/lib/Conversion/ForthStack/LowerForthStack.cpp @@ -3,7 +3,7 @@ // This file implements the pass that lowers every !forth.stack value. The // stack-word table says what each word computes. This file decides where each // cell lives: a cell whose depth and slot are known is an i64 SSA value, and -// the rest live in a per-thread buffer laid out like the memref stack. +// the rest live in a per-thread memref<256xi64> indexed by depth. // //===----------------------------------------------------------------------===// @@ -135,15 +135,19 @@ LogicalResult verifyWordsInlined(ModuleOp module) { return success(); } -/// Whether every op in `body` that takes a stack either has a row or branches. -bool hasRowsFor(Region &body) { +/// Every stack value must come from forth.stack, a row, or a block argument, +/// and flow only into rows and branches. +LogicalResult verifyStackUsers(Region &body) { WalkResult walk = body.walk([](Operation *op) { - if (llvm::any_of(op->getOperandTypes(), isStack) && - !isa(op) && !stack::lookupStackWord(op)) - return WalkResult::interrupt(); - return WalkResult::advance(); + bool usesStack = llvm::any_of(op->getOperandTypes(), isStack) || + llvm::any_of(op->getResultTypes(), isStack); + if (!usesStack || isa(op) || + stack::lookupStackWord(op)) + return WalkResult::advance(); + op->emitOpError("uses a !forth.stack but has no stack-word row"); + return WalkResult::interrupt(); }); - return !walk.wasInterrupted(); + return failure(walk.wasInterrupted()); } /// Joins the shapes that the predecessors seen so far pass to the stack @@ -501,10 +505,8 @@ struct LowerForthStackPass if (fn.isExternal()) continue; (void)eraseUnreachableBlocks(rewriter, fn->getRegions()); - // A function that uses a word with no row yet is left whole for - // convert-forth-to-memref. - if (!hasRowsFor(fn.getBody())) - continue; + if (failed(verifyStackUsers(fn.getBody()))) + return signalPassFailure(); StackSimulator(fn, inferShapes(fn.getBody())).run(); } } diff --git a/lib/Conversion/ForthToGPU/ForthToGPU.cpp b/lib/Conversion/ForthToGPU/ForthToGPU.cpp index 6a363e6..147cbfb 100644 --- a/lib/Conversion/ForthToGPU/ForthToGPU.cpp +++ b/lib/Conversion/ForthToGPU/ForthToGPU.cpp @@ -220,22 +220,19 @@ struct ConvertForthToGPUPass LogicalResult convertFuncToGPU(func::FuncOp funcOp, gpu::GPUModuleOp gpuModule, IRRewriter &rewriter) { - bool isKernel = funcOp->hasAttr("forth.kernel"); - - if (isKernel) { - FailureOr gpuFunc = - createGPUFunc(funcOp, gpuModule, rewriter); - if (failed(gpuFunc)) - return failure(); - (*gpuFunc)->setAttr(gpu::GPUDialect::getKernelFuncAttrName(), - rewriter.getUnitAttr()); - rewriter.eraseOp(funcOp); - } else { - funcOp->moveBefore(&gpuModule.getBodyRegion().front(), - gpuModule.getBodyRegion().front().end()); - if (failed(applyConversionPatterns(funcOp, funcOp.getContext()))) - return failure(); - } + if (!funcOp->hasAttr("forth.kernel")) + return funcOp.emitError() + << "@" << funcOp.getSymName() + << " is not the kernel; inline every Forth word before " + "--convert-forth-to-gpu"; + + FailureOr gpuFunc = + createGPUFunc(funcOp, gpuModule, rewriter); + if (failed(gpuFunc)) + return failure(); + (*gpuFunc)->setAttr(gpu::GPUDialect::getKernelFuncAttrName(), + rewriter.getUnitAttr()); + rewriter.eraseOp(funcOp); return success(); } }; diff --git a/lib/Conversion/ForthToMemRef/CMakeLists.txt b/lib/Conversion/ForthToMemRef/CMakeLists.txt deleted file mode 100644 index 1f85b95..0000000 --- a/lib/Conversion/ForthToMemRef/CMakeLists.txt +++ /dev/null @@ -1,19 +0,0 @@ -add_mlir_conversion_library(MLIRForthToMemRefConversion - ForthToMemRef.cpp - - DEPENDS - MLIRConversionPassIncGen - MLIRForth - - LINK_LIBS PUBLIC - MLIRIR - MLIRPass - MLIRTransformUtils - MLIRMemRefDialect - MLIRArithDialect - MLIRLLVMDialect - MLIRFuncDialect - MLIRControlFlowDialect - MLIRMathDialect - MLIRForth -) diff --git a/lib/Conversion/ForthToMemRef/ForthToMemRef.cpp b/lib/Conversion/ForthToMemRef/ForthToMemRef.cpp deleted file mode 100644 index 4772660..0000000 --- a/lib/Conversion/ForthToMemRef/ForthToMemRef.cpp +++ /dev/null @@ -1,1338 +0,0 @@ -//===- ForthToMemRef.cpp - Forth to MemRef conversion ----------*- C++ -*-===// -// -// This file implements the conversion from Forth dialect to MemRef dialect. -// -//===----------------------------------------------------------------------===// - -#include "warpforth/Conversion/ForthToMemRef/ForthToMemRef.h" -#include "mlir/Dialect/Arith/IR/Arith.h" -#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" -#include "mlir/Dialect/Func/IR/FuncOps.h" -#include "mlir/Dialect/Func/Transforms/FuncConversions.h" -#include "mlir/Dialect/LLVMIR/LLVMDialect.h" -#include "mlir/Dialect/LLVMIR/NVVMDialect.h" -#include "mlir/Dialect/Math/IR/Math.h" -#include "mlir/Dialect/MemRef/IR/MemRef.h" -#include "mlir/IR/BuiltinTypes.h" -#include "mlir/IR/PatternMatch.h" -#include "mlir/Pass/Pass.h" -#include "mlir/Transforms/DialectConversion.h" -#include "mlir/Transforms/RegionUtils.h" -#include "warpforth/Dialect/Forth/ForthDialect.h" - -namespace mlir { -namespace warpforth { - -#define GEN_PASS_DEF_CONVERTFORTHTOMEMREF -#include "warpforth/Conversion/Passes.h.inc" - -namespace { - -// Stack configuration constants -constexpr int64_t kStackSize = 256; -// NVPTX global memory address space for LLVM ptr types. Global addresses are -// numerically equal to their generic addresses, so inttoptr into this space is -// valid and lets NVPTX emit ld.global/st.global after address arithmetic. -constexpr unsigned kGlobalAddressSpace = - static_cast(NVVM::kGlobalMemorySpace); -// NVPTX shared memory address space for LLVM ptr types. -constexpr unsigned kWorkgroupAddressSpace = - static_cast(NVVM::kSharedMemorySpace); - -/// Type converter for forth.stack -> memref + index -class ForthToMemRefTypeConverter : public TypeConverter { -public: - ForthToMemRefTypeConverter() { - // Pass-through for all non-stack types (must be registered first) - addConversion([](Type type) { return type; }); - - // Stack type: !forth.stack -> memref<256xi64> + index - addConversion( - [&](forth::StackType type, - SmallVectorImpl &results) -> std::optional { - auto memrefType = MemRefType::get( - {kStackSize}, IntegerType::get(type.getContext(), 64)); - auto indexType = IndexType::get(type.getContext()); - results.push_back(memrefType); - results.push_back(indexType); - return success(); - }); - } -}; - -/// Push an i64 value onto the stack. Returns the new stack pointer. -static Value pushValue(Location loc, ConversionPatternRewriter &rewriter, - Value memref, Value stackPtr, Value value) { - Value one = rewriter.create(loc, 1); - Value newSP = rewriter.create(loc, stackPtr, one); - rewriter.create(loc, value, memref, newSP); - return newSP; -} - -/// Base for patterns that rewrite one !forth.stack operand into one output -/// stack. Subclasses emit the stack effect on the unpacked (memref, SP) pair -/// and return the new SP. -template -struct StackEffectConversion : public OpConversionPattern { - using OpConversionPattern::OpConversionPattern; - using OneToNOpAdaptor = - typename OpConversionPattern::OneToNOpAdaptor; - - virtual FailureOr - rewriteStack(ForthOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, ConversionPatternRewriter &rewriter) const = 0; - - LogicalResult - matchAndRewrite(ForthOp op, OneToNOpAdaptor adaptor, - ConversionPatternRewriter &rewriter) const final { - ValueRange inputStack = adaptor.getOperands()[0]; - Value memref = inputStack[0]; - FailureOr newSP = - rewriteStack(op, adaptor, memref, inputStack[1], rewriter); - if (failed(newSP)) - return failure(); - rewriter.replaceOpWithMultiple(op, {{memref, *newSP}}); - return success(); - } -}; - -/// Conversion pattern for forth.stack operation. -/// Allocates a memref<256xi64> on the stack and initializes SP to 0. -struct StackOpConversion : public OpConversionPattern { - StackOpConversion(const TypeConverter &typeConverter, MLIRContext *context) - : OpConversionPattern(typeConverter, context) {} - using OneToNOpAdaptor = OpConversionPattern::OneToNOpAdaptor; - - LogicalResult - matchAndRewrite(forth::StackOp op, OneToNOpAdaptor adaptor, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - auto i64Type = rewriter.getI64Type(); - auto memrefType = MemRefType::get({kStackSize}, i64Type); - - // Allocate stack buffer - Value stackBuffer = rewriter.create(loc, memrefType); - - // Initialize stack pointer to 0 - Value initialSP = rewriter.create(loc, 0); - - rewriter.replaceOpWithMultiple(op, {{stackBuffer, initialSP}}); - return success(); - } -}; - -/// Conversion pattern for forth.constant operation. -/// Handles both integer and float constants. -struct ConstantOpConversion : public StackEffectConversion { - using StackEffectConversion::StackEffectConversion; - - FailureOr - rewriteStack(forth::ConstantOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - Value valueToPush; - auto typedValue = cast(op.getValueAttr()); - if (isa(typedValue)) { - // Float: create f64 constant, bitcast to i64 - Value f64Value = rewriter.create( - loc, rewriter.getF64Type(), typedValue); - valueToPush = rewriter.create( - loc, rewriter.getI64Type(), f64Value); - } else { - // Integer: create i64 constant directly - valueToPush = rewriter.create( - loc, rewriter.getI64Type(), typedValue); - } - Value newSP = pushValue(loc, rewriter, memref, stackPtr, valueToPush); - - return newSP; - } -}; - -/// Conversion pattern for forth.dup operation. -/// Duplicates the value at the top of the stack: (a -- a a) -struct DupOpConversion : public StackEffectConversion { - using StackEffectConversion::StackEffectConversion; - - FailureOr - rewriteStack(forth::DupOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - // Load value at current SP and push duplicate - Value topValue = rewriter.create(loc, memref, stackPtr); - Value newSP = pushValue(loc, rewriter, memref, stackPtr, topValue); - - return newSP; - } -}; - -/// Conversion pattern for forth.drop operation. -/// Removes the top element from the stack: (a -- ) -struct DropOpConversion : public StackEffectConversion { - using StackEffectConversion::StackEffectConversion; - - FailureOr - rewriteStack(forth::DropOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - // Decrement SP - Value one = rewriter.create(loc, 1); - Value newSP = rewriter.create(loc, stackPtr, one); - - return newSP; - } -}; - -/// Conversion pattern for forth.swap operation. -/// Swaps the top two elements: (a b -- b a) -struct SwapOpConversion : public StackEffectConversion { - using StackEffectConversion::StackEffectConversion; - - FailureOr - rewriteStack(forth::SwapOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - // Load top two values - Value topValue = rewriter.create(loc, memref, stackPtr); - - Value one = rewriter.create(loc, 1); - Value spMinus1 = rewriter.create(loc, stackPtr, one); - Value secondValue = rewriter.create(loc, memref, spMinus1); - - // Store swapped - rewriter.create(loc, secondValue, memref, stackPtr); - rewriter.create(loc, topValue, memref, spMinus1); - - return stackPtr; - } -}; - -/// Conversion pattern for forth.over operation. -/// Copies the second element to top: (a b -- a b a) -struct OverOpConversion : public StackEffectConversion { - using StackEffectConversion::StackEffectConversion; - - FailureOr - rewriteStack(forth::OverOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - // Load second element (SP - 1) and push copy - Value one = rewriter.create(loc, 1); - Value spMinus1 = rewriter.create(loc, stackPtr, one); - Value secondValue = rewriter.create(loc, memref, spMinus1); - Value newSP = pushValue(loc, rewriter, memref, stackPtr, secondValue); - - return newSP; - } -}; - -/// Conversion pattern for forth.rot operation. -/// Rotates top three elements: (a b c -- b c a) -struct RotOpConversion : public StackEffectConversion { - using StackEffectConversion::StackEffectConversion; - - FailureOr - rewriteStack(forth::RotOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - Value one = rewriter.create(loc, 1); - Value two = rewriter.create(loc, 2); - - // Load top three values - Value c = rewriter.create(loc, memref, stackPtr); - - Value spMinus1 = rewriter.create(loc, stackPtr, one); - Value b = rewriter.create(loc, memref, spMinus1); - - Value spMinus2 = rewriter.create(loc, stackPtr, two); - Value a = rewriter.create(loc, memref, spMinus2); - - // Store rotated: (a b c -- b c a) - rewriter.create(loc, b, memref, spMinus2); - rewriter.create(loc, c, memref, spMinus1); - rewriter.create(loc, a, memref, stackPtr); - - return stackPtr; - } -}; - -/// Conversion pattern for forth.nip operation. -/// Removes the second element: (a b -- b) -struct NipOpConversion : public StackEffectConversion { - using StackEffectConversion::StackEffectConversion; - - FailureOr - rewriteStack(forth::NipOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - // Load top value (b at SP) - Value b = rewriter.create(loc, memref, stackPtr); - - // Store b at SP-1 (overwriting a) - Value one = rewriter.create(loc, 1); - Value spMinus1 = rewriter.create(loc, stackPtr, one); - rewriter.create(loc, b, memref, spMinus1); - - // Net effect: SP-1 (removed one element) - return spMinus1; - } -}; - -/// Conversion pattern for forth.tuck operation. -/// Copies top before second: (a b -- b a b) -struct TuckOpConversion : public StackEffectConversion { - using StackEffectConversion::StackEffectConversion; - - FailureOr - rewriteStack(forth::TuckOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - Value one = rewriter.create(loc, 1); - - // Load top two values - Value b = rewriter.create(loc, memref, stackPtr); - Value spMinus1 = rewriter.create(loc, stackPtr, one); - Value a = rewriter.create(loc, memref, spMinus1); - - // Store: b at SP-1, a at SP, b at SP+1 - rewriter.create(loc, b, memref, spMinus1); - rewriter.create(loc, a, memref, stackPtr); - Value newSP = rewriter.create(loc, stackPtr, one); - rewriter.create(loc, b, memref, newSP); - - // Net effect: SP+1 (added one element) - return newSP; - } -}; - -/// Conversion pattern for forth.pick operation. -/// Copies nth element to top: ( xn ... x0 n -- xn ... x0 xn ) -struct PickOpConversion : public StackEffectConversion { - using StackEffectConversion::StackEffectConversion; - - FailureOr - rewriteStack(forth::PickOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - // Pop n from stack - Value nI64 = rewriter.create(loc, memref, stackPtr); - Value one = rewriter.create(loc, 1); - Value spAfterPop = rewriter.create(loc, stackPtr, one); - - // Cast n to index - Value nIdx = - rewriter.create(loc, rewriter.getIndexType(), nI64); - - // Compute target address: SP' - n - Value targetAddr = rewriter.create(loc, spAfterPop, nIdx); - - // Load the picked value - Value pickedValue = - rewriter.create(loc, memref, targetAddr); - - // Store at SP (where n was), effectively pushing the picked value - rewriter.create(loc, pickedValue, memref, stackPtr); - - // Net effect: SP unchanged (popped n, pushed xn) - return stackPtr; - } -}; - -/// Conversion pattern for forth.roll operation. -/// Rotates nth element to top: ( xn ... x0 n -- xn-1 ... x0 xn ) -/// Uses a CF-based loop to shift elements down. -struct RollOpConversion : public StackEffectConversion { - using StackEffectConversion::StackEffectConversion; - - FailureOr - rewriteStack(forth::RollOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - auto indexType = rewriter.getIndexType(); - - // Pop n from stack - Value nI64 = rewriter.create(loc, memref, stackPtr); - Value one = rewriter.create(loc, 1); - Value spAfterPop = rewriter.create(loc, stackPtr, one); - - // Cast n to index - Value nIdx = rewriter.create(loc, indexType, nI64); - - // Compute address of the element to roll: SP' - n - Value rolledAddr = rewriter.create(loc, spAfterPop, nIdx); - - // Save the value to be rolled to top - Value rolledValue = - rewriter.create(loc, memref, rolledAddr); - - // Split block to create CF-based shift loop. - Block *currentBlock = rewriter.getInsertionBlock(); - Block *continueBlock = rewriter.splitBlock(currentBlock, op->getIterator()); - - // Create loop header and body blocks (inserted before continueBlock). - Block *headerBlock = rewriter.createBlock(continueBlock); - headerBlock->addArgument(indexType, loc); // induction variable - Block *bodyBlock = rewriter.createBlock(continueBlock); - bodyBlock->addArgument(indexType, loc); // induction variable - - // currentBlock -> headerBlock(rolledAddr) - rewriter.setInsertionPointToEnd(currentBlock); - rewriter.create(loc, headerBlock, ValueRange{rolledAddr}); - - // headerBlock: check iv < spAfterPop - rewriter.setInsertionPointToStart(headerBlock); - Value iv = headerBlock->getArgument(0); - Value cond = rewriter.create(loc, arith::CmpIPredicate::slt, - iv, spAfterPop); - rewriter.create(loc, cond, bodyBlock, ValueRange{iv}, - continueBlock, ValueRange{}); - - // bodyBlock: shift memref[iv] = memref[iv+1], branch back to header - rewriter.setInsertionPointToStart(bodyBlock); - Value biv = bodyBlock->getArgument(0); - Value next = rewriter.create(loc, biv, one); - Value shiftedVal = rewriter.create(loc, memref, next); - rewriter.create(loc, shiftedVal, memref, biv); - rewriter.create(loc, headerBlock, ValueRange{next}); - - // continueBlock: store rolled value at top, then rest of original block - rewriter.setInsertionPoint(op); - rewriter.create(loc, rolledValue, memref, spAfterPop); - - // Net effect: SP' = SP - 1 (consumed n) - return spAfterPop; - } -}; - -/// Base template for binary arithmetic operations. -/// Pops two values, applies operation, pushes result: (a b -- result) -/// When IsFloat=true, bitcasts i64->f64 before the op and f64->i64 after. -template -struct BinaryArithOpConversion : public StackEffectConversion { - using Base = StackEffectConversion; - using Base::Base; - using typename Base::OneToNOpAdaptor; - - FailureOr - rewriteStack(ForthOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - Value one = rewriter.create(loc, 1); - - // Load top two values (b at SP, a at SP-1) - Value b = rewriter.create(loc, memref, stackPtr); - Value spMinus1 = rewriter.create(loc, stackPtr, one); - Value a = rewriter.create(loc, memref, spMinus1); - - Value result; - if constexpr (IsFloat) { - // Bitcast i64 -> f64 - auto f64Type = rewriter.getF64Type(); - Value aF = rewriter.create(loc, f64Type, a); - Value bF = rewriter.create(loc, f64Type, b); - Value resF = rewriter.create(loc, aF, bF); - // Bitcast f64 -> i64 - result = - rewriter.create(loc, rewriter.getI64Type(), resF); - } else { - result = rewriter.create(loc, a, b); - } - - // Store result at SP-1 (effectively popping both and pushing result) - rewriter.create(loc, result, memref, spMinus1); - - // New SP is SP-1 (net effect: two pops, one push) - return spMinus1; - } -}; - -// Integer arithmetic -using AddIOpConversion = BinaryArithOpConversion; -using SubIOpConversion = BinaryArithOpConversion; -using MulIOpConversion = BinaryArithOpConversion; -using DivIOpConversion = BinaryArithOpConversion; -using ModOpConversion = BinaryArithOpConversion; -using AndOpConversion = BinaryArithOpConversion; -using OrOpConversion = BinaryArithOpConversion; -using XorOpConversion = BinaryArithOpConversion; -using LshiftOpConversion = - BinaryArithOpConversion; -using RshiftOpConversion = - BinaryArithOpConversion; - -// Float arithmetic -using AddFOpConversion = - BinaryArithOpConversion; -using SubFOpConversion = - BinaryArithOpConversion; -using MulFOpConversion = - BinaryArithOpConversion; -using DivFOpConversion = - BinaryArithOpConversion; - -// Float binary intrinsics (max/min) -using MaxFOpConversion = - BinaryArithOpConversion; -using MinFOpConversion = - BinaryArithOpConversion; - -/// Base template for unary float operations. -/// Pops one value, applies operation, pushes result: (f -- result) -/// Bitcasts i64->f64 before the op and f64->i64 after. -template -struct UnaryFloatOpConversion : public StackEffectConversion { - using Base = StackEffectConversion; - using Base::Base; - using typename Base::OneToNOpAdaptor; - - FailureOr - rewriteStack(ForthOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - // Load value from top of stack - Value a = rewriter.create(loc, memref, stackPtr); - - // Bitcast i64 -> f64 - auto f64Type = rewriter.getF64Type(); - Value aF = rewriter.create(loc, f64Type, a); - - // Apply math/arith op - Value resF = rewriter.create(loc, aF); - - // Bitcast f64 -> i64 - Value result = - rewriter.create(loc, rewriter.getI64Type(), resF); - - // Store result at same position (SP unchanged — unary op) - rewriter.create(loc, result, memref, stackPtr); - - return stackPtr; - } -}; - -// Float unary intrinsics -using ExpFOpConversion = UnaryFloatOpConversion; -using SqrtFOpConversion = UnaryFloatOpConversion; -using LogFOpConversion = UnaryFloatOpConversion; -using AbsFOpConversion = UnaryFloatOpConversion; -using NegFOpConversion = UnaryFloatOpConversion; - -/// Base template for binary comparison operations. -/// Pops two values, compares, pushes -1 (true) or 0 (false): (a b -- flag) -/// When IsFloat=true, bitcasts i64->f64 before comparing. -template -struct BinaryCmpOpConversion : public StackEffectConversion { - using Base = StackEffectConversion; - using Base::Base; - using typename Base::OneToNOpAdaptor; - - FailureOr - rewriteStack(ForthOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - Value one = rewriter.create(loc, 1); - - // Load top two values (b at SP, a at SP-1) - Value b = rewriter.create(loc, memref, stackPtr); - Value spMinus1 = rewriter.create(loc, stackPtr, one); - Value a = rewriter.create(loc, memref, spMinus1); - - Value cmp; - if constexpr (IsFloat) { - auto f64Type = rewriter.getF64Type(); - Value aF = rewriter.create(loc, f64Type, a); - Value bF = rewriter.create(loc, f64Type, b); - cmp = rewriter.create(loc, Predicate, aF, bF); - } else { - cmp = rewriter.create(loc, Predicate, a, b); - } - - // Extend i1 to i64: true = -1 (all bits set), false = 0 - Value result = - rewriter.create(loc, rewriter.getI64Type(), cmp); - - // Store result at SP-1 - rewriter.create(loc, result, memref, spMinus1); - - // New SP is SP-1 (net: two pops, one push) - return spMinus1; - } -}; - -// Integer comparisons -using EqIOpConversion = BinaryCmpOpConversion; -using LtIOpConversion = BinaryCmpOpConversion; -using GtIOpConversion = BinaryCmpOpConversion; -using NeIOpConversion = BinaryCmpOpConversion; -using LeIOpConversion = BinaryCmpOpConversion; -using GeIOpConversion = BinaryCmpOpConversion; - -// Float comparisons (ordered predicates) -using EqFOpConversion = BinaryCmpOpConversion; -using LtFOpConversion = BinaryCmpOpConversion; -using GtFOpConversion = BinaryCmpOpConversion; -using NeFOpConversion = BinaryCmpOpConversion; -using LeFOpConversion = BinaryCmpOpConversion; -using GeFOpConversion = BinaryCmpOpConversion; - -/// Conversion pattern for forth.not operation (bitwise NOT). -/// Unary: pops one value, XORs with -1 (all bits set), pushes result: (a -- ~a) -struct NotOpConversion : public StackEffectConversion { - using StackEffectConversion::StackEffectConversion; - - FailureOr - rewriteStack(forth::NotOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - // Load top value - Value a = rewriter.create(loc, memref, stackPtr); - - // XOR with -1 (all bits set) to flip all bits - Value allOnes = rewriter.create( - loc, rewriter.getI64Type(), rewriter.getI64IntegerAttr(-1)); - Value result = rewriter.create(loc, a, allOnes); - - // Store result at same position (SP unchanged) - rewriter.create(loc, result, memref, stackPtr); - - return stackPtr; - } -}; - -/// Conversion pattern for forth.zero_eq operation (0=). -/// Unary: pops one value, pushes -1 if zero, 0 otherwise: (a -- flag) -struct ZeroEqOpConversion : public StackEffectConversion { - using StackEffectConversion::StackEffectConversion; - - FailureOr - rewriteStack(forth::ZeroEqOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - // Load top value - Value a = rewriter.create(loc, memref, stackPtr); - - // Compare with zero - Value zero = rewriter.create( - loc, rewriter.getI64Type(), rewriter.getI64IntegerAttr(0)); - Value cmp = - rewriter.create(loc, arith::CmpIPredicate::eq, a, zero); - - // Extend i1 to i64: true = -1, false = 0 - Value result = - rewriter.create(loc, rewriter.getI64Type(), cmp); - - // Store result at same position (SP unchanged) - rewriter.create(loc, result, memref, stackPtr); - - return stackPtr; - } -}; - -/// Conversion pattern for forth.param_ref operation. -/// Pushes an array parameter's byte address or a scalar parameter's value. -struct ParamRefOpConversion : public StackEffectConversion { - using StackEffectConversion::StackEffectConversion; - - FailureOr - rewriteStack(forth::ParamRefOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - Value parameter = adaptor.getOperands()[1].front(); - - Value valueToPush; - if (isa(parameter.getType())) { - // Extract pointer as index, then cast to i64 - Value ptrIndex = rewriter.create( - loc, parameter); - valueToPush = rewriter.create( - loc, rewriter.getI64Type(), ptrIndex); - } else if (parameter.getType().isInteger(64)) { - // Scalar i64 param: push value directly. - valueToPush = parameter; - } else if (parameter.getType().isF64()) { - // Scalar f64 param: bitcast to i64 for stack storage. - valueToPush = rewriter.create( - loc, rewriter.getI64Type(), parameter); - } else { - return rewriter.notifyMatchFailure( - op, "unsupported param argument type for param_ref"); - } - - // Push onto stack - Value newSP = pushValue(loc, rewriter, memref, stackPtr, valueToPush); - - return newSP; - } -}; - -/// Memory element type tag for generalized load/store templates. -enum class MemType { I64, F64, I8, I16, I32, F16, BF16, F32 }; - -/// Return the MLIR element type for a given MemType. -static Type getMemElemType(MLIRContext *ctx, MemType mt) { - switch (mt) { - case MemType::I64: - return IntegerType::get(ctx, 64); - case MemType::I32: - return IntegerType::get(ctx, 32); - case MemType::I16: - return IntegerType::get(ctx, 16); - case MemType::I8: - return IntegerType::get(ctx, 8); - case MemType::F64: - return Float64Type::get(ctx); - case MemType::F32: - return Float32Type::get(ctx); - case MemType::F16: - return Float16Type::get(ctx); - case MemType::BF16: - return BFloat16Type::get(ctx); - } - llvm_unreachable("unhandled MemType"); -} - -template -inline constexpr bool isReducedInt = - (MT == MemType::I8 || MT == MemType::I16 || MT == MemType::I32); - -template -inline constexpr bool isReducedFloat = - (MT == MemType::F16 || MT == MemType::BF16 || MT == MemType::F32); - -/// Generalized memory load template. -/// Pops address from stack, loads value via pointer, pushes value. -/// MemType selects the memory element type and the widening strategy. -/// AddressSpace selects global or workgroup memory. -template -struct MemoryLoadOpConversion : public StackEffectConversion { - using Base = StackEffectConversion; - using Base::Base; - using typename Base::OneToNOpAdaptor; - - FailureOr - rewriteStack(ForthOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - auto ptrType = - LLVM::LLVMPointerType::get(rewriter.getContext(), AddressSpace); - - // Load address from stack - Value addrValue = rewriter.create(loc, memref, stackPtr); - - // Load value from memory via pointer - Value ptr = rewriter.create(loc, ptrType, addrValue); - - Type elemType = getMemElemType(rewriter.getContext(), MT); - Value loaded = rewriter.create(loc, elemType, ptr); - - Value valueToPush; - if constexpr (MT == MemType::I64) { - valueToPush = loaded; - } else if constexpr (MT == MemType::F64) { - valueToPush = - rewriter.create(loc, rewriter.getI64Type(), loaded); - } else if constexpr (isReducedInt) { - valueToPush = - rewriter.create(loc, rewriter.getI64Type(), loaded); - } else if constexpr (isReducedFloat) { - Value extended = - rewriter.create(loc, rewriter.getF64Type(), loaded); - valueToPush = rewriter.create( - loc, rewriter.getI64Type(), extended); - } - - // Store loaded value back at same position (replaces address) - rewriter.create(loc, valueToPush, memref, stackPtr); - - return stackPtr; - } -}; - -// Memory load instantiations — full-width -using LoadIOpConversion = MemoryLoadOpConversion; -using LoadFOpConversion = MemoryLoadOpConversion; -using SharedLoadIOpConversion = - MemoryLoadOpConversion; -using SharedLoadFOpConversion = - MemoryLoadOpConversion; - -// Memory load instantiations — reduced-width -using LoadI8OpConversion = MemoryLoadOpConversion; -using SharedLoadI8OpConversion = - MemoryLoadOpConversion; -using LoadI16OpConversion = - MemoryLoadOpConversion; -using SharedLoadI16OpConversion = - MemoryLoadOpConversion; -using LoadI32OpConversion = - MemoryLoadOpConversion; -using SharedLoadI32OpConversion = - MemoryLoadOpConversion; -using LoadF16OpConversion = - MemoryLoadOpConversion; -using SharedLoadF16OpConversion = - MemoryLoadOpConversion; -using LoadBF16OpConversion = - MemoryLoadOpConversion; -using SharedLoadBF16OpConversion = - MemoryLoadOpConversion; -using LoadF32OpConversion = - MemoryLoadOpConversion; -using SharedLoadF32OpConversion = - MemoryLoadOpConversion; - -/// Generalized memory store template. -/// Pops address and value from stack, stores value to memory. -/// MemType selects the memory element type and the narrowing strategy. -template -struct MemoryStoreOpConversion : public StackEffectConversion { - using Base = StackEffectConversion; - using Base::Base; - using typename Base::OneToNOpAdaptor; - - FailureOr - rewriteStack(ForthOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - auto ptrType = - LLVM::LLVMPointerType::get(rewriter.getContext(), AddressSpace); - - // Pop address from stack - Value addrValue = rewriter.create(loc, memref, stackPtr); - - // Pop value from stack - Value one = rewriter.create(loc, 1); - Value spMinus1 = rewriter.create(loc, stackPtr, one); - Value value = rewriter.create(loc, memref, spMinus1); - - // Store value to memory via pointer - Value ptr = rewriter.create(loc, ptrType, addrValue); - - if constexpr (MT == MemType::I64) { - rewriter.create(loc, value, ptr); - } else if constexpr (MT == MemType::F64) { - Value f64Value = - rewriter.create(loc, rewriter.getF64Type(), value); - rewriter.create(loc, f64Value, ptr); - } else if constexpr (isReducedInt) { - Type elemType = getMemElemType(rewriter.getContext(), MT); - Value truncated = rewriter.create(loc, elemType, value); - rewriter.create(loc, truncated, ptr); - } else if constexpr (isReducedFloat) { - Type elemType = getMemElemType(rewriter.getContext(), MT); - Value f64Value = - rewriter.create(loc, rewriter.getF64Type(), value); - Value truncated = - rewriter.create(loc, elemType, f64Value); - rewriter.create(loc, truncated, ptr); - } - - // New stack pointer is SP-2 (popped both address and value) - Value spMinus2 = rewriter.create(loc, spMinus1, one); - return spMinus2; - } -}; - -// Memory store instantiations — full-width -using StoreIOpConversion = MemoryStoreOpConversion; -using StoreFOpConversion = - MemoryStoreOpConversion; -using SharedStoreIOpConversion = - MemoryStoreOpConversion; -using SharedStoreFOpConversion = - MemoryStoreOpConversion; - -// Memory store instantiations — reduced-width -using StoreI8OpConversion = - MemoryStoreOpConversion; -using SharedStoreI8OpConversion = - MemoryStoreOpConversion; -using StoreI16OpConversion = - MemoryStoreOpConversion; -using SharedStoreI16OpConversion = - MemoryStoreOpConversion; -using StoreI32OpConversion = - MemoryStoreOpConversion; -using SharedStoreI32OpConversion = - MemoryStoreOpConversion; -using StoreF16OpConversion = - MemoryStoreOpConversion; -using SharedStoreF16OpConversion = - MemoryStoreOpConversion; -using StoreBF16OpConversion = - MemoryStoreOpConversion; -using SharedStoreBF16OpConversion = - MemoryStoreOpConversion; -using StoreF32OpConversion = - MemoryStoreOpConversion; -using SharedStoreF32OpConversion = - MemoryStoreOpConversion; - -/// Conversion pattern for forth.itof (S>F). -/// Pops i64, converts to f64 via sitofp, bitcasts back to i64, pushes. -struct IToFOpConversion : public StackEffectConversion { - using StackEffectConversion::StackEffectConversion; - - FailureOr - rewriteStack(forth::IToFOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - // Load i64 value from top of stack - Value i64Value = rewriter.create(loc, memref, stackPtr); - - // Convert i64 -> f64 via SIToFPOp - Value f64Value = - rewriter.create(loc, rewriter.getF64Type(), i64Value); - - // Bitcast f64 -> i64 for stack storage - Value result = - rewriter.create(loc, rewriter.getI64Type(), f64Value); - - // Store result (SP unchanged — unary op) - rewriter.create(loc, result, memref, stackPtr); - - return stackPtr; - } -}; - -/// Conversion pattern for forth.ftoi (F>S). -/// Pops i64 (f64 bits), bitcasts to f64, converts to i64 via fptosi, pushes. -struct FToIOpConversion : public StackEffectConversion { - using StackEffectConversion::StackEffectConversion; - - FailureOr - rewriteStack(forth::FToIOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - // Load i64 (f64 bit pattern) from top of stack - Value i64Bits = rewriter.create(loc, memref, stackPtr); - - // Bitcast i64 -> f64 - Value f64Value = - rewriter.create(loc, rewriter.getF64Type(), i64Bits); - - // Convert f64 -> i64 via FPToSIOp - Value result = - rewriter.create(loc, rewriter.getI64Type(), f64Value); - - // Store result (SP unchanged — unary op) - rewriter.create(loc, result, memref, stackPtr); - - return stackPtr; - } -}; - -/// Template for converting GPU indexing ops to intrinsic ops. -/// Creates an intrinsic op with the specified name and pushes the value onto -/// the stack. -template -struct IntrinsicOpConversion : public StackEffectConversion { - using Base = StackEffectConversion; - using typename Base::OneToNOpAdaptor; - - IntrinsicOpConversion(const TypeConverter &typeConverter, - MLIRContext *context, StringRef intrinsicName) - : Base(typeConverter, context), intrinsicName(intrinsicName) {} - - FailureOr - rewriteStack(ForthOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - // Create intrinsic op and push onto stack - Value intrinsicValue = rewriter.create( - loc, rewriter.getIndexType(), rewriter.getStringAttr(intrinsicName)); - Value intrinsicI64 = rewriter.create( - loc, rewriter.getI64Type(), intrinsicValue); - Value newSP = pushValue(loc, rewriter, memref, stackPtr, intrinsicI64); - - return newSP; - } - - std::string intrinsicName; -}; - -/// Conversion pattern for forth.global_id operation. -/// Computes global_id = bid-x * bdim-x + tid-x using intrinsics. -struct GlobalIdOpConversion : public StackEffectConversion { - using StackEffectConversion::StackEffectConversion; - - FailureOr - rewriteStack(forth::GlobalIdOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - // Create intrinsic ops for each component - Value bidX = rewriter.create( - loc, rewriter.getIndexType(), rewriter.getStringAttr("bid-x")); - Value bdimX = rewriter.create( - loc, rewriter.getIndexType(), rewriter.getStringAttr("bdim-x")); - Value tidX = rewriter.create( - loc, rewriter.getIndexType(), rewriter.getStringAttr("tid-x")); - - // Compute: bid-x * bdim-x + tid-x - Value product = rewriter.create(loc, bidX, bdimX); - Value globalId = rewriter.create(loc, product, tidX); - Value globalIdI64 = rewriter.create( - loc, rewriter.getI64Type(), globalId); - Value newSP = pushValue(loc, rewriter, memref, stackPtr, globalIdI64); - - return newSP; - } -}; - -/// Conversion pattern for forth.pop_flag operation. -/// Pops top of stack, compares != 0, returns (memref, newSP, i1 flag). -struct PopFlagOpConversion : public OpConversionPattern { - using OpConversionPattern::OpConversionPattern; - - LogicalResult - matchAndRewrite(forth::PopFlagOp op, OneToNOpAdaptor adaptor, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - ValueRange inputStack = adaptor.getOperands()[0]; - Value memref = inputStack[0]; - Value stackPtr = inputStack[1]; - - // Load top value - Value topValue = rewriter.create(loc, memref, stackPtr); - - // Decrement SP - Value one = rewriter.create(loc, 1); - Value newSP = rewriter.create(loc, stackPtr, one); - - // Compare != 0 - Value zero = rewriter.create(loc, 0, 64); - Value flag = rewriter.create(loc, arith::CmpIPredicate::ne, - topValue, zero); - - // Result 0: output_stack -> {memref, newSP} - // Result 1: flag -> i1 (passes through unchanged) - rewriter.replaceOpWithMultiple(op, {{memref, newSP}, {flag}}); - return success(); - } -}; - -/// Conversion pattern for forth.pop operation. -/// Pops top of stack, returns (memref, newSP, i64 value). -struct PopOpConversion : public OpConversionPattern { - using OpConversionPattern::OpConversionPattern; - - LogicalResult - matchAndRewrite(forth::PopOp op, OneToNOpAdaptor adaptor, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - ValueRange inputStack = adaptor.getOperands()[0]; - Value memref = inputStack[0]; - Value stackPtr = inputStack[1]; - - // Load top value - Value topValue = rewriter.create(loc, memref, stackPtr); - - // Decrement SP - Value one = rewriter.create(loc, 1); - Value newSP = rewriter.create(loc, stackPtr, one); - - // Result 0: output_stack -> {memref, newSP} - // Result 1: value -> i64 (passes through unchanged) - rewriter.replaceOpWithMultiple(op, {{memref, newSP}, {topValue}}); - return success(); - } -}; - -/// Conversion pattern for forth.push_value operation. -/// Pushes a dynamic i64 value onto the stack. -struct PushValueOpConversion - : public StackEffectConversion { - using StackEffectConversion::StackEffectConversion; - - FailureOr - rewriteStack(forth::PushValueOp op, OneToNOpAdaptor adaptor, Value memref, - Value stackPtr, - ConversionPatternRewriter &rewriter) const override { - auto loc = op.getLoc(); - - // The value operand (i64) passes through as-is (not a converted type). - Value value = adaptor.getOperands()[1][0]; - - Value newSP = pushValue(loc, rewriter, memref, stackPtr, value); - - return newSP; - } -}; - -/// Conversion pattern for cf::BranchOp with 1:N type conversion. -/// The built-in populateBranchOpInterfaceTypeConversionPattern uses the old -/// ArrayRef signature and crashes on 1:N conversions. -struct BranchOpConversion : public OpConversionPattern { - using OpConversionPattern::OpConversionPattern; - using OneToNOpAdaptor = OpConversionPattern::OneToNOpAdaptor; - - LogicalResult - matchAndRewrite(cf::BranchOp op, OneToNOpAdaptor adaptor, - ConversionPatternRewriter &rewriter) const override { - SmallVector newOperands; - for (ValueRange vals : adaptor.getOperands()) - llvm::append_range(newOperands, vals); - rewriter.replaceOpWithNewOp(op, op.getDest(), newOperands); - return success(); - } -}; - -/// Conversion pattern for cf::CondBranchOp with 1:N type conversion. -struct CondBranchOpConversion : public OpConversionPattern { - using OpConversionPattern::OpConversionPattern; - using OneToNOpAdaptor = OpConversionPattern::OneToNOpAdaptor; - - LogicalResult - matchAndRewrite(cf::CondBranchOp op, OneToNOpAdaptor adaptor, - ConversionPatternRewriter &rewriter) const override { - SmallVector trueOperands, falseOperands; - - Value condition = adaptor.getOperands()[0][0]; - - unsigned trueCount = op.getTrueDestOperands().size(); - for (unsigned i = 1; i <= trueCount; ++i) - llvm::append_range(trueOperands, adaptor.getOperands()[i]); - - for (unsigned i = 1 + trueCount; i < adaptor.getOperands().size(); ++i) - llvm::append_range(falseOperands, adaptor.getOperands()[i]); - - rewriter.replaceOpWithNewOp( - op, condition, op.getTrueDest(), trueOperands, op.getFalseDest(), - falseOperands); - return success(); - } -}; - -/// Conversion pass implementation. -struct ConvertForthToMemRefPass - : public impl::ConvertForthToMemRefBase { - void runOnOperation() override { - auto *context = &getContext(); - auto module = getOperation(); - - // Dialect conversion does not rewrite unreachable blocks. Remove parser - // continuations before converting !forth.stack values 1:N. - IRRewriter rewriter(context); - module.walk([&](func::FuncOp funcOp) { - (void)eraseUnreachableBlocks(rewriter, funcOp->getRegions()); - }); - - ConversionTarget target(*context); - - // Mark Forth dialect as illegal (to be converted) - target.addIllegalDialect(); - - // Mark MemRef, Arith, LLVM, and CF dialects as legal - target.addLegalDialect(); - - // Mark IntrinsicOp and BarrierOp as legal (to be lowered later) - target.addLegalOp(); - target.addLegalOp(); - - // Use dynamic legality for func operations to ensure they're properly - // converted - target.addDynamicallyLegalOp([&](func::FuncOp op) { - auto isStack = [](Type t) { return isa(t); }; - if (llvm::any_of(op.getFunctionType().getInputs(), isStack) || - llvm::any_of(op.getFunctionType().getResults(), isStack)) - return false; - // Also check non-entry block args (CF control flow) - for (Block &block : op.getFunctionBody()) - if (llvm::any_of(block.getArgumentTypes(), isStack)) - return false; - return true; - }); - - target.addDynamicallyLegalOp([&](func::CallOp op) { - return llvm::none_of(op.getOperandTypes(), - [&](Type t) { return isa(t); }) && - llvm::none_of(op.getResultTypes(), - [&](Type t) { return isa(t); }); - }); - - target.addDynamicallyLegalOp([&](func::ReturnOp op) { - return llvm::none_of(op.getOperandTypes(), - [&](Type t) { return isa(t); }); - }); - - // CF ops are legal but need dynamic legality for type-converted block args - target.addDynamicallyLegalOp( - [&](Operation *op) { - return llvm::none_of(op->getOperandTypes(), - [](Type t) { return isa(t); }); - }); - - ForthToMemRefTypeConverter typeConverter; - RewritePatternSet patterns(context); - - // Add Forth operation conversion patterns - patterns.add< - StackOpConversion, ConstantOpConversion, DupOpConversion, - DropOpConversion, SwapOpConversion, OverOpConversion, RotOpConversion, - NipOpConversion, TuckOpConversion, PickOpConversion, RollOpConversion, - // Integer arithmetic - AddIOpConversion, SubIOpConversion, MulIOpConversion, DivIOpConversion, - ModOpConversion, - // Float arithmetic - AddFOpConversion, SubFOpConversion, MulFOpConversion, DivFOpConversion, - // Float math intrinsics - ExpFOpConversion, SqrtFOpConversion, LogFOpConversion, AbsFOpConversion, - NegFOpConversion, MaxFOpConversion, MinFOpConversion, - // Bitwise - AndOpConversion, OrOpConversion, XorOpConversion, NotOpConversion, - LshiftOpConversion, RshiftOpConversion, - // Integer comparisons - EqIOpConversion, LtIOpConversion, GtIOpConversion, NeIOpConversion, - LeIOpConversion, GeIOpConversion, - // Float comparisons - EqFOpConversion, LtFOpConversion, GtFOpConversion, NeFOpConversion, - LeFOpConversion, GeFOpConversion, - // Other - ZeroEqOpConversion, ParamRefOpConversion, - // Memory ops (int + float, global + shared) - LoadIOpConversion, StoreIOpConversion, LoadFOpConversion, - StoreFOpConversion, SharedLoadIOpConversion, SharedStoreIOpConversion, - SharedLoadFOpConversion, SharedStoreFOpConversion, - // Reduced-width memory ops - LoadI8OpConversion, StoreI8OpConversion, SharedLoadI8OpConversion, - SharedStoreI8OpConversion, LoadI16OpConversion, StoreI16OpConversion, - SharedLoadI16OpConversion, SharedStoreI16OpConversion, - LoadI32OpConversion, StoreI32OpConversion, SharedLoadI32OpConversion, - SharedStoreI32OpConversion, LoadF16OpConversion, StoreF16OpConversion, - SharedLoadF16OpConversion, SharedStoreF16OpConversion, - LoadBF16OpConversion, StoreBF16OpConversion, SharedLoadBF16OpConversion, - SharedStoreBF16OpConversion, LoadF32OpConversion, StoreF32OpConversion, - SharedLoadF32OpConversion, SharedStoreF32OpConversion, - // Type conversions - IToFOpConversion, FToIOpConversion, - // Control flow - PopFlagOpConversion, PopOpConversion, PushValueOpConversion>( - typeConverter, context); - - // Add GPU indexing op conversion patterns - patterns.add>(typeConverter, - context, "tid-x"); - patterns.add>(typeConverter, - context, "tid-y"); - patterns.add>(typeConverter, - context, "tid-z"); - patterns.add>(typeConverter, - context, "bid-x"); - patterns.add>(typeConverter, - context, "bid-y"); - patterns.add>(typeConverter, - context, "bid-z"); - patterns.add>(typeConverter, - context, "bdim-x"); - patterns.add>(typeConverter, - context, "bdim-y"); - patterns.add>(typeConverter, - context, "bdim-z"); - patterns.add>(typeConverter, - context, "gdim-x"); - patterns.add>(typeConverter, - context, "gdim-y"); - patterns.add>(typeConverter, - context, "gdim-z"); - - // GlobalIdOp has custom pattern - patterns.add(typeConverter, context); - - populateFunctionOpInterfaceTypeConversionPattern( - patterns, typeConverter); - - // Custom branch patterns are required for 1:N type conversion. - patterns.add(typeConverter, - context); - populateCallOpTypeConversionPattern(patterns, typeConverter); - populateReturnOpTypeConversionPattern(patterns, typeConverter); - - if (failed(applyPartialConversion(module, target, std::move(patterns)))) - signalPassFailure(); - } -}; - -} // namespace - -std::unique_ptr createConvertForthToMemRefPass() { - return std::make_unique<::mlir::warpforth::ConvertForthToMemRefPass>(); -} - -} // namespace warpforth -} // namespace mlir diff --git a/lib/Conversion/Passes.cpp b/lib/Conversion/Passes.cpp index 2c4b527..dc9a7e3 100644 --- a/lib/Conversion/Passes.cpp +++ b/lib/Conversion/Passes.cpp @@ -15,7 +15,6 @@ #include "mlir/Transforms/Passes.h" #include "warpforth/Conversion/ForthStack/LowerForthStack.h" #include "warpforth/Conversion/ForthToGPU/ForthToGPU.h" -#include "warpforth/Conversion/ForthToMemRef/ForthToMemRef.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" @@ -96,10 +95,8 @@ void buildWarpForthLoweringPipeline(OpPassManager &pm, // precede GPU conversion. pm.addPass(createInlinerPass()); - // Stage 2: Lower the stack. A function the stack lowering cannot take yet - // keeps its Forth ops and falls through to the memref stack. + // Stage 2: Lower the stack to i64 SSA values and a residual buffer pm.addPass(createLowerForthStackPass()); - pm.addPass(createConvertForthToMemRefPass()); // Stage 3: Convert to GPU dialect pm.addPass(createConvertForthToGPUPass()); @@ -156,9 +153,6 @@ void buildWarpForthPipeline(OpPassManager &pm) { void registerConversionPasses() { registerPass( []() -> std::unique_ptr { return createLowerForthStackPass(); }); - registerPass([]() -> std::unique_ptr { - return createConvertForthToMemRefPass(); - }); registerPass( []() -> std::unique_ptr { return createConvertForthToGPUPass(); }); diff --git a/test/Conversion/ForthStack/unknown-stack-user-error.mlir b/test/Conversion/ForthStack/unknown-stack-user-error.mlir new file mode 100644 index 0000000..5be561a --- /dev/null +++ b/test/Conversion/ForthStack/unknown-stack-user-error.mlir @@ -0,0 +1,10 @@ +// RUN: %not %warpforth-opt --allow-unregistered-dialect --lower-forth-stack %s 2>&1 | %FileCheck %s + +// Only Forth words and branches may use a stack, so an op outside the table is +// an error instead of a stack value with no cells. +// CHECK: error: 'test.consume' op uses a !forth.stack but has no stack-word row +func.func @main() { + %0 = forth.stack !forth.stack + "test.consume"(%0) : (!forth.stack) -> () + return +} diff --git a/test/Conversion/ForthToGPU/non-kernel-function-error.mlir b/test/Conversion/ForthToGPU/non-kernel-function-error.mlir new file mode 100644 index 0000000..870f0ed --- /dev/null +++ b/test/Conversion/ForthToGPU/non-kernel-function-error.mlir @@ -0,0 +1,14 @@ +// RUN: %not %warpforth-opt --convert-forth-to-gpu %s 2>&1 | %FileCheck %s + +// Only the kernel reaches GPU conversion, so any other function, such as a +// word that survived inlining, is an error. +// CHECK: error: @helper is not the kernel; inline every Forth word before --convert-forth-to-gpu + +module { + func.func private @helper(%arg0: memref<256xi64>, %arg1: index) -> (memref<256xi64>, index) { + return %arg0, %arg1 : memref<256xi64>, index + } + func.func private @main() attributes {forth.kernel} { + return + } +} diff --git a/test/Conversion/ForthToGPU/private-functions.mlir b/test/Conversion/ForthToGPU/private-functions.mlir deleted file mode 100644 index ed22b83..0000000 --- a/test/Conversion/ForthToGPU/private-functions.mlir +++ /dev/null @@ -1,22 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-gpu %s | %FileCheck %s - -// CHECK: gpu.module @warpforth_module -// Main gets kernel attribute -// CHECK: gpu.func @main() kernel -// CHECK: gpu.return - -// Private helper moved into gpu.module without kernel attr -// CHECK: func.func private @helper -// CHECK-NOT: kernel -// CHECK: return - -module { - func.func private @helper(%arg0: memref<256xi64>, %arg1: index) -> (memref<256xi64>, index) { - return %arg0, %arg1 : memref<256xi64>, index - } - func.func private @main() attributes {forth.kernel} { - %alloca = memref.alloca() : memref<256xi64> - %c0 = arith.constant 0 : index - return - } -} diff --git a/test/Conversion/ForthToMemRef/arithmetic.mlir b/test/Conversion/ForthToMemRef/arithmetic.mlir deleted file mode 100644 index a0bbf4b..0000000 --- a/test/Conversion/ForthToMemRef/arithmetic.mlir +++ /dev/null @@ -1,52 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// CHECK-LABEL: func.func private @main - -// add: pop two, arith.addi, store result -// CHECK: memref.load -// CHECK: arith.subi -// CHECK: memref.load -// CHECK: arith.addi %{{.*}}, %{{.*}} : i64 -// CHECK: memref.store - -// sub: pop two, arith.subi -// CHECK: memref.load -// CHECK: memref.load -// CHECK: arith.subi %{{.*}}, %{{.*}} : i64 -// CHECK: memref.store - -// mul: pop two, arith.muli -// CHECK: memref.load -// CHECK: memref.load -// CHECK: arith.muli %{{.*}}, %{{.*}} : i64 -// CHECK: memref.store - -// div: pop two, arith.divsi -// CHECK: memref.load -// CHECK: memref.load -// CHECK: arith.divsi %{{.*}}, %{{.*}} : i64 -// CHECK: memref.store - -// mod: pop two, arith.remsi -// CHECK: memref.load -// CHECK: memref.load -// CHECK: arith.remsi %{{.*}}, %{{.*}} : i64 -// CHECK: memref.store - -module { - func.func private @main() { - %0 = forth.stack !forth.stack - %1 = forth.constant %0(10 : i64) : !forth.stack -> !forth.stack - %2 = forth.constant %1(20 : i64) : !forth.stack -> !forth.stack - %3 = forth.addi %2 : !forth.stack -> !forth.stack - %4 = forth.constant %3(3 : i64) : !forth.stack -> !forth.stack - %5 = forth.subi %4 : !forth.stack -> !forth.stack - %6 = forth.constant %5(4 : i64) : !forth.stack -> !forth.stack - %7 = forth.muli %6 : !forth.stack -> !forth.stack - %8 = forth.constant %7(2 : i64) : !forth.stack -> !forth.stack - %9 = forth.divi %8 : !forth.stack -> !forth.stack - %10 = forth.constant %9(5 : i64) : !forth.stack -> !forth.stack - %11 = forth.mod %10 : !forth.stack -> !forth.stack - return - } -} diff --git a/test/Conversion/ForthToMemRef/barrier.mlir b/test/Conversion/ForthToMemRef/barrier.mlir deleted file mode 100644 index 68799a6..0000000 --- a/test/Conversion/ForthToMemRef/barrier.mlir +++ /dev/null @@ -1,9 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s -// CHECK-LABEL: func.func private @main -// CHECK: forth.barrier -func.func private @main() { - %0 = forth.stack !forth.stack - forth.barrier - forth.drop %0 : !forth.stack -> !forth.stack - return -} diff --git a/test/Conversion/ForthToMemRef/begin-until.mlir b/test/Conversion/ForthToMemRef/begin-until.mlir deleted file mode 100644 index e9b5b28..0000000 --- a/test/Conversion/ForthToMemRef/begin-until.mlir +++ /dev/null @@ -1,46 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// Test: BEGIN...UNTIL loop conversion to memref with CF-based control flow -// Forth: 10 BEGIN 1 - DUP 0= UNTIL - -// CHECK-LABEL: func.func private @main - -// Stack allocation and literal 10 push: -// CHECK: %[[ALLOCA:.*]] = memref.alloca() : memref<256xi64> -// CHECK: %[[C10:.*]] = arith.constant 10 : i64 -// CHECK: memref.store %[[C10]], %[[ALLOCA]] -// CHECK: cf.br ^bb1 - -// Loop body: push 1, subtract, dup, zero_eq, pop_flag, cond_br -// CHECK: ^bb1(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: arith.constant 1 : i64 -// CHECK: memref.store -// CHECK: arith.subi -// CHECK: memref.store -// CHECK: memref.store -// CHECK: arith.cmpi eq -// CHECK: arith.extsi -// CHECK: memref.store -// CHECK: arith.cmpi ne -// CHECK: cf.cond_br %{{.*}}, ^bb2(%{{.*}}: memref<256xi64>, index), ^bb1(%{{.*}}: memref<256xi64>, index) - -// Exit block -// CHECK: ^bb2(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: return - -module { - func.func private @main() { - %0 = forth.stack !forth.stack - %1 = forth.constant %0(10 : i64) : !forth.stack -> !forth.stack - cf.br ^bb1(%1 : !forth.stack) - ^bb1(%2: !forth.stack): - %3 = forth.constant %2(1 : i64) : !forth.stack -> !forth.stack - %4 = forth.subi %3 : !forth.stack -> !forth.stack - %5 = forth.dup %4 : !forth.stack -> !forth.stack - %6 = forth.zero_eq %5 : !forth.stack -> !forth.stack - %output_stack, %flag = forth.pop_flag %6 : !forth.stack -> !forth.stack, i1 - cf.cond_br %flag, ^bb2(%output_stack : !forth.stack), ^bb1(%output_stack : !forth.stack) - ^bb2(%7: !forth.stack): - return - } -} diff --git a/test/Conversion/ForthToMemRef/begin-while-repeat.mlir b/test/Conversion/ForthToMemRef/begin-while-repeat.mlir deleted file mode 100644 index 99c5c2e..0000000 --- a/test/Conversion/ForthToMemRef/begin-while-repeat.mlir +++ /dev/null @@ -1,56 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// Test: BEGIN...WHILE...REPEAT loop conversion to memref with CF-based control flow -// Forth: 10 BEGIN DUP 0 > WHILE 1 - REPEAT - -// CHECK-LABEL: func.func private @main - -// Stack allocation and literal 10 push: -// CHECK: %[[ALLOCA:.*]] = memref.alloca() : memref<256xi64> -// CHECK: %[[C10:.*]] = arith.constant 10 : i64 -// CHECK: memref.store %[[C10]], %[[ALLOCA]] -// CHECK: cf.br ^bb1 - -// Condition block: DUP, push 0, compare >, pop_flag, cond_br -// CHECK: ^bb1(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: memref.load -// CHECK: memref.store -// CHECK: arith.constant 0 : i64 -// CHECK: memref.store -// CHECK: arith.cmpi sgt -// CHECK: arith.extsi -// CHECK: memref.store -// CHECK: arith.cmpi ne -// CHECK: cf.cond_br %{{.*}}, ^bb2(%{{.*}}: memref<256xi64>, index), ^bb3(%{{.*}}: memref<256xi64>, index) - -// Body block: push 1, subtract, branch back to condition -// CHECK: ^bb2(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: arith.constant 1 : i64 -// CHECK: memref.store -// CHECK: arith.subi -// CHECK: memref.store -// CHECK: cf.br ^bb1 - -// Exit block -// CHECK: ^bb3(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: return - -module { - func.func private @main() { - %0 = forth.stack !forth.stack - %1 = forth.constant %0(10 : i64) : !forth.stack -> !forth.stack - cf.br ^bb1(%1 : !forth.stack) - ^bb1(%2: !forth.stack): - %3 = forth.dup %2 : !forth.stack -> !forth.stack - %4 = forth.constant %3(0 : i64) : !forth.stack -> !forth.stack - %5 = forth.gti %4 : !forth.stack -> !forth.stack - %output_stack, %flag = forth.pop_flag %5 : !forth.stack -> !forth.stack, i1 - cf.cond_br %flag, ^bb2(%output_stack : !forth.stack), ^bb3(%output_stack : !forth.stack) - ^bb2(%6: !forth.stack): - %7 = forth.constant %6(1 : i64) : !forth.stack -> !forth.stack - %8 = forth.subi %7 : !forth.stack -> !forth.stack - cf.br ^bb1(%8 : !forth.stack) - ^bb3(%9: !forth.stack): - return - } -} diff --git a/test/Conversion/ForthToMemRef/bitwise.mlir b/test/Conversion/ForthToMemRef/bitwise.mlir deleted file mode 100644 index 243546a..0000000 --- a/test/Conversion/ForthToMemRef/bitwise.mlir +++ /dev/null @@ -1,64 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// CHECK-LABEL: func.func private @main - -// and: pop two, arith.andi, store result -// CHECK: memref.load -// CHECK: arith.subi -// CHECK: memref.load -// CHECK: arith.andi %{{.*}}, %{{.*}} : i64 -// CHECK: memref.store - -// or: pop two, arith.ori, store result -// CHECK: memref.load -// CHECK: memref.load -// CHECK: arith.ori %{{.*}}, %{{.*}} : i64 -// CHECK: memref.store - -// xor: pop two, arith.xori, store result -// CHECK: memref.load -// CHECK: memref.load -// CHECK: arith.xori %{{.*}}, %{{.*}} : i64 -// CHECK: memref.store - -// not: load one value, xori with -1, store at same SP -// CHECK: memref.load -// CHECK: arith.constant -1 : i64 -// CHECK: arith.xori %{{.*}}, %{{.*}} : i64 -// CHECK: memref.store - -// lshift: pop two, arith.shli, store result -// CHECK: memref.load -// CHECK: memref.load -// CHECK: arith.shli %{{.*}}, %{{.*}} : i64 -// CHECK: memref.store - -// rshift: pop two, arith.shrui, store result -// CHECK: memref.load -// CHECK: memref.load -// CHECK: arith.shrui %{{.*}}, %{{.*}} : i64 -// CHECK: memref.store - -module { - func.func private @main() { - %0 = forth.stack !forth.stack - %1 = forth.constant %0(3 : i64) : !forth.stack -> !forth.stack - %2 = forth.constant %1(5 : i64) : !forth.stack -> !forth.stack - %3 = forth.and %2 : !forth.stack -> !forth.stack - %4 = forth.constant %3(7 : i64) : !forth.stack -> !forth.stack - %5 = forth.constant %4(8 : i64) : !forth.stack -> !forth.stack - %6 = forth.or %5 : !forth.stack -> !forth.stack - %7 = forth.constant %6(15 : i64) : !forth.stack -> !forth.stack - %8 = forth.constant %7(3 : i64) : !forth.stack -> !forth.stack - %9 = forth.xor %8 : !forth.stack -> !forth.stack - %10 = forth.constant %9(42 : i64) : !forth.stack -> !forth.stack - %11 = forth.not %10 : !forth.stack -> !forth.stack - %12 = forth.constant %11(1 : i64) : !forth.stack -> !forth.stack - %13 = forth.constant %12(4 : i64) : !forth.stack -> !forth.stack - %14 = forth.lshift %13 : !forth.stack -> !forth.stack - %15 = forth.constant %14(256 : i64) : !forth.stack -> !forth.stack - %16 = forth.constant %15(2 : i64) : !forth.stack -> !forth.stack - %17 = forth.rshift %16 : !forth.stack -> !forth.stack - return - } -} diff --git a/test/Conversion/ForthToMemRef/comparison.mlir b/test/Conversion/ForthToMemRef/comparison.mlir deleted file mode 100644 index 4a546b2..0000000 --- a/test/Conversion/ForthToMemRef/comparison.mlir +++ /dev/null @@ -1,80 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// CHECK-LABEL: func.func private @main - -// eq: load two values, arith.cmpi eq, extsi to i64, store -// CHECK: memref.load -// CHECK: arith.subi -// CHECK: memref.load -// CHECK: arith.cmpi eq, %{{.*}}, %{{.*}} : i64 -// CHECK: arith.extsi %{{.*}} : i1 to i64 -// CHECK: memref.store - -// lt: load two values, arith.cmpi slt, extsi to i64, store -// CHECK: memref.load -// CHECK: memref.load -// CHECK: arith.cmpi slt, %{{.*}}, %{{.*}} : i64 -// CHECK: arith.extsi %{{.*}} : i1 to i64 -// CHECK: memref.store - -// gt: load two values, arith.cmpi sgt, extsi to i64, store -// CHECK: memref.load -// CHECK: memref.load -// CHECK: arith.cmpi sgt, %{{.*}}, %{{.*}} : i64 -// CHECK: arith.extsi %{{.*}} : i1 to i64 -// CHECK: memref.store - -// zero_eq: load one value, compare with 0, extsi, store at same SP -// CHECK: memref.load -// CHECK: arith.constant 0 : i64 -// CHECK: arith.cmpi eq, %{{.*}}, %{{.*}} : i64 -// CHECK: arith.extsi %{{.*}} : i1 to i64 -// CHECK: memref.store - -// ne: load two values, arith.cmpi ne, extsi to i64, store -// CHECK: memref.load -// CHECK: memref.load -// CHECK: arith.cmpi ne, %{{.*}}, %{{.*}} : i64 -// CHECK: arith.extsi %{{.*}} : i1 to i64 -// CHECK: memref.store - -// le: load two values, arith.cmpi sle, extsi to i64, store -// CHECK: memref.load -// CHECK: memref.load -// CHECK: arith.cmpi sle, %{{.*}}, %{{.*}} : i64 -// CHECK: arith.extsi %{{.*}} : i1 to i64 -// CHECK: memref.store - -// ge: load two values, arith.cmpi sge, extsi to i64, store -// CHECK: memref.load -// CHECK: memref.load -// CHECK: arith.cmpi sge, %{{.*}}, %{{.*}} : i64 -// CHECK: arith.extsi %{{.*}} : i1 to i64 -// CHECK: memref.store - -module { - func.func private @main() { - %0 = forth.stack !forth.stack - %1 = forth.constant %0(1 : i64) : !forth.stack -> !forth.stack - %2 = forth.constant %1(2 : i64) : !forth.stack -> !forth.stack - %3 = forth.eqi %2 : !forth.stack -> !forth.stack - %4 = forth.constant %3(3 : i64) : !forth.stack -> !forth.stack - %5 = forth.constant %4(4 : i64) : !forth.stack -> !forth.stack - %6 = forth.lti %5 : !forth.stack -> !forth.stack - %7 = forth.constant %6(5 : i64) : !forth.stack -> !forth.stack - %8 = forth.constant %7(6 : i64) : !forth.stack -> !forth.stack - %9 = forth.gti %8 : !forth.stack -> !forth.stack - %10 = forth.constant %9(0 : i64) : !forth.stack -> !forth.stack - %11 = forth.zero_eq %10 : !forth.stack -> !forth.stack - %12 = forth.constant %11(7 : i64) : !forth.stack -> !forth.stack - %13 = forth.constant %12(8 : i64) : !forth.stack -> !forth.stack - %14 = forth.nei %13 : !forth.stack -> !forth.stack - %15 = forth.constant %14(9 : i64) : !forth.stack -> !forth.stack - %16 = forth.constant %15(10 : i64) : !forth.stack -> !forth.stack - %17 = forth.lei %16 : !forth.stack -> !forth.stack - %18 = forth.constant %17(11 : i64) : !forth.stack -> !forth.stack - %19 = forth.constant %18(12 : i64) : !forth.stack -> !forth.stack - %20 = forth.gei %19 : !forth.stack -> !forth.stack - return - } -} diff --git a/test/Conversion/ForthToMemRef/control-flow.mlir b/test/Conversion/ForthToMemRef/control-flow.mlir deleted file mode 100644 index 50331cb..0000000 --- a/test/Conversion/ForthToMemRef/control-flow.mlir +++ /dev/null @@ -1,70 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// Test: IF/ELSE/THEN and IF/THEN conversion to memref with CF-based control flow. -// The non-entry block checks cover function-region signature conversion. -// Forth: 1 IF 42 ELSE 99 THEN 0 IF 7 THEN - -// CHECK-LABEL: func.func private @main - -// Stack allocation and literal 1 push: -// CHECK: %[[ALLOCA:.*]] = memref.alloca() : memref<256xi64> -// CHECK: %[[C1:.*]] = arith.constant 1 : i64 -// CHECK: memref.store %[[C1]], %[[ALLOCA]] - -// Pop flag and conditional branch: -// CHECK: %[[FLAG1:.*]] = memref.load -// CHECK: %[[ZERO1:.*]] = arith.constant 0 : i64 -// CHECK: %[[COND1:.*]] = arith.cmpi ne, %[[FLAG1]], %[[ZERO1]] : i64 -// CHECK: cf.cond_br %[[COND1]], ^bb1(%[[ALLOCA]], %{{.*}} : memref<256xi64>, index), ^bb2(%[[ALLOCA]], %{{.*}} : memref<256xi64>, index) - -// Then branch: push 42 -// CHECK: ^bb1(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: arith.constant 42 : i64 -// CHECK: memref.store -// CHECK: cf.br ^bb3 - -// Else branch: push 99 -// CHECK: ^bb2(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: arith.constant 99 : i64 -// CHECK: memref.store -// CHECK: cf.br ^bb3 - -// Merge block: push 0, pop flag, second conditional branch -// CHECK: ^bb3(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: arith.constant 0 : i64 -// CHECK: memref.store -// CHECK: arith.cmpi ne -// CHECK: cf.cond_br - -// Second IF true branch: push 7 -// CHECK: ^bb4(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: arith.constant 7 : i64 -// CHECK: memref.store - -// Final merge and return -// CHECK: ^bb5(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: return - -module { - func.func private @main() { - %0 = forth.stack !forth.stack - %1 = forth.constant %0(1 : i64) : !forth.stack -> !forth.stack - %output_stack, %flag = forth.pop_flag %1 : !forth.stack -> !forth.stack, i1 - cf.cond_br %flag, ^bb1(%output_stack : !forth.stack), ^bb2(%output_stack : !forth.stack) - ^bb1(%2: !forth.stack): - %3 = forth.constant %2(42 : i64) : !forth.stack -> !forth.stack - cf.br ^bb3(%3 : !forth.stack) - ^bb2(%4: !forth.stack): - %5 = forth.constant %4(99 : i64) : !forth.stack -> !forth.stack - cf.br ^bb3(%5 : !forth.stack) - ^bb3(%6: !forth.stack): - %7 = forth.constant %6(0 : i64) : !forth.stack -> !forth.stack - %output_stack_0, %flag_1 = forth.pop_flag %7 : !forth.stack -> !forth.stack, i1 - cf.cond_br %flag_1, ^bb4(%output_stack_0 : !forth.stack), ^bb5(%output_stack_0 : !forth.stack) - ^bb4(%8: !forth.stack): - %9 = forth.constant %8(7 : i64) : !forth.stack -> !forth.stack - cf.br ^bb5(%9 : !forth.stack) - ^bb5(%10: !forth.stack): - return - } -} diff --git a/test/Conversion/ForthToMemRef/do-loop.mlir b/test/Conversion/ForthToMemRef/do-loop.mlir deleted file mode 100644 index b196aff..0000000 --- a/test/Conversion/ForthToMemRef/do-loop.mlir +++ /dev/null @@ -1,71 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// Test: DO...LOOP with I conversion to memref with post-test crossing check -// Forth: 10 0 DO I LOOP - -// CHECK-LABEL: func.func private @main - -// Stack allocation and push 10, 0: -// CHECK: %[[ALLOCA:.*]] = memref.alloca() : memref<256xi64> -// CHECK: arith.constant 10 : i64 -// CHECK: memref.store -// CHECK: arith.constant 0 : i64 -// CHECK: memref.store - -// Pop start and limit from stack: -// CHECK: memref.load -// CHECK: arith.subi -// CHECK: memref.load -// CHECK: arith.subi - -// Loop counter alloca and initialization: -// CHECK: %[[COUNTER:.*]] = memref.alloca() : memref<1xi64> -// CHECK: memref.store %{{.*}}, %[[COUNTER]] -// CHECK: cf.br ^bb1 - -// Loop body: push I (load counter, push to stack), crossing test -// CHECK: ^bb1(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: memref.load %[[COUNTER]] -// CHECK: memref.store -// CHECK: arith.addi -// CHECK: memref.store %{{.*}}, %[[COUNTER]] -// CHECK: arith.subi -// CHECK: arith.subi -// CHECK: arith.xori -// CHECK: arith.cmpi slt -// CHECK: cf.cond_br - -// Exit block -// CHECK: ^bb2(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: return - -module { - func.func private @main() { - %0 = forth.stack !forth.stack - %1 = forth.constant %0(10 : i64) : !forth.stack -> !forth.stack - %2 = forth.constant %1(0 : i64) : !forth.stack -> !forth.stack - %output_stack, %value = forth.pop %2 : !forth.stack -> !forth.stack, i64 - %output_stack_0, %value_1 = forth.pop %output_stack : !forth.stack -> !forth.stack, i64 - %alloca = memref.alloca() : memref<1xi64> - %c0 = arith.constant 0 : index - memref.store %value, %alloca[%c0] : memref<1xi64> - cf.br ^bb1(%output_stack_0 : !forth.stack) - ^bb1(%3: !forth.stack): - %c0_2 = arith.constant 0 : index - %4 = memref.load %alloca[%c0_2] : memref<1xi64> - %5 = forth.push_value %3, %4 : !forth.stack, i64 -> !forth.stack - %c1_i64 = arith.constant 1 : i64 - %c0_3 = arith.constant 0 : index - %6 = memref.load %alloca[%c0_3] : memref<1xi64> - %7 = arith.addi %6, %c1_i64 : i64 - memref.store %7, %alloca[%c0_3] : memref<1xi64> - %8 = arith.subi %6, %value_1 : i64 - %9 = arith.subi %7, %value_1 : i64 - %10 = arith.xori %8, %9 : i64 - %c0_i64 = arith.constant 0 : i64 - %11 = arith.cmpi slt, %10, %c0_i64 : i64 - cf.cond_br %11, ^bb2(%5 : !forth.stack), ^bb1(%5 : !forth.stack) - ^bb2(%12: !forth.stack): - return - } -} diff --git a/test/Conversion/ForthToMemRef/float-arithmetic.mlir b/test/Conversion/ForthToMemRef/float-arithmetic.mlir deleted file mode 100644 index 638b9b6..0000000 --- a/test/Conversion/ForthToMemRef/float-arithmetic.mlir +++ /dev/null @@ -1,44 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// CHECK-LABEL: func.func private @main - -// addf: pop two, bitcast to f64, arith.addf, bitcast back, store -// CHECK: memref.load -// CHECK: arith.subi -// CHECK: memref.load -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: arith.addf %{{.*}}, %{{.*}} : f64 -// CHECK: arith.bitcast %{{.*}} : f64 to i64 -// CHECK: memref.store - -// subf: bitcast, subf, bitcast -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: arith.subf %{{.*}}, %{{.*}} : f64 -// CHECK: arith.bitcast %{{.*}} : f64 to i64 - -// mulf: bitcast, mulf, bitcast -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: arith.mulf %{{.*}}, %{{.*}} : f64 -// CHECK: arith.bitcast %{{.*}} : f64 to i64 - -// divf: bitcast, divf, bitcast -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: arith.divf %{{.*}}, %{{.*}} : f64 -// CHECK: arith.bitcast %{{.*}} : f64 to i64 - -module { - func.func private @main() { - %0 = forth.stack !forth.stack - %1 = forth.constant %0(1.000000e+00 : f64) : !forth.stack -> !forth.stack - %2 = forth.constant %1(2.000000e+00 : f64) : !forth.stack -> !forth.stack - %3 = forth.addf %2 : !forth.stack -> !forth.stack - %4 = forth.subf %3 : !forth.stack -> !forth.stack - %5 = forth.mulf %4 : !forth.stack -> !forth.stack - %6 = forth.divf %5 : !forth.stack -> !forth.stack - return - } -} diff --git a/test/Conversion/ForthToMemRef/float-math-intrinsics.mlir b/test/Conversion/ForthToMemRef/float-math-intrinsics.mlir deleted file mode 100644 index 3153538..0000000 --- a/test/Conversion/ForthToMemRef/float-math-intrinsics.mlir +++ /dev/null @@ -1,70 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// CHECK-LABEL: func.func private @main - -// expf: load, bitcast i64->f64, math.exp, bitcast f64->i64, store (SP unchanged) -// CHECK: memref.load -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: math.exp %{{.*}} : f64 -// CHECK: arith.bitcast %{{.*}} : f64 to i64 -// CHECK: memref.store - -// sqrtf: load, bitcast, math.sqrt, bitcast, store -// CHECK: memref.load -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: math.sqrt %{{.*}} : f64 -// CHECK: arith.bitcast %{{.*}} : f64 to i64 -// CHECK: memref.store - -// logf: load, bitcast, math.log, bitcast, store -// CHECK: memref.load -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: math.log %{{.*}} : f64 -// CHECK: arith.bitcast %{{.*}} : f64 to i64 -// CHECK: memref.store - -// absf: load, bitcast, math.absf, bitcast, store -// CHECK: memref.load -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: math.absf %{{.*}} : f64 -// CHECK: arith.bitcast %{{.*}} : f64 to i64 -// CHECK: memref.store - -// negf: load, bitcast, arith.negf, bitcast, store -// CHECK: memref.load -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: arith.negf %{{.*}} : f64 -// CHECK: arith.bitcast %{{.*}} : f64 to i64 -// CHECK: memref.store - -// maxf: binary — pop two, bitcast, arith.maximumf, bitcast, store -// CHECK: memref.load -// CHECK: arith.subi -// CHECK: memref.load -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: arith.maximumf %{{.*}}, %{{.*}} : f64 -// CHECK: arith.bitcast %{{.*}} : f64 to i64 -// CHECK: memref.store - -// minf: binary — pop two, bitcast, arith.minimumf, bitcast, store -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: arith.minimumf %{{.*}}, %{{.*}} : f64 -// CHECK: arith.bitcast %{{.*}} : f64 to i64 - -module { - func.func private @main() { - %0 = forth.stack !forth.stack - %1 = forth.constant %0(1.000000e+00 : f64) : !forth.stack -> !forth.stack - %2 = forth.expf %1 : !forth.stack -> !forth.stack - %3 = forth.sqrtf %2 : !forth.stack -> !forth.stack - %4 = forth.logf %3 : !forth.stack -> !forth.stack - %5 = forth.absf %4 : !forth.stack -> !forth.stack - %6 = forth.negf %5 : !forth.stack -> !forth.stack - %7 = forth.constant %6(2.000000e+00 : f64) : !forth.stack -> !forth.stack - %8 = forth.maxf %7 : !forth.stack -> !forth.stack - %9 = forth.minf %8 : !forth.stack -> !forth.stack - return - } -} diff --git a/test/Conversion/ForthToMemRef/float-memory.mlir b/test/Conversion/ForthToMemRef/float-memory.mlir deleted file mode 100644 index d54f4a8..0000000 --- a/test/Conversion/ForthToMemRef/float-memory.mlir +++ /dev/null @@ -1,29 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// CHECK-LABEL: func.func private @main - -// loadf: load addr, inttoptr global addrspace, llvm.load f64, bitcast f64->i64, store -// CHECK: memref.load -// CHECK: llvm.inttoptr %{{.*}} : i64 to !llvm.ptr<1> -// CHECK: llvm.load %{{.*}} : !llvm.ptr<1> -> f64 -// CHECK: arith.bitcast %{{.*}} : f64 to i64 -// CHECK: memref.store - -// storef: load addr, load value, inttoptr global addrspace, bitcast i64->f64, llvm.store -// CHECK: memref.load -// CHECK: memref.load -// CHECK: llvm.inttoptr %{{.*}} : i64 to !llvm.ptr<1> -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK: llvm.store %{{.*}}, %{{.*}} : f64, !llvm.ptr<1> - -module { - func.func private @main() { - %0 = forth.stack !forth.stack - %1 = forth.constant %0(1000 : i64) : !forth.stack -> !forth.stack - %2 = forth.loadf %1 : !forth.stack -> !forth.stack - %3 = forth.constant %2(3.140000e+00 : f64) : !forth.stack -> !forth.stack - %4 = forth.constant %3(2000 : i64) : !forth.stack -> !forth.stack - %5 = forth.storef %4 : !forth.stack -> !forth.stack - return - } -} diff --git a/test/Conversion/ForthToMemRef/leave.mlir b/test/Conversion/ForthToMemRef/leave.mlir deleted file mode 100644 index d010ed0..0000000 --- a/test/Conversion/ForthToMemRef/leave.mlir +++ /dev/null @@ -1,43 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// Test: DO...LEAVE...LOOP lowers to CF branch to loop exit. -// Forth: 10 0 DO LEAVE LOOP - -// CHECK-LABEL: func.func private @main -// CHECK: %[[STACK:.*]] = memref.alloca() : memref<256xi64> -// CHECK: cf.br ^bb1(%[[STACK]], %{{.*}} : memref<256xi64>, index) -// CHECK: ^bb1(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: cf.cond_br %true, ^bb2(%{{.*}}: memref<256xi64>, index), ^bb3(%{{.*}}: memref<256xi64>, index) -// CHECK: ^bb2(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: return - -module { - func.func private @main() { - %0 = forth.stack !forth.stack - %1 = forth.constant %0(10 : i64) : !forth.stack -> !forth.stack - %2 = forth.constant %1(0 : i64) : !forth.stack -> !forth.stack - %output_stack, %value = forth.pop %2 : !forth.stack -> !forth.stack, i64 - %output_stack_0, %value_1 = forth.pop %output_stack : !forth.stack -> !forth.stack, i64 - %alloca = memref.alloca() : memref<1xi64> - %c0 = arith.constant 0 : index - memref.store %value, %alloca[%c0] : memref<1xi64> - cf.br ^bb1(%output_stack_0 : !forth.stack) - ^bb1(%3: !forth.stack): - %true = arith.constant true - cf.cond_br %true, ^bb2(%3 : !forth.stack), ^bb3(%3 : !forth.stack) - ^bb2(%4: !forth.stack): - return - ^bb3(%5: !forth.stack): - %c1_i64 = arith.constant 1 : i64 - %c0_2 = arith.constant 0 : index - %6 = memref.load %alloca[%c0_2] : memref<1xi64> - %7 = arith.addi %6, %c1_i64 : i64 - memref.store %7, %alloca[%c0_2] : memref<1xi64> - %8 = arith.subi %6, %value_1 : i64 - %9 = arith.subi %7, %value_1 : i64 - %10 = arith.xori %8, %9 : i64 - %c0_i64 = arith.constant 0 : i64 - %11 = arith.cmpi slt, %10, %c0_i64 : i64 - cf.cond_br %11, ^bb2(%5 : !forth.stack), ^bb1(%5 : !forth.stack) - } -} diff --git a/test/Conversion/ForthToMemRef/literal.mlir b/test/Conversion/ForthToMemRef/literal.mlir deleted file mode 100644 index fce38e4..0000000 --- a/test/Conversion/ForthToMemRef/literal.mlir +++ /dev/null @@ -1,17 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// CHECK-LABEL: func.func private @main -// CHECK: memref.alloca() : memref<256xi64> -// CHECK: arith.constant 0 : index -// CHECK: arith.constant 42 : i64 -// CHECK: arith.constant 1 : index -// CHECK: arith.addi %{{.*}}, %{{.*}} : index -// CHECK: memref.store %{{.*}}, %{{.*}}[%{{.*}}] : memref<256xi64> - -module { - func.func private @main() { - %0 = forth.stack !forth.stack - %1 = forth.constant %0(42 : i64) : !forth.stack -> !forth.stack - return - } -} diff --git a/test/Conversion/ForthToMemRef/memory-ops.mlir b/test/Conversion/ForthToMemRef/memory-ops.mlir deleted file mode 100644 index 47f84a6..0000000 --- a/test/Conversion/ForthToMemRef/memory-ops.mlir +++ /dev/null @@ -1,41 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// CHECK-LABEL: func.func private @main - -// load (@): pop address, inttoptr global addrspace, llvm.load, store back -// CHECK: memref.load %{{.*}}[%{{.*}}] : memref<256xi64> -// CHECK: llvm.inttoptr %{{.*}} : i64 to !llvm.ptr<1> -// CHECK: llvm.load %{{.*}} : !llvm.ptr<1> -> i64 -// CHECK: memref.store %{{.*}}, %{{.*}}[%{{.*}}] : memref<256xi64> - -// store (!): pop address, pop value, inttoptr global addrspace, llvm.store -// CHECK: memref.load -// CHECK: arith.subi -// CHECK: memref.load -// CHECK: llvm.inttoptr %{{.*}} : i64 to !llvm.ptr<1> -// CHECK: llvm.store %{{.*}}, %{{.*}} : i64, !llvm.ptr<1> - -// shared load (S@): pop address, inttoptr shared addrspace, llvm.load -// CHECK: llvm.inttoptr %{{.*}} : i64 to !llvm.ptr<3> -// CHECK: llvm.load %{{.*}} : !llvm.ptr<3> -> i64 - -// shared store (S!): pop address + value, inttoptr shared addrspace, llvm.store -// CHECK: llvm.inttoptr %{{.*}} : i64 to !llvm.ptr<3> -// CHECK: llvm.store %{{.*}}, %{{.*}} : i64, !llvm.ptr<3> - -module { - func.func private @main() { - %0 = forth.stack !forth.stack - %1 = forth.constant %0(1 : i64) : !forth.stack -> !forth.stack - %2 = forth.loadi %1 : !forth.stack -> !forth.stack - %3 = forth.constant %2(42 : i64) : !forth.stack -> !forth.stack - %4 = forth.constant %3(100 : i64) : !forth.stack -> !forth.stack - %5 = forth.storei %4 : !forth.stack -> !forth.stack - %6 = forth.constant %5(2 : i64) : !forth.stack -> !forth.stack - %7 = forth.shared_loadi %6 : !forth.stack -> !forth.stack - %8 = forth.constant %7(9 : i64) : !forth.stack -> !forth.stack - %9 = forth.constant %8(3 : i64) : !forth.stack -> !forth.stack - %10 = forth.shared_storei %9 : !forth.stack -> !forth.stack - return - } -} diff --git a/test/Conversion/ForthToMemRef/nested-control-flow.mlir b/test/Conversion/ForthToMemRef/nested-control-flow.mlir deleted file mode 100644 index 8c09f33..0000000 --- a/test/Conversion/ForthToMemRef/nested-control-flow.mlir +++ /dev/null @@ -1,290 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// === Nested IF: 1 IF 2 IF 3 THEN THEN === -// CHECK-LABEL: func.func private @TEST__NESTED__IF -// CHECK: arith.constant 1 : i64 -// CHECK: memref.store -// CHECK: arith.cmpi ne -// CHECK: cf.cond_br %{{.*}}, ^bb1({{.*}}), ^bb2({{.*}}) - -// Inner IF: push 2, pop_flag, cond_br -// CHECK: ^bb1(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: arith.constant 2 : i64 -// CHECK: memref.store -// CHECK: arith.cmpi ne -// CHECK: cf.cond_br %{{.*}}, ^bb3({{.*}}), ^bb4({{.*}}) - -// Outer merge -> return -// CHECK: ^bb2(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: return - -// Inner true: push 3 -// CHECK: ^bb3(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: arith.constant 3 : i64 -// CHECK: memref.store -// CHECK: cf.br ^bb4 - -// Inner merge -> outer merge -// CHECK: ^bb4(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: cf.br ^bb2 - -// === IF inside DO: 10 0 DO I 5 > IF I THEN LOOP === -// CHECK-LABEL: func.func private @TEST__IF__INSIDE__DO - -// DO loop setup: pop start/limit, alloca counter -// CHECK: arith.constant 10 : i64 -// CHECK: arith.constant 0 : i64 -// CHECK: %[[COUNTER1:.*]] = memref.alloca() : memref<1xi64> -// CHECK: memref.store %{{.*}}, %[[COUNTER1]] -// CHECK: cf.br ^bb1 - -// DO loop header: check counter < limit -// CHECK: ^bb1(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: memref.load %[[COUNTER1]] -// CHECK: arith.cmpi slt -// CHECK: cf.cond_br - -// DO loop body: push I, push 5, compare >, pop_flag, cond_br (IF) -// CHECK: ^bb2(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: memref.load %[[COUNTER1]] -// CHECK: memref.store -// CHECK: arith.constant 5 : i64 -// CHECK: arith.cmpi sgt -// CHECK: arith.cmpi ne -// CHECK: cf.cond_br - -// DO loop exit -> return -// CHECK: ^bb3(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: return - -// IF true: push I -// CHECK: ^bb4(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: memref.load %[[COUNTER1]] -// CHECK: memref.store -// CHECK: cf.br ^bb5 - -// IF merge: increment counter, loop back -// CHECK: ^bb5(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: memref.load %[[COUNTER1]] -// CHECK: arith.addi -// CHECK: memref.store %{{.*}}, %[[COUNTER1]] -// CHECK: cf.br ^bb1 - -// === Nested DO with J: 3 0 DO 4 0 DO J I + LOOP LOOP === -// CHECK-LABEL: func.func private @TEST__NESTED__DO__J - -// Outer DO setup -// CHECK: arith.constant 3 : i64 -// CHECK: arith.constant 0 : i64 -// CHECK: %[[OUTER:.*]] = memref.alloca() : memref<1xi64> -// CHECK: memref.store %{{.*}}, %[[OUTER]] -// CHECK: cf.br ^bb1 - -// Outer loop header: check outer counter < outer limit -// CHECK: ^bb1(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: memref.load %[[OUTER]] -// CHECK: arith.cmpi slt -// CHECK: cf.cond_br - -// Outer loop body: inner DO setup (4 0 DO) -// CHECK: ^bb2(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: arith.constant 4 : i64 -// CHECK: arith.constant 0 : i64 -// CHECK: %[[INNER:.*]] = memref.alloca() : memref<1xi64> -// CHECK: memref.store %{{.*}}, %[[INNER]] -// CHECK: cf.br ^bb4 - -// Outer loop exit -> return -// CHECK: ^bb3(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: return - -// Inner loop header: check inner counter < inner limit -// CHECK: ^bb4(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: memref.load %[[INNER]] -// CHECK: arith.cmpi slt -// CHECK: cf.cond_br - -// Inner loop body: J (load outer counter), I (load inner counter), add -// CHECK: ^bb5(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: memref.load %[[OUTER]] -// CHECK: memref.store -// CHECK: memref.load %[[INNER]] -// CHECK: memref.store -// CHECK: arith.addi -// CHECK: memref.store -// CHECK: memref.load %[[INNER]] -// CHECK: arith.addi -// CHECK: memref.store %{{.*}}, %[[INNER]] -// CHECK: cf.br ^bb4 - -// Inner loop exit -> increment outer counter, loop back -// CHECK: ^bb6(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: memref.load %[[OUTER]] -// CHECK: arith.addi -// CHECK: memref.store %{{.*}}, %[[OUTER]] -// CHECK: cf.br ^bb1 - -// === BEGIN/WHILE/REPEAT inside IF: 5 IF BEGIN DUP WHILE 1 - REPEAT THEN === -// CHECK-LABEL: func.func private @TEST__WHILE__INSIDE__IF - -// Push 5, pop_flag, cond_br (IF) -// CHECK: arith.constant 5 : i64 -// CHECK: memref.store -// CHECK: arith.cmpi ne -// CHECK: cf.cond_br %{{.*}}, ^bb1({{.*}}), ^bb2({{.*}}) - -// IF true -> jump to WHILE header -// CHECK: ^bb1(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: cf.br ^bb3 - -// IF false / WHILE exit merge -> return -// CHECK: ^bb2(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: return - -// WHILE condition: DUP, pop_flag, cond_br -// CHECK: ^bb3(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: memref.load -// CHECK: memref.store -// CHECK: arith.cmpi ne -// CHECK: cf.cond_br %{{.*}}, ^bb4({{.*}}), ^bb5({{.*}}) - -// WHILE body: push 1, subtract, loop back -// CHECK: ^bb4(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: arith.constant 1 : i64 -// CHECK: arith.subi -// CHECK: cf.br ^bb3 - -// WHILE exit -> merge with IF false -// CHECK: ^bb5(%{{.*}}: memref<256xi64>, %{{.*}}: index): -// CHECK: cf.br ^bb2 - -module { - func.func private @TEST__NESTED__IF(%arg0: !forth.stack) -> !forth.stack { - %0 = forth.constant %arg0(1 : i64) : !forth.stack -> !forth.stack - %output_stack, %flag = forth.pop_flag %0 : !forth.stack -> !forth.stack, i1 - cf.cond_br %flag, ^bb1(%output_stack : !forth.stack), ^bb2(%output_stack : !forth.stack) - ^bb1(%1: !forth.stack): - %2 = forth.constant %1(2 : i64) : !forth.stack -> !forth.stack - %output_stack_0, %flag_1 = forth.pop_flag %2 : !forth.stack -> !forth.stack, i1 - cf.cond_br %flag_1, ^bb3(%output_stack_0 : !forth.stack), ^bb4(%output_stack_0 : !forth.stack) - ^bb2(%3: !forth.stack): - return %3 : !forth.stack - ^bb3(%4: !forth.stack): - %5 = forth.constant %4(3 : i64) : !forth.stack -> !forth.stack - cf.br ^bb4(%5 : !forth.stack) - ^bb4(%6: !forth.stack): - cf.br ^bb2(%6 : !forth.stack) - } - func.func private @TEST__IF__INSIDE__DO(%arg0: !forth.stack) -> !forth.stack { - %0 = forth.constant %arg0(10 : i64) : !forth.stack -> !forth.stack - %1 = forth.constant %0(0 : i64) : !forth.stack -> !forth.stack - %output_stack, %value = forth.pop %1 : !forth.stack -> !forth.stack, i64 - %output_stack_0, %value_1 = forth.pop %output_stack : !forth.stack -> !forth.stack, i64 - %alloca = memref.alloca() : memref<1xi64> - %c0 = arith.constant 0 : index - memref.store %value, %alloca[%c0] : memref<1xi64> - cf.br ^bb1(%output_stack_0 : !forth.stack) - ^bb1(%2: !forth.stack): - %c0_2 = arith.constant 0 : index - %3 = memref.load %alloca[%c0_2] : memref<1xi64> - %4 = arith.cmpi slt, %3, %value_1 : i64 - cf.cond_br %4, ^bb2(%2 : !forth.stack), ^bb3(%2 : !forth.stack) - ^bb2(%5: !forth.stack): - %c0_3 = arith.constant 0 : index - %6 = memref.load %alloca[%c0_3] : memref<1xi64> - %7 = forth.push_value %5, %6 : !forth.stack, i64 -> !forth.stack - %8 = forth.constant %7(5 : i64) : !forth.stack -> !forth.stack - %9 = forth.gti %8 : !forth.stack -> !forth.stack - %output_stack_4, %flag = forth.pop_flag %9 : !forth.stack -> !forth.stack, i1 - cf.cond_br %flag, ^bb4(%output_stack_4 : !forth.stack), ^bb5(%output_stack_4 : !forth.stack) - ^bb3(%10: !forth.stack): - return %10 : !forth.stack - ^bb4(%11: !forth.stack): - %c0_5 = arith.constant 0 : index - %12 = memref.load %alloca[%c0_5] : memref<1xi64> - %13 = forth.push_value %11, %12 : !forth.stack, i64 -> !forth.stack - cf.br ^bb5(%13 : !forth.stack) - ^bb5(%14: !forth.stack): - %c0_6 = arith.constant 0 : index - %15 = memref.load %alloca[%c0_6] : memref<1xi64> - %c1_i64 = arith.constant 1 : i64 - %16 = arith.addi %15, %c1_i64 : i64 - memref.store %16, %alloca[%c0_6] : memref<1xi64> - cf.br ^bb1(%14 : !forth.stack) - } - func.func private @TEST__NESTED__DO__J(%arg0: !forth.stack) -> !forth.stack { - %0 = forth.constant %arg0(3 : i64) : !forth.stack -> !forth.stack - %1 = forth.constant %0(0 : i64) : !forth.stack -> !forth.stack - %output_stack, %value = forth.pop %1 : !forth.stack -> !forth.stack, i64 - %output_stack_0, %value_1 = forth.pop %output_stack : !forth.stack -> !forth.stack, i64 - %alloca = memref.alloca() : memref<1xi64> - %c0 = arith.constant 0 : index - memref.store %value, %alloca[%c0] : memref<1xi64> - cf.br ^bb1(%output_stack_0 : !forth.stack) - ^bb1(%2: !forth.stack): - %c0_2 = arith.constant 0 : index - %3 = memref.load %alloca[%c0_2] : memref<1xi64> - %4 = arith.cmpi slt, %3, %value_1 : i64 - cf.cond_br %4, ^bb2(%2 : !forth.stack), ^bb3(%2 : !forth.stack) - ^bb2(%5: !forth.stack): - %6 = forth.constant %5(4 : i64) : !forth.stack -> !forth.stack - %7 = forth.constant %6(0 : i64) : !forth.stack -> !forth.stack - %output_stack_3, %value_4 = forth.pop %7 : !forth.stack -> !forth.stack, i64 - %output_stack_5, %value_6 = forth.pop %output_stack_3 : !forth.stack -> !forth.stack, i64 - %alloca_7 = memref.alloca() : memref<1xi64> - %c0_8 = arith.constant 0 : index - memref.store %value_4, %alloca_7[%c0_8] : memref<1xi64> - cf.br ^bb4(%output_stack_5 : !forth.stack) - ^bb3(%8: !forth.stack): - return %8 : !forth.stack - ^bb4(%9: !forth.stack): - %c0_9 = arith.constant 0 : index - %10 = memref.load %alloca_7[%c0_9] : memref<1xi64> - %11 = arith.cmpi slt, %10, %value_6 : i64 - cf.cond_br %11, ^bb5(%9 : !forth.stack), ^bb6(%9 : !forth.stack) - ^bb5(%12: !forth.stack): - %c0_10 = arith.constant 0 : index - %13 = memref.load %alloca[%c0_10] : memref<1xi64> - %14 = forth.push_value %12, %13 : !forth.stack, i64 -> !forth.stack - %c0_11 = arith.constant 0 : index - %15 = memref.load %alloca_7[%c0_11] : memref<1xi64> - %16 = forth.push_value %14, %15 : !forth.stack, i64 -> !forth.stack - %17 = forth.addi %16 : !forth.stack -> !forth.stack - %c0_12 = arith.constant 0 : index - %18 = memref.load %alloca_7[%c0_12] : memref<1xi64> - %c1_i64 = arith.constant 1 : i64 - %19 = arith.addi %18, %c1_i64 : i64 - memref.store %19, %alloca_7[%c0_12] : memref<1xi64> - cf.br ^bb4(%17 : !forth.stack) - ^bb6(%20: !forth.stack): - %c0_13 = arith.constant 0 : index - %21 = memref.load %alloca[%c0_13] : memref<1xi64> - %c1_i64_14 = arith.constant 1 : i64 - %22 = arith.addi %21, %c1_i64_14 : i64 - memref.store %22, %alloca[%c0_13] : memref<1xi64> - cf.br ^bb1(%20 : !forth.stack) - } - func.func private @TEST__WHILE__INSIDE__IF(%arg0: !forth.stack) -> !forth.stack { - %0 = forth.constant %arg0(5 : i64) : !forth.stack -> !forth.stack - %output_stack, %flag = forth.pop_flag %0 : !forth.stack -> !forth.stack, i1 - cf.cond_br %flag, ^bb1(%output_stack : !forth.stack), ^bb2(%output_stack : !forth.stack) - ^bb1(%1: !forth.stack): - cf.br ^bb3(%1 : !forth.stack) - ^bb2(%2: !forth.stack): - return %2 : !forth.stack - ^bb3(%3: !forth.stack): - %4 = forth.dup %3 : !forth.stack -> !forth.stack - %output_stack_0, %flag_1 = forth.pop_flag %4 : !forth.stack -> !forth.stack, i1 - cf.cond_br %flag_1, ^bb4(%output_stack_0 : !forth.stack), ^bb5(%output_stack_0 : !forth.stack) - ^bb4(%5: !forth.stack): - %6 = forth.constant %5(1 : i64) : !forth.stack -> !forth.stack - %7 = forth.subi %6 : !forth.stack -> !forth.stack - cf.br ^bb3(%7 : !forth.stack) - ^bb5(%8: !forth.stack): - cf.br ^bb2(%8 : !forth.stack) - } - func.func private @main() { - %0 = forth.stack !forth.stack - return - } -} diff --git a/test/Conversion/ForthToMemRef/param-ref.mlir b/test/Conversion/ForthToMemRef/param-ref.mlir deleted file mode 100644 index 2038b6f..0000000 --- a/test/Conversion/ForthToMemRef/param-ref.mlir +++ /dev/null @@ -1,37 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// CHECK-LABEL: func.func private @array_param( -// CHECK-SAME: %[[ARRAY:.*]]: memref<256xi64> {forth.param_name = "data"}) -// CHECK: %[[STACK:.*]] = memref.alloca() : memref<256xi64> -// CHECK: %[[POINTER:.*]] = memref.extract_aligned_pointer_as_index %[[ARRAY]] : memref<256xi64> -> index -// CHECK: %[[ADDRESS:.*]] = arith.index_cast %[[POINTER]] : index to i64 -// CHECK: memref.store %[[ADDRESS]], %[[STACK]][%{{.*}}] : memref<256xi64> - -// CHECK-LABEL: func.func private @i64_param( -// CHECK-SAME: %[[INTEGER:.*]]: i64 {forth.param_name = "count"}) -// CHECK: %[[STACK:.*]] = memref.alloca() : memref<256xi64> -// CHECK: memref.store %[[INTEGER]], %[[STACK]][%{{.*}}] : memref<256xi64> - -// CHECK-LABEL: func.func private @f64_param( -// CHECK-SAME: %[[FLOAT:.*]]: f64 {forth.param_name = "scale"}) -// CHECK: %[[STACK:.*]] = memref.alloca() : memref<256xi64> -// CHECK: %[[BITS:.*]] = arith.bitcast %[[FLOAT]] : f64 to i64 -// CHECK: memref.store %[[BITS]], %[[STACK]][%{{.*}}] : memref<256xi64> - -module { - func.func private @array_param(%arg0: memref<256xi64> {forth.param_name = "data"}) { - %0 = forth.stack !forth.stack - %1 = forth.param_ref %0 %arg0 : !forth.stack, memref<256xi64> -> !forth.stack - return - } - func.func private @i64_param(%arg0: i64 {forth.param_name = "count"}) { - %0 = forth.stack !forth.stack - %1 = forth.param_ref %0 %arg0 : !forth.stack, i64 -> !forth.stack - return - } - func.func private @f64_param(%arg0: f64 {forth.param_name = "scale"}) { - %0 = forth.stack !forth.stack - %1 = forth.param_ref %0 %arg0 : !forth.stack, f64 -> !forth.stack - return - } -} diff --git a/test/Conversion/ForthToMemRef/reduced-width-memory.mlir b/test/Conversion/ForthToMemRef/reduced-width-memory.mlir deleted file mode 100644 index a247287..0000000 --- a/test/Conversion/ForthToMemRef/reduced-width-memory.mlir +++ /dev/null @@ -1,118 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// CHECK-LABEL: func.func private @main - -// --- i8 load: llvm.load i8, extsi to i64 --- -// CHECK: llvm.inttoptr %{{.*}} : i64 to !llvm.ptr<1> -// CHECK-NEXT: llvm.load %{{.*}} : !llvm.ptr<1> -> i8 -// CHECK-NEXT: arith.extsi %{{.*}} : i8 to i64 - -// --- i8 store: trunci i64 to i8, llvm.store --- -// CHECK: arith.trunci %{{.*}} : i64 to i8 -// CHECK-NEXT: llvm.store %{{.*}}, %{{.*}} : i8, !llvm.ptr<1> - -// --- shared i8 load: ptr<3> --- -// CHECK: llvm.inttoptr %{{.*}} : i64 to !llvm.ptr<3> -// CHECK-NEXT: llvm.load %{{.*}} : !llvm.ptr<3> -> i8 -// CHECK-NEXT: arith.extsi %{{.*}} : i8 to i64 - -// --- shared i8 store: ptr<3> --- -// CHECK: arith.trunci %{{.*}} : i64 to i8 -// CHECK-NEXT: llvm.store %{{.*}}, %{{.*}} : i8, !llvm.ptr<3> - -// --- i16 load --- -// CHECK: llvm.load %{{.*}} : !llvm.ptr<1> -> i16 -// CHECK-NEXT: arith.extsi %{{.*}} : i16 to i64 - -// --- i16 store --- -// CHECK: arith.trunci %{{.*}} : i64 to i16 -// CHECK-NEXT: llvm.store %{{.*}}, %{{.*}} : i16, !llvm.ptr<1> - -// --- i32 load --- -// CHECK: llvm.load %{{.*}} : !llvm.ptr<1> -> i32 -// CHECK-NEXT: arith.extsi %{{.*}} : i32 to i64 - -// --- i32 store --- -// CHECK: arith.trunci %{{.*}} : i64 to i32 -// CHECK-NEXT: llvm.store %{{.*}}, %{{.*}} : i32, !llvm.ptr<1> - -// --- f16 load: llvm.load f16, extf to f64, bitcast to i64 --- -// CHECK: llvm.load %{{.*}} : !llvm.ptr<1> -> f16 -// CHECK-NEXT: arith.extf %{{.*}} : f16 to f64 -// CHECK-NEXT: arith.bitcast %{{.*}} : f64 to i64 - -// --- f16 store: bitcast i64 to f64, truncf to f16, llvm.store --- -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK-NEXT: arith.truncf %{{.*}} : f64 to f16 -// CHECK-NEXT: llvm.store %{{.*}}, %{{.*}} : f16, !llvm.ptr<1> - -// --- bf16 load --- -// CHECK: llvm.load %{{.*}} : !llvm.ptr<1> -> bf16 -// CHECK-NEXT: arith.extf %{{.*}} : bf16 to f64 -// CHECK-NEXT: arith.bitcast %{{.*}} : f64 to i64 - -// --- bf16 store --- -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK-NEXT: arith.truncf %{{.*}} : f64 to bf16 -// CHECK-NEXT: llvm.store %{{.*}}, %{{.*}} : bf16, !llvm.ptr<1> - -// --- f32 load --- -// CHECK: llvm.load %{{.*}} : !llvm.ptr<1> -> f32 -// CHECK-NEXT: arith.extf %{{.*}} : f32 to f64 -// CHECK-NEXT: arith.bitcast %{{.*}} : f64 to i64 - -// --- f32 store --- -// CHECK: arith.bitcast %{{.*}} : i64 to f64 -// CHECK-NEXT: arith.truncf %{{.*}} : f64 to f32 -// CHECK-NEXT: llvm.store %{{.*}}, %{{.*}} : f32, !llvm.ptr<1> - -module { - func.func private @main() { - %0 = forth.stack !forth.stack - // i8 load - %1 = forth.constant %0(1 : i64) : !forth.stack -> !forth.stack - %2 = forth.load_i8 %1 : !forth.stack -> !forth.stack - // i8 store - %3 = forth.constant %2(42 : i64) : !forth.stack -> !forth.stack - %4 = forth.constant %3(100 : i64) : !forth.stack -> !forth.stack - %5 = forth.store_i8 %4 : !forth.stack -> !forth.stack - // shared i8 load - %6 = forth.constant %5(2 : i64) : !forth.stack -> !forth.stack - %7 = forth.shared_load_i8 %6 : !forth.stack -> !forth.stack - // shared i8 store - %8 = forth.constant %7(9 : i64) : !forth.stack -> !forth.stack - %9 = forth.constant %8(3 : i64) : !forth.stack -> !forth.stack - %10 = forth.shared_store_i8 %9 : !forth.stack -> !forth.stack - // i16 - %11 = forth.constant %10(1 : i64) : !forth.stack -> !forth.stack - %12 = forth.load_i16 %11 : !forth.stack -> !forth.stack - %13 = forth.constant %12(42 : i64) : !forth.stack -> !forth.stack - %14 = forth.constant %13(100 : i64) : !forth.stack -> !forth.stack - %15 = forth.store_i16 %14 : !forth.stack -> !forth.stack - // i32 - %16 = forth.constant %15(1 : i64) : !forth.stack -> !forth.stack - %17 = forth.load_i32 %16 : !forth.stack -> !forth.stack - %18 = forth.constant %17(42 : i64) : !forth.stack -> !forth.stack - %19 = forth.constant %18(100 : i64) : !forth.stack -> !forth.stack - %20 = forth.store_i32 %19 : !forth.stack -> !forth.stack - // f16 - %21 = forth.constant %20(1 : i64) : !forth.stack -> !forth.stack - %22 = forth.load_f16 %21 : !forth.stack -> !forth.stack - %23 = forth.constant %22(42 : i64) : !forth.stack -> !forth.stack - %24 = forth.constant %23(100 : i64) : !forth.stack -> !forth.stack - %25 = forth.store_f16 %24 : !forth.stack -> !forth.stack - // bf16 - %26 = forth.constant %25(1 : i64) : !forth.stack -> !forth.stack - %27 = forth.load_bf16 %26 : !forth.stack -> !forth.stack - %28 = forth.constant %27(42 : i64) : !forth.stack -> !forth.stack - %29 = forth.constant %28(100 : i64) : !forth.stack -> !forth.stack - %30 = forth.store_bf16 %29 : !forth.stack -> !forth.stack - // f32 - %31 = forth.constant %30(1 : i64) : !forth.stack -> !forth.stack - %32 = forth.load_f32 %31 : !forth.stack -> !forth.stack - %33 = forth.constant %32(42 : i64) : !forth.stack -> !forth.stack - %34 = forth.constant %33(100 : i64) : !forth.stack -> !forth.stack - %35 = forth.store_f32 %34 : !forth.stack -> !forth.stack - return - } -} diff --git a/test/Conversion/ForthToMemRef/stack-init.mlir b/test/Conversion/ForthToMemRef/stack-init.mlir deleted file mode 100644 index 5f3804f..0000000 --- a/test/Conversion/ForthToMemRef/stack-init.mlir +++ /dev/null @@ -1,12 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// CHECK-LABEL: func.func private @main -// CHECK: %[[BUF:.*]] = memref.alloca() : memref<256xi64> -// CHECK: %[[SP:.*]] = arith.constant 0 : index - -module { - func.func private @main() { - %0 = forth.stack !forth.stack - return - } -} diff --git a/test/Conversion/ForthToMemRef/stack-manipulation.mlir b/test/Conversion/ForthToMemRef/stack-manipulation.mlir deleted file mode 100644 index 4da0597..0000000 --- a/test/Conversion/ForthToMemRef/stack-manipulation.mlir +++ /dev/null @@ -1,95 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// CHECK-LABEL: func.func private @main - -// dup: load top, increment SP, store copy -// CHECK: memref.load %{{.*}}[%{{.*}}] : memref<256xi64> -// CHECK: arith.addi -// CHECK: memref.store - -// drop: decrement SP -// CHECK: arith.subi %{{.*}}, %{{.*}} : index - -// swap: load top and second, store crossed -// CHECK: %[[TOP_VAL:.*]] = memref.load %{{.*}}[%[[SWAP_SP:.*]]] : memref<256xi64> -// CHECK: %[[SWAP_SP1:.*]] = arith.subi -// CHECK: %[[SEC_VAL:.*]] = memref.load %{{.*}}[%[[SWAP_SP1]]] : memref<256xi64> -// CHECK: memref.store %[[SEC_VAL]], %{{.*}}[%[[SWAP_SP]]] : memref<256xi64> -// CHECK: memref.store %[[TOP_VAL]], %{{.*}}[%[[SWAP_SP1]]] : memref<256xi64> - -// over: load second element, increment SP, store copy -// CHECK: arith.subi -// CHECK: memref.load %{{.*}}[%{{.*}}] : memref<256xi64> -// CHECK: arith.addi -// CHECK: memref.store - -// rot: load three values, store rotated (a b c -- b c a) -// CHECK: %[[ROT_C:.*]] = memref.load %{{.*}}[%[[ROT_SP:.*]]] : memref<256xi64> -// CHECK: %[[ROT_SP1:.*]] = arith.subi %[[ROT_SP]] -// CHECK: %[[ROT_B:.*]] = memref.load %{{.*}}[%[[ROT_SP1]]] : memref<256xi64> -// CHECK: %[[ROT_SP2:.*]] = arith.subi %[[ROT_SP]] -// CHECK: %[[ROT_A:.*]] = memref.load %{{.*}}[%[[ROT_SP2]]] : memref<256xi64> -// CHECK: memref.store %[[ROT_B]], %{{.*}}[%[[ROT_SP2]]] : memref<256xi64> -// CHECK: memref.store %[[ROT_C]], %{{.*}}[%[[ROT_SP1]]] : memref<256xi64> -// CHECK: memref.store %[[ROT_A]], %{{.*}}[%[[ROT_SP]]] : memref<256xi64> - -// nip: load top, subi SP, store at SP-1 (a b -- b) -// CHECK: %[[NIP_B:.*]] = memref.load %{{.*}}[%{{.*}}] : memref<256xi64> -// CHECK: %[[NIP_SP1:.*]] = arith.subi -// CHECK: memref.store %[[NIP_B]], %{{.*}}[%[[NIP_SP1]]] : memref<256xi64> - -// tuck: load b and a, store b/a/b (a b -- b a b) -// CHECK: %[[TUCK_B:.*]] = memref.load %{{.*}}[%[[TUCK_SP:.*]]] : memref<256xi64> -// CHECK: %[[TUCK_SP1:.*]] = arith.subi -// CHECK: %[[TUCK_A:.*]] = memref.load %{{.*}}[%[[TUCK_SP1]]] : memref<256xi64> -// CHECK: memref.store %[[TUCK_B]], %{{.*}}[%[[TUCK_SP1]]] : memref<256xi64> -// CHECK: memref.store %[[TUCK_A]], %{{.*}}[%[[TUCK_SP]]] : memref<256xi64> -// CHECK: %[[TUCK_NSP:.*]] = arith.addi -// CHECK: memref.store %[[TUCK_B]], %{{.*}}[%[[TUCK_NSP]]] : memref<256xi64> - -// pick: load n, index_cast, subi (dynamic), load picked, store -// CHECK: %[[PICK_N:.*]] = memref.load %{{.*}}[%{{.*}}] : memref<256xi64> -// CHECK: %[[PICK_SP1:.*]] = arith.subi -// CHECK: %[[PICK_NIDX:.*]] = arith.index_cast %[[PICK_N]] -// CHECK: %[[PICK_ADDR:.*]] = arith.subi %[[PICK_SP1]], %[[PICK_NIDX]] -// CHECK: %[[PICK_VAL:.*]] = memref.load %{{.*}}[%[[PICK_ADDR]]] : memref<256xi64> -// CHECK: memref.store %[[PICK_VAL]] - -// roll: load n, index_cast, subi (dynamic), load saved, cf loop with load/store, store saved -// CHECK: %[[ROLL_N:.*]] = memref.load %{{.*}}[%{{.*}}] : memref<256xi64> -// CHECK: %[[ROLL_SP1:.*]] = arith.subi -// CHECK: %[[ROLL_NIDX:.*]] = arith.index_cast %[[ROLL_N]] -// CHECK: %[[ROLL_ADDR:.*]] = arith.subi %[[ROLL_SP1]], %[[ROLL_NIDX]] -// CHECK: %[[ROLL_SAVED:.*]] = memref.load %{{.*}}[%[[ROLL_ADDR]]] : memref<256xi64> -// CHECK: cf.br ^[[ROLL_HDR:.*]](%[[ROLL_ADDR]] : index) -// CHECK: ^[[ROLL_HDR]](%[[ROLL_IV:.*]]: index): -// CHECK: %[[ROLL_CMP:.*]] = arith.cmpi slt, %[[ROLL_IV]], %[[ROLL_SP1]] : index -// CHECK: cf.cond_br %[[ROLL_CMP]], ^[[ROLL_BODY:.*]](%[[ROLL_IV]] : index), ^[[ROLL_EXIT:.*]] -// CHECK: ^[[ROLL_BODY]](%[[ROLL_BIV:.*]]: index): -// CHECK: %[[ROLL_NEXT:.*]] = arith.addi %[[ROLL_BIV]] -// CHECK: %[[ROLL_SHIFTED:.*]] = memref.load %{{.*}}[%[[ROLL_NEXT]]] : memref<256xi64> -// CHECK: memref.store %[[ROLL_SHIFTED]], %{{.*}}[%[[ROLL_BIV]]] : memref<256xi64> -// CHECK: cf.br ^[[ROLL_HDR]](%[[ROLL_NEXT]] : index) -// CHECK: ^[[ROLL_EXIT]]: -// CHECK: memref.store %[[ROLL_SAVED]], %{{.*}}[%[[ROLL_SP1]]] : memref<256xi64> - -module { - func.func private @main() { - %0 = forth.stack !forth.stack - %1 = forth.constant %0(1 : i64) : !forth.stack -> !forth.stack - %2 = forth.constant %1(2 : i64) : !forth.stack -> !forth.stack - %3 = forth.constant %2(3 : i64) : !forth.stack -> !forth.stack - %4 = forth.dup %3 : !forth.stack -> !forth.stack - %5 = forth.drop %4 : !forth.stack -> !forth.stack - %6 = forth.swap %5 : !forth.stack -> !forth.stack - %7 = forth.over %6 : !forth.stack -> !forth.stack - %8 = forth.rot %7 : !forth.stack -> !forth.stack - %9 = forth.nip %8 : !forth.stack -> !forth.stack - %10 = forth.tuck %9 : !forth.stack -> !forth.stack - %11 = forth.constant %10(2 : i64) : !forth.stack -> !forth.stack - %12 = forth.pick %11 : !forth.stack -> !forth.stack - %13 = forth.constant %12(2 : i64) : !forth.stack -> !forth.stack - %14 = forth.roll %13 : !forth.stack -> !forth.stack - return - } -} diff --git a/test/Conversion/ForthToMemRef/user-defined-words.mlir b/test/Conversion/ForthToMemRef/user-defined-words.mlir deleted file mode 100644 index 6634934..0000000 --- a/test/Conversion/ForthToMemRef/user-defined-words.mlir +++ /dev/null @@ -1,26 +0,0 @@ -// RUN: %warpforth-opt --convert-forth-to-memref %s | %FileCheck %s - -// User-defined word signature: (!forth.stack) -> !forth.stack becomes -// (memref<256xi64>, index) -> (memref<256xi64>, index) -// CHECK-LABEL: func.func private @double(%{{.*}}: memref<256xi64>, %{{.*}}: index) -> (memref<256xi64>, index) -// CHECK: memref.load -// CHECK: arith.addi -// CHECK: memref.store -// CHECK: return %{{.*}}, %{{.*}} : memref<256xi64>, index - -// CHECK-LABEL: func.func private @main -// CHECK: call @double(%{{.*}}, %{{.*}}) : (memref<256xi64>, index) -> (memref<256xi64>, index) - -module { - func.func private @double(%arg0: !forth.stack) -> !forth.stack { - %0 = forth.dup %arg0 : !forth.stack -> !forth.stack - %1 = forth.addi %0 : !forth.stack -> !forth.stack - return %1 : !forth.stack - } - func.func private @main() { - %0 = forth.stack !forth.stack - %1 = forth.constant %0(5 : i64) : !forth.stack -> !forth.stack - %2 = call @double(%1) : (!forth.stack) -> !forth.stack - return - } -} diff --git a/test/Pipeline/barrier.forth b/test/Pipeline/barrier.forth index ef1c2b8..8452b30 100644 --- a/test/Pipeline/barrier.forth +++ b/test/Pipeline/barrier.forth @@ -1,5 +1,5 @@ \ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --warpforth-pipeline | %FileCheck %s -\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --convert-forth-to-memref --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID +\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --lower-forth-stack --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID \ CHECK: gpu.binary @warpforth_module \ MID: gpu.func @main \ MID: gpu.barrier diff --git a/test/Pipeline/begin-until.forth b/test/Pipeline/begin-until.forth index 189b487..8f4eb8a 100644 --- a/test/Pipeline/begin-until.forth +++ b/test/Pipeline/begin-until.forth @@ -1,5 +1,5 @@ \ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --warpforth-pipeline | %FileCheck %s -\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --convert-forth-to-memref --convert-scf-to-cf --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID +\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --lower-forth-stack --convert-scf-to-cf --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID \ Verify that BEGIN/UNTIL through the full pipeline produces a gpu.binary \ CHECK: gpu.binary @warpforth_module diff --git a/test/Pipeline/begin-while-repeat.forth b/test/Pipeline/begin-while-repeat.forth index b2998fe..07dd389 100644 --- a/test/Pipeline/begin-while-repeat.forth +++ b/test/Pipeline/begin-while-repeat.forth @@ -1,5 +1,5 @@ \ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --warpforth-pipeline | %FileCheck %s -\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --convert-forth-to-memref --convert-scf-to-cf --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID +\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --lower-forth-stack --convert-scf-to-cf --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID \ Verify that BEGIN/WHILE/REPEAT through the full pipeline produces a gpu.binary \ CHECK: gpu.binary @warpforth_module diff --git a/test/Pipeline/control-flow.forth b/test/Pipeline/control-flow.forth index 6fac4d8..166f4c6 100644 --- a/test/Pipeline/control-flow.forth +++ b/test/Pipeline/control-flow.forth @@ -1,13 +1,15 @@ \ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --warpforth-pipeline | %FileCheck %s -\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --convert-forth-to-memref --convert-scf-to-cf --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID +\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --lower-forth-stack --convert-scf-to-cf --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID \ Verify that control flow through the full pipeline produces a gpu.binary \ CHECK: gpu.binary @warpforth_module -\ Verify intermediate MLIR: gpu.func with conditional branching +\ Verify intermediate MLIR: gpu.func with conditional branching on the loaded +\ cell itself \ MID: gpu.module @warpforth_module \ MID: gpu.func @main(%arg0: memref<256xi64> {forth.param_name = "DATA"}) kernel -\ MID: memref.load +\ MID: %[[LOADED:.*]] = llvm.load +\ MID: arith.cmpi sgt, %[[LOADED]], %{{.*}} : i64 \ MID: arith.cmpi ne \ MID: cf.cond_br \ MID: gpu.return diff --git a/test/Pipeline/do-loop.forth b/test/Pipeline/do-loop.forth index 57fb4b8..e889a26 100644 --- a/test/Pipeline/do-loop.forth +++ b/test/Pipeline/do-loop.forth @@ -1,5 +1,5 @@ \ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --warpforth-pipeline | %FileCheck %s -\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --convert-forth-to-memref --convert-scf-to-cf --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID +\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --lower-forth-stack --convert-scf-to-cf --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID \ Verify that DO/LOOP through the full pipeline produces a gpu.binary \ CHECK: gpu.binary @warpforth_module diff --git a/test/Pipeline/exit.forth b/test/Pipeline/exit.forth index a60294f..1427e1a 100644 --- a/test/Pipeline/exit.forth +++ b/test/Pipeline/exit.forth @@ -1,10 +1,15 @@ \ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --warpforth-pipeline | %FileCheck %s -\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --convert-forth-to-memref --canonicalize | %FileCheck %s --check-prefix=MID --implicit-check-not="arith.constant true" +\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --inline --lower-forth-stack --canonicalize | %FileCheck %s --check-prefix=MID --implicit-check-not="arith.constant true" --implicit-check-not="arith.constant 42" \ CHECK: gpu.binary @warpforth_module -\ MID-LABEL: func.func private @DO_EXIT -\ MID-COUNT-2: return + +\ EXIT leaves the inlined word early: the kernel stores the 7 pushed before +\ EXIT, and the code after EXIT is gone. +\ MID-LABEL: func.func @main +\ MID: %[[SEVEN:.*]] = arith.constant 7 : i64 +\ MID: llvm.store %[[SEVEN]], %{{.*}} : i64, !llvm.ptr<1> +\ MID-NEXT: return \! kernel main \! param DATA i64[4] -: DO-EXIT 1 IF EXIT THEN 42 ; +: DO-EXIT 7 1 IF EXIT THEN DROP 42 ; DO-EXIT DATA 0 CELLS + ! diff --git a/test/Pipeline/float-pipeline.forth b/test/Pipeline/float-pipeline.forth index 2036b97..a11e64e 100644 --- a/test/Pipeline/float-pipeline.forth +++ b/test/Pipeline/float-pipeline.forth @@ -1,15 +1,19 @@ \ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --warpforth-pipeline | %FileCheck %s -\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --convert-forth-to-memref --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID +\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --lower-forth-stack --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID \ Verify that Forth with f64 params through the full pipeline produces a gpu.binary \ CHECK: gpu.binary @warpforth_module -\ Verify intermediate MLIR structure at the memref+gpu stage +\ Verify intermediate MLIR after stack lowering and GPU conversion. The f64 +\ cells travel as i64 bits, and no stack buffer holds them. \ MID: gpu.module @warpforth_module \ MID: gpu.func @main(%arg0: memref<256xf64> {forth.param_name = "DATA"}, %arg1: f64 {forth.param_name = "SCALE"}) kernel -\ MID: memref.alloca() : memref<256xi64> +\ MID-NOT: memref.alloca \ MID: memref.extract_aligned_pointer_as_index %arg0 -\ MID: arith.bitcast %{{.*}} : f64 to i64 +\ MID: llvm.load %{{.*}} : !llvm.ptr<1> -> f64 +\ MID: arith.bitcast %arg1 : f64 to i64 +\ MID: arith.mulf %{{.*}}, %{{.*}} : f64 +\ MID: llvm.store %{{.*}}, %{{.*}} : f64, !llvm.ptr<1> \ MID: gpu.return \! kernel main diff --git a/test/Pipeline/full-pipeline.forth b/test/Pipeline/full-pipeline.forth index c2c77fb..dc9a9ab 100644 --- a/test/Pipeline/full-pipeline.forth +++ b/test/Pipeline/full-pipeline.forth @@ -1,17 +1,20 @@ \ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --warpforth-pipeline | %FileCheck %s -\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --convert-forth-to-memref --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID +\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --lower-forth-stack --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID \ Verify that Forth source through the full pipeline produces a gpu.binary \ CHECK: gpu.binary @warpforth_module -\ Verify intermediate MLIR structure at the memref+gpu stage +\ Verify intermediate MLIR after stack lowering and GPU conversion. The kernel +\ is straight-line, so the loaded cell reaches the store as an SSA value with +\ no stack buffer in between. \ MID: gpu.module @warpforth_module \ MID: gpu.func @main(%arg0: memref<256xi64> {forth.param_name = "DATA"}) kernel -\ MID: memref.alloca() : memref<256xi64> +\ MID-NOT: memref.alloca \ MID: gpu.thread_id x \ MID: memref.extract_aligned_pointer_as_index %arg0 -\ MID: llvm.load -\ MID: llvm.store +\ MID: %[[LOADED:.*]] = llvm.load %{{.*}} : !llvm.ptr<1> -> i64 +\ MID: %[[INCREMENTED:.*]] = arith.addi %[[LOADED]], %{{.*}} : i64 +\ MID: llvm.store %[[INCREMENTED]], %{{.*}} : i64, !llvm.ptr<1> \ MID: gpu.return \! kernel main diff --git a/test/Pipeline/interleaved-control-flow.forth b/test/Pipeline/interleaved-control-flow.forth index 2b5573d..abadb90 100644 --- a/test/Pipeline/interleaved-control-flow.forth +++ b/test/Pipeline/interleaved-control-flow.forth @@ -1,26 +1,25 @@ \ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --warpforth-pipeline | %FileCheck %s -\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --convert-forth-to-memref --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID +\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --inline --lower-forth-stack --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID \ Verify interleaved control flow (multi-WHILE, WHILE+UNTIL) compiles \ through the full pipeline to gpu.binary. \ CHECK: gpu.binary @warpforth_module -\ Verify intermediate MLIR: gpu.func with cf branches, no scf ops +\ Verify intermediate MLIR: both words are inlined into the kernel, which keeps +\ their cf branches, and no word function is left. \ MID: gpu.module @warpforth_module \ MID: gpu.func @main(%arg0: memref<4xi64> {forth.param_name = "DATA"}) kernel -\ MID: gpu.return \ Multi-WHILE: two cond_br exits + one unconditional back-edge -\ MID: func.func private @MULTI_WHILE \ MID: cf.cond_br \ MID: cf.cond_br \ MID: cf.br \ WHILE+UNTIL: WHILE exit + UNTIL exit merge at THEN -\ MID: func.func private @WHILE_UNTIL \ MID: cf.cond_br \ MID: cf.cond_br -\ MID: cf.br +\ MID: gpu.return +\ MID-NOT: func.func \! kernel main \! param DATA i64[4] diff --git a/test/Pipeline/leave.forth b/test/Pipeline/leave.forth index a713318..75ad7a9 100644 --- a/test/Pipeline/leave.forth +++ b/test/Pipeline/leave.forth @@ -1,5 +1,5 @@ \ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --warpforth-pipeline | %FileCheck %s -\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --convert-forth-to-memref --convert-scf-to-cf --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID --implicit-check-not="arith.constant true" +\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --lower-forth-stack --convert-scf-to-cf --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID --implicit-check-not="arith.constant true" \ Verify that LEAVE through the full pipeline produces a gpu.binary \ CHECK: gpu.binary @warpforth_module diff --git a/test/Pipeline/matmul-naive.forth b/test/Pipeline/matmul-naive.forth index 4cae506..153edba 100644 --- a/test/Pipeline/matmul-naive.forth +++ b/test/Pipeline/matmul-naive.forth @@ -1,5 +1,5 @@ \ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --warpforth-pipeline | %FileCheck %s -\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --convert-forth-to-memref --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID +\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --lower-forth-stack --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID \ Verify that a naive integer matmul kernel survives the full pipeline. \ CHECK: gpu.binary @warpforth_module diff --git a/test/Pipeline/multi-param.forth b/test/Pipeline/multi-param.forth index 3cd9b43..64f78f9 100644 --- a/test/Pipeline/multi-param.forth +++ b/test/Pipeline/multi-param.forth @@ -1,5 +1,5 @@ \ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --warpforth-pipeline | %FileCheck %s -\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --convert-forth-to-memref --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID +\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --lower-forth-stack --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID \ Verify multiple params survive the full pipeline \ CHECK: gpu.binary @warpforth_module diff --git a/test/Pipeline/nested-control-flow.forth b/test/Pipeline/nested-control-flow.forth index 38066f0..8805780 100644 --- a/test/Pipeline/nested-control-flow.forth +++ b/test/Pipeline/nested-control-flow.forth @@ -1,5 +1,5 @@ \ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --warpforth-pipeline | %FileCheck %s -\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --convert-forth-to-memref --convert-scf-to-cf --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID +\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --lower-forth-stack --convert-scf-to-cf --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID \ Verify nested DO/LOOP with I and J through full pipeline produces gpu.binary \ CHECK: gpu.binary @warpforth_module diff --git a/test/Pipeline/scalar-param.forth b/test/Pipeline/scalar-param.forth index 00771b0..5a417fc 100644 --- a/test/Pipeline/scalar-param.forth +++ b/test/Pipeline/scalar-param.forth @@ -1,5 +1,5 @@ \ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --warpforth-pipeline | %FileCheck %s -\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --convert-forth-to-memref --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID +\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --lower-forth-stack --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID \ Verify mixed scalar + array params survive the full pipeline \ CHECK: gpu.binary @warpforth_module diff --git a/test/Pipeline/shared-memory.forth b/test/Pipeline/shared-memory.forth index 635e8f1..9fdd0eb 100644 --- a/test/Pipeline/shared-memory.forth +++ b/test/Pipeline/shared-memory.forth @@ -1,5 +1,5 @@ \ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --warpforth-pipeline | %FileCheck %s -\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --convert-forth-to-memref --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID +\ RUN: %warpforth-translate --forth-to-mlir %s | %warpforth-opt --lower-forth-stack --convert-forth-to-gpu | %FileCheck %s --check-prefix=MID \ Verify that shared memory through the full pipeline produces a gpu.binary \ CHECK: gpu.binary @warpforth_module diff --git a/tools/warpforth-opt/CMakeLists.txt b/tools/warpforth-opt/CMakeLists.txt index 966572e..4d2e1f4 100644 --- a/tools/warpforth-opt/CMakeLists.txt +++ b/tools/warpforth-opt/CMakeLists.txt @@ -21,6 +21,5 @@ target_link_libraries(warpforth-opt MLIROptLib MLIRForth MLIRConversionPasses - MLIRForthToMemRefConversion MLIRNVVMTarget ) From e2aa1d7411e834084fae73eda77b7487ab2f1a61 Mon Sep 17 00:00:00 2001 From: Alex Cameron Date: Mon, 9 Nov 2026 05:30:46 +0000 Subject: [PATCH 7/8] refactor(conversion): name one stack-word row WordLowering holds the effect and the compute. StackWordRow is the table entry. A dynamic ROLL shifts cells in shiftCellsDown. --- lib/Conversion/ForthStack/LowerForthStack.cpp | 68 +++++++------------ lib/Conversion/ForthStack/StackWords.cpp | 36 ++++------ lib/Conversion/ForthStack/StackWords.h | 13 ++-- lib/Conversion/ForthToGPU/ForthToGPU.cpp | 4 +- lib/Conversion/Passes.cpp | 24 +++---- lib/Dialect/Forth/ForthDialect.cpp | 3 +- test/Conversion/ForthStack/bitwise.mlir | 4 +- test/Conversion/ForthStack/comparison.mlir | 4 +- test/Conversion/ForthStack/control-flow.mlir | 1 - test/Conversion/ForthStack/float.mlir | 1 - test/Conversion/ForthStack/pick-roll.mlir | 4 +- test/Conversion/ForthStack/residual.mlir | 3 +- .../ForthStack/unknown-stack-user-error.mlir | 2 - .../ForthStack/word-not-inlined-error.mlir | 2 - .../ForthToGPU/non-kernel-function-error.mlir | 2 - 15 files changed, 65 insertions(+), 106 deletions(-) diff --git a/lib/Conversion/ForthStack/LowerForthStack.cpp b/lib/Conversion/ForthStack/LowerForthStack.cpp index 896905c..ba438c4 100644 --- a/lib/Conversion/ForthStack/LowerForthStack.cpp +++ b/lib/Conversion/ForthStack/LowerForthStack.cpp @@ -1,9 +1,6 @@ //===- LowerForthStack.cpp - Lower the Forth stack --------------*- C++ -*-===// // -// This file implements the pass that lowers every !forth.stack value. The -// stack-word table says what each word computes. This file decides where each -// cell lives: a cell whose depth and slot are known is an i64 SSA value, and -// the rest live in a per-thread memref<256xi64> indexed by depth. +// This file implements the pass that lowers every !forth.stack value. // //===----------------------------------------------------------------------===// @@ -41,11 +38,9 @@ namespace warpforth { namespace { using stack::StackEffect; -using stack::StackWord; using stack::WordContext; +using stack::WordLowering; -/// Cells in the residual buffer. Index 0 is never written by a push, so an -/// empty buffer has depth 0. constexpr int64_t kResidualCells = 256; bool isStack(Type type) { return isa(type); } @@ -81,9 +76,9 @@ StackShape transfer(StackShape in, StackEffect effect) { return ResidualShape{kept + effect.pushes}; } -/// The shape where stacks of shapes `a` and `b` meet. Equal shapes are kept. -/// Otherwise the join keeps in registers only the top cells that both sides -/// hold there, and the cells below move to memory. +/// The shape where stacks of shapes `a` and `b` meet. When the shapes differ, +/// the join keeps in registers only the top cells that both sides hold there, +/// and the cells below move to memory. StackShape join(StackShape a, StackShape b) { if (a == b) return a; @@ -135,8 +130,6 @@ LogicalResult verifyWordsInlined(ModuleOp module) { return success(); } -/// Every stack value must come from forth.stack, a row, or a block argument, -/// and flow only into rows and branches. LogicalResult verifyStackUsers(Region &body) { WalkResult walk = body.walk([](Operation *op) { bool usesStack = llvm::any_of(op->getOperandTypes(), isStack) || @@ -197,7 +190,7 @@ DenseMap inferShapes(Region &body) { shapes[op.getResult(0)] = StaticShape{0}; continue; } - const StackWord *word = stack::lookupStackWord(&op); + const WordLowering *word = stack::lookupStackWord(&op); if (!word) continue; shapes[op.getResult(0)] = @@ -208,14 +201,12 @@ DenseMap inferShapes(Region &body) { return shapes; } -/// Rewrites one function. Rows reach the cells only through WordContext. class StackSimulator final : public WordContext { public: StackSimulator(func::FuncOp fn, DenseMap shapes) - : fn(fn), b(fn.getContext()), loc(fn.getLoc()), - shapes(std::move(shapes)) {} + : fn(fn), b(fn.getContext()), shapes(std::move(shapes)), + loc(fn.getLoc()) {} - /// Lowers every stack word in `fn`, then erases the Forth stack ops. void run(); OpBuilder &builder() override { return b; } @@ -229,11 +220,12 @@ class StackSimulator final : public WordContext { private: void expandArguments(Block &block); - void lowerWord(Operation *op, const StackWord &word); + void lowerWord(Operation *op, const WordLowering &word); Value popCell(); void forwardCells(BranchOpInterface branch); void appendEdgeOperands(const StackState &state, StackShape target, SmallVectorImpl &operands); + void shiftCellsDown(Value from, Value top); Value residualBuffer(); Value memoryDepth(const StackState &state); @@ -243,8 +235,6 @@ class StackSimulator final : public WordContext { func::FuncOp fn; OpBuilder b; - /// Location of the op or branch being lowered. - Location loc; DenseMap shapes; /// Keyed by the original !forth.stack value. DenseMap states; @@ -252,11 +242,10 @@ class StackSimulator final : public WordContext { DenseMap> originalArguments; SmallVector lowered; SmallVector replacedArguments; - /// Allocated on first use, so a function whose cells all have static slots - /// has no buffer. Value buffer; // Scratch for the op being lowered. + Location loc; Operation *current = nullptr; StackState working; SmallVector poppedCells; @@ -276,7 +265,7 @@ void StackSimulator::run() { if (isa(op)) { states[op->getResult(0)] = StaticState{}; lowered.push_back(op); - } else if (const StackWord *word = stack::lookupStackWord(op)) { + } else if (const WordLowering *word = stack::lookupStackWord(op)) { lowerWord(op, *word); } else if (auto branch = dyn_cast(op)) { forwardCells(branch); @@ -292,8 +281,6 @@ void StackSimulator::run() { arg.getOwner()->eraseArgument(arg.getArgNumber()); } -/// Gives each stack argument of `block` the arguments its shape needs, placed -/// after it. The stack argument is erased once nothing uses it. void StackSimulator::expandArguments(Block &block) { SmallVector &original = originalArguments[&block]; original = llvm::to_vector(block.getArguments()); @@ -315,7 +302,7 @@ void StackSimulator::expandArguments(Block &block) { } } -void StackSimulator::lowerWord(Operation *op, const StackWord &word) { +void StackSimulator::lowerWord(Operation *op, const WordLowering &word) { current = op; loc = op->getLoc(); b.setInsertionPoint(op); @@ -332,10 +319,6 @@ void StackSimulator::lowerWord(Operation *op, const StackWord &word) { lowered.push_back(op); } -/// Pops the top cell of the working stack. Below the register cells the cell -/// is loaded from memory. A static stack has nothing below its cells, so it -/// widens to an empty residual stack and the load reads index 0, as the memref -/// stack did. Value StackSimulator::popCell() { SmallVector &cells = cellsOf(working); if (!cells.empty()) @@ -362,8 +345,8 @@ Value StackSimulator::peek(Value n) { SmallVector &cells = cellsOf(working); if (std::optional slot = registerSlot(n, cells.size())) return cells[*slot]; - // The register cells are written only as the image this load addresses, and - // they stay the live stack. + // The depth storeCells returns is dropped, so these stores do not change + // `working`. Value top = storeCells(cells, memoryDepth(working)); Value offset = b.create(loc, b.getIndexType(), n); Value index = b.create(loc, top, offset); @@ -381,8 +364,16 @@ void StackSimulator::rollToTop(Value n) { Value offset = b.create(loc, b.getIndexType(), n); Value rolledIndex = b.create(loc, top, offset); Value rolled = b.create(loc, residualBuffer(), rolledIndex); + shiftCellsDown(rolledIndex, top); + b.create(loc, rolled, residualBuffer(), top); + Value index = depth; + for (Value &cell : cells) { + index = b.create(loc, index, indexConstant(1)); + cell = b.create(loc, residualBuffer(), index); + } +} - // for (iv = rolledIndex; iv < top; ++iv) buffer[iv] = buffer[iv + 1] +void StackSimulator::shiftCellsDown(Value from, Value top) { Block *before = b.getInsertionBlock(); Block *after = before->splitBlock(b.getInsertionPoint()); Type indexType = b.getIndexType(); @@ -390,7 +381,7 @@ void StackSimulator::rollToTop(Value n) { Block *body = b.createBlock(after, indexType, loc); b.setInsertionPointToEnd(before); - b.create(loc, header, rolledIndex); + b.create(loc, header, from); b.setInsertionPointToStart(header); Value iv = header->getArgument(0); @@ -406,12 +397,6 @@ void StackSimulator::rollToTop(Value n) { b.create(loc, header, next); b.setInsertionPointToStart(after); - b.create(loc, rolled, residualBuffer(), top); - Value index = depth; - for (Value &cell : cells) { - index = b.create(loc, index, indexConstant(1)); - cell = b.create(loc, residualBuffer(), index); - } } /// Passes each forwarded stack to its successor in the successor's shape. @@ -469,7 +454,6 @@ Value StackSimulator::residualBuffer() { return buffer; } -/// The index of the top memory cell under `state`'s register cells. Value StackSimulator::memoryDepth(const StackState &state) { if (const auto *residual = std::get_if(&state)) return residual->depth; @@ -477,7 +461,7 @@ Value StackSimulator::memoryDepth(const StackState &state) { } /// Pushes `cells` to memory above `depth`, deepest first, and returns the new -/// depth. +/// depth. Index 0 is never written by a push, so an empty buffer has depth 0. Value StackSimulator::storeCells(ArrayRef cells, Value depth) { for (Value cell : cells) { depth = b.create(loc, depth, indexConstant(1)); diff --git a/lib/Conversion/ForthStack/StackWords.cpp b/lib/Conversion/ForthStack/StackWords.cpp index 35ab0f3..eec8c05 100644 --- a/lib/Conversion/ForthStack/StackWords.cpp +++ b/lib/Conversion/ForthStack/StackWords.cpp @@ -32,8 +32,6 @@ constexpr unsigned kGlobalAddressSpace = constexpr unsigned kSharedAddressSpace = static_cast(NVVM::kSharedMemorySpace); -/// Element type of a memory access. Cells are i64; a narrower integer is -/// sign-extended and a float is carried as the bits of an f64. enum class MemType { I64, F64, I8, I16, I32, F16, BF16, F32 }; Type memElementType(MLIRContext *ctx, MemType type) { @@ -58,7 +56,6 @@ Type memElementType(MLIRContext *ctx, MemType type) { llvm_unreachable("unhandled MemType"); } -/// The cell as a value of the memory element type. Value narrow(OpBuilder &b, Location loc, Value cell, MemType type) { Type elementType = memElementType(b.getContext(), type); switch (type) { @@ -80,7 +77,6 @@ Value narrow(OpBuilder &b, Location loc, Value cell, MemType type) { llvm_unreachable("unhandled MemType"); } -/// The loaded memory element as a cell. Value widen(OpBuilder &b, Location loc, Value element, MemType type) { switch (type) { case MemType::I64: @@ -127,15 +123,13 @@ Value gpuIndex(OpBuilder &b, Location loc, StringRef intrinsic) { struct StackWordRow { TypeID op; - StackWord word; + WordLowering word; }; -/// A row built by a family helper, which carries its own effect. -template StackWordRow row(StackWord word) { +template StackWordRow row(WordLowering word) { return {TypeID::get(), std::move(word)}; } -/// A row whose lowering reads the typed op. template StackWordRow row(StackEffect effect, void (*lower)(OpT, WordContext &)) { return {TypeID::get(), @@ -146,7 +140,7 @@ StackWordRow row(StackEffect effect, void (*lower)(OpT, WordContext &)) { /// A word that only reorders cells. It pushes popped(i) for each i in /// `order`, deepest first. -StackWord shuffle(unsigned pops, std::initializer_list order) { +WordLowering shuffle(unsigned pops, std::initializer_list order) { SmallVector pushed(order); auto pushes = static_cast(pushed.size()); return {{pops, pushes}, [pushed](Operation *, WordContext &ctx) { @@ -156,7 +150,7 @@ StackWord shuffle(unsigned pops, std::initializer_list order) { } /// ( a b -- a op b ) -template StackWord intBinary() { +template WordLowering intBinary() { return {{2, 1}, [](Operation *op, WordContext &ctx) { ctx.push(ctx.builder().create(op->getLoc(), ctx.popped(1), ctx.popped(0))); @@ -164,7 +158,7 @@ template StackWord intBinary() { } /// ( a b -- a op b ) on the f64 bits of each cell. -template StackWord floatBinary() { +template WordLowering floatBinary() { return {{2, 1}, [](Operation *op, WordContext &ctx) { OpBuilder &b = ctx.builder(); Location loc = op->getLoc(); @@ -175,7 +169,7 @@ template StackWord floatBinary() { } /// ( x -- op x ) on the f64 bits of the cell. -template StackWord floatUnary() { +template WordLowering floatUnary() { return {{1, 1}, [](Operation *op, WordContext &ctx) { OpBuilder &b = ctx.builder(); Location loc = op->getLoc(); @@ -185,7 +179,7 @@ template StackWord floatUnary() { } /// ( a b -- flag ) -StackWord intCompare(arith::CmpIPredicate predicate) { +WordLowering intCompare(arith::CmpIPredicate predicate) { return {{2, 1}, [predicate](Operation *op, WordContext &ctx) { OpBuilder &b = ctx.builder(); Location loc = op->getLoc(); @@ -196,7 +190,7 @@ StackWord intCompare(arith::CmpIPredicate predicate) { } /// ( a b -- flag ) on the f64 bits of each cell. -StackWord floatCompare(arith::CmpFPredicate predicate) { +WordLowering floatCompare(arith::CmpFPredicate predicate) { return {{2, 1}, [predicate](Operation *op, WordContext &ctx) { OpBuilder &b = ctx.builder(); Location loc = op->getLoc(); @@ -208,7 +202,7 @@ StackWord floatCompare(arith::CmpFPredicate predicate) { } /// ( addr -- x ) -StackWord load(MemType type, unsigned addressSpace) { +WordLowering load(MemType type, unsigned addressSpace) { return {{1, 1}, [type, addressSpace](Operation *op, WordContext &ctx) { OpBuilder &b = ctx.builder(); Location loc = op->getLoc(); @@ -220,7 +214,7 @@ StackWord load(MemType type, unsigned addressSpace) { } /// ( x addr -- ) -StackWord store(MemType type, unsigned addressSpace) { +WordLowering store(MemType type, unsigned addressSpace) { return {{2, 0}, [type, addressSpace](Operation *op, WordContext &ctx) { OpBuilder &b = ctx.builder(); Location loc = op->getLoc(); @@ -231,7 +225,7 @@ StackWord store(MemType type, unsigned addressSpace) { } /// ( -- x ), where `intrinsic` names a GPU index such as "tid-x". -StackWord gpuIndexWord(StringRef intrinsic) { +WordLowering gpuIndexWord(StringRef intrinsic) { return {{0, 1}, [intrinsic](Operation *op, WordContext &ctx) { OpBuilder &b = ctx.builder(); Value index = gpuIndex(b, op->getLoc(), intrinsic); @@ -443,9 +437,9 @@ ArrayRef stackWordRows() { return rows; } -const DenseMap &stackWords() { - static const DenseMap words = [] { - DenseMap words; +const DenseMap &stackWords() { + static const DenseMap words = [] { + DenseMap words; for (const StackWordRow &row : stackWordRows()) { bool inserted = words.try_emplace(row.op, &row.word).second; assert(inserted && "duplicate stack-word row"); @@ -458,7 +452,7 @@ const DenseMap &stackWords() { } // namespace -const StackWord *lookupStackWord(Operation *op) { +const WordLowering *lookupStackWord(Operation *op) { return stackWords().lookup(op->getName().getTypeID()); } diff --git a/lib/Conversion/ForthStack/StackWords.h b/lib/Conversion/ForthStack/StackWords.h index debcfbc..ce11a57 100644 --- a/lib/Conversion/ForthStack/StackWords.h +++ b/lib/Conversion/ForthStack/StackWords.h @@ -1,8 +1,7 @@ //===- StackWords.h - Stack effects of Forth words --------------*- C++ -*-===// // // This file declares the stack-word table. Each row gives one Forth op its -// stack effect and lowers the op's compute on i64 cells. Where the cells live -// is decided by LowerForthStack.cpp alone. +// stack effect and lowers the op's compute on i64 cells. // //===----------------------------------------------------------------------===// @@ -18,8 +17,7 @@ namespace mlir { namespace warpforth { namespace stack { -/// How many cells a word pops, then pushes. The table is the only place that -/// declares a stack effect. +/// How many cells a word pops, then pushes. struct StackEffect { unsigned pops = 0; unsigned pushes = 0; @@ -56,14 +54,13 @@ class WordContext { using LowerFn = std::function; -/// One row of the stack-word table. -struct StackWord { +struct WordLowering { StackEffect effect; LowerFn lower; }; -/// The row for `op`, or null when the table has none. -const StackWord *lookupStackWord(Operation *op); +/// The lowering for `op`, or null when the table has none. +const WordLowering *lookupStackWord(Operation *op); /// Fails, with an error for each one, when a Forth op that takes a /// !forth.stack has no row. The Forth dialect must be loaded. diff --git a/lib/Conversion/ForthToGPU/ForthToGPU.cpp b/lib/Conversion/ForthToGPU/ForthToGPU.cpp index 147cbfb..824a1ba 100644 --- a/lib/Conversion/ForthToGPU/ForthToGPU.cpp +++ b/lib/Conversion/ForthToGPU/ForthToGPU.cpp @@ -106,8 +106,8 @@ static LogicalResult applyConversionPatterns(Operation *op, return applyPartialConversion(op, target, std::move(patterns)); } -/// Pass implementation that wraps func.func operations in a single gpu.module -/// and converts them to gpu.func operations. +/// Wraps the kernel in one gpu.module and converts it to a gpu.func. Any other +/// func.func is an error. struct ConvertForthToGPUPass : public impl::ConvertForthToGPUBase { diff --git a/lib/Conversion/Passes.cpp b/lib/Conversion/Passes.cpp index dc9a7e3..de9e8af 100644 --- a/lib/Conversion/Passes.cpp +++ b/lib/Conversion/Passes.cpp @@ -89,19 +89,13 @@ static StringRef getBinaryFormat(gpu::CompilationTarget target) { void buildWarpForthLoweringPipeline(OpPassManager &pm, const WarpForthPipelineOptions &options) { - // Stage 1: Inline user words while they are still Forth, so the kernel is the - // whole program when its stack is lowered. MLIR's GPU inliner does not - // support inlining a func.func region into a gpu.func region, so this must - // precede GPU conversion. + // MLIR's GPU inliner does not support inlining a func.func region into a + // gpu.func region, so this must precede GPU conversion. pm.addPass(createInlinerPass()); - - // Stage 2: Lower the stack to i64 SSA values and a residual buffer pm.addPass(createLowerForthStackPass()); - - // Stage 3: Convert to GPU dialect pm.addPass(createConvertForthToGPUPass()); - // Stage 4: Optimize the materialized stack and memory IR in the kernel. + // Clean the kernel IR. OpPassManager &gpuModulePM = pm.nest(); gpuModulePM.addNestedPass(createCSEPass()); gpuModulePM.addNestedPass(createCanonicalizerPass()); @@ -110,7 +104,7 @@ void buildWarpForthLoweringPipeline(OpPassManager &pm, gpuModulePM.addNestedPass(createSCCPPass()); gpuModulePM.addNestedPass(createCanonicalizerPass()); - // Stage 5: Attach the configured NVVM target to GPU modules + // Attach the configured NVVM target to GPU modules. GpuNVVMAttachTargetOptions nvvmOptions; nvvmOptions.chip = options.chip.getValue(); nvvmOptions.features = options.features.getValue(); @@ -119,19 +113,19 @@ void buildWarpForthLoweringPipeline(OpPassManager &pm, nvvmOptions.linkLibs.push_back(options.libdevicePath.getValue()); pm.addPass(createGpuNVVMAttachTarget(nvvmOptions)); - // Stage 6: Lower GPU to NVVM with bare pointers + // Lower GPU to NVVM with bare pointers. ConvertGpuOpsToNVVMOpsOptions gpuToNVVMOptions; gpuToNVVMOptions.useBarePtrCallConv = true; pm.addNestedPass( createConvertGpuOpsToNVVMOps(gpuToNVVMOptions)); - // Stage 7: Lower math ops to LLVM intrinsics inside GPU module + // Lower math ops to LLVM intrinsics inside the GPU module. pm.addNestedPass(createConvertMathToLLVMPass()); - // Stage 8: Lower NVVM to LLVM + // Lower NVVM to LLVM. pm.addPass(createConvertNVVMToLLVMPass()); - // Stage 9: Reconcile type conversions + // Reconcile type conversions. pm.addPass(createReconcileUnrealizedCastsPass()); } @@ -139,7 +133,7 @@ void buildWarpForthPipeline(OpPassManager &pm, const WarpForthPipelineOptions &options) { buildWarpForthLoweringPipeline(pm, options); - // Stage 10: Compile GPU module to PTX binary + // Compile the GPU module to a PTX binary. GpuModuleToBinaryPassOptions binaryOptions; binaryOptions.compilationTarget = getBinaryFormat(options.compilationTarget.getValue()).str(); diff --git a/lib/Dialect/Forth/ForthDialect.cpp b/lib/Dialect/Forth/ForthDialect.cpp index 162c1cd..c4abc90 100644 --- a/lib/Dialect/Forth/ForthDialect.cpp +++ b/lib/Dialect/Forth/ForthDialect.cpp @@ -22,8 +22,7 @@ using namespace mlir::forth; #include "warpforth/Dialect/Forth/ForthOps.cpp.inc" namespace { -/// Forth ops hold no state tied to their enclosing word, so every word can be -/// inlined into its caller before the stack is lowered. +/// Forth ops hold no state tied to their enclosing word. struct ForthInlinerInterface : public DialectInlinerInterface { using DialectInlinerInterface::DialectInlinerInterface; diff --git a/test/Conversion/ForthStack/bitwise.mlir b/test/Conversion/ForthStack/bitwise.mlir index 6443074..ffb46f2 100644 --- a/test/Conversion/ForthStack/bitwise.mlir +++ b/test/Conversion/ForthStack/bitwise.mlir @@ -1,7 +1,7 @@ // RUN: %warpforth-opt --lower-forth-stack %s | %FileCheck %s -// `A B op OUT !` for each binary bitwise word: the deeper cell is the left -// operand, and RSHIFT is a logical shift. `A NOT` flips every bit of A. +// `A B op OUT !` for each binary bitwise word. RSHIFT is a logical shift. +// `A NOT` flips every bit of A. // CHECK-LABEL: func.func @bitwise( // CHECK-SAME: %[[A:[^:]*]]: i64, %[[B:[^:]*]]: i64 // CHECK: %[[AND:.*]] = arith.andi %[[A]], %[[B]] : i64 diff --git a/test/Conversion/ForthStack/comparison.mlir b/test/Conversion/ForthStack/comparison.mlir index 12d6b35..e27709e 100644 --- a/test/Conversion/ForthStack/comparison.mlir +++ b/test/Conversion/ForthStack/comparison.mlir @@ -1,7 +1,7 @@ // RUN: %warpforth-opt --lower-forth-stack %s | %FileCheck %s -// `A B op OUT !` for each integer comparison. The deeper cell is the left -// operand, and the flag is the sign-extended i1, so true is -1. +// `A B op OUT !` for each integer comparison. The flag is the sign-extended +// i1, so true is -1. // CHECK-LABEL: func.func @int_comparisons( // CHECK-SAME: %[[A:[^:]*]]: i64, %[[B:[^:]*]]: i64 // CHECK: %[[EQ:.*]] = arith.cmpi eq, %[[A]], %[[B]] : i64 diff --git a/test/Conversion/ForthStack/control-flow.mlir b/test/Conversion/ForthStack/control-flow.mlir index 910ad22..8124e2c 100644 --- a/test/Conversion/ForthStack/control-flow.mlir +++ b/test/Conversion/ForthStack/control-flow.mlir @@ -16,7 +16,6 @@ // CHECK: ^[[JOIN]](%[[RESULT:.*]]: i64): // CHECK: llvm.store %[[RESULT]], %{{.*}} : i64, !llvm.ptr<1> -// A true flag takes the IF arm. // FOLD-LABEL: func.func @if_else( // FOLD: %[[C42:.*]] = arith.constant 42 : i64 // FOLD: llvm.store %[[C42]], %{{.*}} : i64, !llvm.ptr<1> diff --git a/test/Conversion/ForthStack/float.mlir b/test/Conversion/ForthStack/float.mlir index 2995d62..cdf1bb1 100644 --- a/test/Conversion/ForthStack/float.mlir +++ b/test/Conversion/ForthStack/float.mlir @@ -4,7 +4,6 @@ // its result back to i64, so after canonicalization the round trips are gone // and each word applies to the f64 parameters directly. -// `X Y op OUT !`: the deeper cell is the left operand. // CHECK-LABEL: func.func @float_arithmetic( // CHECK-SAME: %[[X:[^:]*]]: f64, %[[Y:[^:]*]]: f64 // CHECK: %[[SUM:.*]] = arith.addf %[[X]], %[[Y]] : f64 diff --git a/test/Conversion/ForthStack/pick-roll.mlir b/test/Conversion/ForthStack/pick-roll.mlir index e105d90..a8c57fc 100644 --- a/test/Conversion/ForthStack/pick-roll.mlir +++ b/test/Conversion/ForthStack/pick-roll.mlir @@ -49,8 +49,8 @@ func.func @literal_roll(%a: memref<1xi64>, %b: memref<1xi64>, %c: memref<1xi64>) } // `10 20 30 N PICK A ! B !`: a runtime index needs addressable cells, so the -// three cells are stored at indices 1 to 3 as the image for one load at -// 3 - N. The cells stay in registers, so B receives 30 directly. +// three cells are stored at indices 1 to 3 for the load at 3 - N. The depth +// of that store is dropped, so the cells stay in registers and B receives 30. // CHECK-LABEL: func.func @dynamic_pick( // CHECK-SAME: %[[N:[^:]*]]: i64 // CHECK: %[[BUFFER:.*]] = memref.alloca() : memref<256xi64> diff --git a/test/Conversion/ForthStack/residual.mlir b/test/Conversion/ForthStack/residual.mlir index bf160a0..9100e35 100644 --- a/test/Conversion/ForthStack/residual.mlir +++ b/test/Conversion/ForthStack/residual.mlir @@ -1,8 +1,7 @@ // RUN: %warpforth-opt --lower-forth-stack %s | %FileCheck %s // `5 + A !`: + needs a second cell that the stack does not have. The pop -// widens the stack to the residual buffer and loads index 0, as the memref -// stack did, instead of failing to compile. +// widens the stack to the residual buffer and loads index 0. // CHECK-LABEL: func.func @underflow( // CHECK: %[[BUFFER:.*]] = memref.alloca() : memref<256xi64> // CHECK: %[[FIVE:.*]] = arith.constant 5 : i64 diff --git a/test/Conversion/ForthStack/unknown-stack-user-error.mlir b/test/Conversion/ForthStack/unknown-stack-user-error.mlir index 5be561a..d8f086d 100644 --- a/test/Conversion/ForthStack/unknown-stack-user-error.mlir +++ b/test/Conversion/ForthStack/unknown-stack-user-error.mlir @@ -1,7 +1,5 @@ // RUN: %not %warpforth-opt --allow-unregistered-dialect --lower-forth-stack %s 2>&1 | %FileCheck %s -// Only Forth words and branches may use a stack, so an op outside the table is -// an error instead of a stack value with no cells. // CHECK: error: 'test.consume' op uses a !forth.stack but has no stack-word row func.func @main() { %0 = forth.stack !forth.stack diff --git a/test/Conversion/ForthStack/word-not-inlined-error.mlir b/test/Conversion/ForthStack/word-not-inlined-error.mlir index 8dc34a5..e0e6c4c 100644 --- a/test/Conversion/ForthStack/word-not-inlined-error.mlir +++ b/test/Conversion/ForthStack/word-not-inlined-error.mlir @@ -1,7 +1,5 @@ // RUN: %not %warpforth-opt --lower-forth-stack %s 2>&1 | %FileCheck %s -// The lowered stack has no calling convention, so every word must be inlined -// before the stack is lowered. // CHECK: error: Forth word @double was not inlined; run --inline before --lower-forth-stack func.func private @double(%s: !forth.stack) -> !forth.stack { diff --git a/test/Conversion/ForthToGPU/non-kernel-function-error.mlir b/test/Conversion/ForthToGPU/non-kernel-function-error.mlir index 870f0ed..c3f7e55 100644 --- a/test/Conversion/ForthToGPU/non-kernel-function-error.mlir +++ b/test/Conversion/ForthToGPU/non-kernel-function-error.mlir @@ -1,7 +1,5 @@ // RUN: %not %warpforth-opt --convert-forth-to-gpu %s 2>&1 | %FileCheck %s -// Only the kernel reaches GPU conversion, so any other function, such as a -// word that survived inlining, is an error. // CHECK: error: @helper is not the kernel; inline every Forth word before --convert-forth-to-gpu module { From 969a71aea22b20f74944b04c93dfb5456b881081 Mon Sep 17 00:00:00 2001 From: Alex Cameron Date: Mon, 9 Nov 2026 05:54:45 +0000 Subject: [PATCH 8/8] fix(conversion): drop unused private Forth words The inliner deletes an unused caller and leaves its private callee. That leftover word still has a stack signature, so a program that never calls it failed to compile. --- lib/Conversion/ForthStack/LowerForthStack.cpp | 17 +++++++++++++ test/Conversion/ForthStack/unused-word.mlir | 24 +++++++++++++++++++ test/Pipeline/unused-word.forth | 14 +++++++++++ 3 files changed, 55 insertions(+) create mode 100644 test/Conversion/ForthStack/unused-word.mlir create mode 100644 test/Pipeline/unused-word.forth diff --git a/lib/Conversion/ForthStack/LowerForthStack.cpp b/lib/Conversion/ForthStack/LowerForthStack.cpp index ba438c4..b115d2d 100644 --- a/lib/Conversion/ForthStack/LowerForthStack.cpp +++ b/lib/Conversion/ForthStack/LowerForthStack.cpp @@ -18,6 +18,7 @@ #include "mlir/IR/BuiltinTypes.h" #include "mlir/IR/PatternMatch.h" #include "mlir/IR/RegionGraphTraits.h" // IWYU pragma: keep +#include "mlir/IR/SymbolTable.h" #include "mlir/Interfaces/ControlFlowInterfaces.h" #include "mlir/Pass/Pass.h" #include "mlir/Transforms/RegionUtils.h" @@ -116,6 +117,21 @@ ArrayRef cellsOf(const StackState &state) { state); } +/// The inliner drops an unused caller and leaves the private callee. +void eraseUnusedPrivateFunctions(ModuleOp module) { + bool erased = true; + while (erased) { + erased = false; + for (func::FuncOp fn : module.getOps()) { + if (!fn.isPrivate() || !SymbolTable::symbolKnownUseEmpty(fn, module)) + continue; + fn.erase(); + erased = true; + break; + } + } +} + /// A word keeps the stack in its signature until the inliner removes it, and /// this pass gives words no calling convention. LogicalResult verifyWordsInlined(ModuleOp module) { @@ -482,6 +498,7 @@ struct LowerForthStackPass void runOnOperation() override { ModuleOp module = getOperation(); + eraseUnusedPrivateFunctions(module); if (failed(verifyWordsInlined(module))) return signalPassFailure(); IRRewriter rewriter(&getContext()); diff --git a/test/Conversion/ForthStack/unused-word.mlir b/test/Conversion/ForthStack/unused-word.mlir new file mode 100644 index 0000000..117db93 --- /dev/null +++ b/test/Conversion/ForthStack/unused-word.mlir @@ -0,0 +1,24 @@ +// RUN: %warpforth-opt --lower-forth-stack %s | %FileCheck %s + +// CHECK-NOT: func.func private +// CHECK-LABEL: func.func @main( +// CHECK: %[[FIVE:.*]] = arith.constant 5 : i64 +// CHECK: llvm.store %[[FIVE]], %{{.*}} : i64, !llvm.ptr<1> + +module { + func.func private @a(%s: !forth.stack) -> !forth.stack { + %0 = forth.dup %s : !forth.stack -> !forth.stack + return %0 : !forth.stack + } + func.func private @b(%s: !forth.stack) -> !forth.stack { + %0 = func.call @a(%s) : (!forth.stack) -> !forth.stack + return %0 : !forth.stack + } + func.func @main(%out: memref<1xi64>) attributes {forth.kernel} { + %0 = forth.stack !forth.stack + %1 = forth.constant %0(5 : i64) : !forth.stack -> !forth.stack + %2 = forth.param_ref %1 %out : !forth.stack, memref<1xi64> -> !forth.stack + %3 = forth.storei %2 : !forth.stack -> !forth.stack + return + } +} diff --git a/test/Pipeline/unused-word.forth b/test/Pipeline/unused-word.forth new file mode 100644 index 0000000..d77f4bd --- /dev/null +++ b/test/Pipeline/unused-word.forth @@ -0,0 +1,14 @@ +\ RUN: %warpforthc -O0 %s -o %t.ptx +\ RUN: %FileCheck %s < %t.ptx + +\ An unused word that only calls another unused word is not part of the kernel. +\ CHECK-NOT: .func +\ CHECK: .entry main( +\ CHECK: st.global.u64 +\ CHECK-NOT: .func + +\! kernel main +\! param OUT i64[1] +: a 1 + ; +: b a ; +5 OUT !