Brainfuck CPU - Hardware Implementation

Brainfuck CPU - Hardware Implementation

Details

Category: Processor

Created: September 03, 2014

Updated: January 27, 2020

Language: Verilog

Other project properties

Development Status: Beta

WishBone compliant: No

WishBone version: n/a

License: LGPL

Description

Brainfuck CPU is a hardware implementation of Brainfuck programing language. It uses simple 2-stage pipelining and Harvard's architecture.

This CPU is very similar to Touring machine. It operates over linear memory space. Main difference is that the memory is finite.

Instruction set is fairy simple. Opcodes are only 3-bit wide. This allows lower usage of resources over original coding (7 bit ASCII). Verion using original instruction set is available as well.

Can't place oposite of > char for some reason, so I'll use "(oposite of >)" instead.

Opcodes

Opcodes:
000 == (oposite of >) (move pointer left)
001 == > (move pointer right)
010 == + (add 1 to value of current memory cell)
011 == - (subtract 1 from value of current memory cell)
100 == , (read from I/O port)
101 == . (write to I/O port)
110 == [ (begining of loop)
111 == ] (end of loop)

ASCII opcodes (7-bit):
0x3C == (oposite of >)
0x3E == >
0x2B == +
0x2D == -
0x2C == ,
0x2E == .
0x5B == [
0x5D == ]
other == NOP

Opcodes timing

At start it is necesary to reset all memory locations to 0. CPU does that automatically after reset.

Operations '+', '-', ',' and '.' are always completed in one cycle. As it is necessary to load or store memory cell from/to memory, '>' and (oposite of >) takes two cycles to finish. Opcode ']' takes two cycles on loop finish and one on end, but '[' is a special case. If loop condition is not met (current cell is not 0) it takes one cycle. But in worst case scenario condition is meet at entry. It means that CPU has to find closing bracket ']'. This can waste many time, but it is situation that should not occur, if program is writen correctly.

Files

CPU is only one file: "brainfuck_cpu.v". It is CPU core and it requires addition of ROM and RAM.

Second file is testbench "brainfuck_cpu_tb.v". It demonstrates execution of "Hello World!" program writen in Brainfuck and compresed to 3 bits.

Parameters

brainfuck_cpu.v accepts 3 parameters:

DATA_ADDR_WIDTH - defines width of data memory address bus and in consequence size of this memory.

ROM_ADDR_WIDTH - defines width of program memory address bus and in consequence size of this memory. Note that Brainfuck language requires a lot of program memory. "Hello World!" program uses 115 cells.

STACK_DEPTH - defines depth of stack. Stack is used to keep track of execution of loops. It's depth imposes maximal level of loops nesting.