# B-type

{% hint style="info" %}
All branch instructions use the B-type instruction format.

* E.g., `BEQ x1, x2, Label`
  * if x1 == x2 then pc <- pc + offset
  * offset computed by compiler/assembler and stored in the immediate field(s)
* Branches read two registers but don't write a register (similar to stores)
  {% endhint %}

## B-Format Instruction Layout

<figure><img src="/files/6m3Gzbl3sdw7oojNJRG7" alt=""><figcaption></figcaption></figure>

* B-format is similar to S-format, with two register sources (rs1/rs2) and a 12-bit immediate
* The 12 immediate bits encode 13-bit signed byte offsets (low bit of offset is always zero, so no need to store it)
* But now immediate represents values `-2^12` to `+2^12 - 1` in 2-byte increments

## Encoding Example

<figure><img src="/files/Vci5H4suWliCD4Nr7mph" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
In the RISC-V architecture, instructions are typically 32 bits (4 bytes) in length and are aligned on 4-byte boundaries. This means that the addresses of these instructions are multiples of 4. Consequently, the lower two bits of an instruction address are always zero.

So why branch immediates only discard the LSB not the low 2 bits?
{% endhint %}

## Immediate Encoding (So Far)

<figure><img src="/files/XbgjVspDthdfWsbqa5XZ" alt=""><figcaption></figcaption></figure>

## Adding Branches to Datapath

<figure><img src="/files/fbir6OxjBhNcaeHUayrz" alt=""><figcaption></figcaption></figure>

### Branch Comparator

<figure><img src="/files/thfjZ0v2KSvIfzqd9SYx" alt=""><figcaption></figcaption></figure>

## All RISC-V Branch Instructions

<figure><img src="/files/ViqkoybA4DmyF9NGFjxP" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://byrzhm.gitbook.io/build-a-risc-v-chip-from-scratch/tutorial/datapath/b-type.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
