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/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/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 be86499..a964e25 100644 --- a/include/warpforth/Conversion/Passes.td +++ b/include/warpforth/Conversion/Passes.td @@ -9,27 +9,27 @@ include "mlir/Pass/PassBase.td" -def ConvertForthToMemRef - : Pass<"convert-forth-to-memref", "mlir::ModuleOp"> { - let summary = "Convert Forth dialect to MemRef dialect"; +def LowerForthStack : Pass<"lower-forth-stack", "mlir::ModuleOp"> { + let summary = "Lower the Forth stack to i64 SSA values"; 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. + 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 cell below the known depth, or one that a runtime `PICK` or `ROLL` index + 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::createConvertForthToMemRefPass()"; + let constructor = "mlir::warpforth::createLowerForthStackPass()"; - let dependentDialects = ["mlir::memref::MemRefDialect", - "mlir::arith::ArithDialect", - "mlir::LLVM::LLVMDialect", + let dependentDialects = ["mlir::arith::ArithDialect", "mlir::cf::ControlFlowDialect", - "mlir::math::MathDialect"]; + "mlir::forth::ForthDialect", + "mlir::LLVM::LLVMDialect", + "mlir::math::MathDialect", + "mlir::memref::MemRefDialect"]; } def ConvertForthToGPU : Pass<"convert-forth-to-gpu", "mlir::ModuleOp"> { @@ -38,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 6393a67..e76e845 100644 --- a/lib/Conversion/CMakeLists.txt +++ b/lib/Conversion/CMakeLists.txt @@ -6,7 +6,7 @@ add_mlir_library(MLIRConversionPasses LINK_LIBS PUBLIC MLIRPass - MLIRForthToMemRefConversion + MLIRForthStackConversion MLIRForthToGPUConversion MLIRGPUDialect MLIRGPUToNVVMTransforms @@ -21,5 +21,5 @@ target_compile_definitions(obj.MLIRConversionPasses PRIVATE WARPFORTH_LIBDEVICE_PATH="${WARPFORTH_LIBDEVICE_PATH}" ) -add_subdirectory(ForthToMemRef) +add_subdirectory(ForthStack) add_subdirectory(ForthToGPU) diff --git a/lib/Conversion/ForthToMemRef/CMakeLists.txt b/lib/Conversion/ForthStack/CMakeLists.txt similarity index 60% rename from lib/Conversion/ForthToMemRef/CMakeLists.txt rename to lib/Conversion/ForthStack/CMakeLists.txt index 1f85b95..0f2692d 100644 --- a/lib/Conversion/ForthToMemRef/CMakeLists.txt +++ b/lib/Conversion/ForthStack/CMakeLists.txt @@ -1,5 +1,6 @@ -add_mlir_conversion_library(MLIRForthToMemRefConversion - ForthToMemRef.cpp +add_mlir_conversion_library(MLIRForthStackConversion + LowerForthStack.cpp + StackWords.cpp DEPENDS MLIRConversionPassIncGen @@ -8,12 +9,15 @@ add_mlir_conversion_library(MLIRForthToMemRefConversion LINK_LIBS PUBLIC MLIRIR MLIRPass - MLIRTransformUtils - MLIRMemRefDialect MLIRArithDialect - MLIRLLVMDialect - MLIRFuncDialect MLIRControlFlowDialect + MLIRControlFlowInterfaces + MLIRDialectUtils + MLIRFuncDialect + MLIRLLVMDialect MLIRMathDialect + MLIRMemRefDialect + MLIRNVVMDialect + MLIRTransformUtils MLIRForth ) diff --git a/lib/Conversion/ForthStack/LowerForthStack.cpp b/lib/Conversion/ForthStack/LowerForthStack.cpp new file mode 100644 index 0000000..b115d2d --- /dev/null +++ b/lib/Conversion/ForthStack/LowerForthStack.cpp @@ -0,0 +1,523 @@ +//===- LowerForthStack.cpp - Lower the Forth stack --------------*- C++ -*-===// +// +// This file implements the pass that lowers every !forth.stack value. +// +//===----------------------------------------------------------------------===// + +#include "warpforth/Conversion/ForthStack/LowerForthStack.h" +#include "StackWords.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/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" +#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/IR/SymbolTable.h" +#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 { +namespace warpforth { + +#define GEN_PASS_DEF_LOWERFORTHSTACK +#include "warpforth/Conversion/Passes.h.inc" + +namespace { + +using stack::StackEffect; +using stack::WordContext; +using stack::WordLowering; + +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 +/// `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; + 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; + +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}; +} + +/// 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; + 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. +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); +} + +ArrayRef cellsOf(const StackState &state) { + return std::visit([](const auto &s) -> ArrayRef { return s.cells; }, + 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) { + 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(); +} + +LogicalResult verifyStackUsers(Region &body) { + WalkResult walk = body.walk([](Operation *op) { + 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 failure(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 WordLowering *word = stack::lookupStackWord(&op); + if (!word) + continue; + shapes[op.getResult(0)] = + transfer(shapes.at(op.getOperand(0)), word->effect); + } + } + } + return shapes; +} + +class StackSimulator final : public WordContext { +public: + StackSimulator(func::FuncOp fn, DenseMap shapes) + : fn(fn), b(fn.getContext()), shapes(std::move(shapes)), + loc(fn.getLoc()) {} + + void run(); + + 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); + } + +private: + void expandArguments(Block &block); + 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); + 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; + 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; + Value buffer; + + // Scratch for the op being lowered. + Location loc; + Operation *current = nullptr; + StackState working; + SmallVector poppedCells; + SmallVector pushedCells; +}; + +void StackSimulator::run() { + Region &body = fn.getBody(); + for (Block &block : body) + expandArguments(block); + for (Block *block : llvm::ReversePostOrderTraversal(&body.front())) { + // 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 WordLowering *word = stack::lookupStackWord(op)) { + lowerWord(op, *word); + } else if (auto branch = dyn_cast(op)) { + forwardCells(branch); + } + op = next; + } + } + for (Operation *op : lowered) + op->dropAllReferences(); + for (Operation *op : lowered) + op->erase(); + for (BlockArgument arg : replacedArguments) + arg.getOwner()->eraseArgument(arg.getArgNumber()); +} + +void StackSimulator::expandArguments(Block &block) { + SmallVector &original = originalArguments[&block]; + original = llvm::to_vector(block.getArguments()); + for (BlockArgument arg : original) { + if (!isStack(arg.getType())) + continue; + 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 WordLowering &word) { + current = op; + loc = op->getLoc(); + b.setInsertionPoint(op); + working = states.at(op->getOperand(0)); + poppedCells.clear(); + for (unsigned i = 0; i < word.effect.pops; ++i) + poppedCells.push_back(popCell()); + pushedCells.clear(); + 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); +} + +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 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); + 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); + 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); + } +} + +void StackSimulator::shiftCellsDown(Value from, Value top) { + 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, from); + + 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); +} + +/// 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 (auto [j, value] : llvm::enumerate(operands.getForwardedOperands())) { + if (!isStack(value.getType())) { + forwarded.push_back(value); + continue; + } + 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; +} + +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. 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)); + b.create(loc, cell, residualBuffer(), depth); + } + return depth; +} + +Value StackSimulator::indexConstant(int64_t value) { + return b.create(loc, value); +} + +struct LowerForthStackPass + : public impl::LowerForthStackBase { + LogicalResult initialize(MLIRContext *context) override { + return stack::verifyStackWordTableCoversDialect(context); + } + + void runOnOperation() override { + ModuleOp module = getOperation(); + eraseUnusedPrivateFunctions(module); + if (failed(verifyWordsInlined(module))) + return signalPassFailure(); + IRRewriter rewriter(&getContext()); + for (auto fn : module.getOps()) { + if (fn.isExternal()) + continue; + (void)eraseUnreachableBlocks(rewriter, fn->getRegions()); + if (failed(verifyStackUsers(fn.getBody()))) + return signalPassFailure(); + StackSimulator(fn, inferShapes(fn.getBody())).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..eec8c05 --- /dev/null +++ b/lib/Conversion/ForthStack/StackWords.cpp @@ -0,0 +1,479 @@ +//===- 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/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" + +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); +constexpr unsigned kSharedAddressSpace = + static_cast(NVVM::kSharedMemorySpace); + +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"); +} + +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"); +} + +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; + WordLowering word; +}; + +template StackWordRow row(WordLowering word) { + return {TypeID::get(), std::move(word)}; +} + +template +StackWordRow row(StackEffect effect, void (*lower)(OpT, WordContext &)) { + return {TypeID::get(), + {effect, [lower](Operation *op, WordContext &ctx) { + lower(cast(op), ctx); + }}}; +} + +/// A word that only reorders cells. It pushes popped(i) for each i in +/// `order`, deepest first. +WordLowering 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 WordLowering intBinary() { + return {{2, 1}, [](Operation *op, WordContext &ctx) { + ctx.push(ctx.builder().create(op->getLoc(), ctx.popped(1), + ctx.popped(0))); + }}; +} + +/// ( a b -- a op b ) on the f64 bits of each cell. +template WordLowering 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 WordLowering 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 ) +WordLowering 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. +WordLowering 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 ) +WordLowering 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 -- ) +WordLowering store(MemType type, unsigned addressSpace) { + return {{2, 0}, [type, addressSpace](Operation *op, WordContext &ctx) { + OpBuilder &b = ctx.builder(); + Location loc = op->getLoc(); + 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". +WordLowering 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) { + OpBuilder &b = ctx.builder(); + auto value = cast(op.getValueAttr()); + if (isa(value)) { + Value f64 = b.create( + op.getLoc(), b.getF64Type(), value); + ctx.push(toCell(b, op.getLoc(), 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(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))); + }), + row({1, 0}, + [](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()); + }), + 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(), CmpIPredicate::ne, ctx.popped(0), + zero)); + }), + }; + return rows; +} + +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"); + (void)inserted; + } + return words; + }(); + return words; +} + +} // namespace + +const WordLowering *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 +} // namespace warpforth +} // namespace mlir diff --git a/lib/Conversion/ForthStack/StackWords.h b/lib/Conversion/ForthStack/StackWords.h new file mode 100644 index 0000000..ce11a57 --- /dev/null +++ b/lib/Conversion/ForthStack/StackWords.h @@ -0,0 +1,73 @@ +//===- 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. +// +//===----------------------------------------------------------------------===// + +#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. +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; + + /// 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; +}; + +using LowerFn = std::function; + +struct WordLowering { + StackEffect effect; + LowerFn lower; +}; + +/// 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. +LogicalResult verifyStackWordTableCoversDialect(MLIRContext *context); + +} // namespace stack +} // namespace warpforth +} // namespace mlir + +#endif diff --git a/lib/Conversion/ForthToGPU/ForthToGPU.cpp b/lib/Conversion/ForthToGPU/ForthToGPU.cpp index 6a363e6..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 { @@ -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/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 32e99eb..de9e8af 100644 --- a/lib/Conversion/Passes.cpp +++ b/lib/Conversion/Passes.cpp @@ -13,8 +13,8 @@ #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" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" @@ -89,18 +89,13 @@ 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. pm.addPass(createInlinerPass()); - - // Stage 3: Convert to GPU dialect (includes private address space annotation) + pm.addPass(createLowerForthStackPass()); 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()); @@ -109,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(); @@ -118,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()); } @@ -138,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(); @@ -150,9 +145,8 @@ void buildWarpForthPipeline(OpPassManager &pm) { } void registerConversionPasses() { - registerPass([]() -> std::unique_ptr { - return createConvertForthToMemRefPass(); - }); + registerPass( + []() -> std::unique_ptr { return createLowerForthStackPass(); }); registerPass( []() -> std::unique_ptr { return createConvertForthToGPUPass(); }); diff --git a/lib/Dialect/Forth/ForthDialect.cpp b/lib/Dialect/Forth/ForthDialect.cpp index aa410a3..c4abc90 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,17 @@ 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. +struct ForthInlinerInterface : public DialectInlinerInterface { + using DialectInlinerInterface::DialectInlinerInterface; + + bool isLegalToInline(Operation *, Region *, bool, IRMapping &) const final { + return true; + } +}; +} // namespace + //===----------------------------------------------------------------------===// // Forth dialect. //===----------------------------------------------------------------------===// @@ -33,4 +45,5 @@ void ForthDialect::initialize() { #define GET_OP_LIST #include "warpforth/Dialect/Forth/ForthOps.cpp.inc" >(); + addInterfaces(); } diff --git a/test/Conversion/ForthStack/bitwise.mlir b/test/Conversion/ForthStack/bitwise.mlir new file mode 100644 index 0000000..ffb46f2 --- /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. 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..e27709e --- /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 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 new file mode 100644 index 0000000..8124e2c --- /dev/null +++ b/test/Conversion/ForthStack/control-flow.mlir @@ -0,0 +1,208 @@ +// 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> + +// 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 +} + +// `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..cdf1bb1 --- /dev/null +++ b/test/Conversion/ForthStack/float.mlir @@ -0,0 +1,179 @@ +// 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. + +// 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/pick-roll.mlir b/test/Conversion/ForthStack/pick-roll.mlir new file mode 100644 index 0000000..a8c57fc --- /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 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> +// 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..9100e35 --- /dev/null +++ b/test/Conversion/ForthStack/residual.mlir @@ -0,0 +1,52 @@ +// 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. +// 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/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 +} 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/unknown-stack-user-error.mlir b/test/Conversion/ForthStack/unknown-stack-user-error.mlir new file mode 100644 index 0000000..d8f086d --- /dev/null +++ b/test/Conversion/ForthStack/unknown-stack-user-error.mlir @@ -0,0 +1,8 @@ +// RUN: %not %warpforth-opt --allow-unregistered-dialect --lower-forth-stack %s 2>&1 | %FileCheck %s + +// 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/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/Conversion/ForthStack/word-not-inlined-error.mlir b/test/Conversion/ForthStack/word-not-inlined-error.mlir new file mode 100644 index 0000000..e0e6c4c --- /dev/null +++ b/test/Conversion/ForthStack/word-not-inlined-error.mlir @@ -0,0 +1,16 @@ +// RUN: %not %warpforth-opt --lower-forth-stack %s 2>&1 | %FileCheck %s + +// 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/Conversion/ForthToGPU/non-kernel-function-error.mlir b/test/Conversion/ForthToGPU/non-kernel-function-error.mlir new file mode 100644 index 0000000..c3f7e55 --- /dev/null +++ b/test/Conversion/ForthToGPU/non-kernel-function-error.mlir @@ -0,0 +1,12 @@ +// RUN: %not %warpforth-opt --convert-forth-to-gpu %s 2>&1 | %FileCheck %s + +// 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/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/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/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/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/test/Pipeline/source-locations.forth b/test/Pipeline/source-locations.forth index 1df9860..b5c03db 100644 --- a/test/Pipeline/source-locations.forth +++ b/test/Pipeline/source-locations.forth @@ -1,12 +1,13 @@ \ 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 -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: 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":5:1) +\ LOWERED: [[LOWERED_LOC]] = loc("{{.*}}source-locations.forth":6:1) 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 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 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> 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 ! 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 )