Debian Codegraph @

examples/femto-riscv-18-test.v

raw
1 /**
2 * Step 18: Creating a RISC-V processor
3 * Mandelbrot in the terminal (test variant: no blink, prints tick between frames)
4 *
5 * Copyright (c) 2020, Bruno Levy
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the above copyright notice, this
12 * list of conditions and the following disclaimer.
13 *
14 * 2. Redistributions in binary form must reproduce the above copyright notice,
15 * this list of conditions and the following disclaimer in the documentation
16 * and/or other materials provided with the distribution.
17 *
18 * 3. Neither the name of the copyright holder nor the names of its
19 * contributors may be used to endorse or promote products derived from
20 * this software without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
23 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
28 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34 `default_nettype none
35 `include "clockworks.v"
36 `include "emitter_uart.v"
37
38 module Memory (
39 input clk,
40 input [31:0] mem_addr, // address to be read
41 output reg [31:0] mem_rdata, // data read from memory
42 input mem_rstrb, // goes high when processor wants to read
43 input [31:0] mem_wdata, // data to be written
44 input [3:0] mem_wmask // masks for writing the 4 bytes (1=write byte)
45 );
46
47 reg [31:0] MEM [0:1535]; // 1536 4-bytes words = 6 Kb of RAM in total
48
49 // Memory-mapped IO in IO page, 1-hot addressing in word address.
50 localparam IO_LEDS_bit = 0; // W five leds
51 localparam IO_UART_DAT_bit = 1; // W data to send (8 bits)
52 localparam IO_UART_CNTL_bit = 2; // R status. bit 9: busy sending
53
54 // Converts an IO_xxx_bit constant into an offset in IO page.
55 function [31:0] IO_BIT_TO_OFFSET;
56 input [31:0] bitid;
57 begin
58 IO_BIT_TO_OFFSET = 1 << (bitid + 2);
59 end
60 endfunction
61
62 `include "riscv_assembly.v"
63
64 `define mandel_shift 10
65 `define mandel_mul (1 << `mandel_shift)
66 `define xmin (-2*`mandel_mul)
67 `define xmax ( 2*`mandel_mul)
68 `define ymin (-2*`mandel_mul)
69 `define ymax ( 2*`mandel_mul)
70 `define dx ((`xmax-`xmin)/80)
71 `define dy ((`ymax-`ymin)/80)
72 `define norm_max (4 << `mandel_shift)
73
74 integer mandelstart_ = 12;
75 integer loop_y_ = 24;
76 integer loop_x_ = 32;
77 integer loop_Z_ = 44;
78 integer exit_Z_ = 136;
79 integer tick_loop_ = 208;
80 integer tick_done_ = 232;
81 integer putc_ = 240;
82 integer putc_L0_ = 248;
83 integer mulsi3_ = 264;
84 integer mulsi3_L0_ = 272;
85 integer mulsi3_L1_ = 284;
86
87 integer colormap_ = 300;
88 integer tick_str_ = 312;
89
90 // X,Y : s0,s1
91 // Cr,Ci : s2,s3
92 // Zr,Zi : s4,s5
93 // Zrr,2Zri,Zii: s6,s7,s8
94 // cnt: s10
95 // 128: s11
96
97 initial begin
98 LI(sp,32'h1800); // End of RAM, 6kB
99 LI(gp,32'h400000); // IO page
100
101 Label(mandelstart_);
102
103 LI(s1,0);
104 LI(s3,`xmin);
105 LI(s11,80);
106
107 Label(loop_y_);
108 LI(s0,0);
109 LI(s2,`ymin);
110
111 Label(loop_x_);
112 MV(s4,s2); // Z <- C
113 MV(s5,s3);
114
115 LI(s10,9); // iter <- 9
116
117 Label(loop_Z_);
118 MV(a0,s4); // Zrr <- (Zr*Zr) >> mandel_shift
119 MV(a1,s4);
120 CALL(LabelRef(mulsi3_));
121 SRLI(s6,a0,`mandel_shift);
122 MV(a0,s4); // Zri <- (Zr*Zi) >> (mandel_shift-1)
123 MV(a1,s5);
124 CALL(LabelRef(mulsi3_));
125 SRAI(s7,a0,`mandel_shift-1);
126 MV(a0,s5); // Zii <- (Zi*Zi) >> (mandel_shift)
127 MV(a1,s5);
128 CALL(LabelRef(mulsi3_));
129 SRLI(s8,a0,`mandel_shift);
130 SUB(s4,s6,s8); // Zr <- Zrr - Zii + Cr
131 ADD(s4,s4,s2);
132 ADD(s5,s7,s3); // Zi <- 2Zri + Cr
133
134 ADD(s6,s6,s8); // if norm > norm max, exit loop
135 LI(s7,`norm_max);
136 BGT(s6,s7,LabelRef(exit_Z_));
137
138 ADDI(s10,s10,-1); // iter--, loop if non-zero
139 BNEZ(s10,LabelRef(loop_Z_));
140
141 Label(exit_Z_);
142 LI(a0,colormap_);
143 ADD(a0,a0,s10);
144 LBU(a0,a0,0);
145 CALL(LabelRef(putc_));
146
147 ADDI(s0,s0,1);
148 ADDI(s2,s2,`dx);
149 BNE(s0,s11,LabelRef(loop_x_));
150
151 LI(a0," ");
152 CALL(LabelRef(putc_));
153 LI(a0,"\n");
154 CALL(LabelRef(putc_));
155
156 ADDI(s1,s1,1);
157 ADDI(s3,s3,`dy);
158 BNE(s1,s11,LabelRef(loop_y_));
159
160 // Print "--- tick ---\n" between frames
161 LI(s0,tick_str_);
162 Label(tick_loop_);
163 LBU(a0,s0,0);
164 BEQZ(a0,LabelRef(tick_done_));
165 CALL(LabelRef(putc_));
166 ADDI(s0,s0,1);
167 J(LabelRef(tick_loop_));
168 Label(tick_done_);
169
170 J(LabelRef(mandelstart_));
171
172 EBREAK(); // I systematically keep it before functions
173 // in case I decide to remove the loop...
174
175 Label(putc_);
176 // Send character to UART
177 SW(a0,gp,IO_BIT_TO_OFFSET(IO_UART_DAT_bit));
178 // Read UART status, and loop until bit 9 (busy sending)
179 // is zero.
180 LI(t0,1<<9);
181 Label(putc_L0_);
182 LW(t1,gp,IO_BIT_TO_OFFSET(IO_UART_CNTL_bit));
183 AND(t1,t1,t0);
184 BNEZ(t1,LabelRef(putc_L0_));
185 RET();
186
187 // Mutiplication routine,
188 // Input in a0 and a1
189 // Result in a0
190 Label(mulsi3_);
191 MV(a2,a0);
192 LI(a0,0);
193 Label(mulsi3_L0_);
194 ANDI(a3,a1,1);
195 BEQZ(a3,LabelRef(mulsi3_L1_));
196 ADD(a0,a0,a2);
197 Label(mulsi3_L1_);
198 SRLI(a1,a1,1);
199 SLLI(a2,a2,1);
200 BNEZ(a1,LabelRef(mulsi3_L0_));
201 RET();
202
203 Label(colormap_);
204 DATAB(" ",".",",",":");
205 DATAB(";","o","x","%");
206 DATAB("#","@", 0 , 0 );
207
208 Label(tick_str_);
209 DATAB("-","-","-"," ");
210 DATAB("t","i","c","k");
211 DATAB(" ","-","-","-");
212 DATAB("\n", 0 , 0 , 0 );
213
214 endASM();
215 end
216
217 wire [29:0] word_addr = mem_addr[31:2];
218
219 always @(posedge clk) begin
220 if(mem_rstrb) begin
221 mem_rdata <= MEM[word_addr];
222 end
223 if(mem_wmask[0]) MEM[word_addr][ 7:0 ] <= mem_wdata[ 7:0 ];
224 if(mem_wmask[1]) MEM[word_addr][15:8 ] <= mem_wdata[15:8 ];
225 if(mem_wmask[2]) MEM[word_addr][23:16] <= mem_wdata[23:16];
226 if(mem_wmask[3]) MEM[word_addr][31:24] <= mem_wdata[31:24];
227 end
228 endmodule
229
230 module Processor (
231 input clk,
232 input resetn,
233 output [31:0] mem_addr,
234 input [31:0] mem_rdata,
235 output mem_rstrb,
236 output [31:0] mem_wdata,
237 output [3:0] mem_wmask
238 );
239
240 reg [31:0] PC=0; // program counter
241 reg [31:0] instr; // current instruction
242
243 // See the table P. 105 in RISC-V manual
244
245 // The 10 RISC-V instructions
246 wire isALUreg = (instr[6:0] == 7'b0110011); // rd <- rs1 OP rs2
247 wire isALUimm = (instr[6:0] == 7'b0010011); // rd <- rs1 OP Iimm
248 wire isBranch = (instr[6:0] == 7'b1100011); // if(rs1 OP rs2) PC<-PC+Bimm
249 wire isJALR = (instr[6:0] == 7'b1100111); // rd <- PC+4; PC<-rs1+Iimm
250 wire isJAL = (instr[6:0] == 7'b1101111); // rd <- PC+4; PC<-PC+Jimm
251 wire isAUIPC = (instr[6:0] == 7'b0010111); // rd <- PC + Uimm
252 wire isLUI = (instr[6:0] == 7'b0110111); // rd <- Uimm
253 wire isLoad = (instr[6:0] == 7'b0000011); // rd <- mem[rs1+Iimm]
254 wire isStore = (instr[6:0] == 7'b0100011); // mem[rs1+Simm] <- rs2
255 wire isSYSTEM = (instr[6:0] == 7'b1110011); // special
256
257 // The 5 immediate formats
258 wire [31:0] Uimm={ instr[31], instr[30:12], {12{1'b0}}};
259 wire [31:0] Iimm={{21{instr[31]}}, instr[30:20]};
260 wire [31:0] Simm={{21{instr[31]}}, instr[30:25],instr[11:7]};
261 wire [31:0] Bimm={{20{instr[31]}}, instr[7],instr[30:25],instr[11:8],1'b0};
262 wire [31:0] Jimm={{12{instr[31]}}, instr[19:12],instr[20],instr[30:21],1'b0};
263
264 // Source and destination registers
265 wire [4:0] rs1Id = instr[19:15];
266 wire [4:0] rs2Id = instr[24:20];
267 wire [4:0] rdId = instr[11:7];
268
269 // function codes
270 wire [2:0] funct3 = instr[14:12];
271 wire [6:0] funct7 = instr[31:25];
272
273 // The registers bank
274 `ifdef FORCE_BRAM
275 (* ram_style = "block" *)
276 `endif
277 reg [31:0] RegisterBank [0:31];
278 reg [31:0] rs1; // value of source
279 reg [31:0] rs2; // registers.
280 wire [31:0] writeBackData; // data to be written to rd
281 wire writeBackEn; // asserted if data should be written to rd
282
283 // The ALU
284 wire [31:0] aluIn1 = rs1;
285 wire [31:0] aluIn2 = isALUreg | isBranch ? rs2 : Iimm;
286
287 wire [4:0] shamt = isALUreg ? rs2[4:0] : instr[24:20]; // shift amount
288
289 // The adder is used by both arithmetic instructions and JALR.
290 wire [31:0] aluPlus = aluIn1 + aluIn2;
291
292 // Use a single 33 bits subtract to do subtraction and all comparisons
293 // (trick borrowed from swapforth/J1)
294 wire [32:0] aluMinus = {1'b1, ~aluIn2} + {1'b0,aluIn1} + 33'b1;
295 wire LT = (aluIn1[31] ^ aluIn2[31]) ? aluIn1[31] : aluMinus[32];
296 wire LTU = aluMinus[32];
297 wire EQ = (aluMinus[31:0] == 0);
298
299 // Flip a 32 bit word. Used by the shifter (a single shifter for
300 // left and right shifts, saves silicium !)
301 function [31:0] flip32;
302 input [31:0] x;
303 flip32 = {x[ 0], x[ 1], x[ 2], x[ 3], x[ 4], x[ 5], x[ 6], x[ 7],
304 x[ 8], x[ 9], x[10], x[11], x[12], x[13], x[14], x[15],
305 x[16], x[17], x[18], x[19], x[20], x[21], x[22], x[23],
306 x[24], x[25], x[26], x[27], x[28], x[29], x[30], x[31]};
307 endfunction
308
309 wire [31:0] shifter_in = (funct3 == 3'b001) ? flip32(aluIn1) : aluIn1;
310
311 /* verilator lint_off WIDTH */
312 wire [31:0] shifter =
313 $signed({instr[30] & aluIn1[31], shifter_in}) >>> aluIn2[4:0];
314 /* verilator lint_on WIDTH */
315
316 wire [31:0] leftshift = flip32(shifter);
317
318
319
320 // ADD/SUB/ADDI:
321 // funct7[5] is 1 for SUB and 0 for ADD. We need also to test instr[5]
322 // to make the difference with ADDI
323 //
324 // SRLI/SRAI/SRL/SRA:
325 // funct7[5] is 1 for arithmetic shift (SRA/SRAI) and
326 // 0 for logical shift (SRL/SRLI)
327 reg [31:0] aluOut;
328 always @(*) begin
329 case(funct3)
330 3'b000: aluOut = (funct7[5] & instr[5]) ? aluMinus[31:0] : aluPlus;
331 3'b001: aluOut = leftshift;
332 3'b010: aluOut = {31'b0, LT};
333 3'b011: aluOut = {31'b0, LTU};
334 3'b100: aluOut = (aluIn1 ^ aluIn2);
335 3'b101: aluOut = shifter;
336 3'b110: aluOut = (aluIn1 | aluIn2);
337 3'b111: aluOut = (aluIn1 & aluIn2);
338 endcase
339 end
340
341 // The predicate for branch instructions
342 reg takeBranch;
343 always @(*) begin
344 case(funct3)
345 3'b000: takeBranch = EQ;
346 3'b001: takeBranch = !EQ;
347 3'b100: takeBranch = LT;
348 3'b101: takeBranch = !LT;
349 3'b110: takeBranch = LTU;
350 3'b111: takeBranch = !LTU;
351 default: takeBranch = 1'b0;
352 endcase
353 end
354
355
356 // Address computation
357 // An adder used to compute branch address, JAL address and AUIPC.
358 // branch->PC+Bimm AUIPC->PC+Uimm JAL->PC+Jimm
359 // Equivalent to PCplusImm = PC + (isJAL ? Jimm : isAUIPC ? Uimm : Bimm)
360 wire [31:0] PCplusImm = PC + ( instr[3] ? Jimm[31:0] :
361 instr[4] ? Uimm[31:0] :
362 Bimm[31:0] );
363 wire [31:0] PCplus4 = PC+4;
364
365 // register write back
366 assign writeBackData = (isJAL || isJALR) ? PCplus4 :
367 isLUI ? Uimm :
368 isAUIPC ? PCplusImm :
369 isLoad ? LOAD_data :
370 aluOut;
371
372 wire [31:0] nextPC = ((isBranch && takeBranch) || isJAL) ? PCplusImm :
373 isJALR ? {aluPlus[31:1],1'b0} :
374 PCplus4;
375
376 wire [31:0] loadstore_addr = rs1 + (isStore ? Simm : Iimm);
377
378 // Load
379 // All memory accesses are aligned on 32 bits boundary. For this
380 // reason, we need some circuitry that does unaligned halfword
381 // and byte load/store, based on:
382 // - funct3[1:0]: 00->byte 01->halfword 10->word
383 // - mem_addr[1:0]: indicates which byte/halfword is accessed
384
385 wire mem_byteAccess = funct3[1:0] == 2'b00;
386 wire mem_halfwordAccess = funct3[1:0] == 2'b01;
387
388
389 wire [15:0] LOAD_halfword =
390 loadstore_addr[1] ? mem_rdata[31:16] : mem_rdata[15:0];
391
392 wire [7:0] LOAD_byte =
393 loadstore_addr[0] ? LOAD_halfword[15:8] : LOAD_halfword[7:0];
394
395 // LOAD, in addition to funct3[1:0], LOAD depends on:
396 // - funct3[2] (instr[14]): 0->do sign expansion 1->no sign expansion
397 wire LOAD_sign =
398 !funct3[2] & (mem_byteAccess ? LOAD_byte[7] : LOAD_halfword[15]);
399
400 wire [31:0] LOAD_data =
401 mem_byteAccess ? {{24{LOAD_sign}}, LOAD_byte} :
402 mem_halfwordAccess ? {{16{LOAD_sign}}, LOAD_halfword} :
403 mem_rdata ;
404
405 // Store
406 // ------------------------------------------------------------------------
407
408 assign mem_wdata[ 7: 0] = rs2[7:0];
409 assign mem_wdata[15: 8] = loadstore_addr[0] ? rs2[7:0] : rs2[15: 8];
410 assign mem_wdata[23:16] = loadstore_addr[1] ? rs2[7:0] : rs2[23:16];
411 assign mem_wdata[31:24] = loadstore_addr[0] ? rs2[7:0] :
412 loadstore_addr[1] ? rs2[15:8] : rs2[31:24];
413
414 // The memory write mask:
415 // 1111 if writing a word
416 // 0011 or 1100 if writing a halfword
417 // (depending on loadstore_addr[1])
418 // 0001, 0010, 0100 or 1000 if writing a byte
419 // (depending on loadstore_addr[1:0])
420
421 wire [3:0] STORE_wmask =
422 mem_byteAccess ?
423 (loadstore_addr[1] ?
424 (loadstore_addr[0] ? 4'b1000 : 4'b0100) :
425 (loadstore_addr[0] ? 4'b0010 : 4'b0001)
426 ) :
427 mem_halfwordAccess ?
428 (loadstore_addr[1] ? 4'b1100 : 4'b0011) :
429 4'b1111;
430
431 // The state machine
432 localparam FETCH_INSTR = 0;
433 localparam WAIT_INSTR = 1;
434 localparam FETCH_REGS = 2;
435 localparam EXECUTE = 3;
436 localparam LOAD = 4;
437 localparam WAIT_DATA = 5;
438 localparam STORE = 6;
439 reg [2:0] state = FETCH_INSTR;
440
441 always @(posedge clk) begin
442 if(!resetn) begin
443 PC <= 0;
444 state <= FETCH_INSTR;
445 end else begin
446 if(writeBackEn && rdId != 0) begin
447 RegisterBank[rdId] <= writeBackData;
448 end
449 case(state)
450 FETCH_INSTR: begin
451 state <= WAIT_INSTR;
452 end
453 WAIT_INSTR: begin
454 instr <= mem_rdata;
455 state <= FETCH_REGS;
456 end
457 FETCH_REGS: begin
458 rs1 <= RegisterBank[rs1Id];
459 rs2 <= RegisterBank[rs2Id];
460 state <= EXECUTE;
461 end
462 EXECUTE: begin
463 if(!isSYSTEM) begin
464 PC <= nextPC;
465 end
466 state <= isLoad ? LOAD :
467 isStore ? STORE :
468 FETCH_INSTR;
469 end
470 LOAD: begin
471 state <= WAIT_DATA;
472 end
473 WAIT_DATA: begin
474 state <= FETCH_INSTR;
475 end
476 STORE: begin
477 state <= FETCH_INSTR;
478 end
479 endcase
480 end
481 end
482
483 assign writeBackEn = (state==EXECUTE && !isBranch && !isStore) ||
484 (state==WAIT_DATA) ;
485
486 assign mem_addr = (state == WAIT_INSTR || state == FETCH_INSTR) ?
487 PC : loadstore_addr ;
488 assign mem_rstrb = (state == FETCH_INSTR || state == LOAD);
489 assign mem_wmask = {4{(state == STORE)}} & STORE_wmask;
490
491 endmodule
492
493
494 module top (
495 input clk_i, // system clock
496 input rst_i, // reset button
497 output [5:0] led, // system LEDs
498 input RXD, // UART receive
499 output TXD // UART transmit
500 );
501
502 wire clk;
503 wire resetn;
504
505 wire [31:0] mem_addr;
506 wire [31:0] mem_rdata;
507 wire mem_rstrb;
508 wire [31:0] mem_wdata;
509 wire [3:0] mem_wmask;
510
511 Processor CPU(
512 .clk(clk),
513 .resetn(resetn),
514 .mem_addr(mem_addr),
515 .mem_rdata(mem_rdata),
516 .mem_rstrb(mem_rstrb),
517 .mem_wdata(mem_wdata),
518 .mem_wmask(mem_wmask)
519 );
520
521 wire [31:0] RAM_rdata;
522 wire [29:0] mem_wordaddr = mem_addr[31:2];
523 wire isIO = mem_addr[22];
524 wire isRAM = !isIO;
525 wire mem_wstrb = |mem_wmask;
526
527 Memory RAM(
528 .clk(clk),
529 .mem_addr(mem_addr),
530 .mem_rdata(RAM_rdata),
531 .mem_rstrb(isRAM & mem_rstrb),
532 .mem_wdata(mem_wdata),
533 .mem_wmask({4{isRAM}}&mem_wmask)
534 );
535
536
537 // Memory-mapped IO in IO page, 1-hot addressing in word address.
538 localparam IO_LEDS_bit = 0; // W five leds
539 localparam IO_UART_DAT_bit = 1; // W data to send (8 bits)
540 localparam IO_UART_CNTL_bit = 2; // R status. bit 9: busy sending
541
542 always @(posedge clk) begin
543 if(isIO & mem_wstrb & mem_wordaddr[IO_LEDS_bit]) begin
544 led <= mem_wdata;
545 end
546 end
547
548 wire uart_valid = isIO & mem_wstrb & mem_wordaddr[IO_UART_DAT_bit];
549 wire uart_ready;
550
551 corescore_emitter_uart #(
552 .clk_freq_hz(`CPU_FREQ*1000000),
553 //.clk_freq_hz(27*1000000),
554 .baud_rate(`BAUD_RATE)
555 ) UART(
556 .i_clk(clk),
557 .i_rst(!resetn),
558 .i_data(mem_wdata[7:0]),
559 .i_valid(uart_valid),
560 .o_ready(uart_ready),
561 .o_uart_tx(TXD)
562 );
563
564 wire [31:0] IO_rdata =
565 mem_wordaddr[IO_UART_CNTL_bit] ? { 22'b0, !uart_ready, 9'b0}
566 : 32'b0;
567
568 assign mem_rdata = isRAM ? RAM_rdata :
569 IO_rdata ;
570
571
572 // Gearbox and reset circuitry.
573 Clockworks #(
574 .SLOW(0) //Specifying a value other than zero here may result in
575 // nextpnr being unable to route the clock for some boards. BUGFIX is under development.
576 ) CW (
577 .CLK(clk_i),
578 .RESET(rst_i),
579 .clk(clk),
580 .resetn(resetn)
581 );
582
583 endmodule