RISC-V Open Architecture

Well, Open Architecture has always caught my eye. In this post, we discuss RISC-V and ISA, the perfect threshold between hardware and software. Through the bridge between two worlds, the magician longs to see.

What is ISA (INSTRUCTION SET ARCHITECTURE) ?

ISA defines the types and the architecture of operation, is how the software controls the hardware, specifically CPU

/* ISA -> Microarchitecture -> Registers & Counters -> Circuits

<———————————————–Lv Abstraction

*/

Challenges imposed by modernity on tradicional ISAs:

  • Moore law
    • Physical Limit
  • Energy Efficiency
    • Architectures like x86 and Arm, always tried to increase performance, adding more instructions and parallelism, but this results in more complex, large, and power-hungry chips
  • Complexity
    • The x86 instruction set, for example, is extremely complex and legacy, carryng decades of support and maintenance becoming increasingly tied up in a swamp of old instructions, making it difficult to optimize and adapt to new demands (AI, Quantum and Embedded)

/* In the name of performance, some paradigms emerged:
Parallel Systems (e.g. IntelDuoCore)
Heterogeneous Systems
Domain specific architectures (DSAs)

*/

RISC-V

Created at the University of Berkeley, California, 2010, as an academic project to develop an open, modular and comprehensive ISA from HPC to Embedded

The limit of ISAs comes both from the hardware (Transistor Miniaturization + Energy Efficiency) and from inflexibility and complexity of the code. RISC-V solves this by offering modularity, enabling innovation without corporate ties and ensuring technological independence, as anyone can design/manufacture a RISC-V processor without relyng on Intel, AMD or ARM.

⚠ The Game Changer on CyberSecurity scenario

RISC-v was designed with security mindset from the start, taking into account errors, bugs, and vulnerabilities seen in major players, such Specter and Meltdown attacks.

Of course, no architecture is invulnerable, but having an open ISA means researchers and developers can continuously refine security features without waiting on proprietary fixes from vendors. The result? A more transparent, adaptable, and security-aware ecosystem—one that learns from past mistakes rather than repeating them.

Security isn’t just about patches. It’s about designing systems that are resilient from the ground up. RISC-V might just be the revolution we needed.

  • ISA open and auditable
  • Minimalist Design == Smaller attack surface
  • Custom instructions for cryptography
  • No backdoor by big bro techs
    • There are those who say that companies like Intel, AMD and Apple can include hidden functions in their codes 👁️‍🗨️

ISA RISC-V

Instructions and Formats

The RISC-V instructions follow a fixed and simplified format, bringing the complexity of decoding by hardware. Example, the position of instruction tends to stay in the same position within the number of bits (e.g. the opcode occupies 7 bits, starting from 0 to 6)

TYPES RISC-V

  • R-Type: Arithmetic and logical operations with three registers.
  • I-Type: Instructions that use an immediate value.
  • S-Type: Used for store instructions.
  • B-Type: Conditional branch instructions.
  • U-Type: Instructions that manipulate 32-bit immediate values.
  • J-Type: Unconditional jump instructions.

# Utilize your prefered LLM to specify the fields below:

print(“Do It: Specify the fields, bits, and description of each RISC-V instruction format: R-Type, I-Type, S-Type, B-Type, J-Type”)

Memory Access and Storage

In RISC-V, interaction with memory occurs through load instructions (lw, lb, lh) and store instructions (sw, sb, sh). Memory is organized hierarchically, with registers being the fastest (i.e., closest to the processor), followed by cache (e.g., multiple levels), DRAM, and disk storage. The principle of locality (temporal and spatial) influences memory access, ensuring that frequently accessed data is kept in faster storage layers within the memory hierarchy.

Examples:

lw x10, 12(x15)    # load a valor in `x15 + 12` and store on x10.
sw x11, 8(x14)     # store a valor x11 on adress `x14 + 8`.

Besides the lw and sw instructions, RISC-V supports operations with bytes and half-words. Example:

  • lb x5, 4(x10): Load byte.
  • lbu x6, 8(x11):Load byte without sign (zero-extended).
  • lh x7, 2(x12): Load a half-word (16 bits).
  • sh x8, 6(x13): Store a half-word.

Essas instruções são úteis para otimizar o uso da memória.

Controle de Fluxo e Estruturas Condicionais

As instruções de controle de fluxo permitem alterar a execução do programa. O RISC-V oferece instruções para loops condicionais e chamadas de função. Exemplo:

Loop: beq x12, x11, end
      add x12, x12, x10
      j Loop
End:

Este código executa a soma repetida de valores enquanto uma condição não for satisfeita.

Outros exemplos:

  • beq x1, x2, label: Se x1 for igual a x2, o fluxo de execução salta para label.
  • bne x3, x4, label: Se x3 for diferente de x4, ocorre um salto para label.
  • blt x5, x6, label: Se x5 for menor que x6, o salto é realizado.

Instruções de Salto e Chamada de Função

As instruções de salto incondicional permitem mudar o fluxo de execução para um endereço específico. São utilizadas para chamadas de função e implementação de estruturas mais complexas.

Exemplos:

  • jal x1, funcao: Salta para o rótulo funcao, armazenando o endereço de retorno em x1.
  • jalr x2, x3, 0: Salta para o endereço armazenado em x3, adicionando um deslocamento de 0.

Immediate

Imediatos são constantes numéricas.

  • Eles aparecem frequentemente no código, portanto, há instruções especiais para eles.
  • Adicionar imediato:

addi x3,x4,10

  • f = g + 10 (em C)
  • onde RISC-V registradores x3,x4 estão associados com variáveis f,g (em C)
  • Sintaxe semelhante à instrução add, exceto que o último argumento é um número em vez de um registrador.
  • Não há subtração de imediatos em RISC-V: por quê?
    • Existem add, sub e addi, mas não subtração
  • Limitar os tipos de operações ao mínimo possível
    • Se uma operação pode ser decomposta em operação mais simples, não incluir
    • addi x1 x2 -10 = sub x1 x2 10

addi x3,x4,-10 (em RISC-V)

f = g – 10 (em C)

————————————————————————-

addi x5, x0, 10     # x5 = 10
addi x6, x0, 20     # x6 = 20
bge x5, x6, else    # Se x5 >= x6,'else'
addi x7, x0, 1      # x7 = 1 
j end               # jump to end
else:
  addi x7, x0, 0    # x7 = 0 
end:

Here, x7 will be 1 if the condition is true, or 0 if it is false. (if-else case)


Example: Loop for to sum elements of array:

addi x8, x0, 0       # i = 0
addi x9, x0, 10      # size of array
add x10, x0, x0      # sum = 0
Loop:
  bge x8, x9, end    # if i >= 10, end loop
  lw x11, 0(x12)     # A[i]
  add x10, x10, x11  # sum += A[i]
  addi x8, x8, 1     # i++
  j Loop             # back loop
end:

No RISC-V, funções são chamadas usando jal e retornam com jr. A pilha é usada para armazenar valores temporários.Exemplo: Implementação de fatorial com recursão:

fact:
  addi sp, sp, -8      # Reserva espaço na pilha
  sw ra, 4(sp)         # Salva endereço de retorno
  sw a0, 0(sp)         # Salva argumento
  li a1, 1             # Define base do fatorial
  ble a0, a1, done     # Se n <= 1, retorna 1
  addi a0, a0, -1      # n - 1
  jal fact             # Chamada recursiva
  lw a0, 0(sp)         # Restaura argumento
  mul a0, a0, a1       # n * fatorial(n-1)
done:
  lw ra, 4(sp)         # Restaura endereço de retorno
  addi sp, sp, 8       # Libera espaço na pilha
  jr ra                # Retorna

Esse código calcula o fatorial usando recursão e manipulação da pilha.


/* NVIDIA, Western Digital e SiFive adotaram esta arquitetura em projetos de novos produtos. Com o crescimento da computação em nuvem, IA e IoT, espera-se que o RISC-V continue sua expansão devido à sua característica aberta
*/

https://community.riscv.org

http://www.riscbook.com/portuguese/

https://www.cs.sfu.ca/~ashriram/Courses/CS295/assets/books/HandP_RISCV.pdf

Leave a Reply

Your email address will not be published. Required fields are marked *

(⌐■_■)╤─ _ -_ _– ─╤╦(̿▀̿ ̿Ĺ̯̿̿▀̿ ̿)̄

Join the club

Stay updated with our latest tips and other news by joining our newsletter.

(˵ ͡° ͜ʖ ͡°˵)

Categories