Simple Sudoku Solver in Verilog
Welcome back to another episode of Simple Sudoku Solvers. In this installment, we dive deep into Verilog, a hardware description language, to build the machine directly. Unlike programming, where you write code that runs on hardware, Verilog involves describing a circuit, which the compiler then converts into gates and flip-flops.
We'll run the solver in a simulator since I don't have access to an actual Sudoku chip. The solver is around 145 lines long, not including the additional 40 lines required for feeding the puzzle and printing the result. You can compile and run the code using Icarus Verilog with the command iverilog -o sudoku sudoku.v && vvp sudoku.
The Verilog code consists of a module with inputs and outputs, representing a circuit. The wire [8:0] x command creates a bundle of nine wires, numbered from 8 to 0. The reg data type represents a value we assign within procedural blocks. There are two types of blocks: always @* describes combinational logic, which is a pure function of its inputs, and always @(posedge clk) describes sequential logic, which runs at every rising clock edge.
For loops, though present, are unrolled completely during synthesis, as synthesizable code cannot contain them. The board is represented as a single 324-bit vector, with four bits per cell and 0 for empty cells.
The solver takes three input wires and outputs three registers. It holds a puzzle on the puzzle wires, waits for a start signal, and checks if the done signal goes high. If the solved flag is set, the board contains the answer; otherwise, it indicates an unsolvable puzzle. The board reading is done using slices, which are functions that extract specific portions of the board. Bit slices work similarly to slices in other programming languages, with +: and -: operators indicating the direction from the start index.
The solver employs several techniques to optimize its performance, such as bitmasks to track digits and a popcount function to count the number of set bits. However, unlike previous solver episodes, this one incorporates parallelism, dividing the work among multiple circuits and minimizing the need for branches. The search strategy has been modified to account for the parallel nature of the system, resulting in a more efficient and faster solver.
Rewritten by urgent.news; may contain errors — check the original.
Source: blog.veitheller.de