# 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="https://733403343-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fz6F38NLmIOefVEORubUB%2Fuploads%2Fgit-blob-7601baf04760f9b511dfd30ec9da25a2579be876%2Fb-type.png?alt=media" 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="https://733403343-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fz6F38NLmIOefVEORubUB%2Fuploads%2Fgit-blob-41a37a99b922c7016523706d6b482f3afb987314%2Fb-encode-example.jpg?alt=media" 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="https://733403343-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fz6F38NLmIOefVEORubUB%2Fuploads%2Fgit-blob-1198f5a19f37cb985c8e0d5594bb9e7754dc6a51%2Fimm-encode-b-so-far.jpg?alt=media" alt=""><figcaption></figcaption></figure>

## Adding Branches to Datapath

<figure><img src="https://733403343-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fz6F38NLmIOefVEORubUB%2Fuploads%2Fgit-blob-829691b0fa09d4fbd179db4ed88568c1533e6def%2Fdatapath5.jpg?alt=media" alt=""><figcaption></figcaption></figure>

### Branch Comparator

<figure><img src="https://733403343-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fz6F38NLmIOefVEORubUB%2Fuploads%2Fgit-blob-e64d0ca5ea506cb817136998f5bd819e5fc9bc59%2Fbranch-comparator.png?alt=media" alt=""><figcaption></figcaption></figure>

## All RISC-V Branch Instructions

<figure><img src="https://733403343-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fz6F38NLmIOefVEORubUB%2Fuploads%2Fgit-blob-faab5566de1893a08e08defbcc4521ef500ebebd%2Fb-type-instructions.png?alt=media" alt=""><figcaption></figcaption></figure>
