Start-Up Code: What Runs Before Main

Your program says "int limit = 5". At power-on, SRAM holds nothing. Somebody has to put the 5 there before the first line of main runs.

You Will Be Able To

  • List what start-up code must do before main, and in which order.
  • Explain why a variable with a first value needs a copy, and a variable without one needs a clear.
  • Recognize from a symptom which start-up step is missing.
Lesson
S6.7
Time
27 min
Runs on
Your browser
Check
5 questions

A board counts events. The source code starts the counter at 0. After every cold start the counter begins at some huge number, yet under the debugger it always begins at 0. The loop that counts is correct.

Before You Start

You need The Boot Flow: the reset address, Boot ROM, and SRAM that holds nothing at a cold start. You need the stack and sp from The Stack Frame.

You need mtvec and a handler from Traps. Sections and symbols come from Assembler, Linker and Loader.

Five questions this page answers
Question
1What does a C program expect to be true when main starts?
2Why must the stack pointer be set by the very first instructions?
3Where are the first values of variables kept while the power is off?
4Why are variables that start at 0 not stored at all?
5What does the program do when one start-up step is missing?

The Idea: Code That Runs Before Main

A C program is written as if four things were already true. There is a stack. A fault has somewhere to go. Every variable with a first value holds that value. Every other variable holds 0.

After reset none of them is true. Every register holds 0. SRAM holds whatever it woke up with. So a short piece of code runs first and makes the four things true. It is called the start-up code. Its last instruction calls main.

Variables that live for the whole program are global variables. The linker sorts them into two sections. Those with a first value, like "limit = 5", go to the section named .data. Those without one go to the section named .bss.

The two sections need different treatment. The values of .data must survive power-off, so they are stored in ROM and copied to SRAM. Nothing is stored for .bss. Start-up code writes 0 over all of it.

New Words

New words on this page
WordMeaning
Global variableA variable that exists for the whole run of the program, at a fixed address.
.dataThe section of global variables that have a first value.
.bssThe section of global variables that have no first value. C promises that they start at 0.
Load addressWhere the stored copy of a section is kept. For .data: in ROM. The place where the program uses the section is its run address. For .data: in SRAM.
Stack topThe first value of sp. On this page it is 0x8001_0000, one past the end of SRAM.
Trap vectorThe address in mtvec. The processor jumps there when it takes a trap.

The names .data and .bss begin with a dot. That is how the tools spell section names.

One Picture: Five Steps

Five Steps Between Reset and MainStep through the picture. Each step prepares something that a C program takes for granted.
  • Processor
  • Memory
  • Control / FSM
Five Steps Between Reset and MainStep through the picture. Each step prepares something that a C program takes for granted. component Processor after reset: sp holds0, mtvec holds 0 component Boot ROM the code, and thefirst values of .data component .data, in SRAM variables with a firstvalue: limit, step component .bss, in SRAM variables that startat 0: count, total component Stack, in SRAM from the top ofSRAM, growing down component main the first function ofthe program 1: sp2: mtvec3: copy4: clear5: call
  1. component Processorafter reset: sp holds 0, mtvec holds 0
    • 1: sp → Stack, in SRAM
    • 2: mtvec → Boot ROM
    • 5: call → main
  2. component Stack, in SRAMfrom the top of SRAM, growing down
  3. component Boot ROMthe code, and the first values of .data
    • 3: copy → .data, in SRAM
  4. component .data, in SRAMvariables with a first value: limit, step
    • 4: clear → .bss, in SRAM
  5. component .bss, in SRAMvariables that start at 0: count, total
  6. component mainthe first function of the program
  1. The stack pointer

    Reset leaves 0 in every register. A function call needs a stack, so the first instruction gives sp an address in SRAM.

  2. The trap vector

    If anything faults from now on, the processor jumps to the address in mtvec. Start-up code puts a handler there early.

  3. Copy .data

    The first values of limit and step are stored in ROM. The program will read and change them in SRAM. So they are copied, word by word.

  4. Clear .bss

    count and total must start at 0. Nothing is stored for them. A loop writes 0 to each word.

  5. Call main

    Only now is the machine in the state that C code expects. Start-up code calls main.

Read the diagram as text
  • Processor: after reset: sp holds 0, mtvec holds 0
  • Boot ROM: the code, and the first values of .data
  • .data, in SRAM: variables with a first value: limit, step
  • .bss, in SRAM: variables that start at 0: count, total
  • Stack, in SRAM: from the top of SRAM, growing down
  • main: the first function of the program
  • Processor → Stack, in SRAM: 1: sp
  • Processor → Boot ROM: 2: mtvec
  • Boot ROM → .data, in SRAM: 3: copy
  • .data, in SRAM → .bss, in SRAM: 4: clear
  • Processor → main: 5: call

The start-up code of the lab. The clear loop is code in ROM; the arrow from .data only shows that .bss follows .data in memory.

The order matters in one place only. The stack pointer comes first, because a call or an interrupt may need the stack at any moment after that.

The Smallest Example, Worked by Hand

A program has four global variables. Two have first values: limit = 5 and step = 3. Two have none: count and total. Its main does two things: count = count + step, then total = limit + count.

Where the linker put everything
SectionHoldsRun addressStored copy
.datalimit, step0x8000_0000 and 0x8000_0004in ROM, at 0xD0 and 0xD4: the words 5 and 3
.bsscount, total0x8000_0008 and 0x8000_000Cnone

Follow SRAM through the start-up code. A question mark is a word that nobody has written since power-on.

Four words of SRAM, step by step
Afterlimitstepcounttotal
power-on????
the copy of .data53??
the clearing of .bss5300
main530 + 3 = 35 + 3 = 8

Now leave the clearing out. Then count starts as a question mark, and so "count + step" is unknown as well. The program is the same. Its answer is not.

The Rules

  1. Rule 1: Set the stack pointer first.

    A call saves its return address on the stack. With sp at 0 that write goes to an address with no memory.

  2. Rule 2: Set the trap vector early.

    A fault before mtvec is set jumps to address 0 and starts the program again, for ever.

  3. Rule 3: Copy .data from its load address to its run address.

    Copy every word from the start of the section to its end. An empty section copies nothing.

  4. Rule 4: Write 0 to every word of .bss.

    C promises that such a variable starts at 0. SRAM does not.

  5. Rule 5: Call main last.

    Use no global variable before the copy and the clear are done.

  6. Rule 6: If main returns, stay in a loop.

    Nothing comes after start-up code. A processor that runs on executes whatever follows.

Sources for These Rules

Patterson and Hennessy, Computer Organization and Design, ARM edition, section 2.12: the linker, the loader and the segments of a program. Harris and Harris, Digital Design and Computer Architecture, ARM edition, section 6.5. It covers the memory map of a program, with its global data and its stack, and linking and loading.

Both books describe a machine with an operating system, where a loader does this work. On a chip without one, start-up code does it. Rules 1 to 6 are common practice for such code. No source in our library lists them.

The stack top of 0x8001_0000 is a choice of this course. On ap_rv32, mtvec is 0 after reset, and every register is 0 after reset in the lab model.

Now Run It

The lab at the end of this page is the hand example as a program. The start-up code and main are rows of instructions in Boot ROM. A small model of the processor runs them and prints every instruction. Here are the rows that change the machine.

Recorded from the lab on Icarus: 11 of its 43 rows. Each row is the address of an instruction, the instruction, and what it did.
00000000 | lui x2, 0x80010 | x2 = 80010000
00000008 | csrw mtvec, x5 | mtvec = 000000c0
00000020 | sw x28, 0(x6) | mem[80000000] = 00000005
00000020 | sw x28, 0(x6) | mem[80000004] = 00000003
00000040 | sw x0, 0(x6) | mem[80000008] = 00000000
00000040 | sw x0, 0(x6) | mem[8000000c] = 00000000
0000004c | jal x1, 0x80 | x1 = 00000050, next is 00000080
00000084 | sw x1, 0(x2) | mem[8000fffc] = 00000050
0000009c | sw x12, 8(x8) | mem[80000008] = 00000003
000000a4 | sw x13, 12(x8) | mem[8000000c] = 00000008
00000050 | jal x0, 0x50 | the program stops here

Rule 1 at work: the first row gives x2, which is sp, the value 80010000. Rule 3 at work: the words 5 and 3 arrive at 80000000 and 80000004. Rule 4 at work: two zeros go to 80000008 and 8000000c.

Then "jal x1, 0x80" calls main. Its first store saves the return address at 8000fffc, just below the stack top. The last row is rule 6: main came back, and the code stays in a loop at address 50.

The last line of the lab: the four variables, in hexadecimal, and the stack pointer at the end.
limit=5 step=3 count=3 total=8 | sp=80010000 | exceptions=0

Now the same program with one step removed each time.

One step left out
Left outLast line of the lab
nothinglimit=5 step=3 count=3 total=8 | sp=80010000 | exceptions=0
the copy of .datalimit=xxxxxxxx step=xxxxxxxx count=xxxxxxxx total=xxxxxxxx | sp=80010000 | exceptions=0
the clearing of .bsslimit=5 step=3 count=xxxxxxxx total=xxxxxxxx | sp=80010000 | exceptions=0
the stack pointerlimit=5 step=3 count=0 total=0 | sp=fffffffc | exceptions=1

Recorded from the lab. An x is a bit that was never written. On silicon it would be a 0 or a 1 that nobody chose.

Without the copy, limit and step are unknown, and everything worked out from them is unknown too. Without the clear, count is unknown. Without the stack pointer the program never gets through main:

From the run without the stack pointer.
exception, no memory at fffffffc for a store at 00000084: mcause=00000007 mepc=00000084, next is 000000c0

Main subtracts 4 from an sp of 0 and tries to store at fffffffc. No memory is there. The processor takes a trap and jumps to the handler, because rule 2 was obeyed. So count and total keep their zeros, and the fault is easy to see.

The lab is a model beside the real processor. A probe ran the same five programs on the real ap_rv32 of this course. The final values of the four variables, the stop address and the number of exceptions were equal in every run.

These labs leave things out. The sections are two words long. The code has no library to prepare. A real start-up file also sets up the clocks and, on larger chips, the caches.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
Keep the first values in ROM and copy themLet each variable be set by code in mainThe compiler handles every variable the same way. The values take room twice: in ROM and in SRAM.
Store nothing for .bssStore its zeros in ROM tooA large buffer costs no ROM at all. Start-up needs a second loop.
Write start-up code in assemblyWrite it in CIt works before a stack exists. It must be written again for each processor.

Could the chip do this in hardware? It could clear SRAM at reset. Then a large SRAM would need many cycles, or a special memory. A loop of three instructions is cheaper.

The Trap: Correct Under the Debugger

Back to the board from the top of the page. The counter is a global variable with no first value. It lives in .bss. The start-up file of that board was copied from an older project, and its clear loop ends one word early.

On a cold start, the last word of .bss keeps what SRAM woke up with. Our counter is that word. Hence the huge number.

Under the debugger the fault hides, as it did for the boot loader. Many debuggers write the whole image, and some clear memory before they start the program. The run you watch is not the run the customer gets.

When a variable is wrong only after a cold start, do not read main. Find the section the variable is in. Then check the loop of that section, and both of its ends.

At Scale

This page2 sections, 4 words
A productmany sections, megabytes

This section looks ahead. The lab has four variables and thirty instructions of start-up code. A product has thousands of variables.

  1. Who knows the addresses

    The lab wrote the addresses into the code by hand. In a real project the linker supplies them as symbols. The next lesson shows where they come from.

  2. Tables of sections

    A large program has several regions to copy and several to clear. Its start-up code walks a table of them. The practice problem of this page asks for such a loop.

  3. More to prepare

    Before main, real start-up code may also start the clocks, switch on caches and call the set-up functions of libraries.

  4. One stack for each processor

    On a chip with several processors, each one runs start-up code and needs a stack top of its own.

Try It

Run the lab. Find the two stores that copy .data and the two that clear .bss.

Delete the first row, which sets x2. Predict the address of the store that fails, then run.

Put that row back. In the row at 034, change 8 to 12: the clear loop now starts one word late. Say which variables end unknown.

Change the two stored words at d0 and d4. Predict the last line.

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: 00000000 | lui x2, 0x80010 | x2 = 80010000 00000004 | addi x5, x0, 192 | x5 = 000000c0 00000008 | csrw mtvec, x5 | mtvec = 000000c0 0000000c | addi x5, x0, 208 | x5 = 000000d0 00000010 | lui x6, 0x80000 | x6 = 80000000 00000014 | addi x7, x6, 8 | x7 = 80000008 00000018 | beq x6, x7, 0x30 | not taken 0000001c | lw x28, 0(x5) | x28 = 00000005 from mem[000000d0] 00000020 | sw x28, 0(x6) | mem[80000000] = 00000005 00000024 | addi x5, x5, 4 | x5 = 000000d4 00000028 | addi x6, x6, 4 | x6 = 80000004 0000002c | bne x6, x7, 0x1c | taken: next is 0000001c 0000001c | lw x28, 0(x5) | x28 = 00000003 from mem[000000d4] 00000020 | sw x28, 0(x6) | mem[80000004] = 00000003 00000024 | addi x5, x5, 4 | x5 = 000000d8 00000028 | addi x6, x6, 4 | x6 = 80000008 0000002c | bne x6, x7, 0x1c | not taken 00000030 | lui x6, 0x80000 | x6 = 80000000 00000034 | addi x6, x6, 8 | x6 = 80000008 00000038 | addi x7, x6, 8 | x7 = 80000010 0000003c | beq x6, x7, 0x4c | not taken 00000040 | sw x0, 0(x6) | mem[80000008] = 00000000 00000044 | addi x6, x6, 4 | x6 = 8000000c 00000048 | bne x6, x7, 0x40 | taken: next is 00000040 00000040 | sw x0, 0(x6) | mem[8000000c] = 00000000 00000044 | addi x6, x6, 4 | x6 = 80000010 00000048 | bne x6, x7, 0x40 | not taken 0000004c | jal x1, 0x80 | x1 = 00000050, next is 00000080 00000080 | addi x2, x2, -4 | x2 = 8000fffc 00000084 | sw x1, 0(x2) | mem[8000fffc] = 00000050 00000088 | lui x8, 0x80000 | x8 = 80000000 0000008c | lw x10, 0(x8) | x10 = 00000005 from mem[80000000] 00000090 | lw x11, 4(x8) | x11 = 00000003 from mem[80000004] 00000094 | lw x12, 8(x8) | x12 = 00000000 from mem[80000008] 00000098 | add x12, x12, x11 | x12 = 00000003 0000009c | sw x12, 8(x8) | mem[80000008] = 00000003 000000a0 | add x13, x10, x12 | x13 = 00000008 000000a4 | sw x13, 12(x8) | mem[8000000c] = 00000008 000000a8 | lw x1, 0(x2) | x1 = 00000050 from mem[8000fffc] 000000ac | addi x2, x2, 4 | x2 = 80010000 000000b0 | jalr x0, 0(x1) | x0 = 00000000, next is 00000050 00000050 | jal x0, 0x50 | the program stops here limit=5 step=3 count=3 total=8 | sp=80010000 | exceptions=0

Check Yourself

Predict the outputThe stored words of .data are now 9 and 4. The start-up code is complete. What is the last line the lab prints?
// Start-up code and a small main, with other first values.
// The program is the task at the top. Each row is one word of the Boot ROM: i(kind, a, b, c).
// The comment beside a row is its address and the same instruction in assembly.
// The linker placed .data at 8000_0000 (two words) and .bss at 8000_0008 (two words).
// The first values of .data are stored in the Boot ROM, at d0.
module tb;
  task automatic the_program();
    // ---- start-up code: what runs before main ----
    i(LUI,   2,  0,  'h80010);        // 000: lui x2, 0x80010      the stack pointer: the top of SRAM
    i(ADDI,  5,  0,  192);            // 004: addi x5, x0, 192
    i(CSRW,  5,  0,  MTVEC);          // 008: csrw mtvec, x5      the trap vector
    // copy .data: from its load address in ROM to its run address in SRAM
    i(ADDI,  5,  0,  208);            // 00c: addi x5, x0, 208      x5: where the values are stored
    i(LUI,   6,  0,  'h80000);        // 010: lui x6, 0x80000      x6: where the program expects them
    i(ADDI,  7,  6,  8);              // 014: addi x7, x6, 8      x7: the end of .data
    i(BEQ,   6,  7,  'h30);           // 018: beq x6, x7, 0x30      an empty section copies nothing
    i(LW,    28, 5,  0);              // 01c: lw x28, 0(x5)
    i(SW,    28, 6,  0);              // 020: sw x28, 0(x6)
    i(ADDI,  5,  5,  4);              // 024: addi x5, x5, 4
    i(ADDI,  6,  6,  4);              // 028: addi x6, x6, 4
    i(BNE,   6,  7,  'h1c);           // 02c: bne x6, x7, 0x1c
    // clear .bss: every word between its start and its end becomes 0
    i(LUI,   6,  0,  'h80000);        // 030: lui x6, 0x80000
    i(ADDI,  6,  6,  8);              // 034: addi x6, x6, 8      x6: the start of .bss
    i(ADDI,  7,  6,  8);              // 038: addi x7, x6, 8      x7: the end of .bss
    i(BEQ,   6,  7,  'h4c);           // 03c: beq x6, x7, 0x4c
    i(SW,    0,  6,  0);              // 040: sw x0, 0(x6)
    i(ADDI,  6,  6,  4);              // 044: addi x6, x6, 4
    i(BNE,   6,  7,  'h40);           // 048: bne x6, x7, 0x40
    i(JAL,   1,  0,  'h80);           // 04c: jal x1, 0x80      call main
    i(JAL,   0,  0,  'h50);           // 050: jal x0, 0x50      main came back: stay here
    // ---- main: count = count + step; total = limit + count ----
    at('h80);
    i(ADDI,  2,  2,  -4);             // 080: addi x2, x2, -4
    i(SW,    1,  2,  0);              // 084: sw x1, 0(x2)      save the return address on the stack
    i(LUI,   8,  0,  'h80000);        // 088: lui x8, 0x80000
    i(LW,    10, 8,  0);              // 08c: lw x10, 0(x8)      limit, in .data
    i(LW,    11, 8,  4);              // 090: lw x11, 4(x8)      step, in .data
    i(LW,    12, 8,  8);              // 094: lw x12, 8(x8)      count, in .bss
    i(ADD,   12, 12, 11);             // 098: add x12, x12, x11
    i(SW,    12, 8,  8);              // 09c: sw x12, 8(x8)
    i(ADD,   13, 10, 12);             // 0a0: add x13, x10, x12
    i(SW,    13, 8,  12);             // 0a4: sw x13, 12(x8)      total, in .bss
    i(LW,    1,  2,  0);              // 0a8: lw x1, 0(x2)
    i(ADDI,  2,  2,  4);              // 0ac: addi x2, x2, 4
    i(JALR,  0,  1,  0);              // 0b0: jalr x0, 0(x1)      return
    // ---- the trap handler of this lab: stop ----
    at('hc0);
    i(JAL,   0,  0,  'hc0);           // 0c0: jal x0, 0xc0
    // ---- the load image of .data: the first values of limit and step ----
    at('hd0);
    i(WORD,  0,  0,  32'h00000009);   // 0d0: .word 0x00000009
    i(WORD,  0,  0,  32'h00000004);   // 0d4: .word 0x00000004
  endtask

  // ---- From here down: a small model of the processor, as test code. ----
  // It is a model beside the real core ap_rv32, not a part of it. It runs one instruction for each clock tick.
  localparam int LUI = 0, ADDI = 1, ANDI = 2, ORI = 3, SLLI = 4, SRLI = 5, ADD = 6, SUB = 7, AND = 8, OR = 9, LW = 10, SW = 11,
                 BEQ = 12, BNE = 13, BLT = 14, BGE = 15, JAL = 16, JALR = 17, CSRR = 18, CSRW = 19, CSRS = 20, CSRC = 21, MRET = 22, WORD = 23;
  localparam int MSTATUS = 'h300, MIE = 'h304, MTVEC = 'h305, MSCRATCH = 'h340, MEPC = 'h341, MCAUSE = 'h342, MIP = 'h344;
  int kind [0:1023], fa [0:1023], fb [0:1023];   // the Boot ROM: one row for each word
  logic [31:0] fc [0:1023];
  int here = 0;                                   // the address of the next row
  task automatic at(input int address);           // the rows that follow start at this address
    here = address;
  endtask
  task automatic i(input int k, input int a, input int b, input logic [31:0] c);   // add one row
    if (here < 4096) begin kind[here >> 2] = k; fa[here >> 2] = a; fb[here >> 2] = b; fc[here >> 2] = c; end
    here += 4;
  endtask
  logic        clk = 0;
  logic [31:0] x [0:31];             // the 32 registers
  logic [31:0] pc;                   // the address of the next instruction
  logic [31:0] ram [0:16383];        // SRAM: 64 KiB from 8000_0000. Nothing is in it at power-on
  logic [31:0] mstatus, mie, mtvec, mscratch, mepc, mcause;   // the machine CSRs of this model
  int          steps, traps, taken;  // instructions, exceptions, interrupts
  bit          stopped;
  localparam int SHOW = 2;            // 2: print every instruction. 1: print events only. 0: print nothing
  task automatic say(input string text);
    if (SHOW != 0) $display("%s", text);
  endtask
  wire [31:0] mip = 32'h0;           // no interrupt source in this lab

  function automatic string cn(input logic [11:0] a);   // the name of a CSR
    case (a)
      MSTATUS: return "mstatus";  MIE: return "mie";  MTVEC: return "mtvec";  MSCRATCH: return "mscratch";
      MEPC: return "mepc";  MCAUSE: return "mcause";  MIP: return "mip";
      default: return "?";
    endcase
  endfunction
  function automatic logic [31:0] csr_value(input logic [11:0] a);
    case (a)
      MSTATUS: return mstatus;  MIE: return mie;  MTVEC: return mtvec;  MSCRATCH: return mscratch;
      MEPC: return mepc;  MCAUSE: return mcause;
      default: return mip;
    endcase
  endfunction
  task automatic csr_store(input logic [11:0] a, input logic [31:0] v);   // each CSR keeps only its writable bits
    case (a)
      MSTATUS:  begin mstatus[3] = v[3];  mstatus[7] = v[7]; end           // MIE and MPIE
      MIE:      mie = v & 32'h0000_0888;                                   // external, timer and software enables
      MTVEC:    mtvec = v & 32'hffff_fffd;
      MSCRATCH: mscratch = v;
      MEPC:     mepc = v & 32'hffff_fffc;
      MCAUSE:   mcause = v;
      default: ;                                                           // mip is read-only
    endcase
  endtask
  // The entry of a trap, for an exception or an interrupt: what the processor does by itself.
  task automatic enter(input logic [31:0] cause, input string text);
    mepc = pc & 32'hffff_fffc;  mcause = cause;
    mstatus[7] = mstatus[3];  mstatus[3] = 1'b0;                           // MPIE takes MIE, MIE closes
    say($sformatf("%s: mcause=%08h mepc=%08h, next is %08h", text, cause, mepc, mtvec & 32'hffff_fffc));
    pc = mtvec & 32'hffff_fffc;
  endtask
  // Start one read or write of a word. The value of a read is in bus_rdata after half a tick.
  logic [31:0] bus_rdata;
  bit          bus_fault;
  task automatic bus(input bit wr, input logic [31:0] ad, input logic [31:0] wd);
    bus_fault = 0;  bus_rdata = 0;
    if (ad[31:12] == 20'h0) begin                                          // Boot ROM: data words can be read
      if (wr) bus_fault = 1;
      else bus_rdata = (kind[ad[11:2]] == WORD) ? fc[ad[11:2]] : 32'h0;
    end
    else if (ad[31:16] == 16'h8000) begin                                  // SRAM
      if (wr) ram[ad[15:2]] = wd;
      else bus_rdata = ram[ad[15:2]];
    end
    else bus_fault = 1;                                                    // nothing answers at this address
  endtask
  // One tick: one instruction, then one rising clock edge.
  task automatic step();
    int k, a, b;
    logic [31:0] c, r1, r2, res, next, ad;
    string text, effect;
    bit writes, take, done, access;
    // An interrupt is taken between two instructions: MIE at 1, and a request that is pending and enabled.
    if (mstatus[3] && (mie & mip) != 0) begin
      if (mie[11] && mip[11]) enter(32'h8000_000b, "interrupt, external");
      else                    enter(32'h8000_0007, "interrupt, machine timer");
      taken++;
    end
    done = 0;  writes = 1;  access = 0;  res = 0;  effect = "";  next = pc + 4;  text = "";
    if (pc >= 32'h1000) begin enter(1, "exception, no instruction at this address");  traps++;  done = 1;  k = WORD;  a = 0;  b = 0;  c = 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]];
    // An immediate has 12 bits with a sign (20 bits in lui). A row outside that range is no instruction.
    if (!done && ((k == LUI && c[31:20] != 0) || ((k == ADDI || k == ANDI || k == ORI || k == LW || k == SW || k == JALR) && !($signed(c) >= -2048 && $signed(c) <= 2047)))) begin
      enter(2, $sformatf("exception, immediate out of range at %08h", pc));  traps++;  done = 1;
    end
    if (!done) case (k)
      LUI:  begin res = c << 12;  text = $sformatf("lui x%0d, 0x%0h", a, c); end
      ADDI: begin res = r1 + c;          text = $sformatf("addi x%0d, x%0d, %0d", a, b, $signed(c)); end
      ANDI: begin res = r1 & c;          text = $sformatf("andi x%0d, x%0d, %0d", a, b, $signed(c)); end
      ORI:  begin res = r1 | c;          text = $sformatf("ori x%0d, x%0d, %0d", a, b, $signed(c)); end
      SLLI: begin res = r1 << c[4:0];    text = $sformatf("slli x%0d, x%0d, %0d", a, b, c); end
      SRLI: begin res = r1 >> c[4:0];    text = $sformatf("srli x%0d, x%0d, %0d", a, b, c); end
      ADD:  begin res = r1 + r2;         text = $sformatf("add x%0d, x%0d, x%0d", a, b, c[4:0]); end
      SUB:  begin res = r1 - r2;         text = $sformatf("sub x%0d, x%0d, x%0d", a, b, c[4:0]); end
      AND:  begin res = r1 & r2;         text = $sformatf("and x%0d, x%0d, x%0d", a, b, c[4:0]); end
      OR:   begin res = r1 | r2;         text = $sformatf("or x%0d, x%0d, x%0d", a, b, c[4:0]); end
      LW, SW: begin
        ad = r1 + c;  access = 1;
        text = $sformatf("%s x%0d, %0d(x%0d)", (k == LW) ? "lw" : "sw", a, $signed(c), b);
        bus(k == SW, ad, x[a[4:0]]);
        if (k == SW) begin writes = 0;  effect = $sformatf("mem[%08h] = %08h", ad, x[a[4:0]]); end
      end
      BEQ, BNE, BLT, BGE: 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));
          default: take = ($signed(r1) >= $signed(r2));
        endcase
        text = $sformatf("%s x%0d, x%0d, 0x%0h", (k == BEQ) ? "beq" : (k == BNE) ? "bne" : (k == BLT) ? "blt" : "bge", a, b, c);
        if (take) begin next = c;  effect = $sformatf("taken: next is %08h", next); end
        else effect = "not taken";
      end
      JAL, JALR: begin
        res = pc + 4;
        if (k == JAL) begin next = c;  text = $sformatf("jal x%0d, 0x%0h", a, c); end
        else begin next = (r1 + c) & ~32'd1;  text = $sformatf("jalr x%0d, %0d(x%0d)", a, $signed(c), b); end
        if (k == JAL && next == pc) begin
          if (SHOW == 2) $display("%08h | %s | the program stops here", pc, text);
          else say($sformatf("the program stops at %08h", pc));
          stopped = 1;  done = 1;
        end
      end
      CSRR: begin res = csr_value(c[11:0]);  text = $sformatf("csrr x%0d, %s", a, cn(c[11:0])); end
      CSRW, CSRS, CSRC: begin
        writes = 0;
        case (k)
          CSRW:    csr_store(c[11:0], x[a[4:0]]);
          CSRS:    csr_store(c[11:0], csr_value(c[11:0]) | x[a[4:0]]);
          default: csr_store(c[11:0], csr_value(c[11:0]) & ~x[a[4:0]]);
        endcase
        text = $sformatf("%s %s, x%0d", (k == CSRW) ? "csrw" : (k == CSRS) ? "csrs" : "csrc", cn(c[11:0]), a);
        effect = $sformatf("%s = %08h", cn(c[11:0]), csr_value(c[11:0]));
      end
      MRET: begin
        writes = 0;  next = mepc;  text = "mret";
        mstatus[3] = mstatus[7];  mstatus[7] = 1'b1;                       // MIE takes MPIE back
        effect = $sformatf("next is %08h, MIE=%0d", next, mstatus[3]);
        if (SHOW == 1) say($sformatf("mret: back to %08h", next));
      end
      default: begin enter(2, $sformatf("exception, illegal instruction %08h at %08h", c, pc));  traps++;  done = 1; end
    endcase
    #1;                                                                    // half a tick: the devices answer
    if (access && !done) begin
      if (bus_fault) begin
        enter((k == LW) ? 5 : 7, $sformatf("exception, no memory at %08h for %s at %08h", ad, (k == LW) ? "a load" : "a store", pc));
        traps++;  done = 1;
      end
      else if (k == LW) begin res = bus_rdata;  effect = $sformatf(" from mem[%08h]", ad); end
    end
    if (!done) begin
      if (writes) begin
        if (a[4:0] != 0) x[a[4:0]] = res;                                  // register 0 is never written
        effect = {$sformatf("x%0d = %08h", a, x[a[4:0]]), effect};
        if (k == JAL || k == JALR) effect = {effect, $sformatf(", next is %08h", next)};
      end
      if (SHOW == 2) $display("%08h | %s | %s", pc, text, effect);
      pc = next;  steps++;
    end
    clk = 1;  #1;  clk = 0;                                                // the rising edge: registers of the chip blocks load
  endtask
  task automatic power_on();
    for (int n = 0; n < 32; n++) x[n] = 0;
    for (int n = 0; n < 16384; n++) ram[n] = 'x;                           // SRAM holds nothing known
    mstatus = 32'h0000_1800;  mie = 0;  mtvec = 0;  mscratch = 0;  mepc = 0;  mcause = 0;   // the values after reset
    pc = 0;  steps = 0;  traps = 0;  taken = 0;  stopped = 0;
  endtask
  task automatic run();
    while (!stopped && steps + traps + taken < 120) step();
  endtask
  initial begin
    for (int n = 0; n < 1024; n++) begin kind[n] = WORD; fa[n] = 0; fb[n] = 0; fc[n] = 0; end   // empty ROM reads as 0
    the_program();
    power_on();
    run();
    if (!stopped) $display("still running after %0d instructions, %0d exceptions and %0d interrupts", steps, traps, taken);
    $display("limit=%0h step=%0h count=%0h total=%0h | sp=%08h | exceptions=%0d", ram[0], ram[1], ram[2], ram[3], x[2], traps);
    $finish;
  end
endmodule
ConceptWhat must be true before start-up code may call any function?
ConceptWhere are the first values of .data kept while the power is off?
ConceptWhy is nothing stored in ROM for .bss?
ConceptAfter a cold start, one global variable without a first value is wrong. All others are right. Where do you look first?

Common Mistakes

Wrong Call a function before the stack pointer is set.

The call saves its return address through sp, which still holds 0.

Fix Make the write to sp the first instruction.

Wrong Expect a variable without a first value to hold 0 by itself.

SRAM keeps nothing through power-off.

Fix Clear every word of .bss in start-up code.

Wrong Test start-up code only with the debugger attached.

The debugger may write or clear memory itself.

Fix Test from a cold start, with the cable off.

Remember

  • Start-up code runs between the reset address and main.
  • It sets the stack pointer first, and the trap vector early.
  • It copies .data from its load address in ROM to its run address in SRAM.
  • It writes 0 to every word of .bss, then calls main.
  • A variable that is wrong only after a cold start points at a missing or short start-up step.

Practice

Report a problem with this page