Wide Values and Offsets: Lui, Auipc, Branches and Jumps

Twelve bits of immediate cannot hold an address of 32 bits, or say how far a jump goes. Three more formats do that work. Their bits look scrambled until you see what they keep fixed.

You Will Be Able To

  • Build a constant of 32 bits from lui and addi, and correct the upper part when bit 11 is 1.
  • Work out the target of a branch or of jal from the address of the instruction and its offset.
  • Collect the bits of a B or J offset from an instruction word, in the right order.
Lesson
S2.18
Time
30 min
Runs on
Your browser
Check
6 questions

The loop of S2.1 ends with bne x5, x0, 0x8. Its word is fe029ce3. Cut at the six places, that word holds no 8 anywhere. The branch still goes to address 8, every time.

Before You Start

You need the six fields and the I and S formats from S2.2. You need sign extension from the same page.

You need the loop of S2.1, with its branch back to address 8.

Five questions this page answers
Question
1How does a program put a constant of 32 bits into a register?
2When must the upper part of such a constant be one larger than it looks?
3From where is the offset of a branch counted?
4Why is bit 0 of an offset not stored?
5Which bits of a branch word are out of line with a store, and why only those?

The Idea: Two Halves for a Value, an Offset for a Target

An immediate of 12 bits stops at 2047. A real program needs 8000_0000, the address of the SRAM. No instruction of 32 bits can carry 32 bits of constant and an opcode as well.

So a wide constant is built in two steps. The first instruction sets the upper 20 bits. It is lui, short for load upper immediate. The second is an ordinary addi, which fills in the lower 12 bits. Twenty and twelve make 32.

The format with 20 bits of immediate is the U format. A second instruction uses it, called auipc. It adds the upper 20 bits to the PC and not to 0. That gives an address near the code, wherever the code was placed.

A branch has the same shortage. It must name a target, and it has only 12 bits. So it stores how far away the target is, and not where it is. That distance is the PC-relative offset: the target is the address of the branch itself plus the offset.

Most branches go a few instructions away, so a short offset is enough. The jump jal has more room, 20 bits, for the longer way to another function. Its format is the J format, and that of the branches is the B format.

New Words

New words on this page
WordMeaning
U formatThe format with an immediate of 20 bits in bits 31 to 12, and rd. Used by lui and auipc.
luiLoad upper immediate: writes the 20 bits into the upper part of rd, and 0 into the lower 12 bits.
auipcAdd upper immediate to PC: writes the PC of this instruction plus the 20 bits shifted left by 12.
PC-relative offsetThe distance in bytes from an instruction to its target. Offset for short. It may be negative.
B formatThe format of the branches: rs1, rs2 and an offset of 13 bits, of which 12 are stored.
J formatThe format of jal: rd and an offset of 21 bits, of which 20 are stored.
MiBA mebibyte: 1024 times 1024 bytes, which is 1 048 576.
Reach of an offsetHow far from itself an instruction can name a target.

One Picture: The Offset of a Branch

Where the Bits of a Branch Offset Come FromStep through the picture. On the left are four pieces of a branch word. On the right is the offset, from its sign down to bit 0.
  • Control / FSM
  • Memory
Where the Bits of a Branch Offset Come FromStep through the picture. On the left are four pieces of a branch word. On the right is the offset, from its sign down to bit 0. component Bit 31 of theword one bit component Bit 7 of the word one bit, in the placewhere rd would be component Bits 30 to 25 ofthe word six bits component Bits 11 to 8 ofthe word four bits component Offset bit 12 andabove the sign, copied up tobit 31 component Offset bit 11 the one bit that isout of line component Offset bits 10 to5 in the same place as ina store component Offset bits 4 to1 in the same place as ina store; bit 0 belowthem is always 0 the signbit 11bits 10 to 5bits 4 to 1
  1. component Bit 31 of the wordone bit
    • the sign → Offset bit 12 and above
  2. component Bits 30 to 25 of the wordsix bits
    • bits 10 to 5 → Offset bits 10 to 5
  3. component Bits 11 to 8 of the wordfour bits
    • bits 4 to 1 → Offset bits 4 to 1
  4. component Bit 7 of the wordone bit, in the place where rd would be
    • bit 11 → Offset bit 11
  5. component Offset bits 4 to 1in the same place as in a store; bit 0 below them is always 0
  6. component Offset bits 10 to 5in the same place as in a store
  7. component Offset bit 12 and abovethe sign, copied up to bit 31
  8. component Offset bit 11the one bit that is out of line
  1. Start from a store

    A branch has rs1 and rs2 and no rd, like a store. So its 12 stored bits sit where the immediate of a store sits.

  2. Bit 0 is not stored

    An offset is always even. Its bit 0 is 0, and no bit of the word is spent on it. The 12 stored bits are offset bits 12 to 1.

  3. Ten bits stay where they were

    Bits 30 to 25 give offset bits 10 to 5. Bits 11 to 8 give offset bits 4 to 1. A store reads the same bits for the same places.

  4. The sign stays in bit 31

    Bit 31 of the word is the sign, as in every format. Here it is offset bit 12.

  5. One bit is out of line

    That leaves offset bit 11. It goes to bit 7 of the word, the place that held bit 0 of a store.

Read the diagram as text
  • Bit 31 of the word: one bit
  • Bit 7 of the word: one bit, in the place where rd would be
  • Bits 30 to 25 of the word: six bits
  • Bits 11 to 8 of the word: four bits
  • Offset bit 12 and above: the sign, copied up to bit 31
  • Offset bit 11: the one bit that is out of line
  • Offset bits 10 to 5: in the same place as in a store
  • Offset bits 4 to 1: in the same place as in a store; bit 0 below them is always 0
  • Bit 31 of the word → Offset bit 12 and above: the sign
  • Bit 7 of the word → Offset bit 11: bit 11
  • Bits 30 to 25 of the word → Offset bits 10 to 5: bits 10 to 5
  • Bits 11 to 8 of the word → Offset bits 4 to 1: bits 4 to 1

The B format is the S format with two bits moved. The J format moves bits in the same spirit.

The three formats of this page, bit by bit
FormatBit 3130 to 2524 to 21Bit 2019 to 1211 to 8Bit 76 to 0
Boffset 12offset 10 to 5rs2rs2rs1, funct3offset 4 to 1offset 11opcode
Uvalue 31value 30 to 25value 24 to 21value 20value 19 to 12rdrdopcode
Joffset 20offset 10 to 5offset 4 to 1offset 11offset 19 to 12rdrdopcode

Read down the columns. Offset bits 10 to 5 are always in bits 30 to 25. The sign is always in bit 31.

The Smallest Example, Worked by Hand

A wide constant: 1234_5678. Split it after the upper five hex digits. The upper part is 12345, and the lower part is 678.

Two instructions for one constant
InstructionWhat it writesx5 afterwards
lui x5, 0x12345the upper 20 bits, and 0 below1234_5000
addi x5, x5, 0x678adds the lower part1234_5678

A harder one: 1234_5fff. The lower part is fff. As a 12-bit immediate, fff is -1, because addi sign-extends. Adding -1 to 1234_5000 gives 1234_4fff. That is 4096 too small.

The cure is to start one higher. Write 12346 into the upper part, and let the -1 bring it down: 1234_6000 less 1 is 1234_5fff. The rule: when bit 11 of the constant is 1, add 1 to the upper part.

A branch offset: the word fe029ce3, at address 10. S2.2 cut it into 1111111, 00000, 00101, 001, 11001 and 1100011. Collect the offset from the picture.

The offset of fe029ce3
Offset bitsCome fromValue
12, the signbit 31 of the word1
11bit 7 of the word: the last bit of 110011
10 to 5bits 30 to 25 of the word111111
4 to 1bits 11 to 8 of the word: the first four bits of 110011100
0not stored0

In order: 1 1 111111 1100 0. As a number of 13 bits in two's complement, that is -8.

The branch is at address 10 in hex, which is 16. Sixteen less 8 is 8. So the target is address 8, the start of the loop.

The Rules

  1. Rule 1: lui writes its 20 bits into bits 31 to 12 of rd, and 0 into bits 11 to 0.

    auipc writes the same value plus the PC of the auipc itself.

  2. Rule 2: A constant of 32 bits is a lui and an addi.

    When bit 11 of the constant is 1, the upper part must be one larger.

  3. Rule 3: The target of a branch or of jal is the PC of that instruction plus its offset.

    The offset is counted from the instruction itself, not from the next one.

  4. Rule 4: Bit 0 of an offset is always 0 and is not stored.

    So 12 stored bits reach 4094 bytes forward and 4096 back. Twenty stored bits reach about 1 MiB each way.

  5. Rule 5: In the B format, only offset bits 12 and 11 are out of line with a store.

    Bit 12 is in bit 31 of the word, and bit 11 is in bit 7.

  6. Rule 6: The J format stores, from bit 31 down, offset bits 20, 10 to 1, 11, and 19 to 12.

    The sign is in bit 31 again.

Sources for These Rules

Every encoding fact on this page is stated as commonly described. That covers the U, B and J formats, the place and the reach of each offset, and what lui and auipc write. The RISC-V specifications are not in the reference library. So none of these facts is checked against them. Each one was compared with the instruction tables of the assembler of this track.

The plan of this track points to two textbooks for this material. They are Patterson and Hennessy, sections 2.5 and 2.10, and Harris and Harris, section 6.4. Those places are not checked either.

Now Run It

The lab at the end of this page builds the two constants of the hand example, and then runs one auipc.

Printed by the lab on Icarus. The instruction-level model of this track printed the same rows.
00000000 | lui x5, 0x12345 | x5 = 12345000
00000004 | addi x5, x5, 1656 | x5 = 12345678
00000008 | lui x6, 0x12346 | x6 = 12346000
0000000c | addi x6, x6, -1 | x6 = 12345fff
00000010 | auipc x7, 0x1 | x7 = 00001010
00000014 | ebreak | stop
instructions=5

Rule 1 at work: rows 1 and 3. After each lui, the lower three hex digits are 000.

Rule 2 at work: rows 3 and 4. The upper part is 12346, one more than the constant shows. The addi of -1 lands on 1234_5fff.

Rule 1 again: row 5. The auipc is at address 10 in hex. It writes 10 plus 1000, both in hex.

Now two instructions with offsets. This program jumps forward over two rows, and then loops once:

The same model. The targets are written as addresses.
00000000 | addi x5, x0, 2 | x5 = 00000002
00000004 | jal x1, 0x10 | x1 = 00000008, next is 00000010
00000010 | addi x5, x5, -1 | x5 = 00000001
00000014 | bne x5, x0, 0x10 | taken: next is 00000010
00000010 | addi x5, x5, -1 | x5 = 00000000
00000014 | bne x5, x0, 0x10 | not taken
00000018 | ebreak | stop
instructions=6

Rule 3 at work: row 2. The jal is at address 4 and lands on 10. Its offset is 12. It also writes 8 into x1: the address of the row after it. S2.3 uses that value.

Here are the words with offsets from this page, cut at the six places. Below them are their immediates, from the instruction tables:

The first six rows are printed by test code on Icarus. The last six come from the assembler and its tables.
fe029ce3 | B | 1111111 00000 00101 001 11001 1100011
fe029ee3 | B | 1111111 00000 00101 001 11101 1100011
7e628fe3 | B | 0111111 00110 00101 000 11111 1100011
00c000ef | J | 0000000 01100 00000 000 00001 1101111
f01ff06f | J | 1111000 00001 11111 111 00000 1101111
123452b7 | U | 0001001 00011 01000 101 00101 0110111
fe029ce3 | bne x5, x0, 0x8 | immediate -8 = fffffff8
fe029ee3 | bne x5, x0, 0x10 | immediate -4 = fffffffc
7e628fe3 | beq x5, x6, 0xffe | immediate 4094 = 00000ffe
00c000ef | jal x1, 0x10 | immediate 12 = 0000000c
f01ff06f | jal x0, 0x0 | immediate -256 = ffffff00
123452b7 | lui x5, 0x12345 | immediate 305418240 = 12345000

Rule 5 at work: rows 1 and 2 differ in one bit of the fifth group. That bit is in bits 11 to 8, so the offsets differ by 4: -8 and -4.

Rule 4 at work: row 3 is the farthest branch forward. Every stored bit except the sign is 1, and the offset is 4094.

Rule 6 at work: rows 4 and 5 are jumps. Row 4 holds 01100 in its second group. That is offset bits 4 to 1 and bit 11: an offset of 12.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
An offset from the PCThe full address of the targetTwelve bits are enough for most branches, and code works at any address. Far targets need more instructions.
Bit 0 of the offset not storedStore every bitTwice the reach from the same bits. Targets must be at even addresses.
Most offset bits in the same place in S, B and JThe offset in plain order in each formatEach bit of the immediate has few possible sources, so the hardware is small. The word is hard to read by eye.
Two instructions for a wide constantInstructions longer than 32 bitsEvery instruction keeps one length. A wide constant costs two instructions.
auipc beside luilui onlyAddresses near the code work wherever the code is placed. One more instruction to build and to check.

The Trap: The Constant That Came Out 4096 Too Small

A programmer needs 1234_5fff in x6. The split looks obvious: the upper five digits for lui, the lower three for addi. The lower three are fff. The assembler takes fff as -1, since that is what those 12 bits mean.

The same model, with the constant split in the middle and no correction.
00000000 | lui x6, 0x12345 | x6 = 12345000
00000004 | addi x6, x6, -1 | x6 = 12344fff
00000008 | ebreak | stop
instructions=2

Read the last value: 1234_4fff. The fourth digit is wrong, and the result is 4096 too small.

Nothing failed. Both instructions are legal, and half of all constants split this way come out right. The error shows only when bit 11 of the constant is 1.

The check is rule 2. In practice, write the pseudo-instruction li with the whole constant, and let the assembler split it. The assembler of this track then makes the two instructions of the lab.

At Scale

A branchreach of about 4 KiB each way
A jalreach of about 1 MiB each way

This section looks ahead. Compilers use these few instructions for every address in a program.

  1. Too far for a branch

    When a target is beyond the reach of a branch, the tools turn the branch round and put a jal behind it. Common practice.

  2. Too far for a jal

    A call to anywhere in 32 bits is an auipc and a jalr together. S2.3 meets jalr.

  3. The immediate generator

    One block of the processor builds all five immediates from the word. You write it in the practice of this page.

  4. Addresses of devices

    Every device address of ap_soc is wide. Reaching UART0 at 1000_0000 starts with a lui.

Try It

Run the lab. Check rows 1 to 4 against the hand example.

Change the rows for x6 so that it ends with 8000_0800. Decide first whether the upper part needs the correction.

Move the auipc row to the top of the program. Predict what x7 holds before you run it.

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: 00000000 | lui x5, 0x12345 | x5 = 12345000 00000004 | addi x5, x5, 1656 | x5 = 12345678 00000008 | lui x6, 0x12346 | x6 = 12346000 0000000c | addi x6, x6, -1 | x6 = 12345fff 00000010 | auipc x7, 0x1 | x7 = 00001010 00000014 | ebreak | stop instructions=5

Check Yourself

Predict the outputThis program runs lui x5, 0x1 and then addi x5, x5, -1. What does the last row say?
// What does x5 hold at the end?
// The program is the task at the top. Each row is one instruction: i(kind, a, b, c).
// The comment beside a row is the same instruction in assembly.
module tb;
  task automatic the_program();
    i(LUI,    5,  0,  'h1);   // 00: lui x5, 0x1
    i(ADDI,   5,  5,  -1);    // 04: addi x5, x5, -1
    i(EBREAK, 0,  0,  0);     // 08: ebreak
  endtask

  // ---- From here down: a small model of an RV32I processor, as test code. You need not change it. ----
  localparam int LUI = 0, AUIPC = 1, JAL = 2, JALR = 3, BEQ = 4, BNE = 5, BLT = 6, BGE = 7, BLTU = 8, BGEU = 9, LW = 10, SW = 11,
                 ADDI = 12, SLTI = 13, SLTIU = 14, XORI = 15, ORI = 16, ANDI = 17, SLLI = 18, SRLI = 19, SRAI = 20,
                 ADD = 21, SUB = 22, SLL = 23, SLT = 24, SLTU = 25, XOR = 26, SRL = 27, SRA = 28, OR = 29, AND = 30, EBREAK = 31;
  int kind [0:63], fa [0:63], fb [0:63], fc [0:63];   // the program: one row for each instruction
  int rows = 0;
  task automatic i(input int k, input int a, input int b, input int c);   // add one row to the program
    if (rows < 64) begin kind[rows] = k; fa[rows] = a; fb[rows] = b; fc[rows] = c; rows++; end
  endtask
  logic [31:0] x [0:31];             // the 32 registers
  logic [31:0] pc;                   // the address of the next instruction
  logic [31:0] mem [0:16383];        // 64 KiB of data memory, from address 8000_0000 up
  int   steps;
  bit   stopped, faulted;
  function automatic string rn(input int n);
    return $sformatf("x%0d", n);
  endfunction
  function automatic string nm(input int k);                // the name of a kind of instruction
    case (k)
      0: return "lui"; 1: return "auipc"; 2: return "jal"; 3: return "jalr"; 4: return "beq"; 5: return "bne"; 
      6: return "blt"; 7: return "bge"; 8: return "bltu"; 9: return "bgeu"; 10: return "lw"; 11: return "sw"; 
      12: return "addi"; 13: return "slti"; 14: return "sltiu"; 15: return "xori"; 16: return "ori"; 17: return "andi"; 
      18: return "slli"; 19: return "srli"; 20: return "srai"; 21: return "add"; 22: return "sub"; 23: return "sll"; 
      24: return "slt"; 25: return "sltu"; 26: return "xor"; 27: return "srl"; 28: return "sra"; 29: return "or"; 
      30: return "and"; 31: return "ebreak"; 
      default: return "?";
    endcase
  endfunction
  // One instruction: read the row at the PC, do what it says, and print one line.
  task automatic step();
    int k, a, b;
    logic [31:0] c, r1, r2, res, next, ad;
    string text, effect;
    bit writes, go, take;
    go = 1;  k = EBREAK;  a = 0;  b = 0;  c = 0;
    if (pc[1:0] != 0 || pc >= 256) begin
      $display("%08h | no instruction at this address", pc);  faulted = 1;  stopped = 1;  go = 0;
    end
    else begin k = kind[pc >> 2];  a = fa[pc >> 2];  b = fb[pc >> 2];  c = fc[pc >> 2]; end
    r1 = x[b[4:0]];  r2 = x[c[4:0]];
    next = pc + 4;  writes = 1;  res = 0;  effect = "";
    if (go) case (k)
      LUI:   begin res = c << 12;       text = $sformatf("lui %s, 0x%0h", rn(a), c); end
      AUIPC: begin res = pc + (c << 12); text = $sformatf("auipc %s, 0x%0h", rn(a), c); end
      JAL:   begin res = pc + 4;  next = c;  text = $sformatf("jal %s, 0x%0h", rn(a), c); end
      JALR:  begin res = pc + 4;  next = (r1 + c) & ~32'd1;  text = $sformatf("jalr %s, %0d(%s)", rn(a), $signed(c), rn(b)); end
      BEQ, BNE, BLT, BGE, BLTU, BGEU: begin
        r1 = x[a[4:0]];  r2 = x[b[4:0]];  writes = 0;
        case (k)
          BEQ:  take = (r1 == r2);
          BNE:  take = (r1 != r2);
          BLT:  take = ($signed(r1) < $signed(r2));
          BGE:  take = ($signed(r1) >= $signed(r2));
          BLTU: take = (r1 < r2);
          default: take = (r1 >= r2);
        endcase
        if (take) next = c;
        text = $sformatf("%s %s, %s, 0x%0h", nm(k), rn(a), rn(b), c);
        if (take) effect = $sformatf("taken: next is %08h", next);
        else effect = "not taken";
      end
      LW, SW: begin
        ad = r1 + c;
        text = $sformatf("%s %s, %0d(%s)", nm(k), rn(a), $signed(c), rn(b));
        if (ad[1:0] != 0 || ad < 32'h8000_0000 || ad > 32'h8000_fffc) begin
          $display("%08h | %s | no data memory at %08h", pc, text, ad);  faulted = 1;  stopped = 1;  go = 0;
        end
        else if (k == LW) begin res = mem[ad[15:2]];  effect = $sformatf(" from mem[%08h]", ad); end
        else begin mem[ad[15:2]] = x[a[4:0]];  writes = 0;  effect = $sformatf("mem[%08h] = %08h", ad, x[a[4:0]]); end
      end
      ADDI:  res = r1 + c;
      SLTI:  res = ($signed(r1) < $signed(c)) ? 1 : 0;
      SLTIU: res = (r1 < c) ? 1 : 0;
      XORI:  res = r1 ^ c;
      ORI:   res = r1 | c;
      ANDI:  res = r1 & c;
      SLLI:  res = r1 << c[4:0];
      SRLI:  res = r1 >> c[4:0];
      SRAI:  res = $signed(r1) >>> c[4:0];
      ADD:   res = r1 + r2;
      SUB:   res = r1 - r2;
      SLL:   res = r1 << r2[4:0];
      SLT:   res = ($signed(r1) < $signed(r2)) ? 1 : 0;
      SLTU:  res = (r1 < r2) ? 1 : 0;
      XOR:   res = r1 ^ r2;
      SRL:   res = r1 >> r2[4:0];
      SRA:   res = $signed(r1) >>> r2[4:0];
      OR:    res = r1 | r2;
      AND:   res = r1 & r2;
      default: begin
        $display("%08h | ebreak | stop", pc);  stopped = 1;  go = 0;
      end
    endcase
    if (k >= ADDI && k <= SRAI) text = $sformatf("%s %s, %s, %0d", nm(k), rn(a), rn(b), $signed(c));
    if (k >= ADD && k <= AND)   text = $sformatf("%s %s, %s, %s", nm(k), rn(a), rn(b), rn(c[4:0]));
    if (go && writes) begin
      if (a[4:0] != 0) x[a[4:0]] = res;                      // register 0 is never written
      effect = {$sformatf("%s = %08h", rn(a), x[a[4:0]]), effect};
      if (k == JAL || k == JALR) begin                       // a jump with x0 as its destination keeps no return address
        if (a[4:0] == 0) effect = $sformatf("next is %08h", next);
        else effect = {effect, $sformatf(", next is %08h", next)};
      end
    end
    if (go) begin
      $display("%08h | %s | %s", pc, text, effect);
      pc = next;  steps++;
    end
  endtask
  task automatic run(input logic [31:0] start);
    pc = start;  steps = 0;  stopped = 0;  faulted = 0;
    while (!stopped && steps < 2000) step();
  endtask
  initial begin
    for (int n = 0; n < 32; n++) x[n] = 0;
    for (int n = 0; n < 16384; n++) mem[n] = 0;
    the_program();
    run(0);
    if (!stopped) $display("still running after %0d instructions", steps);
    $display("x5=%08h", x[5]);
  end
endmodule
ConceptHow does a program put a constant of 32 bits into a register?
ConceptThe constant is 0000_1800. Which upper part does lui need?
ConceptA branch at address 40 in hex has the offset -8. Where does it go?
ConceptWhy is bit 0 of a branch offset not stored?
ConceptIn a branch word, where is offset bit 11?

Common Mistakes

Wrong Split a constant in the middle and stop.

When bit 11 is 1, the addi subtracts, and the result is 4096 too small.

Fix Add 1 to the upper part in that case, or write li and let the assembler do it.

Wrong Count a branch offset from the next instruction.

In RISC-V the offset is added to the address of the branch itself.

Fix Target = address of the branch + offset.

Wrong Read the 12 stored bits of a branch as an S immediate.

Two bits are in other places, and the whole offset is shifted left by one.

Fix Collect bit 12 from bit 31, bit 11 from bit 7, and put a 0 at the bottom.

Remember

  • lui sets the upper 20 bits. A lui and an addi build any constant of 32 bits.
  • When bit 11 of the constant is 1, the upper part must be one larger.
  • The target of a branch or jal is the address of that instruction plus its offset.
  • Bit 0 of an offset is not stored. The sign is in bit 31. Only a few bits are out of line.

Practice

Report a problem with this page