[Icestudio] Hardware FORTH. Prueba de concepto

134 views
Skip to first unread message

Juan Gonzalez Gomez

unread,
Jun 25, 2023, 11:49:41 AM6/25/23
to FPGA-WARS: explorando el lado libre
Llevo unos días trabajando en una idea de concepto: realizar circuitos utilizando la filosofía del lenguaje FORTH [1]

Cada palabra de Forth es un bloque de icestudio. Las palabras primitivas están implementadas directamente en hardware, mientras que el resto de palabras lo están a partir de otros bloques-palabras

En el lenguaje Forth se define una máquina virtual muy sencilla, que tiene 2 pilas: Una de datos y otra de retorno. La clave está en el bloque 'hardware forth' que es el que incluye la pila de datos

Los "programas" se construyen uniendo los bloques palabras a través de un bus, que llega hasta el bloque "Hardware forth". Este bus se realimenta hacia los bloques de nuevo para poder leer los datos de la pila

He comenzado de momento implementando una máquina Forth de datos de 1-bit (para usarla de prueba de concepto). El programa de ejemplo que he probado es el siguiente. Descrito en sintaxis de Forth es: 0 1 +  (Realiza la suma 1+0. El resultado queda almacenado en la pila de datos)

hardware-forth-1.png

El primer bloque (K) introduce el literal 0 en la pila, el siguiente el literal 1 tambien en la pila, y por último, el bloque `+` extrae los dos últimos operandos de la pila, realiza la suma y deja el resultado en la pila
La ejecución es secuencial. Al apretar el botón de start se ejecuta el primer bloque (literal 0). Al terminal le pasa el control al de su derecha (literal 1) y éste a su vez al de la suma. Las entradas/salidas HF son en realidad un bus compartido por donde circulan los datos hacia la pila (y desde ella)


Lo interesante de este enfoque es que en el lenguaje Forth, todo se construye a partir de unas pocas palabras primitivas. Si las tenemos implementadas en hardware, se podrán hacer prototipos muy rápios en hardware pensando en "software". No tengo muy claro hacia donde va esto, pero está resultando muy interesante, y es algo que quiero explorar 😀

Os iré contando los avances. De momento lo dejo como prueba de concepto, y he visto que es totalmente viable. Según vaya sacando tiempo lo iré retomando

Las pruebas iniciales las estoy dejando en el repositorio de los cuadernos técnicos, para escribir algún día uno sobre esto


(El ejemplo que os he puesto en el pantallazo se corresponde con 08-Pila.ice)

Saludos, Obijuan


charli va

unread,
Jun 25, 2023, 12:04:34 PM6/25/23
to fpga-wars-explora...@googlegroups.com
Super interesante esto que mandas! yo llevo un tiempo también jugando con Forth (aunque de momento sólo he estado jugando a nivel software) porque me parece una de esas cosas que está en los pilares de la informática con un valor incalculable y han quedado sólo como "curiosidades" pero que realmente estoy seguro que tienen una nueva lectura con los ojos de hoy.

Realmente este primer ejercicio que mandas me ha parecido super sugerente, ¡super atento a lo que vayas haciendo!

Por si a alguien le interesa , este libro me parece una joya:


Un abrazo y gracias por compartir!!!

--
Has recibido este mensaje porque estás suscrito al grupo "FPGAwars: explorando el lado libre" de Grupos de Google.
Para cancelar la suscripción a este grupo y dejar de recibir sus mensajes, envía un correo electrónico a fpga-wars-explorando-el...@googlegroups.com.
Para ver esta conversación en el sitio web, visita https://groups.google.com/d/msgid/fpga-wars-explorando-el-lado-libre/CABqu7xqZY-n2oPDTGvC%2BUghg6NVmNcGpZkBuGhd_-RYdSHj1OA%40mail.gmail.com.

Obijuan

unread,
Jun 25, 2023, 12:17:07 PM6/25/23
to FPGAwars: explorando el lado libre
Sí, yo también pienso que FORTH es una joya, y está en los niveles más bajos del software, aunque se puede usar como lenguaje de alto nivel.

Gracias a los trabajos de Alexandre Dumont (@adumont), he redescubierto el Forth y por fin he comprendido sus fundamentos. Los comenta muy bien adumont en este repositorio: https://github.com/adumont/AlexForth6809

Estos "hilos" forth son los que estoy implementando en hardware, pero en vez de ser un motor software, estoy usando un motor hardware. Y me he quedado muy sorprendido de los sencillo y simple que ha resultado su implementación.. Y creo  que para hacer prototipos hardware esto puede ser muy interesante

y quien sabe, tal vez en el futuro podamos construir un compilador Forth en el que nos compile directamente a hardware (Bien a bloques de icestudio o bien directamente a algún lenguaje HDL)

Saludos, Obijuan

charli va

unread,
Jun 25, 2023, 12:27:57 PM6/25/23
to fpga-wars-explora...@googlegroups.com
O directamente como estás haciendo una "máquina virtual" FORTH o deberíamso llamarla máquina FORTH!  yo creo que en aquellos momento iniciales se veía muy unido el hardware al software y las personas que andaban pensando en estas cosas tenían esa capacidad natural de ver "la máquina" en funcionamiento, es una maravilla.

Le echaré un vistazo al enlace de Alex Dumont, Forth está muy vivo más de lo que parece, las personas que llevan https://www.forth2020.org/.  hacen charlas online bastante a menudo, lo están llevando a colegios (sobre todo por américa del sur) para enseñar computación a los más pequeños y aunque no he investigado mucho en esa línea, he llegado a ver imágenes de programas gráficos hechos en forth por escolares.

Un tema apasionante, nuevamente Maestro, miles de gracias por compartir tus aventuras!

Alfredo Carmona Mirats

unread,
Jun 25, 2023, 12:56:49 PM6/25/23
to fpga-wars-explora...@googlegroups.com
¡WoW!....
Me parece Genial.
Imagino la potencia y rapidez de cálculo y ejecución, al no necesitar parentesis ni código que tenga que compilarse previamente.
Sería dar respuesta en tiempo Real... a las entradas del Sistema.
Te felicito por esa gran idea.


Juan Gonzalez Gomez

unread,
Jun 26, 2023, 5:44:47 AM6/26/23
to fpga-wars-explora...@googlegroups.com
¡Gracias Alfredo! 😀

Veremos a ver dónde nos lleva esta idea... hay que seguir explorando

Saludos, Obijuan


Juan Gonzalez Gomez

unread,
Jun 26, 2023, 5:52:14 AM6/26/23
to fpga-wars-explora...@googlegroups.com
Sigo con las pruebas de concepto. De momento los datos siguen siendo de 1 bit (la pila es de datos de 1 bit). He añadido el primer periférico mapeado en la dirección 0. Es un LED. Utilizando la instrucción store (!) lo podemos encender sin más
que almacenar el valor 1 en la dirección 0

Para comprobar que todo sigue funcionando, he hecho este programa que enciende el LED y calcula la suma 0 + 1 (y el resultado se deja en la pila)

El programa en Forth es:  1 0 !  0 1 +

Y este es el circuito en Hardware Forth:

hardware-forth-2.png

El siguiente paso será añadir un puerto de entrada (de 1 bit) para leer un pulsador con la palabra @ (Fetch)

Saludos, Obijuan

Juan Gonzalez Gomez

unread,
Jun 26, 2023, 2:21:00 PM6/26/23
to fpga-wars-explora...@googlegroups.com
Ya he implementado un puerto de entrada de 1-bit, conectado al botón, y se lee mediante la palabra FORTH @ (fetch). La dirección asignada al pulsador es la 1 (la 0 es para el led)

Para probarlo he implementado las palabras BEGIN y AGAIN que permiten hacer un bucle infinito en Forth. En hardware los bucles infinitos son muy sencillos: al ser bucles espaciales, basta con tirar un cable al comienzo para que las señal de
activación vuelva a pasar otra vez por todos los bloques

El programa FORTH implementado es:  BEGIN 1 @ 0 ! AGAIN

En Hardware Forth es este:

hardware-forth-3.png


Este programa lee constantemente el pulsador y muestra su estado en el LED. Al apretarlo el LED se enciende, y al soltarlo se apaga

Ya tenemos bastantes cosas en este mini-Hardware Forth: Podemos leer de una dirección (y leer el botón), podemos escribir en otra dirección (y así encender el LED) y también podemos hacer bucles infinitos!!!!!

Lo siguiente será ampliar los datos a 2-bits (Ahora son de 1 bits) y añadir memoria RAM para poder tener variables

El hardware forth final mínimo tendrá que tener datos de 8-bits al menos, pila de datos de 8-bits, pila de retorno de 8-bits, memoria ram y más periféricos (puerto serie, temporizador....)

Saludos, Obijuan


Jo mo

unread,
Jun 29, 2023, 2:11:57 PM6/29/23
to FPGAwars: explorando el lado libre
Hola Juan,

Gracias for this interesting forth researches!
i have just a very little idea about that Forth language,  i just remember that you previously made the J1a Forth processor block! which of course can read forth code!

But making block for each command of the forth code !?!? 

As most of the "computer code" is made to be executed sequentialy by the same hardware (core)!
i suppose that a forth code implemented that way ( every command is executed by a different hardware one following the other)
it will not be faster than the code executed by a single core (ALU)

But if the code is very repetitive (eg: process the 400'000 pixels of a picture,) i imagine this ways of processing code is interesting because the work can be pipelined!
and there we can gain a lot of speed! (eg: if the processing of one pixel needs 50 différent icestudio forth blocks, than the processing of the entire set of pixels can be  up to a maximum of 50 times faster than using a single core processor)

But the longer the pipelines is, the more it becomes complex to keep it efficient! (eg the process will be slowed down by the slower of our  50 pipeline stages,... )

To summarize i do not have yet a clear idea/understanding about all that :-)

Keep up your good work 

have a nice week guys

gustavo arriaga

unread,
Jun 29, 2023, 3:53:35 PM6/29/23
to fpga-wars-explora...@googlegroups.com
Obijuan ayudanos a seguirte de los cuadernos me quede porque no te puedo seguir por el nivel dime como hago y menos se ingles hablo español y tengo la icembus alambra

--
Has recibido este mensaje porque estás suscrito al grupo "FPGAwars: explorando el lado libre" de Grupos de Google.
Para cancelar la suscripción a este grupo y dejar de recibir sus mensajes, envía un correo electrónico a fpga-wars-explorando-el...@googlegroups.com.

Democrito

unread,
Jun 29, 2023, 7:36:14 PM6/29/23
to FPGAwars: explorando el lado libre
Experimentando me he encontrado con circuitos parecidos, que desde un bus  se pueda controlar "situaciones", es algo que hay que seguir investigando.

Obijuan

unread,
Jul 1, 2023, 3:45:02 AM7/1/23
to FPGAwars: explorando el lado libre
Hi Joaquin!

Thanks for your comments

El jueves, 29 de junio de 2023 a las 20:11:57 UTC+2, joa...@gmail.com escribió:
Hola Juan,

Gracias for this interesting forth researches!
i have just a very little idea about that Forth language,  i just remember that you previously made the J1a Forth processor block! which of course can read forth code!

But making block for each command of the forth code !?!? 

Yes, i know it sounds wierd... but the main idea of the Forth language is that you define your own words (a word in Forth is an action or a subrutine that perform some computation)  
How do you create words? Using the primitive words you like. Primitive words are small actions implemented in the system lowest level (Tipically in asembly languaje). Then, using 
this primitive words, you define your own words, according to your needs

How many primitive words are defined in the Forth language? None. You can decide which one to use. Of course, there is an Ansi Forth which defines many standar words for you 
to use... but it is up to you. There are Forth implementations with more than 20 primitive words, but others with only 8, and even with 3!

Based on that primitive words, you define new words. What is amazing is how you can implement many behaviours just by combining these primitive words. That is the idea I want 
to test in hardware: Implement a few primitive blocks and then, without knowing hardware, to be able to implement more complex behaviours just by combining the primitive blocks


As most of the "computer code" is made to be executed sequentialy by the same hardware (core)!
i suppose that a forth code implemented that way ( every command is executed by a different hardware one following the other)
it will not be faster than the code executed by a single core (ALU)

It depends on the implementation, but the software Forth code should be compiled first to assembly language (machine code) and that code executed by the CPU. The mapping between forth words and 
assembly language is not 1 to 1, so every forth word will need usually many assembly instructions. And it will take many cycles to execute. For example the 1 1 + Forth program (to compute 1+1) consist of 
3 Forth primitive words (2 are numbers and one is +). The compiled Forth program in machine code should push 1 to the stack, then push another 1 and then execute the + words, which will pop the first operation from 
the stack, then the second, execute the add operation (using its alu) and then pushing the result on the stack. How many assembly instructions are needed for doing that actions? It depends on the compiler and the cpu

In the hardware Forth you need less cycles as that actions are done faster: push 1 to the stack only requires 1 cycle.  In my initial implementation (not optimized) the + word needs 3 cycles: one for poping the first argument, another 
for the second and one more for pushing the result on the stack

In general, it takes less cyles.... but... you are consuming way more hardware resources than the Software Forth


But if the code is very repetitive (eg: process the 400'000 pixels of a picture,) i imagine this ways of processing code is interesting because the work can be pipelined!
and there we can gain a lot of speed! (eg: if the processing of one pixel needs 50 différent icestudio forth blocks, than the processing of the entire set of pixels can be  up to a maximum of 50 times faster than using a single core processor)

Yes, it can be done that way. But even if no pipeline is used, you can create two hardware Forth threads in paralell very easy. You can implement independent behaviours in paralell easily (For example two diffefent controllers, 
one for the screen and another for the sound)


But the longer the pipelines is, the more it becomes complex to keep it efficient! (eg the process will be slowed down by the slower of our  50 pipeline stages,... )

To summarize i do not have yet a clear idea/understanding about all that :-)

Me too. I do not have a clear idea, that is the main reason I am doing this proof of concept. Maybe it is useless. Or maybe not. I just want to have fun understanding Forth and exploring its implementation 
in hardware. And of course I will share it with the community

My intuition tells me that it can be usefull for fast prototiping in hardware. Not for final implementations but just for testing new controllers and ideas, or maybe for implementing hardware testbenches fast and easily

Of course, if you already know an HDL language, and your are good are implementing hardware, it is better to do it directly in HDL. But the main idea of Icestudio is to let people test and design hardware without 
knowing an HDL language. With the Hardware Forth you can create simple hardware if you know Forth. Some people will find it usefull, but others will prefer to learn hdl and not forth

Best regards,
Obijuan


Jo mo

unread,
Jul 3, 2023, 4:11:11 AM7/3/23
to FPGAwars: explorando el lado libre
Hola Juan

Thanks a lot for this detailed explanation, i started, this weekend, and will continue learning about Forth, and try following your findings!
I also encourage you to go deeper into that proof of concept ! Something interesting can come out of any research/exploration path ! You are one of the Jacques Yves Cousteau of the fpga world ;-)

if you end up with something nice, than we will need a plugin where we just enter the forth code (text) and it automatically places all the needed forth blocks with their wiring !

This idea of "converting" soft code to hardware is interesting, we can imagine doing it for plainty of other codes (C,Faust, ...)
Looking on the internet about the subject, it pointed me back to High-level synthesis (HLS) concept. This tools have different levels of optimisation (ressources wise)
But no one have done something for Forth! The reason may be (as you wrote) that forth words/instructions are not all fully predefined/standardized (this additional definition being made by the  Forth coding user).

About the beginners knowing/learning hdl code, it seams to me that in a close future, we should count on AI help as much as someone working with mathematics is using a calculator!
From the test i did, i can conclude that those AI are already very good at Verilog!
I bet that we will have in less than 2 years an AI plugin in icestudio ;-). To helps us generate verilog code and to convert the verilog code directly to an icestudio block

Soon, people will just learn "speaking" to their AI and they will be able to generate their code in every possible language.
This week i installed Opera on my android phone and it includes the Aira Ai(which is also powered by Chatgpt) and i have a free brain assistant with me every were i go !  i will never be alone any-more :-)

Sorry for that off topic end of message ;-)
Reply all
Reply to author
Forward
0 new messages