diff --git a/chips/yosys/tests/asicworld/code_tidbits_fsm_using_function.v b/chips/yosys/tests/asicworld/code_tidbits_fsm_using_function.v new file mode 100644 index 0000000000000000000000000000000000000000..f97cd85210e81016a0ea8aca65456dbb8f1e3914 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_tidbits_fsm_using_function.v @@ -0,0 +1,94 @@ +//----------------------------------------------------- +// This is FSM demo program using function +// Design Name : fsm_using_function +// File Name : fsm_using_function.v +//----------------------------------------------------- +module fsm_using_function ( +clock , // clock +reset , // Active high, syn reset +req_0 , // Request 0 +req_1 , // Request 1 +gnt_0 , // Grant 0 +gnt_1 +); +//-------------Input Ports----------------------------- +input clock,reset,req_0,req_1; + //-------------Output Ports---------------------------- +output gnt_0,gnt_1; +//-------------Input ports Data Type------------------- +wire clock,reset,req_0,req_1; +//-------------Output Ports Data Type------------------ +reg gnt_0,gnt_1; +//-------------Internal Constants-------------------------- +parameter SIZE = 3 ; +parameter IDLE = 3'b001,GNT0 = 3'b010,GNT1 = 3'b100 ; +//-------------Internal Variables--------------------------- +reg [SIZE-1:0] state ;// Seq part of the FSM +wire [SIZE-1:0] next_state ;// combo part of FSM +//----------Code startes Here------------------------ +assign next_state = fsm_function(state, req_0, req_1); +//----------Function for Combo Logic----------------- +function [SIZE-1:0] fsm_function; + input [SIZE-1:0] state ; + input req_0 ; + input req_1 ; + case(state) + IDLE : if (req_0 == 1'b1) begin + fsm_function = GNT0; + end else if (req_1 == 1'b1) begin + fsm_function= GNT1; + end else begin + fsm_function = IDLE; + end + GNT0 : if (req_0 == 1'b1) begin + fsm_function = GNT0; + end else begin + fsm_function = IDLE; + end + GNT1 : if (req_1 == 1'b1) begin + fsm_function = GNT1; + end else begin + fsm_function = IDLE; + end + default : fsm_function = IDLE; + endcase +endfunction +//----------Seq Logic----------------------------- +always @ (posedge clock) +begin : FSM_SEQ + if (reset == 1'b1) begin + state <= #1 IDLE; + end else begin + state <= #1 next_state; + end +end +//----------Output Logic----------------------------- +always @ (posedge clock) +begin : OUTPUT_LOGIC +if (reset == 1'b1) begin + gnt_0 <= #1 1'b0; + gnt_1 <= #1 1'b0; +end +else begin + case(state) + IDLE : begin + gnt_0 <= #1 1'b0; + gnt_1 <= #1 1'b0; + end + GNT0 : begin + gnt_0 <= #1 1'b1; + gnt_1 <= #1 1'b0; + end + GNT1 : begin + gnt_0 <= #1 1'b0; + gnt_1 <= #1 1'b1; + end + default : begin + gnt_0 <= #1 1'b0; + gnt_1 <= #1 1'b0; + end + endcase +end +end // End Of Block OUTPUT_LOGIC + +endmodule // End of Module arbiter diff --git a/chips/yosys/tests/asicworld/code_tidbits_fsm_using_single_always.v b/chips/yosys/tests/asicworld/code_tidbits_fsm_using_single_always.v new file mode 100644 index 0000000000000000000000000000000000000000..dc06154d381b3c70013e01b3c81b08144af57911 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_tidbits_fsm_using_single_always.v @@ -0,0 +1,63 @@ +//==================================================== +// This is FSM demo program using single always +// for both seq and combo logic +// Design Name : fsm_using_single_always +// File Name : fsm_using_single_always.v +//===================================================== +module fsm_using_single_always ( +clock , // clock +reset , // Active high, syn reset +req_0 , // Request 0 +req_1 , // Request 1 +gnt_0 , // Grant 0 +gnt_1 +); +//=============Input Ports============================= +input clock,reset,req_0,req_1; + //=============Output Ports=========================== +output gnt_0,gnt_1; +//=============Input ports Data Type=================== +wire clock,reset,req_0,req_1; +//=============Output Ports Data Type================== +reg gnt_0,gnt_1; +//=============Internal Constants====================== +parameter SIZE = 3 ; +parameter IDLE = 3'b001,GNT0 = 3'b010,GNT1 = 3'b100 ; +//=============Internal Variables====================== +reg [SIZE-1:0] state ;// Seq part of the FSM +reg [SIZE-1:0] next_state ;// combo part of FSM +//==========Code startes Here========================== +always @ (posedge clock) +begin : FSM +if (reset == 1'b1) begin + state <= #1 IDLE; + gnt_0 <= 0; + gnt_1 <= 0; +end else + case(state) + IDLE : if (req_0 == 1'b1) begin + state <= #1 GNT0; + gnt_0 <= 1; + end else if (req_1 == 1'b1) begin + gnt_1 <= 1; + state <= #1 GNT1; + end else begin + state <= #1 IDLE; + end + GNT0 : if (req_0 == 1'b1) begin + state <= #1 GNT0; + end else begin + gnt_0 <= 0; + state <= #1 IDLE; + end + GNT1 : if (req_1 == 1'b1) begin + state <= #1 GNT1; + end else begin + gnt_1 <= 0; + state <= #1 IDLE; + end + default : state <= #1 IDLE; +endcase +end + +endmodule // End of Module arbiter diff --git a/chips/yosys/tests/asicworld/code_tidbits_nonblocking.v b/chips/yosys/tests/asicworld/code_tidbits_nonblocking.v new file mode 100644 index 0000000000000000000000000000000000000000..fd0e4ca74950f95e6bf6f83111b5cc46e3e05ef0 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_tidbits_nonblocking.v @@ -0,0 +1,17 @@ +module nonblocking (clk,a,c); +input clk; +input a; +output c; + +wire clk; +wire a; +reg c; +reg b; + +always @ (posedge clk ) +begin + b <= a; + c <= b; +end + +endmodule diff --git a/chips/yosys/tests/asicworld/code_tidbits_reg_combo_example.v b/chips/yosys/tests/asicworld/code_tidbits_reg_combo_example.v new file mode 100644 index 0000000000000000000000000000000000000000..17765025a91af18dd32ddbc2e80210aa008138a8 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_tidbits_reg_combo_example.v @@ -0,0 +1,13 @@ +module reg_combo_example( a, b, y); +input a, b; +output y; + +reg y; +wire a, b; + +always @ ( a or b) +begin + y = a & b; +end + +endmodule diff --git a/chips/yosys/tests/asicworld/code_tidbits_reg_seq_example.v b/chips/yosys/tests/asicworld/code_tidbits_reg_seq_example.v new file mode 100644 index 0000000000000000000000000000000000000000..9627b9e04c59ae687c103f9101349ff6704d3a9e --- /dev/null +++ b/chips/yosys/tests/asicworld/code_tidbits_reg_seq_example.v @@ -0,0 +1,15 @@ +module reg_seq_example( clk, reset, d, q); +input clk, reset, d; +output q; + +reg q; +wire clk, reset, d; + +always @ (posedge clk or posedge reset) +if (reset) begin + q <= 1'b0; +end else begin + q <= d; +end + +endmodule diff --git a/chips/yosys/tests/asicworld/code_tidbits_syn_reset.v b/chips/yosys/tests/asicworld/code_tidbits_syn_reset.v new file mode 100644 index 0000000000000000000000000000000000000000..37120eeee8cbe4b3d14de60b815ce77a74dfc99d --- /dev/null +++ b/chips/yosys/tests/asicworld/code_tidbits_syn_reset.v @@ -0,0 +1,19 @@ +module syn_reset (clk,reset,a,c); + input clk; + input reset; + input a; + output c; + + wire clk; + wire reset; + wire a; + reg c; + +always @ (posedge clk ) + if ( reset == 1'b1) begin + c <= 0; + end else begin + c <= a; + end + +endmodule diff --git a/chips/yosys/tests/asicworld/code_tidbits_wire_example.v b/chips/yosys/tests/asicworld/code_tidbits_wire_example.v new file mode 100644 index 0000000000000000000000000000000000000000..577a535d1b4945235671cac4ace7888f81774261 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_tidbits_wire_example.v @@ -0,0 +1,9 @@ +module wire_example( a, b, y); + input a, b; + output y; + + wire a, b, y; + + assign y = a & b; + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_addbit.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_addbit.v new file mode 100644 index 0000000000000000000000000000000000000000..22063b052777f79cc732e44662e75d8eca27b479 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_addbit.v @@ -0,0 +1,24 @@ +module addbit ( +a , // first input +b , // Second input +ci , // Carry input +sum , // sum output +co // carry output +); +//Input declaration +input a; +input b; +input ci; +//Ouput declaration +output sum; +output co; +//Port Data types +wire a; +wire b; +wire ci; +wire sum; +wire co; +//Code starts here +assign {co,sum} = a + b + ci; + +endmodule // End of Module addbit diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_always_example.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_always_example.v new file mode 100644 index 0000000000000000000000000000000000000000..16174a17f160982ae51cbab16d7acd795f2d112a --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_always_example.v @@ -0,0 +1,11 @@ +module always_example(); +reg clk,reset,enable,q_in,data; + +always @ (posedge clk) +if (reset) begin + data <= 0; +end else if (enable) begin + data <= q_in; +end + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_bus_con.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_bus_con.v new file mode 100644 index 0000000000000000000000000000000000000000..7815f04699496eccc2a5e6f01264e33972136c12 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_bus_con.v @@ -0,0 +1,8 @@ +module bus_con (a,b, y); + input [3:0] a, b; + output [7:0] y; + wire [7:0] y; + + assign y = {a,b}; + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_comment.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_comment.v new file mode 100644 index 0000000000000000000000000000000000000000..62d5875c5847d6c4f29981a769d87278b385633a --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_comment.v @@ -0,0 +1,25 @@ +/* This is a + Multi line comment + example */ +module addbit ( +a, +b, +ci, +sum, +co); + +// Input Ports Single line comment +input a; +input b; +input ci; +// Output ports +output sum; +output co; +// Data Types +wire a; +wire b; +wire ci; +wire sum; +wire co; + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_counter.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_counter.v new file mode 100644 index 0000000000000000000000000000000000000000..6018d07f7b96ef1e0065290d8a98e7ecd34a6109 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_counter.v @@ -0,0 +1,19 @@ +//----------------------------------------------------- +// Design Name : counter +// File Name : counter.v +// Function : 4 bit up counter +// Coder : Deepak +//----------------------------------------------------- +module counter (clk, reset, enable, count); +input clk, reset, enable; +output [3:0] count; +reg [3:0] count; + +always @ (posedge clk) +if (reset == 1'b1) begin + count <= 0; +end else if ( enable == 1'b1) begin + count <= count + 1; +end + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_counter_tb.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_counter_tb.v new file mode 100644 index 0000000000000000000000000000000000000000..e2902d1e5438a29af57f88657b6d72bea172b071 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_counter_tb.v @@ -0,0 +1,100 @@ +/////////////////////////////////////////////////////////////////////////// +// MODULE : counter_tb // +// TOP MODULE : -- // +// // +// PURPOSE : 4-bit up counter test bench // +// // +// DESIGNER : Deepak Kumar Tala // +// // +// Revision History // +// // +// DEVELOPMENT HISTORY : // +// Rev0.0 : Jan 03, 2003 // +// Initial Revision // +// // +/////////////////////////////////////////////////////////////////////////// +module testbench; + +integer file; +reg clk = 0, reset = 0, enable = 0; +wire [3:0] count; +reg dut_error = 0; + +counter U0 ( +.clk (clk), +.reset (reset), +.enable (enable), +.count (count) +); + +event reset_enable; +event terminate_sim; + +initial + file = $fopen(`outfile); + +always + #5 clk = !clk; + +initial +@ (terminate_sim) begin + $fdisplay (file, "Terminating simulation"); + if (dut_error == 0) begin + $fdisplay (file, "Simulation Result : PASSED"); + end + else begin + $fdisplay (file, "Simulation Result : FAILED"); + end + $fdisplay (file, "###################################################"); + #1 $finish; +end + + + +event reset_done; + +initial +forever begin + @ (reset_enable); + @ (negedge clk) + $fdisplay (file, "Applying reset"); + reset = 1; + @ (negedge clk) + reset = 0; + $fdisplay (file, "Came out of Reset"); + -> reset_done; +end + +initial begin + #10 -> reset_enable; + @ (reset_done); + @ (negedge clk); + enable = 1; + repeat (5) + begin + @ (negedge clk); + end + enable = 0; + #5 -> terminate_sim; +end + + +reg [3:0] count_compare; + +always @ (posedge clk) +if (reset == 1'b1) + count_compare <= 0; +else if ( enable == 1'b1) + count_compare <= count_compare + 1; + + + +always @ (negedge clk) +if (count_compare != count) begin + $fdisplay (file, "DUT ERROR AT TIME%d",$time); + $fdisplay (file, "Expected value %d, Got Value %d", count_compare, count); + dut_error = 1; + #5 -> terminate_sim; +end + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_d_ff.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_d_ff.v new file mode 100644 index 0000000000000000000000000000000000000000..ba18b708af66e455433ff14ec92770fddff5a852 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_d_ff.v @@ -0,0 +1,14 @@ +// D flip-flop Code +module d_ff ( d, clk, q, q_bar); +input d ,clk; +output q, q_bar; +wire d ,clk; +reg q, q_bar; + +always @ (posedge clk) +begin + q <= d; + q_bar <= !d; +end + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_decoder.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_decoder.v new file mode 100644 index 0000000000000000000000000000000000000000..6cb4c7999c241b79e35c5d57578143b7fd812963 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_decoder.v @@ -0,0 +1,14 @@ +module decoder (in,out); +input [2:0] in; +output [7:0] out; +wire [7:0] out; +assign out = (in == 3'b000 ) ? 8'b0000_0001 : +(in == 3'b001 ) ? 8'b0000_0010 : +(in == 3'b010 ) ? 8'b0000_0100 : +(in == 3'b011 ) ? 8'b0000_1000 : +(in == 3'b100 ) ? 8'b0001_0000 : +(in == 3'b101 ) ? 8'b0010_0000 : +(in == 3'b110 ) ? 8'b0100_0000 : +(in == 3'b111 ) ? 8'b1000_0000 : 8'h00; + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_decoder_always.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_decoder_always.v new file mode 100644 index 0000000000000000000000000000000000000000..5b31a2414e2d298526c29707a62ae93db8c0be15 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_decoder_always.v @@ -0,0 +1,20 @@ +module decoder_always (in,out); +input [2:0] in; +output [7:0] out; +reg [7:0] out; + +always @ (in) +begin + out = 0; + case (in) + 3'b001 : out = 8'b0000_0001; + 3'b010 : out = 8'b0000_0010; + 3'b011 : out = 8'b0000_0100; + 3'b100 : out = 8'b0000_1000; + 3'b101 : out = 8'b0001_0000; + 3'b110 : out = 8'b0100_0000; + 3'b111 : out = 8'b1000_0000; + endcase +end + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_escape_id.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_escape_id.v new file mode 100644 index 0000000000000000000000000000000000000000..54eab1141854c4237dec6bd70e824cfce3870244 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_escape_id.v @@ -0,0 +1,14 @@ +// There must be white space after the +// string which uses escape character +module \1dff ( +q, // Q output +\q~ , // Q_out output +d, // D input +cl$k, // CLOCK input +\reset* // Reset input +); + +input d, cl$k, \reset* ; +output q, \q~ ; + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_explicit.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_explicit.v new file mode 100644 index 0000000000000000000000000000000000000000..267db56edff9700489b481fc93b51da702e9887c --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_explicit.v @@ -0,0 +1,35 @@ +module explicit(); +reg clk,d,rst,pre; +wire q; + +// Here q_bar is not connected +// We can connect ports in any order +dff u0 ( +.q (q), +.d (d), +.clk (clk), +.q_bar (), +.rst (rst), +.pre (pre) +); + +endmodule + +// D fli-flop +module dff (q, q_bar, clk, d, rst, pre); +input clk, d, rst, pre; +output q, q_bar; +reg q; + +assign q_bar = ~q; + +always @ (posedge clk) +if (rst == 1'b1) begin + q <= 0; +end else if (pre == 1'b1) begin + q <= 1; +end else begin + q <= d; +end + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_first_counter.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_first_counter.v new file mode 100644 index 0000000000000000000000000000000000000000..c257bae64b36a234cbea7784824f861979c7ecc7 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_first_counter.v @@ -0,0 +1,47 @@ +//----------------------------------------------------- +// This is my second Verilog Design +// Design Name : first_counter +// File Name : first_counter.v +// Function : This is a 4 bit up-counter with +// Synchronous active high reset and +// with active high enable signal +//----------------------------------------------------- +module first_counter ( +clock , // Clock input of the design +reset , // active high, synchronous Reset input +enable , // Active high enable signal for counter +counter_out // 4 bit vector output of the counter +); // End of port list +//-------------Input Ports----------------------------- +input clock ; +input reset ; +input enable ; +//-------------Output Ports---------------------------- +output [3:0] counter_out ; +//-------------Input ports Data Type------------------- +// By rule all the input ports should be wires +wire clock ; +wire reset ; +wire enable ; +//-------------Output Ports Data Type------------------ +// Output port can be a storage element (reg) or a wire +reg [3:0] counter_out ; + +//------------Code Starts Here------------------------- +// Since this counter is a positive edge trigged one, +// We trigger the below block with respect to positive +// edge of the clock. +always @ (posedge clock) +begin : COUNTER // Block Name + // At every rising edge of clock we check if reset is active + // If active, we load the counter output with 4'b0000 + if (reset == 1'b1) begin + counter_out <= 4'b0000; + end + // If enable is active, then we increment the counter + else if (enable == 1'b1) begin + counter_out <= counter_out + 1; + end +end // End of Block COUNTER + +endmodule // End of Module counter diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_first_counter_tb.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_first_counter_tb.v new file mode 100644 index 0000000000000000000000000000000000000000..bdca371e5efce0f8193c6812d926602d2f0c20b2 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_first_counter_tb.v @@ -0,0 +1,37 @@ +module testbench(); +// Declare inputs as regs and outputs as wires +reg clock = 1, reset = 0, enable = 0; +wire [3:0] counter_out; +integer file; + +// Initialize all variables +initial begin + file = $fopen(`outfile); + $fdisplay (file, "time\t clk reset enable counter"); + #5 reset = 1; // Assert the reset + #10 reset = 0; // De-assert the reset + #10 enable = 1; // Assert enable + #100 enable = 0; // De-assert enable + #5 $finish; // Terminate simulation +end + +always @(negedge clock) + $fdisplay (file, "%g\t %b %b %b %b", + $time, clock, reset, enable, counter_out); + +// Clock generator +initial begin + #1; + forever + #5 clock = ~clock; // Toggle clock every 5 ticks +end + +// Connect DUT to test bench +first_counter U_counter ( +clock, +reset, +enable, +counter_out +); + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_flip_flop.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_flip_flop.v new file mode 100644 index 0000000000000000000000000000000000000000..aeb784423cb443fd2ec919601de4382d2752e302 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_flip_flop.v @@ -0,0 +1,15 @@ +module flif_flop (clk,reset, q, d); +input clk, reset, d; +output q; +reg q; + +always @ (posedge clk ) +begin + if (reset == 1) begin + q <= 0; + end else begin + q <= d; + end +end + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_fsm_full.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_fsm_full.v new file mode 100644 index 0000000000000000000000000000000000000000..0be754c974e47cd92f1cb78484541fc88ff22939 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_fsm_full.v @@ -0,0 +1,114 @@ +module fsm_full( +clock , // Clock +reset , // Active high reset +req_0 , // Active high request from agent 0 +req_1 , // Active high request from agent 1 +req_2 , // Active high request from agent 2 +req_3 , // Active high request from agent 3 +gnt_0 , // Active high grant to agent 0 +gnt_1 , // Active high grant to agent 1 +gnt_2 , // Active high grant to agent 2 +gnt_3 // Active high grant to agent 3 +); +// Port declaration here +input clock ; // Clock +input reset ; // Active high reset +input req_0 ; // Active high request from agent 0 +input req_1 ; // Active high request from agent 1 +input req_2 ; // Active high request from agent 2 +input req_3 ; // Active high request from agent 3 +output gnt_0 ; // Active high grant to agent 0 +output gnt_1 ; // Active high grant to agent 1 +output gnt_2 ; // Active high grant to agent 2 +output gnt_3 ; // Active high grant to agent + +// Internal Variables +reg gnt_0 ; // Active high grant to agent 0 +reg gnt_1 ; // Active high grant to agent 1 +reg gnt_2 ; // Active high grant to agent 2 +reg gnt_3 ; // Active high grant to agent + +parameter [2:0] IDLE = 3'b000; +parameter [2:0] GNT0 = 3'b001; +parameter [2:0] GNT1 = 3'b010; +parameter [2:0] GNT2 = 3'b011; +parameter [2:0] GNT3 = 3'b100; + +reg [2:0] state, next_state; + +always @ (state or req_0 or req_1 or req_2 or req_3) +begin + next_state = 0; + case(state) + IDLE : if (req_0 == 1'b1) begin + next_state = GNT0; + end else if (req_1 == 1'b1) begin + next_state= GNT1; + end else if (req_2 == 1'b1) begin + next_state= GNT2; + end else if (req_3 == 1'b1) begin + next_state= GNT3; + end else begin + next_state = IDLE; + end + GNT0 : if (req_0 == 1'b0) begin + next_state = IDLE; + end else begin + next_state = GNT0; + end + GNT1 : if (req_1 == 1'b0) begin + next_state = IDLE; + end else begin + next_state = GNT1; + end + GNT2 : if (req_2 == 1'b0) begin + next_state = IDLE; + end else begin + next_state = GNT2; + end + GNT3 : if (req_3 == 1'b0) begin + next_state = IDLE; + end else begin + next_state = GNT3; + end + default : next_state = IDLE; + endcase +end + +always @ (posedge clock) +begin : OUTPUT_LOGIC + if (reset) begin + gnt_0 <= 1'b0; + gnt_1 <= 1'b0; + gnt_2 <= 1'b0; + gnt_3 <= 1'b0; + state <= IDLE; + end else begin + state <= next_state; + case(state) + IDLE : begin + gnt_0 <= 1'b0; + gnt_1 <= 1'b0; + gnt_2 <= 1'b0; + gnt_3 <= 1'b0; + end + GNT0 : begin + gnt_0 <= 1'b1; + end + GNT1 : begin + gnt_1 <= 1'b1; + end + GNT2 : begin + gnt_2 <= 1'b1; + end + GNT3 : begin + gnt_3 <= 1'b1; + end + default : begin + state <= IDLE; + end + endcase + end +end + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_fsm_full_tb.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_fsm_full_tb.v new file mode 100644 index 0000000000000000000000000000000000000000..7c0e2d570ed79e83f0c8dd678ad708dfeda55953 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_fsm_full_tb.v @@ -0,0 +1,54 @@ +module testbench(); +reg clock = 0 , reset ; +reg req_0 , req_1 , req_2 , req_3; +wire gnt_0 , gnt_1 , gnt_2 , gnt_3 ; +integer file; + +initial begin + // $dumpfile("testbench.vcd"); + // $dumpvars(0, testbench); + file = $fopen(`outfile); + $fdisplay(file, "Time\t R0 R1 R2 R3 G0 G1 G2 G3"); + clock = 0; + reset = 1; + req_0 = 0; + req_1 = 0; + req_2 = 0; + req_3 = 0; + #10 reset = 1; + #10 reset = 0; + #10 req_0 = 1; + #20 req_0 = 0; + #10 req_1 = 1; + #20 req_1 = 0; + #10 req_2 = 1; + #20 req_2 = 0; + #10 req_3 = 1; + #20 req_3 = 0; + #10 $finish; +end + +always @(negedge clock) + $fdisplay(file, "%g\t %b %b %b %b %b %b %b %b", + $time, req_0, req_1, req_2, req_3, gnt_0, gnt_1, gnt_2, gnt_3); + +initial begin + #1; + forever + #2 clock = ~clock; +end + +fsm_full U_fsm_full( +clock , // Clock +reset , // Active high reset +req_0 , // Active high request from agent 0 +req_1 , // Active high request from agent 1 +req_2 , // Active high request from agent 2 +req_3 , // Active high request from agent 3 +gnt_0 , // Active high grant to agent 0 +gnt_1 , // Active high grant to agent 1 +gnt_2 , // Active high grant to agent 2 +gnt_3 // Active high grant to agent 3 +); + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_good_code.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_good_code.v new file mode 100644 index 0000000000000000000000000000000000000000..6ba776446a295dbf79046b542509f712718e0ca6 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_good_code.v @@ -0,0 +1,18 @@ + module addbit ( + a, + b, + ci, + sum, + co); + input a; + input b; + input ci; + output sum; + output co; + wire a; + wire b; + wire ci; + wire sum; + wire co; + + endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_if_else.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_if_else.v new file mode 100644 index 0000000000000000000000000000000000000000..19b91d3f2a2547879f4c5424ed3269702f95ffcf --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_if_else.v @@ -0,0 +1,13 @@ +module if_else(); + +reg dff; +wire clk,din,reset; + +always @ (posedge clk) +if (reset) begin + dff <= 0; +end else begin + dff <= din; +end + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_multiply.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_multiply.v new file mode 100644 index 0000000000000000000000000000000000000000..bcab608cbb6ad1746cfda5eecf500c1b2f189b7b --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_multiply.v @@ -0,0 +1,8 @@ +module muliply (a,product); + input [3:0] a; + output [4:0] product; + wire [4:0] product; + + assign product = a << 1; + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_mux_21.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_mux_21.v new file mode 100644 index 0000000000000000000000000000000000000000..70f57205bfd713250d5219288970eae83c70ffec --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_mux_21.v @@ -0,0 +1,9 @@ +module mux_21 (a,b,sel,y); + input a, b; + output y; + input sel; + wire y; + + assign y = (sel) ? b : a; + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_n_out_primitive.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_n_out_primitive.v new file mode 100644 index 0000000000000000000000000000000000000000..b857384174b4f0d41daf058889d3200eea67db83 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_n_out_primitive.v @@ -0,0 +1,13 @@ +module n_out_primitive(); + +wire out,out_0,out_1,out_2,out_3,out_a,out_b,out_c; +wire in; + +// one output Buffer gate +buf u_buf0 (out,in); +// four output Buffer gate +buf u_buf1 (out_0, out_1, out_2, out_3, in); +// three output Invertor gate +not u_not0 (out_a, out_b, out_c, in); + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_parallel_if.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_parallel_if.v new file mode 100644 index 0000000000000000000000000000000000000000..1cf8658b0b856b38c0dc478c3ec98632a7a3b613 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_parallel_if.v @@ -0,0 +1,21 @@ +module parallel_if(); + +reg [3:0] counter; +wire clk,reset,enable, up_en, down_en; + +always @ (posedge clk) +// If reset is asserted +if (reset == 1'b0) begin + counter <= 4'b0000; +end else begin + // If counter is enable and up count is mode + if (enable == 1'b1 && up_en == 1'b1) begin + counter <= counter + 1'b1; + end + // If counter is enable and down count is mode + if (enable == 1'b1 && down_en == 1'b1) begin + counter <= counter - 1'b1; + end +end + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_parity.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_parity.v new file mode 100644 index 0000000000000000000000000000000000000000..27941f309d1b300f4954314f4cc5f02726594c6c --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_parity.v @@ -0,0 +1,41 @@ +//----------------------------------------------------- +// This is simple parity Program +// Design Name : parity +// File Name : parity.v +// Function : This program shows how a verilog +// primitive/module port connection are done +// Coder : Deepak +//----------------------------------------------------- +module parity ( +a , // First input +b , // Second input +c , // Third Input +d , // Fourth Input +y // Parity output +); + +// Input Declaration +input a ; +input b ; +input c ; +input d ; +// Ouput Declaration +output y ; +// port data types +wire a ; +wire b ; +wire c ; +wire d ; +wire y ; +// Internal variables +wire out_0 ; +wire out_1 ; + +// Code starts Here +xor u0 (out_0,a,b); + +xor u1 (out_1,c,d); + +xor u2 (y,out_0,out_1); + +endmodule // End Of Module parity diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_simple_function.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_simple_function.v new file mode 100644 index 0000000000000000000000000000000000000000..5818a1d4a1a9bc0f95249c66e8abe5d8c9fd95e3 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_simple_function.v @@ -0,0 +1,10 @@ +module simple_function(); + +function myfunction; +input a, b, c, d; +begin + myfunction = ((a+b) + (c-d)); +end +endfunction + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_simple_if.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_simple_if.v new file mode 100644 index 0000000000000000000000000000000000000000..67fa8bcb113009d568489e20070c52d667b1ed91 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_simple_if.v @@ -0,0 +1,11 @@ +module simple_if(); + +reg latch; +wire enable,din; + +always @ (enable or din) +if (enable) begin + latch <= din; +end + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_task_global.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_task_global.v new file mode 100644 index 0000000000000000000000000000000000000000..3ae8627973fd0b44d04091c6b039f99b1652f266 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_task_global.v @@ -0,0 +1,12 @@ +module task_global(); + +reg [7:0] temp_out; +reg [7:0] temp_in; + +task convert; +begin + temp_out = (9/5) *( temp_in + 32); +end +endtask + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_tri_buf.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_tri_buf.v new file mode 100644 index 0000000000000000000000000000000000000000..3df0d7009ae3df86e47764d2363eee95620b2d63 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_tri_buf.v @@ -0,0 +1,9 @@ +module tri_buf (a,b,enable); + input a; + output b; + input enable; + wire b; + +assign b = (enable) ? a : 1'bz; + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_v2k_reg.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_v2k_reg.v new file mode 100644 index 0000000000000000000000000000000000000000..537a9e8542b2ec6b8d63ed327ca23560a6ecb343 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_v2k_reg.v @@ -0,0 +1,24 @@ +module v2k_reg(); + +// v2k allows to init variables +reg a = 0; +// Here only last variable is set to 0, i.e d = 0 +// Rest b, c are set to x +reg b, c, d = 0; +// reg data type can be signed in v2k +// We can assign with signed constants +reg signed [7:0] data = 8'shF0; + +// Function can return signed values +// Its ports can contain signed ports +function signed [7:0] adder; + input a_in; + input b_in; + input c_in; + input signed [7:0] data_in; + begin + adder = a_in + b_in + c_in + data_in; + end +endfunction + +endmodule diff --git a/chips/yosys/tests/asicworld/code_verilog_tutorial_which_clock.v b/chips/yosys/tests/asicworld/code_verilog_tutorial_which_clock.v new file mode 100644 index 0000000000000000000000000000000000000000..934015ac02e3f8f268e6fd9b4509359415972524 --- /dev/null +++ b/chips/yosys/tests/asicworld/code_verilog_tutorial_which_clock.v @@ -0,0 +1,12 @@ +module which_clock (x,y,q,d); +input x,y,d; +output q; +reg q; + +always @ (posedge x or posedge y) + if (x) + q <= 1'b0; + else + q <= d; + +endmodule diff --git a/chips/yosys/tests/asicworld/generate_mk.py b/chips/yosys/tests/asicworld/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..2f1df064605630b4c9d342dcded11f7069c61e57 --- /dev/null +++ b/chips/yosys/tests/asicworld/generate_mk.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile + +gen_tests_makefile.generate_autotest("*.v", "-e") diff --git a/chips/yosys/tests/asicworld/xfirrtl b/chips/yosys/tests/asicworld/xfirrtl new file mode 100644 index 0000000000000000000000000000000000000000..08bf4ccd856ab0730474a20883c8a004184d95af --- /dev/null +++ b/chips/yosys/tests/asicworld/xfirrtl @@ -0,0 +1,23 @@ +# This file contains the names of verilog files to exclude from verilog to FIRRTL regression tests due to known failures. +code_hdl_models_arbiter.v error: reg rst; cannot be driven by primitives or continuous assignment. +code_hdl_models_clk_div_45.v yosys issue: 2nd PMUXTREE pass yields: ERROR: Negative edge clock on FF clk_div_45.$procdff$49. +code_hdl_models_d_ff_gates.v combinational loop +code_hdl_models_d_latch_gates.v combinational loop +code_hdl_models_dff_async_reset.v $adff +code_hdl_models_tff_async_reset.v $adff +code_hdl_models_uart.v $adff +code_tidbits_asyn_reset.v $adff +code_tidbits_reg_seq_example.v $adff +code_verilog_tutorial_always_example.v empty module +code_verilog_tutorial_escape_id.v make_id issues (name begins with a digit) +code_verilog_tutorial_explicit.v firrtl backend bug (empty module) +code_verilog_tutorial_first_counter.v error: reg rst; cannot be driven by primitives or continuous assignment. +code_verilog_tutorial_fsm_full.v error: reg reset; cannot be driven by primitives or continuous assignment. +code_verilog_tutorial_if_else.v empty module (everything is under 'always @ (posedge clk)') +[code_verilog_tutorial_n_out_primitive.v empty module +code_verilog_tutorial_parallel_if.v empty module (everything is under 'always @ (posedge clk)') +code_verilog_tutorial_simple_function.v empty module (no hardware) +code_verilog_tutorial_simple_if.v empty module (everything is under 'always @ (posedge clk)') +code_verilog_tutorial_task_global.v empty module (everything is under 'always @ (posedge clk)') +code_verilog_tutorial_v2k_reg.v empty module +code_verilog_tutorial_which_clock.v $adff diff --git a/chips/yosys/tests/blif/.gitignore b/chips/yosys/tests/blif/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..e87afd97c3b381b83d7829594d887e153a4534e7 --- /dev/null +++ b/chips/yosys/tests/blif/.gitignore @@ -0,0 +1 @@ +/*.out diff --git a/chips/yosys/tests/blif/bug2729.ys b/chips/yosys/tests/blif/bug2729.ys new file mode 100644 index 0000000000000000000000000000000000000000..0cbc21aa08e969850594fdca34402041f6dc1b89 --- /dev/null +++ b/chips/yosys/tests/blif/bug2729.ys @@ -0,0 +1,20 @@ +read_verilog < gatesi.blif.out.tmp && mv gatesi.blif.out.tmp gatesi.blif.out +! diff gatesi.blif.out gatesi.blif.ok diff --git a/chips/yosys/tests/blif/generate_mk.py b/chips/yosys/tests/blif/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..6a921d5a026cbd59f805c297d1c28db16de0c1e9 --- /dev/null +++ b/chips/yosys/tests/blif/generate_mk.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile + +gen_tests_makefile.generate(["--yosys-scripts"]) diff --git a/chips/yosys/tests/bram/.gitignore b/chips/yosys/tests/bram/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..9c595a6fb7692405a5c4a10e1caf93d7a5bd9c37 --- /dev/null +++ b/chips/yosys/tests/bram/.gitignore @@ -0,0 +1 @@ +temp diff --git a/chips/yosys/tests/bram/generate_mk.py b/chips/yosys/tests/bram/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..5a76b9a290647e949cd5325874534c84ece347e3 --- /dev/null +++ b/chips/yosys/tests/bram/generate_mk.py @@ -0,0 +1,326 @@ +#!/usr/bin/env python3 + +import argparse +import os +import sys +import random +import glob + +sys.path.append("..") +import gen_tests_makefile + +debug_mode = False + +def create_bram(dsc_f, sim_f, ref_f, tb_f, k1, k2, or_next): + while True: + init = 0 # random.randrange(2) + abits = random.randrange(1, 8) + dbits = random.randrange(1, 8) + groups = random.randrange(2, 5) + + if random.randrange(2): + abits = 2 ** random.randrange(1, 4) + if random.randrange(2): + dbits = 2 ** random.randrange(1, 4) + + while True: + wrmode = [ random.randrange(0, 2) for i in range(groups) ] + if wrmode.count(1) == 0: continue + if wrmode.count(0) == 0: continue + break + + if random.randrange(2): + maxpol = 4 + maxtransp = 1 + maxclocks = 4 + else: + maxpol = None + clkpol = random.randrange(4) + maxtransp = 2 + maxclocks = 1 + + def generate_enable(i): + if wrmode[i]: + v = 2 ** random.randrange(0, 4) + while dbits < v or dbits % v != 0: + v //= 2 + return v + return 0 + + def generate_transp(i): + if wrmode[i] == 0: + return random.randrange(maxtransp) + return 0 + + def generate_clkpol(i): + if maxpol is None: + return clkpol + return random.randrange(maxpol) + + ports = [ random.randrange(1, 3) for i in range(groups) ] + enable = [ generate_enable(i) for i in range(groups) ] + transp = [ generate_transp(i) for i in range(groups) ] + clocks = [ random.randrange(maxclocks)+1 for i in range(groups) ] + clkpol = [ generate_clkpol(i) for i in range(groups) ] + break + + print("bram bram_%02d_%02d" % (k1, k2), file=dsc_f) + print(" init %d" % init, file=dsc_f) + print(" abits %d" % abits, file=dsc_f) + print(" dbits %d" % dbits, file=dsc_f) + print(" groups %d" % groups, file=dsc_f) + print(" ports %s" % " ".join(["%d" % i for i in ports]), file=dsc_f) + print(" wrmode %s" % " ".join(["%d" % i for i in wrmode]), file=dsc_f) + print(" enable %s" % " ".join(["%d" % i for i in enable]), file=dsc_f) + print(" transp %s" % " ".join(["%d" % i for i in transp]), file=dsc_f) + print(" clocks %s" % " ".join(["%d" % i for i in clocks]), file=dsc_f) + print(" clkpol %s" % " ".join(["%d" % i for i in clkpol]), file=dsc_f) + print("endbram", file=dsc_f) + print("match bram_%02d_%02d" % (k1, k2), file=dsc_f) + if random.randrange(2): + non_zero_enables = [chr(ord('A') + i) for i in range(len(enable)) if enable[i]] + if len(non_zero_enables): + print(" shuffle_enable %c" % random.choice(non_zero_enables), file=dsc_f) + if or_next: + print(" or_next_if_better", file=dsc_f) + print("endmatch", file=dsc_f) + + states = set() + v_ports = set() + v_stmts = list() + v_always = dict() + + tb_decls = list() + tb_clocks = list() + tb_addr = list() + tb_din = list() + tb_dout = list() + tb_addrlist = list() + + addrmask = (1 << abits) - 1 + + for i in range(10): + tb_addrlist.append(random.randrange(1048576) & addrmask) + + t = random.randrange(1048576) + for i in range(10): + tb_addrlist.append((t ^ (1 << i)) & addrmask) + + v_stmts.append("(* nomem2reg *) reg [%d:0] memory [0:%d];" % (dbits-1, 2**abits-1)) + + portindex = 0 + last_always_hdr = (-1, "") + + addr2en = {} + + for p1 in range(groups): + for p2 in range(ports[p1]): + pf = "%c%d" % (chr(ord("A") + p1), p2 + 1) + portindex += 1 + + v_stmts.append("`ifndef SYNTHESIS") + v_stmts.append(" event UPDATE_%s;" % pf) + v_stmts.append("`endif") + + if clocks[p1] and not ("CLK%d" % clocks[p1]) in v_ports: + v_ports.add("CLK%d" % clocks[p1]) + v_stmts.append("input CLK%d;" % clocks[p1]) + tb_decls.append("reg CLK%d = 0;" % clocks[p1]) + tb_clocks.append("CLK%d" % clocks[p1]) + + v_ports.add("%sADDR" % pf) + v_stmts.append("input [%d:0] %sADDR;" % (abits-1, pf)) + if transp[p1]: + v_stmts.append("reg [%d:0] %sADDR_Q;" % (abits-1, pf)) + tb_decls.append("reg [%d:0] %sADDR;" % (abits-1, pf)) + tb_addr.append("%sADDR" % pf) + + v_ports.add("%sDATA" % pf) + v_stmts.append("%s [%d:0] %sDATA;" % ("input" if wrmode[p1] else "output reg", dbits-1, pf)) + + if wrmode[p1]: + tb_decls.append("reg [%d:0] %sDATA;" % (dbits-1, pf)) + tb_din.append("%sDATA" % pf) + else: + tb_decls.append("wire [%d:0] %sDATA;" % (dbits-1, pf)) + tb_decls.append("wire [%d:0] %sDATA_R;" % (dbits-1, pf)) + tb_dout.append("%sDATA" % pf) + + if wrmode[p1] and enable[p1]: + v_ports.add("%sEN" % pf) + v_stmts.append("input [%d:0] %sEN;" % (enable[p1]-1, pf)) + tb_decls.append("reg [%d:0] %sEN;" % (enable[p1]-1, pf)) + tb_din.append("%sEN" % pf) + addr2en["%sADDR" % pf] = "%sEN" % pf + + assign_op = "<=" + if clocks[p1] == 0: + always_hdr = "always @* begin" + assign_op = "=" + elif clkpol[p1] == 0: + always_hdr = "always @(negedge CLK%d) begin" % clocks[p1] + elif clkpol[p1] == 1: + always_hdr = "always @(posedge CLK%d) begin" % clocks[p1] + else: + if not ("CP", clkpol[p1]) in states: + v_stmts.append("parameter CLKPOL%d = 0;" % clkpol[p1]) + states.add(("CP", clkpol[p1])) + if not ("CPW", clocks[p1], clkpol[p1]) in states: + v_stmts.append("wire CLK%d_CLKPOL%d = CLK%d == CLKPOL%d;" % (clocks[p1], clkpol[p1], clocks[p1], clkpol[p1])) + states.add(("CPW", clocks[p1], clkpol[p1])) + always_hdr = "always @(posedge CLK%d_CLKPOL%d) begin" % (clocks[p1], clkpol[p1]) + + if last_always_hdr[1] != always_hdr: + last_always_hdr = (portindex, always_hdr) + v_always[last_always_hdr] = list() + + if wrmode[p1]: + for i in range(enable[p1]): + enrange = "[%d:%d]" % ((i+1)*dbits/enable[p1]-1, i*dbits/enable[p1]) + v_always[last_always_hdr].append((portindex, pf, "if (%sEN[%d]) memory[%sADDR]%s = %sDATA%s;" % (pf, i, pf, enrange, pf, enrange))) + elif transp[p1]: + v_always[last_always_hdr].append((sum(ports)+1, pf, "%sADDR_Q %s %sADDR;" % (pf, assign_op, pf))) + v_stmts.append("always @* %sDATA = memory[%sADDR_Q];" % (pf, pf)) + else: + v_always[last_always_hdr].append((0, pf, "%sDATA %s memory[%sADDR];" % (pf, assign_op, pf))) + + for always_hdr in sorted(v_always): + v_stmts.append(always_hdr[1]) + triggered_events = set() + time_cursor = 0 + v_always[always_hdr].sort() + for t, p, s in v_always[always_hdr]: + if time_cursor != t or not p in triggered_events: + v_stmts.append(" `ifndef SYNTHESIS") + stmt = "" + if time_cursor != t: + stmt += " #%d;" % (t-time_cursor) + time_cursor = t + if not p in triggered_events: + stmt += (" -> UPDATE_%s;" % p) + triggered_events.add(p) + v_stmts.append(" %s" % stmt) + v_stmts.append(" `endif") + v_stmts.append(" %s" % s) + v_stmts.append("end") + + print("module bram_%02d_%02d(%s);" % (k1, k2, ", ".join(sorted(v_ports))), file=sim_f) + for stmt in v_stmts: + print(" %s" % stmt, file=sim_f) + print("endmodule", file=sim_f) + + print("module bram_%02d_%02d_ref(%s);" % (k1, k2, ", ".join(sorted(v_ports))), file=ref_f) + for stmt in v_stmts: + print(" %s" % stmt, file=ref_f) + print("endmodule", file=ref_f) + + print("module bram_%02d_%02d_tb;" % (k1, k2), file=tb_f) + for stmt in tb_decls: + print(" %s" % stmt, file=tb_f) + print(" bram_%02d_%02d uut (" % (k1, k2), file=tb_f) + print(" " + ",\n ".join([".%s(%s)" % (p, p) for p in (tb_clocks + tb_addr + tb_din + tb_dout)]), file=tb_f) + print(" );", file=tb_f) + print(" bram_%02d_%02d_ref ref (" % (k1, k2), file=tb_f) + print(" " + ",\n ".join([".%s(%s)" % (p, p) for p in (tb_clocks + tb_addr + tb_din)]) + ",", file=tb_f) + print(" " + ",\n ".join([".%s(%s_R)" % (p, p) for p in tb_dout]), file=tb_f) + print(" );", file=tb_f) + + expr_dout = "{%s}" % ", ".join(tb_dout) + expr_dout_ref = "{%s}" % ", ".join(i + "_R" for i in tb_dout) + + print(" wire error = %s !== %s;" % (expr_dout, expr_dout_ref), file=tb_f) + + print(" initial begin", file=tb_f) + + if debug_mode: + print(" $dumpfile(`vcd_file);", file=tb_f) + print(" $dumpvars(0, bram_%02d_%02d_tb);" % (k1, k2), file=tb_f) + print(" #%d;" % (1000 + k2), file=tb_f) + + for p in (tb_clocks + tb_addr + tb_din): + if p[-2:] == "EN": + print(" %s <= ~0;" % p, file=tb_f) + else: + print(" %s <= 0;" % p, file=tb_f) + print(" #1000;", file=tb_f) + + for v in [1, 0, 1, 0]: + for p in tb_clocks: + print(" %s = %d;" % (p, v), file=tb_f) + print(" #1000;", file=tb_f) + + for i in range(20 if debug_mode else 100): + if len(tb_clocks): + c = random.choice(tb_clocks) + print(" %s = !%s;" % (c, c), file=tb_f) + print(" #100;", file=tb_f) + print(" $display(\"bram_%02d_%02d %3d: %%b %%b %%s\", %s, %s, error ? \"ERROR\" : \"OK\");" % + (k1, k2, i, expr_dout, expr_dout_ref), file=tb_f) + a2e = {} + for p in tb_addr: + addr = random.choice(tb_addrlist) + if p in addr2en: + if addr not in a2e: + a2e[addr] = [] + a2e[addr].append(addr2en[p]) + print(" %s <= %d;" % (p, addr), file=tb_f) + enzero = set() + for v in a2e.values(): + x = random.choice(v) + for s in v: + if s != x: + enzero.add(s) + for p in tb_din: + val = 0 if p in enzero else random.randrange(1048576) + print(" %s <= %d;" % (p, val), file=tb_f) + print(" #900;", file=tb_f) + + print(" end", file=tb_f) + print("endmodule", file=tb_f) + +parser = argparse.ArgumentParser(formatter_class = argparse.ArgumentDefaultsHelpFormatter) +parser.add_argument('-S', '--seed', type = int, help = 'seed for PRNG') +parser.add_argument('-c', '--count', type = int, default = 5, help = 'number of test cases to generate') +parser.add_argument('-d', '--debug', action='store_true') +args = parser.parse_args() + +debug_mode = args.debug + +if args.seed is not None: + seed = args.seed +else: + seed = (int(os.times()[4]*100) + os.getpid()) % 900000 + 100000 + +print("bram PRNG seed: %d" % seed) +random.seed(seed) + +os.makedirs("temp", exist_ok=True) + +for k1 in range(args.count): + dsc_f = open("temp/brams_%02d.txt" % k1, "w") + sim_f = open("temp/brams_%02d.v" % k1, "w") + ref_f = open("temp/brams_%02d_ref.v" % k1, "w") + tb_f = open("temp/brams_%02d_tb.v" % k1, "w") + + for f in [sim_f, ref_f, tb_f]: + print("`timescale 1 ns / 1 ns", file=f) + + lenk2 = 1 if debug_mode else 10 + for k2 in range(lenk2): + create_bram(dsc_f, sim_f, ref_f, tb_f, k1, k2, random.randrange(2 if k2+1 < lenk2 else 1)) + +configs = sorted(set( + os.path.basename(f).replace("brams_", "").replace(".txt", "") + for f in glob.glob("temp/brams_*.txt") +)) + +def create_tests(): + for i in configs: + for j in configs: + if i != j: + gen_tests_makefile.generate_cmd_test( + f"bram_{i}_{j}", + f"bash run-single.sh {i} {j}" + ) + +gen_tests_makefile.generate_custom(create_tests) diff --git a/chips/yosys/tests/bram/run-single.sh b/chips/yosys/tests/bram/run-single.sh new file mode 100644 index 0000000000000000000000000000000000000000..f7ce6f644db539f301fecede24423cff2c6e3fc6 --- /dev/null +++ b/chips/yosys/tests/bram/run-single.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -e +${YOSYS} -qq -f verilog -p "proc; opt; memory -nomap -bram temp/brams_${2}.txt; opt -fast -full" \ + -l temp/synth_${1}_${2}.log -o temp/synth_${1}_${2}.v temp/brams_${1}.v +iverilog -Dvcd_file=\"temp/tb_${1}_${2}.vcd\" -DSIMLIB_MEMDELAY=1 -o temp/tb_${1}_${2}.tb temp/brams_${1}_tb.v \ + temp/brams_${1}_ref.v temp/synth_${1}_${2}.v temp/brams_${2}.v ../../techlibs/common/simlib.v +temp/tb_${1}_${2}.tb > temp/tb_${1}_${2}.txt +if grep -q ERROR temp/tb_${1}_${2}.txt; then + grep -HC2 ERROR temp/tb_${1}_${2}.txt | head + exit 1 +fi +exit 0 diff --git a/chips/yosys/tests/bugpoint/.gitignore b/chips/yosys/tests/bugpoint/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..1012c66cc9337aeb806613613ec27181b593ac8d --- /dev/null +++ b/chips/yosys/tests/bugpoint/.gitignore @@ -0,0 +1,5 @@ +bugpoint-case.* +*.log +*.err +*.temp +run-test.mk diff --git a/chips/yosys/tests/bugpoint/failures.ys b/chips/yosys/tests/bugpoint/failures.ys new file mode 100644 index 0000000000000000000000000000000000000000..1f7168e33ec5bbfdc166e2fe5fc498cd38d0ef16 --- /dev/null +++ b/chips/yosys/tests/bugpoint/failures.ys @@ -0,0 +1,29 @@ +write_file fail.temp << EOF +logger -expect error "Missing -script or -command option." 1 +bugpoint -suffix fail -yosys ${YOSYS} +EOF +exec -expect-return 0 -- ${YOSYS} -qq mods.il -s fail.temp + +write_file fail.temp << EOF +logger -expect error "do not crash on this design" 1 +bugpoint -suffix fail -yosys ${YOSYS} -command "dump" +EOF +exec -expect-return 0 -- ${YOSYS} -qq mods.il -s fail.temp + +write_file fail.temp << EOF +logger -expect error "returned value 3 instead of expected 7" 1 +bugpoint -suffix fail -yosys ${YOSYS} -command raise_error -expect-return 7 +EOF +exec -expect-return 0 -- ${YOSYS} -qq mods.il -s fail.temp + +write_file fail.temp << EOF +logger -expect error "not found in the log file!" 1 +bugpoint -suffix fail -yosys ${YOSYS} -command raise_error -grep "nope" +EOF +exec -expect-return 0 -- ${YOSYS} -qq mods.il -s fail.temp + +write_file fail.temp << EOF +logger -expect error "not found in stderr log!" 1 +bugpoint -suffix fail -yosys ${YOSYS} -command raise_error -err-grep "nope" +EOF +exec -expect-return 0 -- ${YOSYS} -qq mods.il -s fail.temp diff --git a/chips/yosys/tests/bugpoint/generate_mk.py b/chips/yosys/tests/bugpoint/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..6a921d5a026cbd59f805c297d1c28db16de0c1e9 --- /dev/null +++ b/chips/yosys/tests/bugpoint/generate_mk.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile + +gen_tests_makefile.generate(["--yosys-scripts"]) diff --git a/chips/yosys/tests/bugpoint/mod_constraints.ys b/chips/yosys/tests/bugpoint/mod_constraints.ys new file mode 100644 index 0000000000000000000000000000000000000000..23b4bf68c64491ecff9c40508a1c19743cfe97c6 --- /dev/null +++ b/chips/yosys/tests/bugpoint/mod_constraints.ys @@ -0,0 +1,83 @@ +read_rtlil mods.il +select -assert-count 7 w:* +select -assert-mod-count 3 =* +select -assert-count 4 c:* +design -stash base + +# everything is removed by default +design -load base +bugpoint -suffix mods -yosys ${YOSYS} -command raise_error -expect-return 3 +select -assert-count 1 w:* +select -assert-mod-count 1 =* +select -assert-none c:* + +# don't remove wires +design -load base +bugpoint -suffix mods -yosys ${YOSYS} -command raise_error -expect-return 3 -modules -cells +select -assert-count 3 w:* +select -assert-mod-count 1 =* +select -assert-none c:* + +# don't remove cells or their connections +design -load base +bugpoint -suffix mods -yosys ${YOSYS} -command raise_error -expect-return 3 -wires -modules +select -assert-count 5 w:* +select -assert-mod-count 1 =* +select -assert-count 4 c:* + +# don't remove cells but do remove their connections +design -load base +bugpoint -suffix mods -yosys ${YOSYS} -command raise_error -expect-return 3 -wires -modules -connections +select -assert-count 1 w:* +select -assert-mod-count 1 =* +select -assert-count 4 c:* + +# don't remove modules +design -load base +bugpoint -suffix mods -yosys ${YOSYS} -command raise_error -expect-return 3 -wires -cells +select -assert-count 1 w:* +select -assert-mod-count 3 =* +select -assert-none c:* + +# can keep wires +design -load base +setattr -set bugpoint_keep 1 w:w_b +bugpoint -suffix mods -yosys ${YOSYS} -command raise_error -expect-return 3 +select -assert-count 2 w:* +select -assert-mod-count 1 =* +select -assert-none c:* + +# a wire with keep won't keep the cell/module containing it +design -load base +setattr -set bugpoint_keep 1 w:w_o +bugpoint -suffix mods -yosys ${YOSYS} -command raise_error -expect-return 3 +select -assert-count 1 w:* +select -assert-mod-count 1 =* +select -assert-none c:* + +# can keep cells (and do it without the associated module) +design -load base +setattr -set bugpoint_keep 1 c:c_a +bugpoint -suffix mods -yosys ${YOSYS} -command raise_error -expect-return 3 +select -assert-count 1 w:* +select -assert-mod-count 1 =* +select -assert-count 1 c:* + +# can keep modules +design -load base +setattr -mod -set bugpoint_keep 1 m_a +bugpoint -suffix mods -yosys ${YOSYS} -command raise_error -expect-return 3 +select -assert-count 1 w:* +select -assert-mod-count 2 =* +select -assert-none c:* + +# minimize to just the path connecting w_a and w_c +# which happens via w_b, w_i, w_o, m_a, c_a and c_b +write_file script.temp << EOF +select -assert-none w:w_a %co* w:w_c %ci* %i +EOF +design -load base +bugpoint -suffix mods -yosys ${YOSYS} -script script.temp -grep "Assertion failed" +select -assert-count 5 w:* +select -assert-mod-count 2 =* +select -assert-count 2 c:* diff --git a/chips/yosys/tests/bugpoint/mods.il b/chips/yosys/tests/bugpoint/mods.il new file mode 100644 index 0000000000000000000000000000000000000000..fe3ce6522585c8f14cd8c60add5f724e0d1042da --- /dev/null +++ b/chips/yosys/tests/bugpoint/mods.il @@ -0,0 +1,38 @@ +module \m_a + wire input 1 \w_i + wire output 2 \w_o + connect \w_o \w_i +end + +module \m_b + wire input 1 \w_i + wire output 2 \w_o +end + +attribute \top 1 +module \top + attribute \raise_error 3 + wire \w_a + wire \w_b + wire \w_c + + cell \m_a \c_a + connect \w_i \w_a + connect \w_o \w_b + end + + cell \m_a \c_b + connect \w_i \w_b + connect \w_o \w_c + end + + cell \m_b \c_c + connect \w_i \w_c + connect \w_o \w_a + end + + cell \m_b \c_d + connect \w_i 1'0 + connect \w_o 1'1 + end +end diff --git a/chips/yosys/tests/bugpoint/proc_constraints.ys b/chips/yosys/tests/bugpoint/proc_constraints.ys new file mode 100644 index 0000000000000000000000000000000000000000..6c905b48c5915e0d64c219cf0db672a4e805e1d8 --- /dev/null +++ b/chips/yosys/tests/bugpoint/proc_constraints.ys @@ -0,0 +1,49 @@ +read_rtlil procs.il +select -assert-count 2 p:* +design -stash err_q + +# processes get removed by default +design -load err_q +bugpoint -suffix procs -yosys ${YOSYS} -command raise_error -expect-return 4 +select -assert-none p:* + +# individual processes can be kept +design -load err_q +setattr -set bugpoint_keep 1 p:proc_a +bugpoint -suffix procs -yosys ${YOSYS} -command raise_error -expect-return 4 +select -assert-count 1 p:* + +# all processes can be kept +design -load err_q +bugpoint -suffix procs -yosys ${YOSYS} -command raise_error -expect-return 4 -wires +select -assert-count 2 p:* + +# d and clock are connected after proc +design -load err_q +proc +select -assert-count 3 w:d %co +select -assert-count 3 w:clock %co + +# no assigns means no d +design -load err_q +bugpoint -suffix procs -yosys ${YOSYS} -command raise_error -expect-return 4 -assigns +proc +select -assert-count 1 w:d %co + +# no updates means no clock +design -load err_q +bugpoint -suffix procs -yosys ${YOSYS} -command raise_error -expect-return 4 -updates +proc +select -assert-count 1 w:clock %co + +# can remove ports +design -load err_q +select -assert-count 5 x:* +bugpoint -suffix procs -yosys ${YOSYS} -command raise_error -expect-return 4 -ports +select -assert-none x:* + +# can keep ports +design -load err_q +setattr -set bugpoint_keep 1 i:d o:q +bugpoint -suffix procs -yosys ${YOSYS} -command raise_error -expect-return 4 -ports +select -assert-count 2 x:* diff --git a/chips/yosys/tests/bugpoint/procs.il b/chips/yosys/tests/bugpoint/procs.il new file mode 100644 index 0000000000000000000000000000000000000000..e780dc7cde988133605350a877c7fc5815367e74 --- /dev/null +++ b/chips/yosys/tests/bugpoint/procs.il @@ -0,0 +1,42 @@ +module \ff_with_en_and_sync_reset + wire $0\q[1:1] + wire $0\q[0:0] + attribute \raise_error 4 + wire width 2 output 5 \q + wire width 2 input 4 \d + wire input 3 \enable + wire input 2 \reset + wire input 1 \clock + + process \proc_a + assign $0\q[0:0] \q [0] + switch \reset + case 1'1 + assign $0\q[0:0] 1'0 + case + switch \enable + case 1'1 + assign $0\q[0:0] \d [0] + case + end + end + sync posedge \clock + update \q [0] $0\q[0:0] + end + + process \proc_b + assign $0\q[1:1] \q [1] + switch \reset + case 1'1 + assign $0\q[1:1] 1'0 + case + switch \enable + case 1'1 + assign $0\q[1:1] \d [1] + case + end + end + sync posedge \clock + update \q [1] $0\q[1:1] + end +end diff --git a/chips/yosys/tests/bugpoint/raise_error.ys b/chips/yosys/tests/bugpoint/raise_error.ys new file mode 100644 index 0000000000000000000000000000000000000000..3985c7115ddfa1e794424ae32b2cd3c606e42408 --- /dev/null +++ b/chips/yosys/tests/bugpoint/raise_error.ys @@ -0,0 +1,63 @@ +read_verilog -noblackbox << EOF +(* raise_error=7 *) +module top(); +endmodule + +(* raise_error="help me" *) +module other(); +endmodule + +(* raise_error *) +module def(); +endmodule +EOF +select -assert-mod-count 3 =* +design -stash read + +# empty design does not raise_error +design -reset +logger -expect log "'raise_error' attribute not found" 1 +raise_error +logger -check-expected + +# raise_error with int exits with status +design -load read +setattr -mod -unset raise_error def other +dump +bugpoint -suffix error -yosys ${YOSYS} -command raise_error -expect-return 7 +select -assert-mod-count 1 =* +select -assert-mod-count 1 top + +# raise_error -always still uses 'raise_error' attribute if possible +design -load read +setattr -mod -unset raise_error def other +bugpoint -suffix error -yosys ${YOSYS} -command "raise_error -always" -expect-return 7 +select -assert-mod-count 1 =* +select -assert-mod-count 1 top + +# raise_error with string prints message and exits with 1 +design -load read +setattr -mod -unset raise_error top def +bugpoint -suffix error -yosys ${YOSYS} -command raise_error -grep "help me" -expect-return 1 +select -assert-mod-count 1 =* +select -assert-mod-count 1 other + +# raise_error with no value exits with 1 +design -load read +setattr -mod -unset raise_error top +delete other +bugpoint -suffix error -yosys ${YOSYS} -command raise_error -expect-return 1 +select -assert-mod-count 1 =* +select -assert-mod-count 1 def + +# raise_error -stderr prints to stderr and exits with 1 +design -load read +setattr -mod -unset raise_error top def +bugpoint -suffix error -yosys ${YOSYS} -command "raise_error -stderr" -err-grep "help me" -expect-return 1 +select -assert-mod-count 1 =* +select -assert-mod-count 1 other + +# empty design can raise_error -always +design -reset +bugpoint -suffix error -yosys ${YOSYS} -command "raise_error -always" -grep "ERROR: No 'raise_error' attribute found" -expect-return 1 +bugpoint -suffix error -yosys ${YOSYS} -command "raise_error -always -stderr" -err-grep "No 'raise_error' attribute found" -expect-return 1 diff --git a/chips/yosys/tests/check_mem/bad_il.ys b/chips/yosys/tests/check_mem/bad_il.ys new file mode 100644 index 0000000000000000000000000000000000000000..06968c32cb875d90d8e48de7f6e616d8b0613b0b --- /dev/null +++ b/chips/yosys/tests/check_mem/bad_il.ys @@ -0,0 +1,47 @@ +read_rtlil << EOF +module \top + wire input 1 \clk + wire output 1 \o + memory size 2 offset 1 \my_array + cell $meminit \bad_init + parameter \WORDS 1 + parameter \MEMID "\\my_array" + parameter \ABITS 32 + parameter \WIDTH 1 + parameter \PRIORITY 1 + connect \ADDR 0 + connect \DATA 1'0 + end + cell $memwr \bad_wr + parameter \MEMID "\\my_array" + parameter \CLK_ENABLE 1 + parameter \CLK_POLARITY 1 + parameter \PRIORITY 1 + parameter \ABITS 2 + parameter \WIDTH 1 + connect \EN 1'1 + connect \CLK \clk + connect \ADDR 2'00 + connect \DATA 1'0 + end + cell $memrd \bad_rd + parameter \MEMID "\\my_array" + parameter \CLK_ENABLE 0 + parameter \CLK_POLARITY 1 + parameter \TRANSPARENT 0 + parameter \ABITS 2 + parameter \WIDTH 1 + connect \CLK 1'x + connect \EN 1'x + connect \ADDR 2'11 + connect \DATA \o + end +end +EOF + +logger -expect warning "initializes address 0" 1 +logger -expect warning "writes address 0" 1 +logger -expect warning "reads address 3" 1 +check_mem +logger -check-expected +design -reset diff --git a/chips/yosys/tests/check_mem/generate_mk.py b/chips/yosys/tests/check_mem/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..ee8dbeb44f36ca79a900822f07ade22fd02afdf0 --- /dev/null +++ b/chips/yosys/tests/check_mem/generate_mk.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile + +gen_tests_makefile.generate(["--check-sv", "--yosys-scripts"], yosys_cmds="hierarchy; proc; check_mem -assert") diff --git a/chips/yosys/tests/check_mem/init.sv b/chips/yosys/tests/check_mem/init.sv new file mode 100644 index 0000000000000000000000000000000000000000..f55a0d1c51619a23215a77187885d14b8eea16f2 --- /dev/null +++ b/chips/yosys/tests/check_mem/init.sv @@ -0,0 +1,15 @@ +module top ( + input logic clk, + input logic idx, + output logic [2:0] out_data +); + (* nomem2reg *) + logic my_array [3:2][2:0] = '{'{0, 1, 1}, '{1, 0, 1}}; + + always_comb begin + for (int i=0; i < 3; i++) begin + out_data[i] = my_array[{1'b1, idx}][i]; + end + end + +endmodule diff --git a/chips/yosys/tests/check_mem/init_correct.ys b/chips/yosys/tests/check_mem/init_correct.ys new file mode 100644 index 0000000000000000000000000000000000000000..5e922c7dffbd7ab2a8892e3076579256d16d5d2d --- /dev/null +++ b/chips/yosys/tests/check_mem/init_correct.ys @@ -0,0 +1,44 @@ +read -sv << EOT +module top; + (* nomem2reg *) + logic a1 [2:3][3:1] = '{'{0, 1, 1}, '{1, 0, 1}}; + + always_comb begin + assert(a1[2][3] == 0); + assert(a1[2][2] == 1); + assert(a1[2][1] == 1); + assert(a1[3][3] == 1); + assert(a1[3][2] == 0); + assert(a1[3][1] == 1); + end + + (* nomem2reg *) + logic [1:0] a2 [6:5][2:4] = '{'{0, 1, 2}, '{1, 0, 3}}; + + always_comb begin + assert(a2[6][2] == 0); + assert(a2[6][3] == 1); + assert(a2[6][4] == 2); + assert(a2[5][2] == 1); + assert(a2[5][3] == 0); + assert(a2[5][4] == 3); + end + + (* nomem2reg *) + logic [1:0] a3 [-2:-1][-1:1] = '{'{0, 1, 2}, '{1, 0, 3}}; + + always_comb begin + assert(a3[-2][-1] == 0); + assert(a3[-2][0] == 1); + assert(a3[-2][1] == 2); + assert(a3[-1][-1] == 1); + assert(a3[-1][0] == 0); + assert(a3[-1][1] == 3); + end +endmodule +EOT +hierarchy +proc +memory +async2sync +sat -enable_undef -verify -prove-asserts diff --git a/chips/yosys/tests/check_mem/negative_idx.sv b/chips/yosys/tests/check_mem/negative_idx.sv new file mode 100644 index 0000000000000000000000000000000000000000..99a26cdae7caae84650e97f77a2ebd1310a7b497 --- /dev/null +++ b/chips/yosys/tests/check_mem/negative_idx.sv @@ -0,0 +1,13 @@ +module top; + (* nomem2reg *) + logic [1:0] a3 [-2:-1][-1:1] = '{'{0, 1, 2}, '{1, 0, 3}}; + + always_comb begin + assert(a3[-2][-1] == 0); + assert(a3[-2][0] == 1); + assert(a3[-2][1] == 2); + assert(a3[-1][-1] == 1); + assert(a3[-1][0] == 0); + assert(a3[-1][1] == 3); + end +endmodule diff --git a/chips/yosys/tests/check_mem/non_zero.sv b/chips/yosys/tests/check_mem/non_zero.sv new file mode 100644 index 0000000000000000000000000000000000000000..5b3f45c0a1c4159af8a806e9d0ac621ec6c2e828 --- /dev/null +++ b/chips/yosys/tests/check_mem/non_zero.sv @@ -0,0 +1,21 @@ +module top ( + input logic clk, + input logic [3:1][2:0] in_data, + output logic [3:1][2:0] out_data +); + (* nomem2reg *) + logic [2:0] my_array [3:1]; + + always_ff @(posedge clk) begin + for (int i = 1; i <= 3; i++) begin + my_array[i] <= in_data[i]; + end + end + + always_comb begin + for (int i = 1; i <= 3; i++) begin + out_data[i] = my_array[i]; + end + end + +endmodule diff --git a/chips/yosys/tests/check_mem/power_of_two.sv b/chips/yosys/tests/check_mem/power_of_two.sv new file mode 100644 index 0000000000000000000000000000000000000000..786168ea079f4ed15099890ecd8722289a920591 --- /dev/null +++ b/chips/yosys/tests/check_mem/power_of_two.sv @@ -0,0 +1,24 @@ +module top ( + input logic clk, + input logic [1:0][5:0] in_data, + output logic [1:0][5:0] out_data +); + (* nomem2reg *) + logic my_array [1:0][5:0]; + + always_ff @(posedge clk) begin + for (int i = 0; i < 2; i++) begin + for (int j = 0; j <= 5; j++) begin + my_array[i][j] <= in_data[i][j]; + end + end + end + + always_comb begin + for (int i = 0; i < 2; i++) begin + for (int j = 0; j <= 5; j++) begin + out_data[i][j] = my_array[i][j]; + end + end + end +endmodule diff --git a/chips/yosys/tests/check_mem/sub_addr.sv b/chips/yosys/tests/check_mem/sub_addr.sv new file mode 100644 index 0000000000000000000000000000000000000000..025bdc881b475a3f684d4f8d0dc1025cec898a26 --- /dev/null +++ b/chips/yosys/tests/check_mem/sub_addr.sv @@ -0,0 +1,18 @@ +module memtest05(clk, addr, wdata, rdata, wen); + +input clk; +input [1:0] addr; +input [7:0] wdata; +output reg [7:0] rdata; +input [3:0] wen; + +reg [7:0] mem [0:3]; + +integer i; +always @(posedge clk) begin + for (i = 0; i < 4; i = i+1) + if (wen[i]) mem[addr][i*2 +: 2] <= wdata[i*2 +: 2]; + rdata <= mem[addr]; +end + +endmodule diff --git a/chips/yosys/tests/check_mem/variable.ys b/chips/yosys/tests/check_mem/variable.ys new file mode 100644 index 0000000000000000000000000000000000000000..8da49758bc11ff6311e24d392262d808103770d5 --- /dev/null +++ b/chips/yosys/tests/check_mem/variable.ys @@ -0,0 +1,65 @@ + + +read_rtlil << EOF +module \top + wire input 1 \clk + wire input 2 width 2 \addr + wire output 1 \o + memory size 3 offset 0 \my_array + # potentially dangerous - requires external control to avoid illegal access + cell $memrd \bad_rd + parameter \MEMID "\\my_array" + parameter \CLK_ENABLE 0 + parameter \CLK_POLARITY 1 + parameter \TRANSPARENT 0 + parameter \ABITS 2 + parameter \WIDTH 1 + connect \CLK 1'x + connect \EN 1'x + connect \ADDR \addr + connect \DATA \o + end + wire width 2 \n_addr + cell $not \not_addr + parameter \A_SIGNED 0 + parameter \A_WIDTH 2 + parameter \Y_WIDTH 2 + connect \A \addr + connect \Y \n_addr + end + # address is partially const, making the illegal access of 2'11 impossible + cell $memrd \partial_const_rd + parameter \MEMID "\\my_array" + parameter \CLK_ENABLE 0 + parameter \CLK_POLARITY 1 + parameter \TRANSPARENT 0 + parameter \ABITS 2 + parameter \WIDTH 1 + connect \CLK 1'x + connect \EN 1'x + connect \ADDR { 1'0 \addr [0] } + connect \DATA \o + end + # address is non-const but limited to 2'10 and 2'01 - both of which are valid + cell $memrd \limited_rd + parameter \MEMID "\\my_array" + parameter \CLK_ENABLE 0 + parameter \CLK_POLARITY 1 + parameter \TRANSPARENT 0 + parameter \ABITS 2 + parameter \WIDTH 1 + connect \CLK 1'x + connect \EN 1'x + connect \ADDR { \n_addr [0] \addr [0] } + connect \DATA \o + end +end +EOF + +logger -expect warning "potentially dangerous non-const input \\addr" 1 +# unhandled false-positives +# logger -werror "potentially dangerous non-const input \{ 1'0" +# logger -werror "potentially dangerous non-const input \{ \\n_addr" +check_mem -non-const +logger -check-expected +design -reset diff --git a/chips/yosys/tests/common.mk b/chips/yosys/tests/common.mk new file mode 100644 index 0000000000000000000000000000000000000000..eb9dcf260e11003bc093db1df5404f54f407698d --- /dev/null +++ b/chips/yosys/tests/common.mk @@ -0,0 +1,80 @@ +ROOT_DIR := $(abspath $(dir $(lastword $(MAKEFILE_LIST)))) +BUILD_DIR ?= $(realpath $(ROOT_DIR)/../build) +BUILD_CMD := $(BUILD_DIR)/$(PROGRAM_PREFIX) +SRC_DIR := $(realpath $(ROOT_DIR)/..) + +SBY ?= sby +ABC ?= $(BUILD_CMD)yosys-abc +YOSYS ?= $(BUILD_CMD)yosys +YOSYS_CONFIG ?= $(BUILD_CMD)yosys-config +YOSYS_FILTERLIB ?= $(BUILD_CMD)yosys-filterlib +YOSYS_SMTBMC ?= $(BUILD_CMD)yosys-smtbmc +YOSYS_WITNESS ?= @$(BUILD_CMD)yosys-witness +YOSYS_MAX_THREADS ?= 4 +COVERAGE_DIR ?= $(realpath $(ROOT_DIR)/..)/coverage +COVERAGE_HTML ?= $(realpath $(ROOT_DIR)/..)/coverage_html +LLVM_PROFILE_FILE ?= $(COVERAGE_DIR)/coverage_%p.profraw +VERIFIC_DIR ?= /usr/local/src/verific_lib + +export BUILD_DIR +export SBY +export ABC +export YOSYS +export YOSYS_CONFIG +export YOSYS_FILTERLIB +export YOSYS_SMTBMC +export YOSYS_WITNESS +export YOSYS_MAX_THREADS +export LLVM_PROFILE_FILE +export LLVM_PROFILE_FILE_BUFFER_SIZE=0 + +ifeq ($(or $(V),$(VERBOSE)),1) + QUIET := +else + QUIET := >/dev/null 2>&1 +endif + +all: + +ifndef OVERRIDE_MAIN +clean: + @rm -f *.log *.result +endif + +define run_test + @set -e; \ + rc=0; \ + ( set -e; $(2) ) $(QUIET) || rc=$$?; \ + if [ $$rc -eq 0 ]; then \ + echo "PASS $1"; \ + echo PASS > $1.result; \ + else \ + echo "FAIL $1"; \ + echo FAIL > $1.result; \ + fi +endef + +.PHONY: summary +summary: + @pass=$$(find . -type f -name '*.result' -exec grep '^PASS$$' {} + | wc -l); \ + fail=$$(find . -type f -name '*.result' -exec grep '^FAIL$$' {} + | wc -l); \ + total=$$((pass + fail)); \ + echo "=========================="; \ + echo "Tests: $$total"; \ + echo "Passed: $$pass"; \ + echo "Failed: $$fail"; \ + echo "=========================="; \ + if [ $$fail -ne 0 ]; then \ + echo; \ + $(MAKE) --no-print-directory report; \ + fi; \ + test $$fail -eq 0 + +.PHONY: report +report: + @echo "==========================" + @echo "Failing tests:" + @find . -name '*.result' -type f -exec grep -H '^FAIL$$' {} + \ + | cut -d: -f1 \ + | sed 's|^\./||; s|\.result$$||' + @echo "==========================" diff --git a/chips/yosys/tests/cxxrtl/.gitignore b/chips/yosys/tests/cxxrtl/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..91caee98625885c484e703c2713520a0c4d82feb --- /dev/null +++ b/chips/yosys/tests/cxxrtl/.gitignore @@ -0,0 +1 @@ +cxxrtl-test-* diff --git a/chips/yosys/tests/cxxrtl/generate_mk.py b/chips/yosys/tests/cxxrtl/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..b75c78e97e562d9c35f7c5afd94027642c1e546c --- /dev/null +++ b/chips/yosys/tests/cxxrtl/generate_mk.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile + +def run_subtest(name): + gen_tests_makefile.generate_cmd_test(f"cxxrtl_{name}", [ + f"$${{CXX:-g++}} -std=c++11 -O2 -o cxxrtl-test-{name} -I../../backends/cxxrtl/runtime test_{name}.cc -lstdc++", + f"./cxxrtl-test-{name}", + ]) + +def compile_only(): + gen_tests_makefile.generate_cmd_test("cxxrtl_unconnected_output", [ + '$(YOSYS) -p "read_verilog test_unconnected_output.v; select =*; proc; clean; write_cxxrtl cxxrtl-test-unconnected_output.cc"', + f'$${{CXX:-g++}} -std=c++11 -c -o cxxrtl-test-unconnected_output -I../../backends/cxxrtl/runtime cxxrtl-test-unconnected_output.cc', + ]) + +def main(): + def callback(): + run_subtest("value") + run_subtest("value_fuzz") + compile_only() + + gen_tests_makefile.generate_custom(callback) + +if __name__ == "__main__": + main() diff --git a/chips/yosys/tests/cxxrtl/test_unconnected_output.v b/chips/yosys/tests/cxxrtl/test_unconnected_output.v new file mode 100644 index 0000000000000000000000000000000000000000..84d172bdbbf1cecd26d92463e7c7e862376f09b0 --- /dev/null +++ b/chips/yosys/tests/cxxrtl/test_unconnected_output.v @@ -0,0 +1,24 @@ +(* cxxrtl_blackbox *) +module blackbox(...); + (* cxxrtl_edge = "p" *) + input clk; + + (* cxxrtl_sync *) + output [7:0] out1; + + (* cxxrtl_sync *) + output [7:0] out2; +endmodule + +module unconnected_output( + input clk, + in, + output out +); + blackbox bb ( + .clock (clock), + .in (in), + .out1 (out), + .out2 (/* unconnected */), + ); +endmodule diff --git a/chips/yosys/tests/cxxrtl/test_value.cc b/chips/yosys/tests/cxxrtl/test_value.cc new file mode 100644 index 0000000000000000000000000000000000000000..b6fe3cf4a29c13fa44f4c1b057bae8b01bb61a59 --- /dev/null +++ b/chips/yosys/tests/cxxrtl/test_value.cc @@ -0,0 +1,60 @@ +#include +#include + +#include "cxxrtl/cxxrtl.h" + +int main() +{ + { + // shl exceeding Bits should be masked + cxxrtl::value<6> a(1u); + cxxrtl::value<6> b(8u); + cxxrtl::value<6> c = a.shl(b); + assert(c.get() == 0); + } + + { + // sshr of unreasonably large size should sign extend correctly + cxxrtl::value<64> a(0u, 0x80000000u); + cxxrtl::value<64> b(0u, 1u); + cxxrtl::value<64> c = a.sshr(b); + assert(c.get() == 0xffffffffffffffffu); + } + + { + // sshr of exteeding Bits should sign extend correctly + cxxrtl::value<8> a(0x80u); + cxxrtl::value<8> b(10u); + cxxrtl::value<8> c = a.sshr(b); + assert(c.get() == 0xffu); + } + + { + // Sign extension should occur correctly + cxxrtl::value<64> a(0x23456789u, 0x8abcdef1u); + cxxrtl::value<8> b(32u); + cxxrtl::value<64> c = a.sshr(b); + assert(c.get() == 0xffffffff8abcdef1u); + } + + { + // ctlz should work with Bits that are a multiple of chunk size + cxxrtl::value<32> a(0x00040000u); + assert(a.ctlz() == 13); + } + + { + // bmux clears top bits of result + cxxrtl::value<8> val(0x1fu); + cxxrtl::value<1> sel(0u); + assert(val.template bmux<4>(sel).get() == 0xfu); + } + + { + // stream operator smoke test + cxxrtl::value<8> val(0x1fu); + std::ostringstream oss; + oss << val; + assert(oss.str() == "8'1f"); + } +} diff --git a/chips/yosys/tests/cxxrtl/test_value_fuzz.cc b/chips/yosys/tests/cxxrtl/test_value_fuzz.cc new file mode 100644 index 0000000000000000000000000000000000000000..500f48a7a4c8fa7a0655f87c49bfe22a94048665 --- /dev/null +++ b/chips/yosys/tests/cxxrtl/test_value_fuzz.cc @@ -0,0 +1,360 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cxxrtl/cxxrtl.h" + +template +T rand_int(T min = std::numeric_limits::min(), T max = std::numeric_limits::max()) +{ + static_assert(std::is_integral::value, "T must be an integral type."); + static_assert(!std::is_same::value && !std::is_same::value, + "Using char with uniform_int_distribution is undefined behavior."); + + static std::mt19937 generator = [] { + std::random_device rd; + std::mt19937 mt{rd()}; + return mt; + }(); + + std::uniform_int_distribution dist(min, max); + return dist(generator); +} + +int64_t sext(size_t bits, uint64_t value) +{ + return (int64_t)(value << (64 - bits)) >> (64 - bits); +} + +struct BinaryOperationBase +{ + void tweak_input(uint64_t &a, uint64_t &b) {} +}; + +template +void test_binary_operation_for_bitsize(Operation &op) +{ + constexpr int iteration_count = 10000000; + + constexpr uint64_t mask = std::numeric_limits::max() >> (64 - Bits); + + using chunk_type = typename cxxrtl::value::chunk::type; + constexpr size_t chunk_bits = cxxrtl::value::chunk::bits; + + for (int iteration = 0; iteration < iteration_count; iteration++) { + uint64_t ia = rand_int() >> (64 - Bits); + uint64_t ib = rand_int() >> (64 - Bits); + op.tweak_input(ia, ib); + + cxxrtl::value va, vb; + for (size_t i = 0; i * chunk_bits < Bits; i++) { + va.data[i] = (chunk_type)(ia >> (i * chunk_bits)); + vb.data[i] = (chunk_type)(ib >> (i * chunk_bits)); + } + + uint64_t iresult = op.reference_impl(Bits, ia, ib) & mask; + cxxrtl::value vresult = op.template testing_impl(va, vb); + + for (size_t i = 0; i * chunk_bits < Bits; i++) { + if ((chunk_type)(iresult >> (i * chunk_bits)) != vresult.data[i]) { + std::printf("Test failure:\n"); + std::printf("Bits: %zu\n", Bits); + std::printf("a: %016" PRIx64 "\n", ia); + std::printf("b: %016" PRIx64 "\n", ib); + std::printf("iresult: %016" PRIx64 "\n", iresult); + std::printf("vresult: %016" PRIx64 "\n", vresult.template get()); + + std::terminate(); + } + } + } + std::printf("Test passed @ Bits = %zu.\n", Bits); +} + +template +void test_binary_operation(Operation &op) +{ + // Test at a variety of bitwidths + test_binary_operation_for_bitsize<8>(op); + test_binary_operation_for_bitsize<32>(op); + test_binary_operation_for_bitsize<42>(op); + test_binary_operation_for_bitsize<63>(op); + test_binary_operation_for_bitsize<64>(op); +} + +template +struct UnaryOperationWrapper : BinaryOperationBase +{ + Operation &op; + + UnaryOperationWrapper(Operation &op) : op(op) {} + + uint64_t reference_impl(size_t bits, uint64_t a, uint64_t b) + { + return op.reference_impl(bits, a); + } + + template + cxxrtl::value testing_impl(cxxrtl::value a, cxxrtl::value b) + { + return op.template testing_impl(a); + } +}; + +template +void test_unary_operation(Operation &op) +{ + UnaryOperationWrapper wrapped(op); + test_binary_operation(wrapped); +} + +struct ShlTest : BinaryOperationBase +{ + ShlTest() + { + std::printf("Randomized tests for value::shl:\n"); + test_binary_operation(*this); + } + + uint64_t reference_impl(size_t bits, uint64_t a, uint64_t b) + { + return b >= 64 ? 0 : a << b; + } + + template + cxxrtl::value testing_impl(cxxrtl::value a, cxxrtl::value b) + { + return a.shl(b); + } + + void tweak_input(uint64_t &, uint64_t &b) + { + b &= 0x7f; + } +} shl; + +struct ShrTest : BinaryOperationBase +{ + ShrTest() + { + std::printf("Randomized tests for value::shr:\n"); + test_binary_operation(*this); + } + + uint64_t reference_impl(size_t bits, uint64_t a, uint64_t b) + { + return b >= 64 ? 0 : a >> b; + } + + template + cxxrtl::value testing_impl(cxxrtl::value a, cxxrtl::value b) + { + return a.shr(b); + } + + void tweak_input(uint64_t &, uint64_t &b) + { + b &= 0x7f; + } +} shr; + +struct SshrTest : BinaryOperationBase +{ + SshrTest() + { + std::printf("Randomized tests for value::sshr:\n"); + test_binary_operation(*this); + } + + uint64_t reference_impl(size_t bits, uint64_t a, uint64_t b) + { + int64_t sa = (int64_t)(a << (64 - bits)); + return sa >> (b >= bits ? 63 : (b + 64 - bits)); + } + + template + cxxrtl::value testing_impl(cxxrtl::value a, cxxrtl::value b) + { + return a.sshr(b); + } + + void tweak_input(uint64_t &, uint64_t &b) + { + b &= 0x7f; + } +} sshr; + +struct AddTest : BinaryOperationBase +{ + AddTest() + { + std::printf("Randomized tests for value::add:\n"); + test_binary_operation(*this); + } + + uint64_t reference_impl(size_t bits, uint64_t a, uint64_t b) + { + return a + b; + } + + template + cxxrtl::value testing_impl(cxxrtl::value a, cxxrtl::value b) + { + return a.add(b); + } +} add; + +struct SubTest : BinaryOperationBase +{ + SubTest() + { + std::printf("Randomized tests for value::sub:\n"); + test_binary_operation(*this); + } + + uint64_t reference_impl(size_t bits, uint64_t a, uint64_t b) + { + return a - b; + } + + template + cxxrtl::value testing_impl(cxxrtl::value a, cxxrtl::value b) + { + return a.sub(b); + } +} sub; + +struct CtlzTest +{ + CtlzTest() + { + std::printf("Randomized tests for value::ctlz:\n"); + test_unary_operation(*this); + } + + uint64_t reference_impl(size_t bits, uint64_t a) + { + if (a == 0) + return bits; + if (sizeof(long) == 4) + return __builtin_clzll(a) - (64 - bits); + else + return __builtin_clzl(a) - (64 - bits); + } + + template + cxxrtl::value testing_impl(cxxrtl::value a) + { + size_t result = a.ctlz(); + return cxxrtl::value((cxxrtl::chunk_t)result); + } +} ctlz; + +struct UdivTest : BinaryOperationBase +{ + UdivTest() + { + std::printf("Randomized tests for value::udivmod (div):\n"); + test_binary_operation(*this); + } + + uint64_t reference_impl(size_t bits, uint64_t a, uint64_t b) + { + return a / b; + } + + template + cxxrtl::value testing_impl(cxxrtl::value a, cxxrtl::value b) + { + return std::get<0>(a.udivmod(b)); + } + + void tweak_input(uint64_t &, uint64_t &b) + { + if (b == 0) b = 1; // Avoid divide by zero + } +} udiv; + +struct UmodTest : BinaryOperationBase +{ + UmodTest() + { + std::printf("Randomized tests for value::udivmod (mod):\n"); + test_binary_operation(*this); + } + + uint64_t reference_impl(size_t bits, uint64_t a, uint64_t b) + { + return a % b; + } + + template + cxxrtl::value testing_impl(cxxrtl::value a, cxxrtl::value b) + { + return std::get<1>(a.udivmod(b)); + } + + void tweak_input(uint64_t &, uint64_t &b) + { + if (b == 0) b = 1; // Avoid divide by zero + } +} umod; + +struct SdivTest : BinaryOperationBase +{ + SdivTest() + { + std::printf("Randomized tests for value::sdivmod (div):\n"); + test_binary_operation(*this); + } + + uint64_t reference_impl(size_t bits, uint64_t a, uint64_t b) + { + return (uint64_t)(sext(bits, a) / sext(bits, b)); + } + + template + cxxrtl::value testing_impl(cxxrtl::value a, cxxrtl::value b) + { + return std::get<0>(a.sdivmod(b)); + } + + void tweak_input(uint64_t &, uint64_t &b) + { + if (b == 0) b = 1; // Avoid divide by zero + } +} sdiv; + +struct SmodTest : BinaryOperationBase +{ + SmodTest() + { + std::printf("Randomized tests for value::sdivmod (mod):\n"); + test_binary_operation(*this); + } + + uint64_t reference_impl(size_t bits, uint64_t a, uint64_t b) + { + return (uint64_t)(sext(bits, a) % sext(bits, b)); + } + + template + cxxrtl::value testing_impl(cxxrtl::value a, cxxrtl::value b) + { + return std::get<1>(a.sdivmod(b)); + } + + void tweak_input(uint64_t &, uint64_t &b) + { + if (b == 0) b = 1; // Avoid divide by zero + } +} smod; + +int main() +{ +} diff --git a/chips/yosys/tests/errors/syntax_err01.v b/chips/yosys/tests/errors/syntax_err01.v new file mode 100644 index 0000000000000000000000000000000000000000..44e23dc137875eedb59998878eed9ed307645548 --- /dev/null +++ b/chips/yosys/tests/errors/syntax_err01.v @@ -0,0 +1,3 @@ +module a; +integer [31:0]w; +endmodule diff --git a/chips/yosys/tests/errors/syntax_err02.v b/chips/yosys/tests/errors/syntax_err02.v new file mode 100644 index 0000000000000000000000000000000000000000..78b076d2dc938baa6454f5f514f18b1e6c995b77 --- /dev/null +++ b/chips/yosys/tests/errors/syntax_err02.v @@ -0,0 +1,6 @@ +module a; +task to ( + input integer [3:0]x +); +endtask +endmodule diff --git a/chips/yosys/tests/errors/syntax_err03.v b/chips/yosys/tests/errors/syntax_err03.v new file mode 100644 index 0000000000000000000000000000000000000000..ec43bcc09658374a730f689c8af5ffc1227d323d --- /dev/null +++ b/chips/yosys/tests/errors/syntax_err03.v @@ -0,0 +1,6 @@ +module a; +task to ( + input [3]x +); +endtask +endmodule diff --git a/chips/yosys/tests/errors/syntax_err04.v b/chips/yosys/tests/errors/syntax_err04.v new file mode 100644 index 0000000000000000000000000000000000000000..dce45a49b7116b1148e8364861d8e17a597e7311 --- /dev/null +++ b/chips/yosys/tests/errors/syntax_err04.v @@ -0,0 +1,3 @@ +module a; +wire [3]x; +endmodule diff --git a/chips/yosys/tests/errors/syntax_err05.v b/chips/yosys/tests/errors/syntax_err05.v new file mode 100644 index 0000000000000000000000000000000000000000..0d134b692d02ab8dcf6e653672fcd40b01a983fd --- /dev/null +++ b/chips/yosys/tests/errors/syntax_err05.v @@ -0,0 +1,3 @@ +module a; +input x[2:0]; +endmodule diff --git a/chips/yosys/tests/errors/syntax_err06.v b/chips/yosys/tests/errors/syntax_err06.v new file mode 100644 index 0000000000000000000000000000000000000000..ca1dc5ba78fc95a05307edcaff070119db77b2b7 --- /dev/null +++ b/chips/yosys/tests/errors/syntax_err06.v @@ -0,0 +1,5 @@ +module a; +initial +begin : label1 +end: label2 +endmodule diff --git a/chips/yosys/tests/errors/syntax_err07.v b/chips/yosys/tests/errors/syntax_err07.v new file mode 100644 index 0000000000000000000000000000000000000000..207fd8a93332cce1fcc0897dc9618bff989de4d4 --- /dev/null +++ b/chips/yosys/tests/errors/syntax_err07.v @@ -0,0 +1,5 @@ +module a; +wire [5:0]x; +wire [3:0]y; +assign y = (4)55; +endmodule diff --git a/chips/yosys/tests/errors/syntax_err08.v b/chips/yosys/tests/errors/syntax_err08.v new file mode 100644 index 0000000000000000000000000000000000000000..28617ab75ab571d53fd0d6a1e95592a278bf5ba7 --- /dev/null +++ b/chips/yosys/tests/errors/syntax_err08.v @@ -0,0 +1,5 @@ +module a; +wire [5:0]x; +wire [3:0]y; +assign y = x 55; +endmodule diff --git a/chips/yosys/tests/errors/syntax_err09.v b/chips/yosys/tests/errors/syntax_err09.v new file mode 100644 index 0000000000000000000000000000000000000000..9db022768b0102cde8adacd34357d247448e2f9c --- /dev/null +++ b/chips/yosys/tests/errors/syntax_err09.v @@ -0,0 +1,2 @@ +module a(input wire x = 1'b0); +endmodule diff --git a/chips/yosys/tests/errors/syntax_err10.v b/chips/yosys/tests/errors/syntax_err10.v new file mode 100644 index 0000000000000000000000000000000000000000..d3280405c807e85f86b0af1f4c90bf332fdffeb4 --- /dev/null +++ b/chips/yosys/tests/errors/syntax_err10.v @@ -0,0 +1,3 @@ +module a; +parameter integer [2:0]x=0; +endmodule diff --git a/chips/yosys/tests/errors/syntax_err11.v b/chips/yosys/tests/errors/syntax_err11.v new file mode 100644 index 0000000000000000000000000000000000000000..f3cde9dfca7802dba753c5700c4b71a338ba4da8 --- /dev/null +++ b/chips/yosys/tests/errors/syntax_err11.v @@ -0,0 +1,3 @@ +module a; +parameter integer real x=0; +endmodule diff --git a/chips/yosys/tests/errors/syntax_err12.v b/chips/yosys/tests/errors/syntax_err12.v new file mode 100644 index 0000000000000000000000000000000000000000..f9b5d5b0b1fce0336f9c769388f57dec5614ee35 --- /dev/null +++ b/chips/yosys/tests/errors/syntax_err12.v @@ -0,0 +1,7 @@ +interface iface; +endinterface + +module a ( + iface x = 1'b0 +); +endmodule diff --git a/chips/yosys/tests/errors/syntax_err13.v b/chips/yosys/tests/errors/syntax_err13.v new file mode 100644 index 0000000000000000000000000000000000000000..35843df58740c60e4aacc6e44b929d10d045a93b --- /dev/null +++ b/chips/yosys/tests/errors/syntax_err13.v @@ -0,0 +1,3 @@ +module a #(p = 0) +(); +endmodule diff --git a/chips/yosys/tests/fmt/.gitignore b/chips/yosys/tests/fmt/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..e6ae0d8797f0482f8a225e95a3f43a04bc1cc6c9 --- /dev/null +++ b/chips/yosys/tests/fmt/.gitignore @@ -0,0 +1,2 @@ +iverilog-* +yosys-* diff --git a/chips/yosys/tests/fmt/always_comb.v b/chips/yosys/tests/fmt/always_comb.v new file mode 100644 index 0000000000000000000000000000000000000000..7147786bebf3dcc2f7fec6d68e586d4b3ed6535d --- /dev/null +++ b/chips/yosys/tests/fmt/always_comb.v @@ -0,0 +1,24 @@ +module top(input clk); + reg a = 0; + reg b = 0; + wire y; + + sub s (.a(a), .b(b), .y(y)); + + always @(posedge clk) begin + a <= (!a && !b) || (a && !b); + b <= (a && !b) || (a && b); + end +endmodule + +module sub(input a, input b, output wire y); + assign y = a & b; + + // Not fit for our purposes: always @* if (a) $display(a, b, y); + // + // We compare output against iverilog, but async iverilog $display fires + // even before values have propagated -- i.e. combinations of a/b/y will be + // shown where a & b are both 1, but y has not yet taken the value 1. We + // don't, so we specify it in the conditional. + always @* if (y & (y == (a & b))) $display(a, b, y); +endmodule diff --git a/chips/yosys/tests/fmt/always_comb_tb.cc b/chips/yosys/tests/fmt/always_comb_tb.cc new file mode 100644 index 0000000000000000000000000000000000000000..5812500535ad1c8f538711c12aaaea0036c8a796 --- /dev/null +++ b/chips/yosys/tests/fmt/always_comb_tb.cc @@ -0,0 +1,16 @@ +#include "yosys-always_comb.cc" + +int main() +{ + cxxrtl_design::p_top uut1, uut2; + + for (int i = 0; i < 20; ++i) { + uut1.p_clk.set(!uut1.p_clk); + uut1.step(); + + uut2.p_clk.set(!uut2.p_clk); + uut2.step(); + } + + return 0; +} diff --git a/chips/yosys/tests/fmt/always_comb_tb.v b/chips/yosys/tests/fmt/always_comb_tb.v new file mode 100644 index 0000000000000000000000000000000000000000..3cc4496a04f43a4e56eb389124f83dc1344520f7 --- /dev/null +++ b/chips/yosys/tests/fmt/always_comb_tb.v @@ -0,0 +1,9 @@ +module tb; + reg clk = 0; + + top uut1 (.clk(clk)); + top uut2 (.clk(clk)); + + always #1 clk <= ~clk; + initial #20 $finish; +endmodule diff --git a/chips/yosys/tests/fmt/always_display.v b/chips/yosys/tests/fmt/always_display.v new file mode 100644 index 0000000000000000000000000000000000000000..593c5afc08ceb3bcda7919fda5a38e45e3044e38 --- /dev/null +++ b/chips/yosys/tests/fmt/always_display.v @@ -0,0 +1,17 @@ +module m(input clk, rst, en, input [31:0] data); + +`ifdef EVENT_CLK + always @(posedge clk) +`endif +`ifdef EVENT_CLK_RST + always @(posedge clk or negedge rst) +`endif +`ifdef EVENT_STAR + always @(*) +`endif +`ifdef COND_EN + if (en) +`endif + $display("data=%d", data); + +endmodule diff --git a/chips/yosys/tests/fmt/always_full.v b/chips/yosys/tests/fmt/always_full.v new file mode 100644 index 0000000000000000000000000000000000000000..4d3df7a615c72261a06a81f2298f9726d10ecf9a --- /dev/null +++ b/chips/yosys/tests/fmt/always_full.v @@ -0,0 +1,236 @@ +module always_full(input clk); + + always @(posedge clk) begin + + $display("==> small unsigned %%d"); + $display(":%d:", 16'haa); + $display(":%-d:", 16'haa); + $display(":%+d:", 16'haa); + $display(":%+-d:", 16'haa); + $display(":%0d:", 16'haa); + $display(":%-0d:", 16'haa); + $display(":%+0d:", 16'haa); + $display(":%+-0d:", 16'haa); + $display(":%20d:", 16'haa); + $display(":%-20d:", 16'haa); + $display(":%+20d:", 16'haa); + $display(":%+-20d:", 16'haa); + $display(":%020d:", 16'haa); + $display(":%-020d:", 16'haa); + $display(":%+020d:", 16'haa); + $display(":%+-020d:", 16'haa); + + $display("==> big unsigned %%d"); + $display(":%d:", 16'haaaa); + $display(":%-d:", 16'haaaa); + $display(":%+d:", 16'haaaa); + $display(":%+-d:", 16'haaaa); + $display(":%0d:", 16'haaaa); + $display(":%-0d:", 16'haaaa); + $display(":%+0d:", 16'haaaa); + $display(":%+-0d:", 16'haaaa); + $display(":%20d:", 16'haaaa); + $display(":%-20d:", 16'haaaa); + $display(":%+20d:", 16'haaaa); + $display(":%+-20d:", 16'haaaa); + $display(":%020d:", 16'haaaa); + $display(":%-020d:", 16'haaaa); + $display(":%+020d:", 16'haaaa); + $display(":%+-020d:", 16'haaaa); + + $display("==> small signed %%d"); + $display(":%d:", 16'shaa); + $display(":%-d:", 16'shaa); + $display(":%+d:", 16'shaa); + $display(":%+-d:", 16'shaa); + $display(":%0d:", 16'shaa); + $display(":%-0d:", 16'shaa); + $display(":%+0d:", 16'shaa); + $display(":%+-0d:", 16'shaa); + $display(":%20d:", 16'shaa); + $display(":%-20d:", 16'shaa); + $display(":%+20d:", 16'shaa); + $display(":%+-20d:", 16'shaa); + $display(":%020d:", 16'shaa); + $display(":%-020d:", 16'shaa); + $display(":%+020d:", 16'shaa); + $display(":%+-020d:", 16'shaa); + + $display("==> big signed %%d"); + $display(":%d:", 16'shaaaa); + $display(":%-d:", 16'shaaaa); + $display(":%+d:", 16'shaaaa); + $display(":%+-d:", 16'shaaaa); + $display(":%0d:", 16'shaaaa); + $display(":%-0d:", 16'shaaaa); + $display(":%+0d:", 16'shaaaa); + $display(":%+-0d:", 16'shaaaa); + $display(":%20d:", 16'shaaaa); + $display(":%-20d:", 16'shaaaa); + $display(":%+20d:", 16'shaaaa); + $display(":%+-20d:", 16'shaaaa); + $display(":%020d:", 16'shaaaa); + $display(":%-020d:", 16'shaaaa); + $display(":%+020d:", 16'shaaaa); + $display(":%+-020d:", 16'shaaaa); + + $display("==> small unsigned %%h"); + $display(":%h:", 16'haa); + $display(":%-h:", 16'haa); + $display(":%0h:", 16'haa); + $display(":%-0h:", 16'haa); + $display(":%20h:", 16'haa); + $display(":%-20h:", 16'haa); + $display(":%020h:", 16'haa); + $display(":%-020h:", 16'haa); + + $display("==> big unsigned %%h"); + $display(":%h:", 16'haaaa); + $display(":%-h:", 16'haaaa); + $display(":%0h:", 16'haaaa); + $display(":%-0h:", 16'haaaa); + $display(":%20h:", 16'haaaa); + $display(":%-20h:", 16'haaaa); + $display(":%020h:", 16'haaaa); + $display(":%-020h:", 16'haaaa); + + $display("==> small signed %%h"); + $display(":%h:", 16'shaa); + $display(":%-h:", 16'shaa); + $display(":%0h:", 16'shaa); + $display(":%-0h:", 16'shaa); + $display(":%20h:", 16'shaa); + $display(":%-20h:", 16'shaa); + $display(":%020h:", 16'shaa); + $display(":%-020h:", 16'shaa); + + $display("==> big signed %%h"); + $display(":%h:", 16'shaaaa); + $display(":%-h:", 16'shaaaa); + $display(":%0h:", 16'shaaaa); + $display(":%-0h:", 16'shaaaa); + $display(":%20h:", 16'shaaaa); + $display(":%-20h:", 16'shaaaa); + $display(":%020h:", 16'shaaaa); + $display(":%-020h:", 16'shaaaa); + + $display("==> small unsigned %%o"); + $display(":%o:", 16'haa); + $display(":%-o:", 16'haa); + $display(":%0o:", 16'haa); + $display(":%-0o:", 16'haa); + $display(":%20o:", 16'haa); + $display(":%-20o:", 16'haa); + $display(":%020o:", 16'haa); + $display(":%-020o:", 16'haa); + + $display("==> big unsigned %%o"); + $display(":%o:", 16'haaaa); + $display(":%-o:", 16'haaaa); + $display(":%0o:", 16'haaaa); + $display(":%-0o:", 16'haaaa); + $display(":%20o:", 16'haaaa); + $display(":%-20o:", 16'haaaa); + $display(":%020o:", 16'haaaa); + $display(":%-020o:", 16'haaaa); + + $display("==> small signed %%o"); + $display(":%o:", 16'shaa); + $display(":%-o:", 16'shaa); + $display(":%0o:", 16'shaa); + $display(":%-0o:", 16'shaa); + $display(":%20o:", 16'shaa); + $display(":%-20o:", 16'shaa); + $display(":%020o:", 16'shaa); + $display(":%-020o:", 16'shaa); + + $display("==> big signed %%o"); + $display(":%o:", 16'shaaaa); + $display(":%-o:", 16'shaaaa); + $display(":%0o:", 16'shaaaa); + $display(":%-0o:", 16'shaaaa); + $display(":%20o:", 16'shaaaa); + $display(":%-20o:", 16'shaaaa); + $display(":%020o:", 16'shaaaa); + $display(":%-020o:", 16'shaaaa); + + $display("==> small unsigned %%b"); + $display(":%b:", 16'haa); + $display(":%-b:", 16'haa); + $display(":%0b:", 16'haa); + $display(":%-0b:", 16'haa); + $display(":%20b:", 16'haa); + $display(":%-20b:", 16'haa); + $display(":%020b:", 16'haa); + $display(":%-020b:", 16'haa); + + $display("==> big unsigned %%b"); + $display(":%b:", 16'haaaa); + $display(":%-b:", 16'haaaa); + $display(":%0b:", 16'haaaa); + $display(":%-0b:", 16'haaaa); + $display(":%20b:", 16'haaaa); + $display(":%-20b:", 16'haaaa); + $display(":%020b:", 16'haaaa); + $display(":%-020b:", 16'haaaa); + + $display("==> small signed %%b"); + $display(":%b:", 16'shaa); + $display(":%-b:", 16'shaa); + $display(":%0b:", 16'shaa); + $display(":%-0b:", 16'shaa); + $display(":%20b:", 16'shaa); + $display(":%-20b:", 16'shaa); + $display(":%020b:", 16'shaa); + $display(":%-020b:", 16'shaa); + + $display("==> big signed %%b"); + $display(":%b:", 16'shaaaa); + $display(":%-b:", 16'shaaaa); + $display(":%0b:", 16'shaaaa); + $display(":%-0b:", 16'shaaaa); + $display(":%20b:", 16'shaaaa); + $display(":%-20b:", 16'shaaaa); + $display(":%020b:", 16'shaaaa); + $display(":%-020b:", 16'shaaaa); + + $display("==> time %%t"); + $display(":%t:", $time); + $display(":%-t:", $time); + $display(":%0t:", $time); + $display(":%-0t:", $time); + $display(":%10t:", $time); + $display(":%-10t:", $time); + $display(":%015t:", $time); + $display(":%-015t:", $time); + + $display("===> %%s"); + $display(":%10s:", "foo"); + $display(":%010s:", "foo"); + $display(":%-10s:", "foo"); + $display(":%-010s:", "foo"); + + $display("===> %%c"); + $display(":%10c:", "foo"); + $display(":%010c:", "foo"); + $display(":%-10c:", "foo"); + $display(":%-010c:", "foo"); + + $display("==> aliases"); + $display(":%x:", 16'shaa); + $display(":%X:", 16'shaa); + $display(":%H:", 16'shaa); + $display(":%O:", 16'shaa); + $display(":%B:", 16'shaa); + + $display("==> default base"); + $displayh(16'haa); + $displayo(16'haa); + $displayb(16'haa); + + $display("==> write/format"); + $display("%d", 1, "%d", 1); + + end + +endmodule diff --git a/chips/yosys/tests/fmt/always_full_tb.cc b/chips/yosys/tests/fmt/always_full_tb.cc new file mode 100644 index 0000000000000000000000000000000000000000..94991ca25b55e2d23a0dc920fbad9e60613af260 --- /dev/null +++ b/chips/yosys/tests/fmt/always_full_tb.cc @@ -0,0 +1,14 @@ +#include "yosys-always_full.cc" + +int main() +{ + struct : public performer { + int64_t vlog_time() const override { return 1; } + void on_print(const lazy_fmt &output, const cxxrtl::metadata_map &) override { std::cerr << output(); } + } performer; + + cxxrtl_design::p_always__full uut; + uut.p_clk.set(!uut.p_clk); + uut.step(&performer); + return 0; +} diff --git a/chips/yosys/tests/fmt/always_full_tb.v b/chips/yosys/tests/fmt/always_full_tb.v new file mode 100644 index 0000000000000000000000000000000000000000..0c2599cc2632900eb490723f44de47858efd0ae9 --- /dev/null +++ b/chips/yosys/tests/fmt/always_full_tb.v @@ -0,0 +1,12 @@ +module always_full_tb; + + reg clk = 0; + + always_full uut (.clk(clk)); + + always begin + #1 clk <= ~clk; + #1 $finish; + end + +endmodule diff --git a/chips/yosys/tests/fmt/display_lm.v b/chips/yosys/tests/fmt/display_lm.v new file mode 100644 index 0000000000000000000000000000000000000000..d96f233f064ceb6c625f5198c2a3878bffe5c4a4 --- /dev/null +++ b/chips/yosys/tests/fmt/display_lm.v @@ -0,0 +1,12 @@ +module top; + mid mid_uut (); +endmodule + +module mid (); + bot bot_uut (); +endmodule + +module bot (); + initial $display("%%l: %l\n%%m: %m"); + always $display("%%l: %l\n%%m: %m"); +endmodule diff --git a/chips/yosys/tests/fmt/display_lm_tb.cc b/chips/yosys/tests/fmt/display_lm_tb.cc new file mode 100644 index 0000000000000000000000000000000000000000..7a593d72919203c7fa115b45366c40ada5535a41 --- /dev/null +++ b/chips/yosys/tests/fmt/display_lm_tb.cc @@ -0,0 +1,9 @@ +#include "yosys-display_lm.cc" + +int main() +{ + cxxrtl_design::p_top uut; + + uut.step(); + return 0; +} diff --git a/chips/yosys/tests/fmt/fuzz/.gitignore b/chips/yosys/tests/fmt/fuzz/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..88ea7e2ef91028682992825514a03158716a0b5c --- /dev/null +++ b/chips/yosys/tests/fmt/fuzz/.gitignore @@ -0,0 +1,2 @@ +fuzztest +build diff --git a/chips/yosys/tests/fmt/fuzz/CMakeLists.txt b/chips/yosys/tests/fmt/fuzz/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..6f7c43da8885786453db2f0e3e8552e6a499c22b --- /dev/null +++ b/chips/yosys/tests/fmt/fuzz/CMakeLists.txt @@ -0,0 +1,23 @@ +cmake_minimum_required(VERSION 3.14) +project(cxxrtl_division_fuzz) + +set(CMAKE_CXX_STANDARD 17) + +add_subdirectory(fuzztest) + +enable_testing() + +include(GoogleTest) + +fuzztest_setup_fuzzing_flags() + +include_directories(../../..) + +add_executable( + x_test + x_test.cc + ../../../libs/bigint/BigUnsigned.cc +) + +link_fuzztest(x_test) +gtest_discover_tests(x_test) diff --git a/chips/yosys/tests/fmt/fuzz/x_test.cc b/chips/yosys/tests/fmt/fuzz/x_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..ee061861f90a559acaf9b1812bfcfd33f8002752 --- /dev/null +++ b/chips/yosys/tests/fmt/fuzz/x_test.cc @@ -0,0 +1,44 @@ +#include "fuzztest/fuzztest.h" +#include "gtest/gtest.h" + +#include +#include "backends/cxxrtl/cxxrtl.h" +#include "libs/bigint/BigUnsigned.hh" + +using namespace cxxrtl_yosys; + +void Formats128BitIntegers(chunk_t x0, chunk_t x1, chunk_t x2, chunk_t x3, bool signed_) +{ + // Compare output to BigUnsigned. + value<128> v; + v = v.blit<127, 64>(value<64>{x1, x0}); + v = v.blit<63, 0>(value<64>{x3, x2}); + + std::ostringstream oss; + oss << value_formatted<128>(v, false, false, ' ', 0, 10, signed_, false, false); + auto actual = oss.str(); + + BigUnsigned u; + bool negative = signed_ && v.is_neg(); + if (negative) + v = v.neg(); + u.bitShiftLeft(v.slice<127, 64>().val().get(), 64); + u.bitOr(u, v.slice<63, 0>().val().get()); + + std::string expected; + + if (u.isZero()) { + expected = "0"; + } else { + while (!u.isZero()) { + expected += '0' + (u % 10).toInt(); + u /= 10; + } + if (negative) + expected += '-'; + std::reverse(expected.begin(), expected.end()); + } + + EXPECT_EQ(actual, expected); +} +FUZZ_TEST(CxxrtlDivisionFuzz, Formats128BitIntegers); diff --git a/chips/yosys/tests/fmt/generate_mk.py b/chips/yosys/tests/fmt/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..2e94d45009779b71782890bdf8f0305189dda358 --- /dev/null +++ b/chips/yosys/tests/fmt/generate_mk.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile + +def initial_display(): + gen_tests_makefile.generate_cmd_test("initial_display", [ + f"$(YOSYS) -p \"read_verilog initial_display.v\" | awk '/<<>>/,/<<>>/ {{print $$0}}' >yosys-initial_display.log 2>&1", + "iverilog -o iverilog-initial_display initial_display.v", + "./iverilog-initial_display >iverilog-initial_display.log", + "diff yosys-initial_display.log iverilog-initial_display.log", + ]) + + +def always_display(): + cases = [ + ("clk", "-DEVENT_CLK"), + ("clk_rst", "-DEVENT_CLK_RST"), + ("star", "-DEVENT_STAR"), + ("clk_en", "-DEVENT_CLK -DCOND_EN"), + ("clk_rst_en", "-DEVENT_CLK_RST -DCOND_EN"), + ("star_en", "-DEVENT_STAR -DCOND_EN"), + ] + + for name, defs in cases: + gen_tests_makefile.generate_cmd_test(f"always_display_{name}", [ + f"$(YOSYS) -p \"read_verilog {defs} always_display.v; proc; opt_expr -mux_bool; clean\" -o yosys-always_display-{name}-1.v", + f"$(YOSYS) -p \"read_verilog yosys-always_display-{name}-1.v; proc; opt_expr -mux_bool; clean\" -o yosys-always_display-{name}-2.v", + f"diff yosys-always_display-{name}-1.v yosys-always_display-{name}-2.v", + ]) + + +def roundtrip(): + cases = [ + ("dec_unsigned", '-DBASE_DEC -DSIGN=""'), + ("dec_signed", '-DBASE_DEC -DSIGN="signed"'), + ("hex_unsigned", '-DBASE_HEX -DSIGN=""'), + ("hex_signed", '-DBASE_HEX -DSIGN="signed"'), + ("oct_unsigned", '-DBASE_HEX -DSIGN=""'), + ("oct_signed", '-DBASE_HEX -DSIGN="signed"'), + ("bin_unsigned", '-DBASE_HEX -DSIGN=""'), + ("bin_signed", '-DBASE_HEX -DSIGN="signed"'), + ] + + for name, defs in cases: + gen_tests_makefile.generate_cmd_test(f"roundtrip_{name}", [ + f"$(YOSYS) -p \"read_verilog {defs} roundtrip.v; proc; clean\" -o yosys-roundtrip-{name}-1.v", + f"$(YOSYS) -p \"read_verilog yosys-roundtrip-{name}-1.v; proc; clean\" -o yosys-roundtrip-{name}-2.v", + f"diff yosys-roundtrip-{name}-1.v yosys-roundtrip-{name}-2.v", + + f"iverilog {defs} -o iverilog-roundtrip-{name} roundtrip.v roundtrip_tb.v", + f"./iverilog-roundtrip-{name} >iverilog-roundtrip-{name}.log", + + f"iverilog {defs} -o iverilog-roundtrip-{name}-1 yosys-roundtrip-{name}-1.v roundtrip_tb.v", + f"./iverilog-roundtrip-{name}-1 >iverilog-roundtrip-{name}-1.log", + + f"iverilog {defs} -o iverilog-roundtrip-{name}-2 yosys-roundtrip-{name}-2.v roundtrip_tb.v", + f"./iverilog-roundtrip-{name}-2 >iverilog-roundtrip-{name}-2.log", + + f"diff iverilog-roundtrip-{name}.log iverilog-roundtrip-{name}-1.log", + f"diff iverilog-roundtrip-{name}-1.log iverilog-roundtrip-{name}-2.log", + ]) + + +def cxxrtl(): + cases = ["always_full", "always_comb"] + + for name in cases: + gen_tests_makefile.generate_cmd_test(f"cxxrtl_{name}", [ + f"$(YOSYS) -p \"read_verilog {name}.v; proc; clean; write_cxxrtl -print-output std::cerr yosys-{name}.cc\"", + f"$${{CXX:-g++}} -std=c++11 -o yosys-{name} -I../../backends/cxxrtl/runtime {name}_tb.cc -lstdc++", + f"./yosys-{name} 2>yosys-{name}.log", + + f"iverilog -o iverilog-{name} {name}.v {name}_tb.v", + f"./iverilog-{name} | grep -v \"$finish called\" >iverilog-{name}.log", + + f"diff iverilog-{name}.log yosys-{name}.log", + ]) + + +def extra(): + gen_tests_makefile.generate_cmd_test("always_full_equiv", [ + "$(YOSYS) -p \"read_verilog always_full.v; prep; clean\" -o yosys-always_full-1.v", + "iverilog -o iverilog-always_full-1 yosys-always_full-1.v always_full_tb.v", + "./iverilog-always_full-1 > tmp.log", + "grep -v '\\$finish called' tmp.log > iverilog-always_full-1.log", + "diff iverilog-always_full.log iverilog-always_full-1.log", + ], deps=["cxxrtl_always_full"]) + + gen_tests_makefile.generate_cmd_test("display_lm", [ + "$(YOSYS) -p \"read_verilog display_lm.v\" >yosys-display_lm.log 2>&1", + "$(YOSYS) -p \"read_verilog display_lm.v; write_cxxrtl yosys-display_lm.cc\"", + f"$${{CXX:-g++}} -std=c++11 -o yosys-display_lm_cc -I../../backends/cxxrtl/runtime display_lm_tb.cc -lstdc++", + "./yosys-display_lm_cc >yosys-display_lm_cc.log", + "grep \"^%l: \\\\\\bot\\$$\" \"yosys-display_lm.log\"", + "grep \"^%m: \\\\\\bot\\$$\" \"yosys-display_lm.log\"", + "grep \"^%l: \\\\\\bot\\$$\" \"yosys-display_lm_cc.log\"", + "grep \"^%m: \\\\\\bot\\$$\" \"yosys-display_lm_cc.log\"", + ]) + + +def main(): + def callback(): + initial_display() + always_display() + roundtrip() + cxxrtl() + extra() + + gen_tests_makefile.generate_custom(callback) + + +if __name__ == "__main__": + main() diff --git a/chips/yosys/tests/fmt/initial_display.v b/chips/yosys/tests/fmt/initial_display.v new file mode 100644 index 0000000000000000000000000000000000000000..d3ef9ed769173ae5defebe59c778ac2953a9418d --- /dev/null +++ b/chips/yosys/tests/fmt/initial_display.v @@ -0,0 +1,255 @@ +module m; + initial $display("<<>>"); + + initial $display("==> small unsigned %%d"); + initial $display(":%d:", 16'haa); + initial $display(":%-d:", 16'haa); + initial $display(":%+d:", 16'haa); + initial $display(":%+-d:", 16'haa); + initial $display(":%0d:", 16'haa); + initial $display(":%-0d:", 16'haa); + initial $display(":%+0d:", 16'haa); + initial $display(":%+-0d:", 16'haa); + initial $display(":%20d:", 16'haa); + initial $display(":%-20d:", 16'haa); + initial $display(":%+20d:", 16'haa); + initial $display(":%+-20d:", 16'haa); + initial $display(":%020d:", 16'haa); + initial $display(":%-020d:", 16'haa); + initial $display(":%+020d:", 16'haa); + initial $display(":%+-020d:", 16'haa); + + initial $display("==> big unsigned %%d"); + initial $display(":%d:", 16'haaaa); + initial $display(":%-d:", 16'haaaa); + initial $display(":%+d:", 16'haaaa); + initial $display(":%+-d:", 16'haaaa); + initial $display(":%0d:", 16'haaaa); + initial $display(":%-0d:", 16'haaaa); + initial $display(":%+0d:", 16'haaaa); + initial $display(":%+-0d:", 16'haaaa); + initial $display(":%20d:", 16'haaaa); + initial $display(":%-20d:", 16'haaaa); + initial $display(":%+20d:", 16'haaaa); + initial $display(":%+-20d:", 16'haaaa); + initial $display(":%020d:", 16'haaaa); + initial $display(":%-020d:", 16'haaaa); + initial $display(":%+020d:", 16'haaaa); + initial $display(":%+-020d:", 16'haaaa); + + initial $display("==> small signed %%d"); + initial $display(":%d:", 16'shaa); + initial $display(":%-d:", 16'shaa); + initial $display(":%+d:", 16'shaa); + initial $display(":%+-d:", 16'shaa); + initial $display(":%0d:", 16'shaa); + initial $display(":%-0d:", 16'shaa); + initial $display(":%+0d:", 16'shaa); + initial $display(":%+-0d:", 16'shaa); + initial $display(":%20d:", 16'shaa); + initial $display(":%-20d:", 16'shaa); + initial $display(":%+20d:", 16'shaa); + initial $display(":%+-20d:", 16'shaa); + initial $display(":%020d:", 16'shaa); + initial $display(":%-020d:", 16'shaa); + initial $display(":%+020d:", 16'shaa); + initial $display(":%+-020d:", 16'shaa); + + initial $display("==> big signed %%d"); + initial $display(":%d:", 16'shaaaa); + initial $display(":%-d:", 16'shaaaa); + initial $display(":%+d:", 16'shaaaa); + initial $display(":%+-d:", 16'shaaaa); + initial $display(":%0d:", 16'shaaaa); + initial $display(":%-0d:", 16'shaaaa); + initial $display(":%+0d:", 16'shaaaa); + initial $display(":%+-0d:", 16'shaaaa); + initial $display(":%20d:", 16'shaaaa); + initial $display(":%-20d:", 16'shaaaa); + initial $display(":%+20d:", 16'shaaaa); + initial $display(":%+-20d:", 16'shaaaa); + initial $display(":%020d:", 16'shaaaa); + initial $display(":%-020d:", 16'shaaaa); + initial $display(":%+020d:", 16'shaaaa); + initial $display(":%+-020d:", 16'shaaaa); + + initial $display("==> small unsigned %%h"); + initial $display(":%h:", 16'haa); + initial $display(":%-h:", 16'haa); + initial $display(":%0h:", 16'haa); + initial $display(":%-0h:", 16'haa); + initial $display(":%20h:", 16'haa); + initial $display(":%-20h:", 16'haa); + initial $display(":%020h:", 16'haa); + initial $display(":%-020h:", 16'haa); + + initial $display("==> big unsigned %%h"); + initial $display(":%h:", 16'haaaa); + initial $display(":%-h:", 16'haaaa); + initial $display(":%0h:", 16'haaaa); + initial $display(":%-0h:", 16'haaaa); + initial $display(":%20h:", 16'haaaa); + initial $display(":%-20h:", 16'haaaa); + initial $display(":%020h:", 16'haaaa); + initial $display(":%-020h:", 16'haaaa); + + initial $display("==> small signed %%h"); + initial $display(":%h:", 16'shaa); + initial $display(":%-h:", 16'shaa); + initial $display(":%0h:", 16'shaa); + initial $display(":%-0h:", 16'shaa); + initial $display(":%20h:", 16'shaa); + initial $display(":%-20h:", 16'shaa); + initial $display(":%020h:", 16'shaa); + initial $display(":%-020h:", 16'shaa); + + initial $display("==> big signed %%h"); + initial $display(":%h:", 16'shaaaa); + initial $display(":%-h:", 16'shaaaa); + initial $display(":%0h:", 16'shaaaa); + initial $display(":%-0h:", 16'shaaaa); + initial $display(":%20h:", 16'shaaaa); + initial $display(":%-20h:", 16'shaaaa); + initial $display(":%020h:", 16'shaaaa); + initial $display(":%-020h:", 16'shaaaa); + + initial $display("==> small unsigned %%o"); + initial $display(":%o:", 16'haa); + initial $display(":%-o:", 16'haa); + initial $display(":%0o:", 16'haa); + initial $display(":%-0o:", 16'haa); + initial $display(":%20o:", 16'haa); + initial $display(":%-20o:", 16'haa); + initial $display(":%020o:", 16'haa); + initial $display(":%-020o:", 16'haa); + + initial $display("==> big unsigned %%o"); + initial $display(":%o:", 16'haaaa); + initial $display(":%-o:", 16'haaaa); + initial $display(":%0o:", 16'haaaa); + initial $display(":%-0o:", 16'haaaa); + initial $display(":%20o:", 16'haaaa); + initial $display(":%-20o:", 16'haaaa); + initial $display(":%020o:", 16'haaaa); + initial $display(":%-020o:", 16'haaaa); + + initial $display("==> small signed %%o"); + initial $display(":%o:", 16'shaa); + initial $display(":%-o:", 16'shaa); + initial $display(":%0o:", 16'shaa); + initial $display(":%-0o:", 16'shaa); + initial $display(":%20o:", 16'shaa); + initial $display(":%-20o:", 16'shaa); + initial $display(":%020o:", 16'shaa); + initial $display(":%-020o:", 16'shaa); + + initial $display("==> big signed %%o"); + initial $display(":%o:", 16'shaaaa); + initial $display(":%-o:", 16'shaaaa); + initial $display(":%0o:", 16'shaaaa); + initial $display(":%-0o:", 16'shaaaa); + initial $display(":%20o:", 16'shaaaa); + initial $display(":%-20o:", 16'shaaaa); + initial $display(":%020o:", 16'shaaaa); + initial $display(":%-020o:", 16'shaaaa); + + initial $display("==> small unsigned %%b"); + initial $display(":%b:", 16'haa); + initial $display(":%-b:", 16'haa); + initial $display(":%0b:", 16'haa); + initial $display(":%-0b:", 16'haa); + initial $display(":%20b:", 16'haa); + initial $display(":%-20b:", 16'haa); + initial $display(":%020b:", 16'haa); + initial $display(":%-020b:", 16'haa); + + initial $display("==> big unsigned %%b"); + initial $display(":%b:", 16'haaaa); + initial $display(":%-b:", 16'haaaa); + initial $display(":%0b:", 16'haaaa); + initial $display(":%-0b:", 16'haaaa); + initial $display(":%20b:", 16'haaaa); + initial $display(":%-20b:", 16'haaaa); + initial $display(":%020b:", 16'haaaa); + initial $display(":%-020b:", 16'haaaa); + + initial $display("==> small signed %%b"); + initial $display(":%b:", 16'shaa); + initial $display(":%-b:", 16'shaa); + initial $display(":%0b:", 16'shaa); + initial $display(":%-0b:", 16'shaa); + initial $display(":%20b:", 16'shaa); + initial $display(":%-20b:", 16'shaa); + initial $display(":%020b:", 16'shaa); + initial $display(":%-020b:", 16'shaa); + + initial $display("==> big signed %%b"); + initial $display(":%b:", 16'shaaaa); + initial $display(":%-b:", 16'shaaaa); + initial $display(":%0b:", 16'shaaaa); + initial $display(":%-0b:", 16'shaaaa); + initial $display(":%20b:", 16'shaaaa); + initial $display(":%-20b:", 16'shaaaa); + initial $display(":%020b:", 16'shaaaa); + initial $display(":%-020b:", 16'shaaaa); + + initial $display("==> time %%t"); + initial $display(":%t:", $time); + initial $display(":%-t:", $time); + initial $display(":%0t:", $time); + initial $display(":%-0t:", $time); + initial $display(":%10t:", $time); + initial $display(":%-10t:", $time); + initial $display(":%015t:", $time); + initial $display(":%-015t:", $time); + + initial $display("===> %%s"); + initial $display(":%10s:", "foo"); + initial $display(":%010s:", "foo"); + initial $display(":%-10s:", "foo"); + initial $display(":%-010s:", "foo"); + + initial $display("===> %%c"); + initial $display(":%10c:", "foo"); + initial $display(":%010c:", "foo"); + initial $display(":%-10c:", "foo"); + initial $display(":%-010c:", "foo"); + + initial $display("==> aliases"); + initial $display(":%x:", 16'shaa); + initial $display(":%X:", 16'shaa); + initial $display(":%H:", 16'shaa); + initial $display(":%O:", 16'shaa); + initial $display(":%B:", 16'shaa); + + initial $display("==> x/z"); + initial $display(":%d:", 16'b1010101010101010); + initial $display(":%d:", 16'b101010101010101x); + initial $display(":%d:", 16'b101010101010101z); + initial $display(":%x:", 16'b1010101010101010); + initial $display(":%x:", 16'b101010101010101x); + initial $display(":%x:", 16'b101010101010101z); + initial $display(":%x:", 16'b101010101010xxxx); + initial $display(":%x:", 16'b101010101010zzzz); + initial $display(":%o:", 16'b1010101010101010); + initial $display(":%o:", 16'b101010101010101x); + initial $display(":%o:", 16'b101010101010101z); + initial $display(":%o:", 16'b1010101010101xxx); + initial $display(":%o:", 16'b1010101010101zzz); + initial $display(":%b:", 16'b1010101010101010); + initial $display(":%b:", 16'b101010101010101x); + initial $display(":%b:", 16'b101010101010101z); + + initial $display("==> default base"); + initial $displayh(16'haa); + initial $displayo(16'haa); + initial $displayb(16'haa); + + initial $display("==> write/format"); + initial $display("%d", 1, "%d", 1); + // this one hits a bug in iverilog: + // initial $display("%s", $sformatf("%d", 1, "%d", 1)); + + initial $display("<<>>"); + +endmodule diff --git a/chips/yosys/tests/fmt/roundtrip.v b/chips/yosys/tests/fmt/roundtrip.v new file mode 100644 index 0000000000000000000000000000000000000000..7b50039cd2633af73eb34eb4bce06183a2d403ea --- /dev/null +++ b/chips/yosys/tests/fmt/roundtrip.v @@ -0,0 +1,22 @@ +module m(input clk, input `SIGN [31:0] data); + + always @(posedge clk) + // All on a single line to avoid order effects. +`ifdef BASE_DEC + $display(":%d:%-d:%+d:%+-d:%0d:%-0d:%+0d:%+-0d:%20d:%-20d:%+20d:%+-20d:%020d:%-020d:%+020d:%+-020d:", + data, data, data, data, data, data, data, data, data, data, data, data, data, data, data, data); +`endif +`ifdef BASE_HEX + $display(":%h:%-h:%0h:%-0h:%20h:%-20h:%020h:%-020h:", + data, data, data, data, data, data, data, data); +`endif +`ifdef BASE_OCT + $display(":%o:%-o:%0o:%-0o:%20o:%-20o:%020o:%-020o:", + data, data, data, data, data, data, data, data); +`endif +`ifdef BASE_BIN + $display(":%b:%-b:%0b:%-0b:%20b:%-20b:%020b:%-020b:", + data, data, data, data, data, data, data, data); +`endif + +endmodule diff --git a/chips/yosys/tests/fmt/roundtrip_tb.v b/chips/yosys/tests/fmt/roundtrip_tb.v new file mode 100644 index 0000000000000000000000000000000000000000..988b8d8c2c0b5aea4de648febf8683c1610a0249 --- /dev/null +++ b/chips/yosys/tests/fmt/roundtrip_tb.v @@ -0,0 +1,13 @@ +module tb; + reg clk = 1'b0; + reg [31:0] data; + + m dut(.clk(clk), .data(data)); + + initial begin + data = 32'haa; + #10; clk = 1; #10; clk = 0; + data = 32'haaaa; + #10; clk = 1; #10; clk = 0; + end +endmodule diff --git a/chips/yosys/tests/fsm/.gitignore b/chips/yosys/tests/fsm/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..90ea6e92a975d81076f6ec8bab6349178e053a5e --- /dev/null +++ b/chips/yosys/tests/fsm/.gitignore @@ -0,0 +1 @@ +uut_*.* diff --git a/chips/yosys/tests/fsm/generate_mk.py b/chips/yosys/tests/fsm/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..8e3f68c5b5ff1e9102c6954c3cf3392f43578aff --- /dev/null +++ b/chips/yosys/tests/fsm/generate_mk.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile + +import argparse +import sys +import random + +# set to 'True' to compare verific with yosys +test_verific = False + +def random_expr(variables): + c = random.choice(['bin', 'uni', 'var', 'const']) + if c == 'bin': + op = random.choice(['+', '-', '*', '<', '<=', '==', '!=', '>=', '>', '<<', '>>', '<<<', '>>>', '|', '&', '^', '~^', '||', '&&']) + return "(%s %s %s)" % (random_expr(variables), op, random_expr(variables)) + if c == 'uni': + op = random.choice(['+', '-', '~', '|', '&', '^', '~^', '!', '$signed', '$unsigned']) + return "%s(%s)" % (op, random_expr(variables)) + if c == 'var': + return random.choice(variables) + if c == 'const': + bits = random.randint(1, 32) + return "%d'd%s" % (bits, random.randint(0, 2**bits-1)) + raise AssertionError + +parser = argparse.ArgumentParser(formatter_class = argparse.ArgumentDefaultsHelpFormatter) +parser.add_argument('-S', '--seed', type = int, help = 'seed for PRNG') +parser.add_argument('-c', '--count', type = int, default = 50, help = 'number of test cases to generate') +args = parser.parse_args() + +seed = args.seed +if seed is None: + seed = random.randrange(sys.maxsize) +print("fsm PRNG seed: %d" % seed) +random.seed(seed) + +gen_tests_makefile.remove_generated("uut_*.*") + +for idx in range(args.count): + with open('uut_%05d.v' % idx, 'w') as f: + with gen_tests_makefile.redirect_stdout(f): + rst2 = random.choice([False, True]) + if rst2: + print('module uut_%05d(clk, rst1, rst2, rst, a, b, c, x, y, z);' % (idx)) + print(' input clk, rst1, rst2;') + print(' output rst;') + print(' assign rst = rst1 || rst2;') + else: + print('module uut_%05d(clk, rst, a, b, c, x, y, z);' % (idx)) + print(' input clk, rst;') + variables=['a', 'b', 'c', 'x', 'y', 'z'] + print(' input%s [%d:0] a;' % (random.choice(['', ' signed']), random.randint(0, 31))) + print(' input%s [%d:0] b;' % (random.choice(['', ' signed']), random.randint(0, 31))) + print(' input%s [%d:0] c;' % (random.choice(['', ' signed']), random.randint(0, 31))) + print(' output reg%s [%d:0] x;' % (random.choice(['', ' signed']), random.randint(0, 31))) + print(' output reg%s [%d:0] y;' % (random.choice(['', ' signed']), random.randint(0, 31))) + print(' output reg%s [%d:0] z;' % (random.choice(['', ' signed']), random.randint(0, 31))) + state_bits = random.randint(5, 16); + print(' %sreg [%d:0] state;' % (random.choice(['', '(* fsm_encoding = "one-hot" *)', + '(* fsm_encoding = "binary" *)']), state_bits-1)) + states=[] + for i in range(random.randint(2, 10)): + n = random.randint(0, 2**state_bits-1) + if n not in states: + states.append(n) + print(' always @(posedge clk) begin') + print(' if (%s) begin' % ('rst1' if rst2 else 'rst')) + print(' x <= %d;' % random.randint(0, 2**31-1)) + print(' y <= %d;' % random.randint(0, 2**31-1)) + print(' z <= %d;' % random.randint(0, 2**31-1)) + print(' state <= %d;' % random.choice(states)) + print(' end else begin') + print(' case (state)') + for state in states: + print(' %d: begin' % state) + for var in ('x', 'y', 'z'): + print(' %s <= %s;' % (var, random_expr(variables))) + next_states = states[:] + for i in range(random.randint(0, len(states))): + next_state = random.choice(next_states) + next_states.remove(next_state) + print(' if ((%s) %s (%s)) state <= %s;' % (random_expr(variables), + random.choice(['<', '<=', '>=', '>']), random_expr(variables), next_state)) + print(' end') + print(' endcase') + if rst2: + print(' if (rst2) begin') + print(' x <= a;') + print(' y <= b;') + print(' z <= c;') + print(' state <= %d;' % random.choice(states)) + print(' end') + print(' end') + print(' end') + print('endmodule') + with open('uut_%05d.ys' % idx, 'w') as f: + with gen_tests_makefile.redirect_stdout(f): + if test_verific: + print('read_verilog uut_%05d.v' % idx) + print('proc;; rename uut_%05d gold' % idx) + print('verific -vlog2k uut_%05d.v' % idx) + print('verific -import uut_%05d' % idx) + print('rename uut_%05d gate' % idx) + else: + print('read_verilog uut_%05d.v' % idx) + print('proc;;') + print('copy uut_%05d gold' % idx) + print('rename uut_%05d gate' % idx) + print('cd gate') + print('opt; wreduce; share%s; opt; fsm;;' % random.choice(['', ' -aggressive'])) + print('cd ..') + print('miter -equiv -flatten -ignore_gold_x -make_outputs -make_outcmp gold gate miter') + print('sat -verify-no-timeout -timeout 20 -seq 5 -set-at 1 %s_rst 1 -prove trigger 0 -prove-skip 1 -show-inputs -show-outputs miter' % ('gold' if rst2 else 'in')) + +gen_tests_makefile.generate(["--yosys-scripts"]) diff --git a/chips/yosys/tests/functional/.gitignore b/chips/yosys/tests/functional/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..f0c4cf14e4519ee1cf6913163fde29fcbf71b861 --- /dev/null +++ b/chips/yosys/tests/functional/.gitignore @@ -0,0 +1,6 @@ +my_module_cxxrtl.cc +my_module_functional_cxx.cc +vcd_harness +*.vcd +*.smt2 +*.rkt diff --git a/chips/yosys/tests/functional/README.md b/chips/yosys/tests/functional/README.md new file mode 100644 index 0000000000000000000000000000000000000000..12f975929c1bff280a1fcb128dac9c3995ebf05f --- /dev/null +++ b/chips/yosys/tests/functional/README.md @@ -0,0 +1,19 @@ +Tests for the functional backend use pytest as a testrunner. + +Run with `pytest -v` + +Pytest options you might want: + +- `-v`: More progress indication. + +- `--basetemp tmp`: Store test files (including vcd results) in tmp. + CAREFUL: contents of tmp will be deleted + +- `-k `: Run only tests that contain the pattern, e.g. + `-k cxx` or `-k smt` or `-k demux` or `-k 'cxx[demux` + +- `-s`: Don't hide stdout/stderr from the test code. + +Custom options for functional backend tests: + +- `--per-cell N`: Run only N tests for each cell. diff --git a/chips/yosys/tests/functional/conftest.py b/chips/yosys/tests/functional/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..a9fbb3c5947d34fcc4cd8fbe075e910d3d2181fb --- /dev/null +++ b/chips/yosys/tests/functional/conftest.py @@ -0,0 +1,34 @@ +import pytest +from rtlil_cells import generate_test_cases +import random + +random_seed = random.getrandbits(32) + +def pytest_configure(config): + config.addinivalue_line("markers", "smt: test uses smtlib/z3") + config.addinivalue_line("markers", "rkt: test uses racket/rosette") + +def pytest_addoption(parser): + parser.addoption("--per-cell", type=int, default=None, help="run only N tests per cell") + parser.addoption("--steps", type=int, default=1000, help="run each test for N steps") + parser.addoption("--seed", type=int, default=random_seed, help="seed for random number generation, use random seed if unspecified") + +def pytest_collection_finish(session): + print('random seed: {}'.format(session.config.getoption("seed"))) + +@pytest.fixture +def num_steps(request): + return request.config.getoption("steps") + +@pytest.fixture +def rnd(request): + seed1 = request.config.getoption("seed") + return lambda seed2: random.Random('{}-{}'.format(seed1, seed2)) + +def pytest_generate_tests(metafunc): + if "cell" in metafunc.fixturenames: + per_cell = metafunc.config.getoption("per_cell", default=None) + seed1 = metafunc.config.getoption("seed") + rnd = lambda seed2: random.Random('{}-{}'.format(seed1, seed2)) + names, cases = generate_test_cases(per_cell, rnd) + metafunc.parametrize("cell,parameters", cases, ids=names) diff --git a/chips/yosys/tests/functional/generate_mk.py b/chips/yosys/tests/functional/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..3d63d1fe90e658964824a6234c4b1a66c3ccfbed --- /dev/null +++ b/chips/yosys/tests/functional/generate_mk.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile + +def callback(): + gen_tests_makefile.generate_cmd_test("functional",f'pytest -v -m "not smt and not rkt" . "$$@"') + +gen_tests_makefile.generate_custom(callback) diff --git a/chips/yosys/tests/functional/picorv32.v b/chips/yosys/tests/functional/picorv32.v new file mode 100644 index 0000000000000000000000000000000000000000..cfc7ce0627a1bba4912ee1276858fe7b48bfb0df --- /dev/null +++ b/chips/yosys/tests/functional/picorv32.v @@ -0,0 +1,3044 @@ +/* + * PicoRV32 -- A Small RISC-V (RV32I) Processor Core + * + * Copyright (C) 2015 Claire Xenia Wolf + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +/* verilator lint_off WIDTH */ +/* verilator lint_off PINMISSING */ +/* verilator lint_off CASEOVERLAP */ +/* verilator lint_off CASEINCOMPLETE */ + +`timescale 1 ns / 1 ps +// `default_nettype none +// `define DEBUGNETS +// `define DEBUGREGS +// `define DEBUGASM +// `define DEBUG + +`ifdef DEBUG + `define debug(debug_command) debug_command +`else + `define debug(debug_command) +`endif + +`ifdef FORMAL + `define FORMAL_KEEP (* keep *) + `define assert(assert_expr) assert(assert_expr) +`else + `ifdef DEBUGNETS + `define FORMAL_KEEP (* keep *) + `else + `define FORMAL_KEEP + `endif + `define assert(assert_expr) empty_statement +`endif + +// uncomment this for register file in extra module +// `define PICORV32_REGS picorv32_regs + +// this macro can be used to check if the verilog files in your +// design are read in the correct order. +`define PICORV32_V + + +/*************************************************************** + * picorv32 + ***************************************************************/ + +module picorv32 #( + parameter [ 0:0] ENABLE_COUNTERS = 1, + parameter [ 0:0] ENABLE_COUNTERS64 = 1, + parameter [ 0:0] ENABLE_REGS_16_31 = 1, + parameter [ 0:0] ENABLE_REGS_DUALPORT = 1, + parameter [ 0:0] LATCHED_MEM_RDATA = 0, + parameter [ 0:0] TWO_STAGE_SHIFT = 1, + parameter [ 0:0] BARREL_SHIFTER = 0, + parameter [ 0:0] TWO_CYCLE_COMPARE = 0, + parameter [ 0:0] TWO_CYCLE_ALU = 0, + parameter [ 0:0] COMPRESSED_ISA = 0, + parameter [ 0:0] CATCH_MISALIGN = 1, + parameter [ 0:0] CATCH_ILLINSN = 1, + parameter [ 0:0] ENABLE_PCPI = 0, + parameter [ 0:0] ENABLE_MUL = 0, + parameter [ 0:0] ENABLE_FAST_MUL = 0, + parameter [ 0:0] ENABLE_DIV = 0, + parameter [ 0:0] ENABLE_IRQ = 0, + parameter [ 0:0] ENABLE_IRQ_QREGS = 1, + parameter [ 0:0] ENABLE_IRQ_TIMER = 1, + parameter [ 0:0] ENABLE_TRACE = 0, + parameter [ 0:0] REGS_INIT_ZERO = 0, + parameter [31:0] MASKED_IRQ = 32'h 0000_0000, + parameter [31:0] LATCHED_IRQ = 32'h ffff_ffff, + parameter [31:0] PROGADDR_RESET = 32'h 0000_0000, + parameter [31:0] PROGADDR_IRQ = 32'h 0000_0010, + parameter [31:0] STACKADDR = 32'h ffff_ffff +) ( + input clk, resetn, + output reg trap, + + output reg mem_valid, + output reg mem_instr, + input mem_ready, + + output reg [31:0] mem_addr, + output reg [31:0] mem_wdata, + output reg [ 3:0] mem_wstrb, + input [31:0] mem_rdata, + + // Look-Ahead Interface + output mem_la_read, + output mem_la_write, + output [31:0] mem_la_addr, + output reg [31:0] mem_la_wdata, + output reg [ 3:0] mem_la_wstrb, + + // Pico Co-Processor Interface (PCPI) + output reg pcpi_valid, + output reg [31:0] pcpi_insn, + output [31:0] pcpi_rs1, + output [31:0] pcpi_rs2, + input pcpi_wr, + input [31:0] pcpi_rd, + input pcpi_wait, + input pcpi_ready, + + // IRQ Interface + input [31:0] irq, + output reg [31:0] eoi, + +`ifdef RISCV_FORMAL + output reg rvfi_valid, + output reg [63:0] rvfi_order, + output reg [31:0] rvfi_insn, + output reg rvfi_trap, + output reg rvfi_halt, + output reg rvfi_intr, + output reg [ 1:0] rvfi_mode, + output reg [ 1:0] rvfi_ixl, + output reg [ 4:0] rvfi_rs1_addr, + output reg [ 4:0] rvfi_rs2_addr, + output reg [31:0] rvfi_rs1_rdata, + output reg [31:0] rvfi_rs2_rdata, + output reg [ 4:0] rvfi_rd_addr, + output reg [31:0] rvfi_rd_wdata, + output reg [31:0] rvfi_pc_rdata, + output reg [31:0] rvfi_pc_wdata, + output reg [31:0] rvfi_mem_addr, + output reg [ 3:0] rvfi_mem_rmask, + output reg [ 3:0] rvfi_mem_wmask, + output reg [31:0] rvfi_mem_rdata, + output reg [31:0] rvfi_mem_wdata, + + output reg [63:0] rvfi_csr_mcycle_rmask, + output reg [63:0] rvfi_csr_mcycle_wmask, + output reg [63:0] rvfi_csr_mcycle_rdata, + output reg [63:0] rvfi_csr_mcycle_wdata, + + output reg [63:0] rvfi_csr_minstret_rmask, + output reg [63:0] rvfi_csr_minstret_wmask, + output reg [63:0] rvfi_csr_minstret_rdata, + output reg [63:0] rvfi_csr_minstret_wdata, +`endif + + // Trace Interface + output reg trace_valid, + output reg [35:0] trace_data +); + localparam integer irq_timer = 0; + localparam integer irq_ebreak = 1; + localparam integer irq_buserror = 2; + + localparam integer irqregs_offset = ENABLE_REGS_16_31 ? 32 : 16; + localparam integer regfile_size = (ENABLE_REGS_16_31 ? 32 : 16) + 4*ENABLE_IRQ*ENABLE_IRQ_QREGS; + localparam integer regindex_bits = (ENABLE_REGS_16_31 ? 5 : 4) + ENABLE_IRQ*ENABLE_IRQ_QREGS; + + localparam WITH_PCPI = ENABLE_PCPI || ENABLE_MUL || ENABLE_FAST_MUL || ENABLE_DIV; + + localparam [35:0] TRACE_BRANCH = {4'b 0001, 32'b 0}; + localparam [35:0] TRACE_ADDR = {4'b 0010, 32'b 0}; + localparam [35:0] TRACE_IRQ = {4'b 1000, 32'b 0}; + + reg [63:0] count_cycle, count_instr; + reg [31:0] reg_pc, reg_next_pc, reg_op1, reg_op2, reg_out; + reg [4:0] reg_sh; + + reg [31:0] next_insn_opcode; + reg [31:0] dbg_insn_opcode; + reg [31:0] dbg_insn_addr; + + wire dbg_mem_valid = mem_valid; + wire dbg_mem_instr = mem_instr; + wire dbg_mem_ready = mem_ready; + wire [31:0] dbg_mem_addr = mem_addr; + wire [31:0] dbg_mem_wdata = mem_wdata; + wire [ 3:0] dbg_mem_wstrb = mem_wstrb; + wire [31:0] dbg_mem_rdata = mem_rdata; + + assign pcpi_rs1 = reg_op1; + assign pcpi_rs2 = reg_op2; + + wire [31:0] next_pc; + + reg irq_delay; + reg irq_active; + reg [31:0] irq_mask; + reg [31:0] irq_pending; + reg [31:0] timer; + +`ifndef PICORV32_REGS + reg [31:0] cpuregs [0:regfile_size-1]; + + integer i; + initial begin + if (REGS_INIT_ZERO) begin + for (i = 0; i < regfile_size; i = i+1) + cpuregs[i] = 0; + end + end +`endif + + task empty_statement; + // This task is used by the `assert directive in non-formal mode to + // avoid empty statement (which are unsupported by plain Verilog syntax). + begin end + endtask + +`ifdef DEBUGREGS + wire [31:0] dbg_reg_x0 = 0; + wire [31:0] dbg_reg_x1 = cpuregs[1]; + wire [31:0] dbg_reg_x2 = cpuregs[2]; + wire [31:0] dbg_reg_x3 = cpuregs[3]; + wire [31:0] dbg_reg_x4 = cpuregs[4]; + wire [31:0] dbg_reg_x5 = cpuregs[5]; + wire [31:0] dbg_reg_x6 = cpuregs[6]; + wire [31:0] dbg_reg_x7 = cpuregs[7]; + wire [31:0] dbg_reg_x8 = cpuregs[8]; + wire [31:0] dbg_reg_x9 = cpuregs[9]; + wire [31:0] dbg_reg_x10 = cpuregs[10]; + wire [31:0] dbg_reg_x11 = cpuregs[11]; + wire [31:0] dbg_reg_x12 = cpuregs[12]; + wire [31:0] dbg_reg_x13 = cpuregs[13]; + wire [31:0] dbg_reg_x14 = cpuregs[14]; + wire [31:0] dbg_reg_x15 = cpuregs[15]; + wire [31:0] dbg_reg_x16 = cpuregs[16]; + wire [31:0] dbg_reg_x17 = cpuregs[17]; + wire [31:0] dbg_reg_x18 = cpuregs[18]; + wire [31:0] dbg_reg_x19 = cpuregs[19]; + wire [31:0] dbg_reg_x20 = cpuregs[20]; + wire [31:0] dbg_reg_x21 = cpuregs[21]; + wire [31:0] dbg_reg_x22 = cpuregs[22]; + wire [31:0] dbg_reg_x23 = cpuregs[23]; + wire [31:0] dbg_reg_x24 = cpuregs[24]; + wire [31:0] dbg_reg_x25 = cpuregs[25]; + wire [31:0] dbg_reg_x26 = cpuregs[26]; + wire [31:0] dbg_reg_x27 = cpuregs[27]; + wire [31:0] dbg_reg_x28 = cpuregs[28]; + wire [31:0] dbg_reg_x29 = cpuregs[29]; + wire [31:0] dbg_reg_x30 = cpuregs[30]; + wire [31:0] dbg_reg_x31 = cpuregs[31]; +`endif + + // Internal PCPI Cores + + wire pcpi_mul_wr; + wire [31:0] pcpi_mul_rd; + wire pcpi_mul_wait; + wire pcpi_mul_ready; + + wire pcpi_div_wr; + wire [31:0] pcpi_div_rd; + wire pcpi_div_wait; + wire pcpi_div_ready; + + reg pcpi_int_wr; + reg [31:0] pcpi_int_rd; + reg pcpi_int_wait; + reg pcpi_int_ready; + + generate if (ENABLE_FAST_MUL) begin + picorv32_pcpi_fast_mul pcpi_mul ( + .clk (clk ), + .resetn (resetn ), + .pcpi_valid(pcpi_valid ), + .pcpi_insn (pcpi_insn ), + .pcpi_rs1 (pcpi_rs1 ), + .pcpi_rs2 (pcpi_rs2 ), + .pcpi_wr (pcpi_mul_wr ), + .pcpi_rd (pcpi_mul_rd ), + .pcpi_wait (pcpi_mul_wait ), + .pcpi_ready(pcpi_mul_ready ) + ); + end else if (ENABLE_MUL) begin + picorv32_pcpi_mul pcpi_mul ( + .clk (clk ), + .resetn (resetn ), + .pcpi_valid(pcpi_valid ), + .pcpi_insn (pcpi_insn ), + .pcpi_rs1 (pcpi_rs1 ), + .pcpi_rs2 (pcpi_rs2 ), + .pcpi_wr (pcpi_mul_wr ), + .pcpi_rd (pcpi_mul_rd ), + .pcpi_wait (pcpi_mul_wait ), + .pcpi_ready(pcpi_mul_ready ) + ); + end else begin + assign pcpi_mul_wr = 0; + assign pcpi_mul_rd = 32'bx; + assign pcpi_mul_wait = 0; + assign pcpi_mul_ready = 0; + end endgenerate + + generate if (ENABLE_DIV) begin + picorv32_pcpi_div pcpi_div ( + .clk (clk ), + .resetn (resetn ), + .pcpi_valid(pcpi_valid ), + .pcpi_insn (pcpi_insn ), + .pcpi_rs1 (pcpi_rs1 ), + .pcpi_rs2 (pcpi_rs2 ), + .pcpi_wr (pcpi_div_wr ), + .pcpi_rd (pcpi_div_rd ), + .pcpi_wait (pcpi_div_wait ), + .pcpi_ready(pcpi_div_ready ) + ); + end else begin + assign pcpi_div_wr = 0; + assign pcpi_div_rd = 32'bx; + assign pcpi_div_wait = 0; + assign pcpi_div_ready = 0; + end endgenerate + + always @* begin + pcpi_int_wr = 0; + pcpi_int_rd = 32'bx; + pcpi_int_wait = |{ENABLE_PCPI && pcpi_wait, (ENABLE_MUL || ENABLE_FAST_MUL) && pcpi_mul_wait, ENABLE_DIV && pcpi_div_wait}; + pcpi_int_ready = |{ENABLE_PCPI && pcpi_ready, (ENABLE_MUL || ENABLE_FAST_MUL) && pcpi_mul_ready, ENABLE_DIV && pcpi_div_ready}; + + (* parallel_case *) + case (1'b1) + ENABLE_PCPI && pcpi_ready: begin + pcpi_int_wr = ENABLE_PCPI ? pcpi_wr : 0; + pcpi_int_rd = ENABLE_PCPI ? pcpi_rd : 0; + end + (ENABLE_MUL || ENABLE_FAST_MUL) && pcpi_mul_ready: begin + pcpi_int_wr = pcpi_mul_wr; + pcpi_int_rd = pcpi_mul_rd; + end + ENABLE_DIV && pcpi_div_ready: begin + pcpi_int_wr = pcpi_div_wr; + pcpi_int_rd = pcpi_div_rd; + end + endcase + end + + + // Memory Interface + + reg [1:0] mem_state; + reg [1:0] mem_wordsize; + reg [31:0] mem_rdata_word; + reg [31:0] mem_rdata_q; + reg mem_do_prefetch; + reg mem_do_rinst; + reg mem_do_rdata; + reg mem_do_wdata; + + wire mem_xfer; + reg mem_la_secondword, mem_la_firstword_reg, last_mem_valid; + wire mem_la_firstword = COMPRESSED_ISA && (mem_do_prefetch || mem_do_rinst) && next_pc[1] && !mem_la_secondword; + wire mem_la_firstword_xfer = COMPRESSED_ISA && mem_xfer && (!last_mem_valid ? mem_la_firstword : mem_la_firstword_reg); + + reg prefetched_high_word; + reg clear_prefetched_high_word; + reg [15:0] mem_16bit_buffer; + + wire [31:0] mem_rdata_latched_noshuffle; + wire [31:0] mem_rdata_latched; + + wire mem_la_use_prefetched_high_word = COMPRESSED_ISA && mem_la_firstword && prefetched_high_word && !clear_prefetched_high_word; + assign mem_xfer = (mem_valid && mem_ready) || (mem_la_use_prefetched_high_word && mem_do_rinst); + + wire mem_busy = |{mem_do_prefetch, mem_do_rinst, mem_do_rdata, mem_do_wdata}; + wire mem_done = resetn && ((mem_xfer && |mem_state && (mem_do_rinst || mem_do_rdata || mem_do_wdata)) || (&mem_state && mem_do_rinst)) && + (!mem_la_firstword || (~&mem_rdata_latched[1:0] && mem_xfer)); + + assign mem_la_write = resetn && !mem_state && mem_do_wdata; + assign mem_la_read = resetn && ((!mem_la_use_prefetched_high_word && !mem_state && (mem_do_rinst || mem_do_prefetch || mem_do_rdata)) || + (COMPRESSED_ISA && mem_xfer && (!last_mem_valid ? mem_la_firstword : mem_la_firstword_reg) && !mem_la_secondword && &mem_rdata_latched[1:0])); + assign mem_la_addr = (mem_do_prefetch || mem_do_rinst) ? {next_pc[31:2] + mem_la_firstword_xfer, 2'b00} : {reg_op1[31:2], 2'b00}; + + assign mem_rdata_latched_noshuffle = (mem_xfer || LATCHED_MEM_RDATA) ? mem_rdata : mem_rdata_q; + + assign mem_rdata_latched = COMPRESSED_ISA && mem_la_use_prefetched_high_word ? {16'bx, mem_16bit_buffer} : + COMPRESSED_ISA && mem_la_secondword ? {mem_rdata_latched_noshuffle[15:0], mem_16bit_buffer} : + COMPRESSED_ISA && mem_la_firstword ? {16'bx, mem_rdata_latched_noshuffle[31:16]} : mem_rdata_latched_noshuffle; + + always @(posedge clk) begin + if (!resetn) begin + mem_la_firstword_reg <= 0; + last_mem_valid <= 0; + end else begin + if (!last_mem_valid) + mem_la_firstword_reg <= mem_la_firstword; + last_mem_valid <= mem_valid && !mem_ready; + end + end + + always @* begin + (* full_case *) + case (mem_wordsize) + 0: begin + mem_la_wdata = reg_op2; + mem_la_wstrb = 4'b1111; + mem_rdata_word = mem_rdata; + end + 1: begin + mem_la_wdata = {2{reg_op2[15:0]}}; + mem_la_wstrb = reg_op1[1] ? 4'b1100 : 4'b0011; + case (reg_op1[1]) + 1'b0: mem_rdata_word = {16'b0, mem_rdata[15: 0]}; + 1'b1: mem_rdata_word = {16'b0, mem_rdata[31:16]}; + endcase + end + 2: begin + mem_la_wdata = {4{reg_op2[7:0]}}; + mem_la_wstrb = 4'b0001 << reg_op1[1:0]; + case (reg_op1[1:0]) + 2'b00: mem_rdata_word = {24'b0, mem_rdata[ 7: 0]}; + 2'b01: mem_rdata_word = {24'b0, mem_rdata[15: 8]}; + 2'b10: mem_rdata_word = {24'b0, mem_rdata[23:16]}; + 2'b11: mem_rdata_word = {24'b0, mem_rdata[31:24]}; + endcase + end + endcase + end + + always @(posedge clk) begin + if (mem_xfer) begin + mem_rdata_q <= COMPRESSED_ISA ? mem_rdata_latched : mem_rdata; + next_insn_opcode <= COMPRESSED_ISA ? mem_rdata_latched : mem_rdata; + end + + if (COMPRESSED_ISA && mem_done && (mem_do_prefetch || mem_do_rinst)) begin + case (mem_rdata_latched[1:0]) + 2'b00: begin // Quadrant 0 + case (mem_rdata_latched[15:13]) + 3'b000: begin // C.ADDI4SPN + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= {2'b0, mem_rdata_latched[10:7], mem_rdata_latched[12:11], mem_rdata_latched[5], mem_rdata_latched[6], 2'b00}; + end + 3'b010: begin // C.LW + mem_rdata_q[31:20] <= {5'b0, mem_rdata_latched[5], mem_rdata_latched[12:10], mem_rdata_latched[6], 2'b00}; + mem_rdata_q[14:12] <= 3'b 010; + end + 3'b 110: begin // C.SW + {mem_rdata_q[31:25], mem_rdata_q[11:7]} <= {5'b0, mem_rdata_latched[5], mem_rdata_latched[12:10], mem_rdata_latched[6], 2'b00}; + mem_rdata_q[14:12] <= 3'b 010; + end + endcase + end + 2'b01: begin // Quadrant 1 + case (mem_rdata_latched[15:13]) + 3'b 000: begin // C.ADDI + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= $signed({mem_rdata_latched[12], mem_rdata_latched[6:2]}); + end + 3'b 010: begin // C.LI + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= $signed({mem_rdata_latched[12], mem_rdata_latched[6:2]}); + end + 3'b 011: begin + if (mem_rdata_latched[11:7] == 2) begin // C.ADDI16SP + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= $signed({mem_rdata_latched[12], mem_rdata_latched[4:3], + mem_rdata_latched[5], mem_rdata_latched[2], mem_rdata_latched[6], 4'b 0000}); + end else begin // C.LUI + mem_rdata_q[31:12] <= $signed({mem_rdata_latched[12], mem_rdata_latched[6:2]}); + end + end + 3'b100: begin + if (mem_rdata_latched[11:10] == 2'b00) begin // C.SRLI + mem_rdata_q[31:25] <= 7'b0000000; + mem_rdata_q[14:12] <= 3'b 101; + end + if (mem_rdata_latched[11:10] == 2'b01) begin // C.SRAI + mem_rdata_q[31:25] <= 7'b0100000; + mem_rdata_q[14:12] <= 3'b 101; + end + if (mem_rdata_latched[11:10] == 2'b10) begin // C.ANDI + mem_rdata_q[14:12] <= 3'b111; + mem_rdata_q[31:20] <= $signed({mem_rdata_latched[12], mem_rdata_latched[6:2]}); + end + if (mem_rdata_latched[12:10] == 3'b011) begin // C.SUB, C.XOR, C.OR, C.AND + if (mem_rdata_latched[6:5] == 2'b00) mem_rdata_q[14:12] <= 3'b000; + if (mem_rdata_latched[6:5] == 2'b01) mem_rdata_q[14:12] <= 3'b100; + if (mem_rdata_latched[6:5] == 2'b10) mem_rdata_q[14:12] <= 3'b110; + if (mem_rdata_latched[6:5] == 2'b11) mem_rdata_q[14:12] <= 3'b111; + mem_rdata_q[31:25] <= mem_rdata_latched[6:5] == 2'b00 ? 7'b0100000 : 7'b0000000; + end + end + 3'b 110: begin // C.BEQZ + mem_rdata_q[14:12] <= 3'b000; + { mem_rdata_q[31], mem_rdata_q[7], mem_rdata_q[30:25], mem_rdata_q[11:8] } <= + $signed({mem_rdata_latched[12], mem_rdata_latched[6:5], mem_rdata_latched[2], + mem_rdata_latched[11:10], mem_rdata_latched[4:3]}); + end + 3'b 111: begin // C.BNEZ + mem_rdata_q[14:12] <= 3'b001; + { mem_rdata_q[31], mem_rdata_q[7], mem_rdata_q[30:25], mem_rdata_q[11:8] } <= + $signed({mem_rdata_latched[12], mem_rdata_latched[6:5], mem_rdata_latched[2], + mem_rdata_latched[11:10], mem_rdata_latched[4:3]}); + end + endcase + end + 2'b10: begin // Quadrant 2 + case (mem_rdata_latched[15:13]) + 3'b000: begin // C.SLLI + mem_rdata_q[31:25] <= 7'b0000000; + mem_rdata_q[14:12] <= 3'b 001; + end + 3'b010: begin // C.LWSP + mem_rdata_q[31:20] <= {4'b0, mem_rdata_latched[3:2], mem_rdata_latched[12], mem_rdata_latched[6:4], 2'b00}; + mem_rdata_q[14:12] <= 3'b 010; + end + 3'b100: begin + if (mem_rdata_latched[12] == 0 && mem_rdata_latched[6:2] == 0) begin // C.JR + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= 12'b0; + end + if (mem_rdata_latched[12] == 0 && mem_rdata_latched[6:2] != 0) begin // C.MV + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:25] <= 7'b0000000; + end + if (mem_rdata_latched[12] != 0 && mem_rdata_latched[11:7] != 0 && mem_rdata_latched[6:2] == 0) begin // C.JALR + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:20] <= 12'b0; + end + if (mem_rdata_latched[12] != 0 && mem_rdata_latched[6:2] != 0) begin // C.ADD + mem_rdata_q[14:12] <= 3'b000; + mem_rdata_q[31:25] <= 7'b0000000; + end + end + 3'b110: begin // C.SWSP + {mem_rdata_q[31:25], mem_rdata_q[11:7]} <= {4'b0, mem_rdata_latched[8:7], mem_rdata_latched[12:9], 2'b00}; + mem_rdata_q[14:12] <= 3'b 010; + end + endcase + end + endcase + end + end + + always @(posedge clk) begin + if (resetn && !trap) begin + if (mem_do_prefetch || mem_do_rinst || mem_do_rdata) + `assert(!mem_do_wdata); + + if (mem_do_prefetch || mem_do_rinst) + `assert(!mem_do_rdata); + + if (mem_do_rdata) + `assert(!mem_do_prefetch && !mem_do_rinst); + + if (mem_do_wdata) + `assert(!(mem_do_prefetch || mem_do_rinst || mem_do_rdata)); + + if (mem_state == 2 || mem_state == 3) + `assert(mem_valid || mem_do_prefetch); + end + end + + always @(posedge clk) begin + if (!resetn || trap) begin + if (!resetn) + mem_state <= 0; + if (!resetn || mem_ready) + mem_valid <= 0; + mem_la_secondword <= 0; + prefetched_high_word <= 0; + end else begin + if (mem_la_read || mem_la_write) begin + mem_addr <= mem_la_addr; + mem_wstrb <= mem_la_wstrb & {4{mem_la_write}}; + end + if (mem_la_write) begin + mem_wdata <= mem_la_wdata; + end + case (mem_state) + 0: begin + if (mem_do_prefetch || mem_do_rinst || mem_do_rdata) begin + mem_valid <= !mem_la_use_prefetched_high_word; + mem_instr <= mem_do_prefetch || mem_do_rinst; + mem_wstrb <= 0; + mem_state <= 1; + end + if (mem_do_wdata) begin + mem_valid <= 1; + mem_instr <= 0; + mem_state <= 2; + end + end + 1: begin + `assert(mem_wstrb == 0); + `assert(mem_do_prefetch || mem_do_rinst || mem_do_rdata); + `assert(mem_valid == !mem_la_use_prefetched_high_word); + `assert(mem_instr == (mem_do_prefetch || mem_do_rinst)); + if (mem_xfer) begin + if (COMPRESSED_ISA && mem_la_read) begin + mem_valid <= 1; + mem_la_secondword <= 1; + if (!mem_la_use_prefetched_high_word) + mem_16bit_buffer <= mem_rdata[31:16]; + end else begin + mem_valid <= 0; + mem_la_secondword <= 0; + if (COMPRESSED_ISA && !mem_do_rdata) begin + if (~&mem_rdata[1:0] || mem_la_secondword) begin + mem_16bit_buffer <= mem_rdata[31:16]; + prefetched_high_word <= 1; + end else begin + prefetched_high_word <= 0; + end + end + mem_state <= mem_do_rinst || mem_do_rdata ? 0 : 3; + end + end + end + 2: begin + `assert(mem_wstrb != 0); + `assert(mem_do_wdata); + if (mem_xfer) begin + mem_valid <= 0; + mem_state <= 0; + end + end + 3: begin + `assert(mem_wstrb == 0); + `assert(mem_do_prefetch); + if (mem_do_rinst) begin + mem_state <= 0; + end + end + endcase + end + + if (clear_prefetched_high_word) + prefetched_high_word <= 0; + end + + + // Instruction Decoder + + reg instr_lui, instr_auipc, instr_jal, instr_jalr; + reg instr_beq, instr_bne, instr_blt, instr_bge, instr_bltu, instr_bgeu; + reg instr_lb, instr_lh, instr_lw, instr_lbu, instr_lhu, instr_sb, instr_sh, instr_sw; + reg instr_addi, instr_slti, instr_sltiu, instr_xori, instr_ori, instr_andi, instr_slli, instr_srli, instr_srai; + reg instr_add, instr_sub, instr_sll, instr_slt, instr_sltu, instr_xor, instr_srl, instr_sra, instr_or, instr_and; + reg instr_rdcycle, instr_rdcycleh, instr_rdinstr, instr_rdinstrh, instr_ecall_ebreak; + reg instr_getq, instr_setq, instr_retirq, instr_maskirq, instr_waitirq, instr_timer; + wire instr_trap; + + reg [regindex_bits-1:0] decoded_rd, decoded_rs1, decoded_rs2; + reg [31:0] decoded_imm, decoded_imm_j; + reg decoder_trigger; + reg decoder_trigger_q; + reg decoder_pseudo_trigger; + reg decoder_pseudo_trigger_q; + reg compressed_instr; + + reg is_lui_auipc_jal; + reg is_lb_lh_lw_lbu_lhu; + reg is_slli_srli_srai; + reg is_jalr_addi_slti_sltiu_xori_ori_andi; + reg is_sb_sh_sw; + reg is_sll_srl_sra; + reg is_lui_auipc_jal_jalr_addi_add_sub; + reg is_slti_blt_slt; + reg is_sltiu_bltu_sltu; + reg is_beq_bne_blt_bge_bltu_bgeu; + reg is_lbu_lhu_lw; + reg is_alu_reg_imm; + reg is_alu_reg_reg; + reg is_compare; + + assign instr_trap = (CATCH_ILLINSN || WITH_PCPI) && !{instr_lui, instr_auipc, instr_jal, instr_jalr, + instr_beq, instr_bne, instr_blt, instr_bge, instr_bltu, instr_bgeu, + instr_lb, instr_lh, instr_lw, instr_lbu, instr_lhu, instr_sb, instr_sh, instr_sw, + instr_addi, instr_slti, instr_sltiu, instr_xori, instr_ori, instr_andi, instr_slli, instr_srli, instr_srai, + instr_add, instr_sub, instr_sll, instr_slt, instr_sltu, instr_xor, instr_srl, instr_sra, instr_or, instr_and, + instr_rdcycle, instr_rdcycleh, instr_rdinstr, instr_rdinstrh, + instr_getq, instr_setq, instr_retirq, instr_maskirq, instr_waitirq, instr_timer}; + + wire is_rdcycle_rdcycleh_rdinstr_rdinstrh; + assign is_rdcycle_rdcycleh_rdinstr_rdinstrh = |{instr_rdcycle, instr_rdcycleh, instr_rdinstr, instr_rdinstrh}; + + reg [63:0] new_ascii_instr; + `FORMAL_KEEP reg [63:0] dbg_ascii_instr; + `FORMAL_KEEP reg [31:0] dbg_insn_imm; + `FORMAL_KEEP reg [4:0] dbg_insn_rs1; + `FORMAL_KEEP reg [4:0] dbg_insn_rs2; + `FORMAL_KEEP reg [4:0] dbg_insn_rd; + `FORMAL_KEEP reg [31:0] dbg_rs1val; + `FORMAL_KEEP reg [31:0] dbg_rs2val; + `FORMAL_KEEP reg dbg_rs1val_valid; + `FORMAL_KEEP reg dbg_rs2val_valid; + + always @* begin + new_ascii_instr = ""; + + if (instr_lui) new_ascii_instr = "lui"; + if (instr_auipc) new_ascii_instr = "auipc"; + if (instr_jal) new_ascii_instr = "jal"; + if (instr_jalr) new_ascii_instr = "jalr"; + + if (instr_beq) new_ascii_instr = "beq"; + if (instr_bne) new_ascii_instr = "bne"; + if (instr_blt) new_ascii_instr = "blt"; + if (instr_bge) new_ascii_instr = "bge"; + if (instr_bltu) new_ascii_instr = "bltu"; + if (instr_bgeu) new_ascii_instr = "bgeu"; + + if (instr_lb) new_ascii_instr = "lb"; + if (instr_lh) new_ascii_instr = "lh"; + if (instr_lw) new_ascii_instr = "lw"; + if (instr_lbu) new_ascii_instr = "lbu"; + if (instr_lhu) new_ascii_instr = "lhu"; + if (instr_sb) new_ascii_instr = "sb"; + if (instr_sh) new_ascii_instr = "sh"; + if (instr_sw) new_ascii_instr = "sw"; + + if (instr_addi) new_ascii_instr = "addi"; + if (instr_slti) new_ascii_instr = "slti"; + if (instr_sltiu) new_ascii_instr = "sltiu"; + if (instr_xori) new_ascii_instr = "xori"; + if (instr_ori) new_ascii_instr = "ori"; + if (instr_andi) new_ascii_instr = "andi"; + if (instr_slli) new_ascii_instr = "slli"; + if (instr_srli) new_ascii_instr = "srli"; + if (instr_srai) new_ascii_instr = "srai"; + + if (instr_add) new_ascii_instr = "add"; + if (instr_sub) new_ascii_instr = "sub"; + if (instr_sll) new_ascii_instr = "sll"; + if (instr_slt) new_ascii_instr = "slt"; + if (instr_sltu) new_ascii_instr = "sltu"; + if (instr_xor) new_ascii_instr = "xor"; + if (instr_srl) new_ascii_instr = "srl"; + if (instr_sra) new_ascii_instr = "sra"; + if (instr_or) new_ascii_instr = "or"; + if (instr_and) new_ascii_instr = "and"; + + if (instr_rdcycle) new_ascii_instr = "rdcycle"; + if (instr_rdcycleh) new_ascii_instr = "rdcycleh"; + if (instr_rdinstr) new_ascii_instr = "rdinstr"; + if (instr_rdinstrh) new_ascii_instr = "rdinstrh"; + + if (instr_getq) new_ascii_instr = "getq"; + if (instr_setq) new_ascii_instr = "setq"; + if (instr_retirq) new_ascii_instr = "retirq"; + if (instr_maskirq) new_ascii_instr = "maskirq"; + if (instr_waitirq) new_ascii_instr = "waitirq"; + if (instr_timer) new_ascii_instr = "timer"; + end + + reg [63:0] q_ascii_instr; + reg [31:0] q_insn_imm; + reg [31:0] q_insn_opcode; + reg [4:0] q_insn_rs1; + reg [4:0] q_insn_rs2; + reg [4:0] q_insn_rd; + reg dbg_next; + + wire launch_next_insn; + reg dbg_valid_insn; + + reg [63:0] cached_ascii_instr; + reg [31:0] cached_insn_imm; + reg [31:0] cached_insn_opcode; + reg [4:0] cached_insn_rs1; + reg [4:0] cached_insn_rs2; + reg [4:0] cached_insn_rd; + + always @(posedge clk) begin + q_ascii_instr <= dbg_ascii_instr; + q_insn_imm <= dbg_insn_imm; + q_insn_opcode <= dbg_insn_opcode; + q_insn_rs1 <= dbg_insn_rs1; + q_insn_rs2 <= dbg_insn_rs2; + q_insn_rd <= dbg_insn_rd; + dbg_next <= launch_next_insn; + + if (!resetn || trap) + dbg_valid_insn <= 0; + else if (launch_next_insn) + dbg_valid_insn <= 1; + + if (decoder_trigger_q) begin + cached_ascii_instr <= new_ascii_instr; + cached_insn_imm <= decoded_imm; + if (&next_insn_opcode[1:0]) + cached_insn_opcode <= next_insn_opcode; + else + cached_insn_opcode <= {16'b0, next_insn_opcode[15:0]}; + cached_insn_rs1 <= decoded_rs1; + cached_insn_rs2 <= decoded_rs2; + cached_insn_rd <= decoded_rd; + end + + if (launch_next_insn) begin + dbg_insn_addr <= next_pc; + end + end + + always @* begin + dbg_ascii_instr = q_ascii_instr; + dbg_insn_imm = q_insn_imm; + dbg_insn_opcode = q_insn_opcode; + dbg_insn_rs1 = q_insn_rs1; + dbg_insn_rs2 = q_insn_rs2; + dbg_insn_rd = q_insn_rd; + + if (dbg_next) begin + if (decoder_pseudo_trigger_q) begin + dbg_ascii_instr = cached_ascii_instr; + dbg_insn_imm = cached_insn_imm; + dbg_insn_opcode = cached_insn_opcode; + dbg_insn_rs1 = cached_insn_rs1; + dbg_insn_rs2 = cached_insn_rs2; + dbg_insn_rd = cached_insn_rd; + end else begin + dbg_ascii_instr = new_ascii_instr; + if (&next_insn_opcode[1:0]) + dbg_insn_opcode = next_insn_opcode; + else + dbg_insn_opcode = {16'b0, next_insn_opcode[15:0]}; + dbg_insn_imm = decoded_imm; + dbg_insn_rs1 = decoded_rs1; + dbg_insn_rs2 = decoded_rs2; + dbg_insn_rd = decoded_rd; + end + end + end + +`ifdef DEBUGASM + always @(posedge clk) begin + if (dbg_next) begin + $display("debugasm %x %x %s", dbg_insn_addr, dbg_insn_opcode, dbg_ascii_instr ? dbg_ascii_instr : "*"); + end + end +`endif + +`ifdef DEBUG + always @(posedge clk) begin + if (dbg_next) begin + if (&dbg_insn_opcode[1:0]) + $display("DECODE: 0x%08x 0x%08x %-0s", dbg_insn_addr, dbg_insn_opcode, dbg_ascii_instr ? dbg_ascii_instr : "UNKNOWN"); + else + $display("DECODE: 0x%08x 0x%04x %-0s", dbg_insn_addr, dbg_insn_opcode[15:0], dbg_ascii_instr ? dbg_ascii_instr : "UNKNOWN"); + end + end +`endif + + always @(posedge clk) begin + is_lui_auipc_jal <= |{instr_lui, instr_auipc, instr_jal}; + is_lui_auipc_jal_jalr_addi_add_sub <= |{instr_lui, instr_auipc, instr_jal, instr_jalr, instr_addi, instr_add, instr_sub}; + is_slti_blt_slt <= |{instr_slti, instr_blt, instr_slt}; + is_sltiu_bltu_sltu <= |{instr_sltiu, instr_bltu, instr_sltu}; + is_lbu_lhu_lw <= |{instr_lbu, instr_lhu, instr_lw}; + is_compare <= |{is_beq_bne_blt_bge_bltu_bgeu, instr_slti, instr_slt, instr_sltiu, instr_sltu}; + + if (mem_do_rinst && mem_done) begin + instr_lui <= mem_rdata_latched[6:0] == 7'b0110111; + instr_auipc <= mem_rdata_latched[6:0] == 7'b0010111; + instr_jal <= mem_rdata_latched[6:0] == 7'b1101111; + instr_jalr <= mem_rdata_latched[6:0] == 7'b1100111 && mem_rdata_latched[14:12] == 3'b000; + instr_retirq <= mem_rdata_latched[6:0] == 7'b0001011 && mem_rdata_latched[31:25] == 7'b0000010 && ENABLE_IRQ; + instr_waitirq <= mem_rdata_latched[6:0] == 7'b0001011 && mem_rdata_latched[31:25] == 7'b0000100 && ENABLE_IRQ; + + is_beq_bne_blt_bge_bltu_bgeu <= mem_rdata_latched[6:0] == 7'b1100011; + is_lb_lh_lw_lbu_lhu <= mem_rdata_latched[6:0] == 7'b0000011; + is_sb_sh_sw <= mem_rdata_latched[6:0] == 7'b0100011; + is_alu_reg_imm <= mem_rdata_latched[6:0] == 7'b0010011; + is_alu_reg_reg <= mem_rdata_latched[6:0] == 7'b0110011; + + { decoded_imm_j[31:20], decoded_imm_j[10:1], decoded_imm_j[11], decoded_imm_j[19:12], decoded_imm_j[0] } <= $signed({mem_rdata_latched[31:12], 1'b0}); + + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= mem_rdata_latched[19:15]; + decoded_rs2 <= mem_rdata_latched[24:20]; + + if (mem_rdata_latched[6:0] == 7'b0001011 && mem_rdata_latched[31:25] == 7'b0000000 && ENABLE_IRQ && ENABLE_IRQ_QREGS) + decoded_rs1[regindex_bits-1] <= 1; // instr_getq + + if (mem_rdata_latched[6:0] == 7'b0001011 && mem_rdata_latched[31:25] == 7'b0000010 && ENABLE_IRQ) + decoded_rs1 <= ENABLE_IRQ_QREGS ? irqregs_offset : 3; // instr_retirq + + compressed_instr <= 0; + if (COMPRESSED_ISA && mem_rdata_latched[1:0] != 2'b11) begin + compressed_instr <= 1; + decoded_rd <= 0; + decoded_rs1 <= 0; + decoded_rs2 <= 0; + + { decoded_imm_j[31:11], decoded_imm_j[4], decoded_imm_j[9:8], decoded_imm_j[10], decoded_imm_j[6], + decoded_imm_j[7], decoded_imm_j[3:1], decoded_imm_j[5], decoded_imm_j[0] } <= $signed({mem_rdata_latched[12:2], 1'b0}); + + case (mem_rdata_latched[1:0]) + 2'b00: begin // Quadrant 0 + case (mem_rdata_latched[15:13]) + 3'b000: begin // C.ADDI4SPN + is_alu_reg_imm <= |mem_rdata_latched[12:5]; + decoded_rs1 <= 2; + decoded_rd <= 8 + mem_rdata_latched[4:2]; + end + 3'b010: begin // C.LW + is_lb_lh_lw_lbu_lhu <= 1; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rd <= 8 + mem_rdata_latched[4:2]; + end + 3'b110: begin // C.SW + is_sb_sh_sw <= 1; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rs2 <= 8 + mem_rdata_latched[4:2]; + end + endcase + end + 2'b01: begin // Quadrant 1 + case (mem_rdata_latched[15:13]) + 3'b000: begin // C.NOP / C.ADDI + is_alu_reg_imm <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= mem_rdata_latched[11:7]; + end + 3'b001: begin // C.JAL + instr_jal <= 1; + decoded_rd <= 1; + end + 3'b 010: begin // C.LI + is_alu_reg_imm <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= 0; + end + 3'b 011: begin + if (mem_rdata_latched[12] || mem_rdata_latched[6:2]) begin + if (mem_rdata_latched[11:7] == 2) begin // C.ADDI16SP + is_alu_reg_imm <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= mem_rdata_latched[11:7]; + end else begin // C.LUI + instr_lui <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= 0; + end + end + end + 3'b100: begin + if (!mem_rdata_latched[11] && !mem_rdata_latched[12]) begin // C.SRLI, C.SRAI + is_alu_reg_imm <= 1; + decoded_rd <= 8 + mem_rdata_latched[9:7]; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rs2 <= {mem_rdata_latched[12], mem_rdata_latched[6:2]}; + end + if (mem_rdata_latched[11:10] == 2'b10) begin // C.ANDI + is_alu_reg_imm <= 1; + decoded_rd <= 8 + mem_rdata_latched[9:7]; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + end + if (mem_rdata_latched[12:10] == 3'b011) begin // C.SUB, C.XOR, C.OR, C.AND + is_alu_reg_reg <= 1; + decoded_rd <= 8 + mem_rdata_latched[9:7]; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rs2 <= 8 + mem_rdata_latched[4:2]; + end + end + 3'b101: begin // C.J + instr_jal <= 1; + end + 3'b110: begin // C.BEQZ + is_beq_bne_blt_bge_bltu_bgeu <= 1; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rs2 <= 0; + end + 3'b111: begin // C.BNEZ + is_beq_bne_blt_bge_bltu_bgeu <= 1; + decoded_rs1 <= 8 + mem_rdata_latched[9:7]; + decoded_rs2 <= 0; + end + endcase + end + 2'b10: begin // Quadrant 2 + case (mem_rdata_latched[15:13]) + 3'b000: begin // C.SLLI + if (!mem_rdata_latched[12]) begin + is_alu_reg_imm <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= mem_rdata_latched[11:7]; + decoded_rs2 <= {mem_rdata_latched[12], mem_rdata_latched[6:2]}; + end + end + 3'b010: begin // C.LWSP + if (mem_rdata_latched[11:7]) begin + is_lb_lh_lw_lbu_lhu <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= 2; + end + end + 3'b100: begin + if (mem_rdata_latched[12] == 0 && mem_rdata_latched[11:7] != 0 && mem_rdata_latched[6:2] == 0) begin // C.JR + instr_jalr <= 1; + decoded_rd <= 0; + decoded_rs1 <= mem_rdata_latched[11:7]; + end + if (mem_rdata_latched[12] == 0 && mem_rdata_latched[6:2] != 0) begin // C.MV + is_alu_reg_reg <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= 0; + decoded_rs2 <= mem_rdata_latched[6:2]; + end + if (mem_rdata_latched[12] != 0 && mem_rdata_latched[11:7] != 0 && mem_rdata_latched[6:2] == 0) begin // C.JALR + instr_jalr <= 1; + decoded_rd <= 1; + decoded_rs1 <= mem_rdata_latched[11:7]; + end + if (mem_rdata_latched[12] != 0 && mem_rdata_latched[6:2] != 0) begin // C.ADD + is_alu_reg_reg <= 1; + decoded_rd <= mem_rdata_latched[11:7]; + decoded_rs1 <= mem_rdata_latched[11:7]; + decoded_rs2 <= mem_rdata_latched[6:2]; + end + end + 3'b110: begin // C.SWSP + is_sb_sh_sw <= 1; + decoded_rs1 <= 2; + decoded_rs2 <= mem_rdata_latched[6:2]; + end + endcase + end + endcase + end + end + + if (decoder_trigger && !decoder_pseudo_trigger) begin + pcpi_insn <= WITH_PCPI ? mem_rdata_q : 'bx; + + instr_beq <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b000; + instr_bne <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b001; + instr_blt <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b100; + instr_bge <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b101; + instr_bltu <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b110; + instr_bgeu <= is_beq_bne_blt_bge_bltu_bgeu && mem_rdata_q[14:12] == 3'b111; + + instr_lb <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b000; + instr_lh <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b001; + instr_lw <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b010; + instr_lbu <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b100; + instr_lhu <= is_lb_lh_lw_lbu_lhu && mem_rdata_q[14:12] == 3'b101; + + instr_sb <= is_sb_sh_sw && mem_rdata_q[14:12] == 3'b000; + instr_sh <= is_sb_sh_sw && mem_rdata_q[14:12] == 3'b001; + instr_sw <= is_sb_sh_sw && mem_rdata_q[14:12] == 3'b010; + + instr_addi <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b000; + instr_slti <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b010; + instr_sltiu <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b011; + instr_xori <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b100; + instr_ori <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b110; + instr_andi <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b111; + + instr_slli <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b001 && mem_rdata_q[31:25] == 7'b0000000; + instr_srli <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0000000; + instr_srai <= is_alu_reg_imm && mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0100000; + + instr_add <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b000 && mem_rdata_q[31:25] == 7'b0000000; + instr_sub <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b000 && mem_rdata_q[31:25] == 7'b0100000; + instr_sll <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b001 && mem_rdata_q[31:25] == 7'b0000000; + instr_slt <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b010 && mem_rdata_q[31:25] == 7'b0000000; + instr_sltu <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b011 && mem_rdata_q[31:25] == 7'b0000000; + instr_xor <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b100 && mem_rdata_q[31:25] == 7'b0000000; + instr_srl <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0000000; + instr_sra <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0100000; + instr_or <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b110 && mem_rdata_q[31:25] == 7'b0000000; + instr_and <= is_alu_reg_reg && mem_rdata_q[14:12] == 3'b111 && mem_rdata_q[31:25] == 7'b0000000; + + instr_rdcycle <= ((mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11000000000000000010) || + (mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11000000000100000010)) && ENABLE_COUNTERS; + instr_rdcycleh <= ((mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11001000000000000010) || + (mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11001000000100000010)) && ENABLE_COUNTERS && ENABLE_COUNTERS64; + instr_rdinstr <= (mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11000000001000000010) && ENABLE_COUNTERS; + instr_rdinstrh <= (mem_rdata_q[6:0] == 7'b1110011 && mem_rdata_q[31:12] == 'b11001000001000000010) && ENABLE_COUNTERS && ENABLE_COUNTERS64; + + instr_ecall_ebreak <= ((mem_rdata_q[6:0] == 7'b1110011 && !mem_rdata_q[31:21] && !mem_rdata_q[19:7]) || + (COMPRESSED_ISA && mem_rdata_q[15:0] == 16'h9002)); + + instr_getq <= mem_rdata_q[6:0] == 7'b0001011 && mem_rdata_q[31:25] == 7'b0000000 && ENABLE_IRQ && ENABLE_IRQ_QREGS; + instr_setq <= mem_rdata_q[6:0] == 7'b0001011 && mem_rdata_q[31:25] == 7'b0000001 && ENABLE_IRQ && ENABLE_IRQ_QREGS; + instr_maskirq <= mem_rdata_q[6:0] == 7'b0001011 && mem_rdata_q[31:25] == 7'b0000011 && ENABLE_IRQ; + instr_timer <= mem_rdata_q[6:0] == 7'b0001011 && mem_rdata_q[31:25] == 7'b0000101 && ENABLE_IRQ && ENABLE_IRQ_TIMER; + + is_slli_srli_srai <= is_alu_reg_imm && |{ + mem_rdata_q[14:12] == 3'b001 && mem_rdata_q[31:25] == 7'b0000000, + mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0000000, + mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0100000 + }; + + is_jalr_addi_slti_sltiu_xori_ori_andi <= instr_jalr || is_alu_reg_imm && |{ + mem_rdata_q[14:12] == 3'b000, + mem_rdata_q[14:12] == 3'b010, + mem_rdata_q[14:12] == 3'b011, + mem_rdata_q[14:12] == 3'b100, + mem_rdata_q[14:12] == 3'b110, + mem_rdata_q[14:12] == 3'b111 + }; + + is_sll_srl_sra <= is_alu_reg_reg && |{ + mem_rdata_q[14:12] == 3'b001 && mem_rdata_q[31:25] == 7'b0000000, + mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0000000, + mem_rdata_q[14:12] == 3'b101 && mem_rdata_q[31:25] == 7'b0100000 + }; + + is_lui_auipc_jal_jalr_addi_add_sub <= 0; + is_compare <= 0; + + (* parallel_case *) + case (1'b1) + instr_jal: + decoded_imm <= decoded_imm_j; + |{instr_lui, instr_auipc}: + decoded_imm <= mem_rdata_q[31:12] << 12; + |{instr_jalr, is_lb_lh_lw_lbu_lhu, is_alu_reg_imm}: + decoded_imm <= $signed(mem_rdata_q[31:20]); + is_beq_bne_blt_bge_bltu_bgeu: + decoded_imm <= $signed({mem_rdata_q[31], mem_rdata_q[7], mem_rdata_q[30:25], mem_rdata_q[11:8], 1'b0}); + is_sb_sh_sw: + decoded_imm <= $signed({mem_rdata_q[31:25], mem_rdata_q[11:7]}); + default: + decoded_imm <= 1'bx; + endcase + end + + if (!resetn) begin + is_beq_bne_blt_bge_bltu_bgeu <= 0; + is_compare <= 0; + + instr_beq <= 0; + instr_bne <= 0; + instr_blt <= 0; + instr_bge <= 0; + instr_bltu <= 0; + instr_bgeu <= 0; + + instr_addi <= 0; + instr_slti <= 0; + instr_sltiu <= 0; + instr_xori <= 0; + instr_ori <= 0; + instr_andi <= 0; + + instr_add <= 0; + instr_sub <= 0; + instr_sll <= 0; + instr_slt <= 0; + instr_sltu <= 0; + instr_xor <= 0; + instr_srl <= 0; + instr_sra <= 0; + instr_or <= 0; + instr_and <= 0; + end + end + + + // Main State Machine + + localparam cpu_state_trap = 8'b10000000; + localparam cpu_state_fetch = 8'b01000000; + localparam cpu_state_ld_rs1 = 8'b00100000; + localparam cpu_state_ld_rs2 = 8'b00010000; + localparam cpu_state_exec = 8'b00001000; + localparam cpu_state_shift = 8'b00000100; + localparam cpu_state_stmem = 8'b00000010; + localparam cpu_state_ldmem = 8'b00000001; + + reg [7:0] cpu_state; + reg [1:0] irq_state; + + `FORMAL_KEEP reg [127:0] dbg_ascii_state; + + always @* begin + dbg_ascii_state = ""; + if (cpu_state == cpu_state_trap) dbg_ascii_state = "trap"; + if (cpu_state == cpu_state_fetch) dbg_ascii_state = "fetch"; + if (cpu_state == cpu_state_ld_rs1) dbg_ascii_state = "ld_rs1"; + if (cpu_state == cpu_state_ld_rs2) dbg_ascii_state = "ld_rs2"; + if (cpu_state == cpu_state_exec) dbg_ascii_state = "exec"; + if (cpu_state == cpu_state_shift) dbg_ascii_state = "shift"; + if (cpu_state == cpu_state_stmem) dbg_ascii_state = "stmem"; + if (cpu_state == cpu_state_ldmem) dbg_ascii_state = "ldmem"; + end + + reg set_mem_do_rinst; + reg set_mem_do_rdata; + reg set_mem_do_wdata; + + reg latched_store; + reg latched_stalu; + reg latched_branch; + reg latched_compr; + reg latched_trace; + reg latched_is_lu; + reg latched_is_lh; + reg latched_is_lb; + reg [regindex_bits-1:0] latched_rd; + + reg [31:0] current_pc; + assign next_pc = latched_store && latched_branch ? reg_out & ~1 : reg_next_pc; + + reg [3:0] pcpi_timeout_counter; + reg pcpi_timeout; + + reg [31:0] next_irq_pending; + reg do_waitirq; + + reg [31:0] alu_out, alu_out_q; + reg alu_out_0, alu_out_0_q; + reg alu_wait, alu_wait_2; + + reg [31:0] alu_add_sub; + reg [31:0] alu_shl, alu_shr; + reg alu_eq, alu_ltu, alu_lts; + + generate if (TWO_CYCLE_ALU) begin + always @(posedge clk) begin + alu_add_sub <= instr_sub ? reg_op1 - reg_op2 : reg_op1 + reg_op2; + alu_eq <= reg_op1 == reg_op2; + alu_lts <= $signed(reg_op1) < $signed(reg_op2); + alu_ltu <= reg_op1 < reg_op2; + alu_shl <= reg_op1 << reg_op2[4:0]; + alu_shr <= $signed({instr_sra || instr_srai ? reg_op1[31] : 1'b0, reg_op1}) >>> reg_op2[4:0]; + end + end else begin + always @* begin + alu_add_sub = instr_sub ? reg_op1 - reg_op2 : reg_op1 + reg_op2; + alu_eq = reg_op1 == reg_op2; + alu_lts = $signed(reg_op1) < $signed(reg_op2); + alu_ltu = reg_op1 < reg_op2; + alu_shl = reg_op1 << reg_op2[4:0]; + alu_shr = $signed({instr_sra || instr_srai ? reg_op1[31] : 1'b0, reg_op1}) >>> reg_op2[4:0]; + end + end endgenerate + + always @* begin + alu_out_0 = 'bx; + (* parallel_case, full_case *) + case (1'b1) + instr_beq: + alu_out_0 = alu_eq; + instr_bne: + alu_out_0 = !alu_eq; + instr_bge: + alu_out_0 = !alu_lts; + instr_bgeu: + alu_out_0 = !alu_ltu; + is_slti_blt_slt && (!TWO_CYCLE_COMPARE || !{instr_beq,instr_bne,instr_bge,instr_bgeu}): + alu_out_0 = alu_lts; + is_sltiu_bltu_sltu && (!TWO_CYCLE_COMPARE || !{instr_beq,instr_bne,instr_bge,instr_bgeu}): + alu_out_0 = alu_ltu; + endcase + + alu_out = 'bx; + (* parallel_case, full_case *) + case (1'b1) + is_lui_auipc_jal_jalr_addi_add_sub: + alu_out = alu_add_sub; + is_compare: + alu_out = alu_out_0; + instr_xori || instr_xor: + alu_out = reg_op1 ^ reg_op2; + instr_ori || instr_or: + alu_out = reg_op1 | reg_op2; + instr_andi || instr_and: + alu_out = reg_op1 & reg_op2; + BARREL_SHIFTER && (instr_sll || instr_slli): + alu_out = alu_shl; + BARREL_SHIFTER && (instr_srl || instr_srli || instr_sra || instr_srai): + alu_out = alu_shr; + endcase + +`ifdef RISCV_FORMAL_BLACKBOX_ALU + alu_out_0 = $anyseq; + alu_out = $anyseq; +`endif + end + + reg clear_prefetched_high_word_q; + always @(posedge clk) clear_prefetched_high_word_q <= clear_prefetched_high_word; + + always @* begin + clear_prefetched_high_word = clear_prefetched_high_word_q; + if (!prefetched_high_word) + clear_prefetched_high_word = 0; + if (latched_branch || irq_state || !resetn) + clear_prefetched_high_word = COMPRESSED_ISA; + end + + reg cpuregs_write; + reg [31:0] cpuregs_wrdata; + reg [31:0] cpuregs_rs1; + reg [31:0] cpuregs_rs2; + reg [regindex_bits-1:0] decoded_rs; + + always @* begin + cpuregs_write = 0; + cpuregs_wrdata = 'bx; + + if (cpu_state == cpu_state_fetch) begin + (* parallel_case *) + case (1'b1) + latched_branch: begin + cpuregs_wrdata = reg_pc + (latched_compr ? 2 : 4); + cpuregs_write = 1; + end + latched_store && !latched_branch: begin + cpuregs_wrdata = latched_stalu ? alu_out_q : reg_out; + cpuregs_write = 1; + end + ENABLE_IRQ && irq_state[0]: begin + cpuregs_wrdata = reg_next_pc | latched_compr; + cpuregs_write = 1; + end + ENABLE_IRQ && irq_state[1]: begin + cpuregs_wrdata = irq_pending & ~irq_mask; + cpuregs_write = 1; + end + endcase + end + end + +`ifndef PICORV32_REGS + always @(posedge clk) begin + if (resetn && cpuregs_write && latched_rd) +`ifdef PICORV32_TESTBUG_001 + cpuregs[latched_rd ^ 1] <= cpuregs_wrdata; +`elsif PICORV32_TESTBUG_002 + cpuregs[latched_rd] <= cpuregs_wrdata ^ 1; +`else + cpuregs[latched_rd] <= cpuregs_wrdata; +`endif + end + + always @* begin + decoded_rs = 'bx; + if (ENABLE_REGS_DUALPORT) begin +`ifndef RISCV_FORMAL_BLACKBOX_REGS + cpuregs_rs1 = decoded_rs1 ? cpuregs[decoded_rs1] : 0; + cpuregs_rs2 = decoded_rs2 ? cpuregs[decoded_rs2] : 0; +`else + cpuregs_rs1 = decoded_rs1 ? $anyseq : 0; + cpuregs_rs2 = decoded_rs2 ? $anyseq : 0; +`endif + end else begin + decoded_rs = (cpu_state == cpu_state_ld_rs2) ? decoded_rs2 : decoded_rs1; +`ifndef RISCV_FORMAL_BLACKBOX_REGS + cpuregs_rs1 = decoded_rs ? cpuregs[decoded_rs] : 0; +`else + cpuregs_rs1 = decoded_rs ? $anyseq : 0; +`endif + cpuregs_rs2 = cpuregs_rs1; + end + end +`else + wire[31:0] cpuregs_rdata1; + wire[31:0] cpuregs_rdata2; + + wire [5:0] cpuregs_waddr = latched_rd; + wire [5:0] cpuregs_raddr1 = ENABLE_REGS_DUALPORT ? decoded_rs1 : decoded_rs; + wire [5:0] cpuregs_raddr2 = ENABLE_REGS_DUALPORT ? decoded_rs2 : 0; + + `PICORV32_REGS cpuregs ( + .clk(clk), + .wen(resetn && cpuregs_write && latched_rd), + .waddr(cpuregs_waddr), + .raddr1(cpuregs_raddr1), + .raddr2(cpuregs_raddr2), + .wdata(cpuregs_wrdata), + .rdata1(cpuregs_rdata1), + .rdata2(cpuregs_rdata2) + ); + + always @* begin + decoded_rs = 'bx; + if (ENABLE_REGS_DUALPORT) begin + cpuregs_rs1 = decoded_rs1 ? cpuregs_rdata1 : 0; + cpuregs_rs2 = decoded_rs2 ? cpuregs_rdata2 : 0; + end else begin + decoded_rs = (cpu_state == cpu_state_ld_rs2) ? decoded_rs2 : decoded_rs1; + cpuregs_rs1 = decoded_rs ? cpuregs_rdata1 : 0; + cpuregs_rs2 = cpuregs_rs1; + end + end +`endif + + assign launch_next_insn = cpu_state == cpu_state_fetch && decoder_trigger && (!ENABLE_IRQ || irq_delay || irq_active || !(irq_pending & ~irq_mask)); + + always @(posedge clk) begin + trap <= 0; + reg_sh <= 'bx; + reg_out <= 'bx; + set_mem_do_rinst = 0; + set_mem_do_rdata = 0; + set_mem_do_wdata = 0; + + alu_out_0_q <= alu_out_0; + alu_out_q <= alu_out; + + alu_wait <= 0; + alu_wait_2 <= 0; + + if (launch_next_insn) begin + dbg_rs1val <= 'bx; + dbg_rs2val <= 'bx; + dbg_rs1val_valid <= 0; + dbg_rs2val_valid <= 0; + end + + if (WITH_PCPI && CATCH_ILLINSN) begin + if (resetn && pcpi_valid && !pcpi_int_wait) begin + if (pcpi_timeout_counter) + pcpi_timeout_counter <= pcpi_timeout_counter - 1; + end else + pcpi_timeout_counter <= ~0; + pcpi_timeout <= !pcpi_timeout_counter; + end + + if (ENABLE_COUNTERS) begin + count_cycle <= resetn ? count_cycle + 1 : 0; + if (!ENABLE_COUNTERS64) count_cycle[63:32] <= 0; + end else begin + count_cycle <= 'bx; + count_instr <= 'bx; + end + + next_irq_pending = ENABLE_IRQ ? irq_pending & LATCHED_IRQ : 'bx; + + if (ENABLE_IRQ && ENABLE_IRQ_TIMER && timer) begin + timer <= timer - 1; + end + + decoder_trigger <= mem_do_rinst && mem_done; + decoder_trigger_q <= decoder_trigger; + decoder_pseudo_trigger <= 0; + decoder_pseudo_trigger_q <= decoder_pseudo_trigger; + do_waitirq <= 0; + + trace_valid <= 0; + + if (!ENABLE_TRACE) + trace_data <= 'bx; + + if (!resetn) begin + reg_pc <= PROGADDR_RESET; + reg_next_pc <= PROGADDR_RESET; + if (ENABLE_COUNTERS) + count_instr <= 0; + latched_store <= 0; + latched_stalu <= 0; + latched_branch <= 0; + latched_trace <= 0; + latched_is_lu <= 0; + latched_is_lh <= 0; + latched_is_lb <= 0; + pcpi_valid <= 0; + pcpi_timeout <= 0; + irq_active <= 0; + irq_delay <= 0; + irq_mask <= ~0; + next_irq_pending = 0; + irq_state <= 0; + eoi <= 0; + timer <= 0; + if (~STACKADDR) begin + latched_store <= 1; + latched_rd <= 2; + reg_out <= STACKADDR; + end + cpu_state <= cpu_state_fetch; + end else + (* parallel_case, full_case *) + case (cpu_state) + cpu_state_trap: begin + trap <= 1; + end + + cpu_state_fetch: begin + mem_do_rinst <= !decoder_trigger && !do_waitirq; + mem_wordsize <= 0; + + current_pc = reg_next_pc; + + (* parallel_case *) + case (1'b1) + latched_branch: begin + current_pc = latched_store ? (latched_stalu ? alu_out_q : reg_out) & ~1 : reg_next_pc; + `debug($display("ST_RD: %2d 0x%08x, BRANCH 0x%08x", latched_rd, reg_pc + (latched_compr ? 2 : 4), current_pc);) + end + latched_store && !latched_branch: begin + `debug($display("ST_RD: %2d 0x%08x", latched_rd, latched_stalu ? alu_out_q : reg_out);) + end + ENABLE_IRQ && irq_state[0]: begin + current_pc = PROGADDR_IRQ; + irq_active <= 1; + mem_do_rinst <= 1; + end + ENABLE_IRQ && irq_state[1]: begin + eoi <= irq_pending & ~irq_mask; + next_irq_pending = next_irq_pending & irq_mask; + end + endcase + + if (ENABLE_TRACE && latched_trace) begin + latched_trace <= 0; + trace_valid <= 1; + if (latched_branch) + trace_data <= (irq_active ? TRACE_IRQ : 0) | TRACE_BRANCH | (current_pc & 32'hfffffffe); + else + trace_data <= (irq_active ? TRACE_IRQ : 0) | (latched_stalu ? alu_out_q : reg_out); + end + + reg_pc <= current_pc; + reg_next_pc <= current_pc; + + latched_store <= 0; + latched_stalu <= 0; + latched_branch <= 0; + latched_is_lu <= 0; + latched_is_lh <= 0; + latched_is_lb <= 0; + latched_rd <= decoded_rd; + latched_compr <= compressed_instr; + + if (ENABLE_IRQ && ((decoder_trigger && !irq_active && !irq_delay && |(irq_pending & ~irq_mask)) || irq_state)) begin + irq_state <= + irq_state == 2'b00 ? 2'b01 : + irq_state == 2'b01 ? 2'b10 : 2'b00; + latched_compr <= latched_compr; + if (ENABLE_IRQ_QREGS) + latched_rd <= irqregs_offset | irq_state[0]; + else + latched_rd <= irq_state[0] ? 4 : 3; + end else + if (ENABLE_IRQ && (decoder_trigger || do_waitirq) && instr_waitirq) begin + if (irq_pending) begin + latched_store <= 1; + reg_out <= irq_pending; + reg_next_pc <= current_pc + (compressed_instr ? 2 : 4); + mem_do_rinst <= 1; + end else + do_waitirq <= 1; + end else + if (decoder_trigger) begin + `debug($display("-- %-0t", $time);) + irq_delay <= irq_active; + reg_next_pc <= current_pc + (compressed_instr ? 2 : 4); + if (ENABLE_TRACE) + latched_trace <= 1; + if (ENABLE_COUNTERS) begin + count_instr <= count_instr + 1; + if (!ENABLE_COUNTERS64) count_instr[63:32] <= 0; + end + if (instr_jal) begin + mem_do_rinst <= 1; + reg_next_pc <= current_pc + decoded_imm_j; + latched_branch <= 1; + end else begin + mem_do_rinst <= 0; + mem_do_prefetch <= !instr_jalr && !instr_retirq; + cpu_state <= cpu_state_ld_rs1; + end + end + end + + cpu_state_ld_rs1: begin + reg_op1 <= 'bx; + reg_op2 <= 'bx; + + (* parallel_case *) + case (1'b1) + (CATCH_ILLINSN || WITH_PCPI) && instr_trap: begin + if (WITH_PCPI) begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_op1 <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + if (ENABLE_REGS_DUALPORT) begin + pcpi_valid <= 1; + `debug($display("LD_RS2: %2d 0x%08x", decoded_rs2, cpuregs_rs2);) + reg_sh <= cpuregs_rs2; + reg_op2 <= cpuregs_rs2; + dbg_rs2val <= cpuregs_rs2; + dbg_rs2val_valid <= 1; + if (pcpi_int_ready) begin + mem_do_rinst <= 1; + pcpi_valid <= 0; + reg_out <= pcpi_int_rd; + latched_store <= pcpi_int_wr; + cpu_state <= cpu_state_fetch; + end else + if (CATCH_ILLINSN && (pcpi_timeout || instr_ecall_ebreak)) begin + pcpi_valid <= 0; + `debug($display("EBREAK OR UNSUPPORTED INSN AT 0x%08x", reg_pc);) + if (ENABLE_IRQ && !irq_mask[irq_ebreak] && !irq_active) begin + next_irq_pending[irq_ebreak] = 1; + cpu_state <= cpu_state_fetch; + end else + cpu_state <= cpu_state_trap; + end + end else begin + cpu_state <= cpu_state_ld_rs2; + end + end else begin + `debug($display("EBREAK OR UNSUPPORTED INSN AT 0x%08x", reg_pc);) + if (ENABLE_IRQ && !irq_mask[irq_ebreak] && !irq_active) begin + next_irq_pending[irq_ebreak] = 1; + cpu_state <= cpu_state_fetch; + end else + cpu_state <= cpu_state_trap; + end + end + ENABLE_COUNTERS && is_rdcycle_rdcycleh_rdinstr_rdinstrh: begin + (* parallel_case, full_case *) + case (1'b1) + instr_rdcycle: + reg_out <= count_cycle[31:0]; + instr_rdcycleh && ENABLE_COUNTERS64: + reg_out <= count_cycle[63:32]; + instr_rdinstr: + reg_out <= count_instr[31:0]; + instr_rdinstrh && ENABLE_COUNTERS64: + reg_out <= count_instr[63:32]; + endcase + latched_store <= 1; + cpu_state <= cpu_state_fetch; + end + is_lui_auipc_jal: begin + reg_op1 <= instr_lui ? 0 : reg_pc; + reg_op2 <= decoded_imm; + if (TWO_CYCLE_ALU) + alu_wait <= 1; + else + mem_do_rinst <= mem_do_prefetch; + cpu_state <= cpu_state_exec; + end + ENABLE_IRQ && ENABLE_IRQ_QREGS && instr_getq: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_out <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + latched_store <= 1; + cpu_state <= cpu_state_fetch; + end + ENABLE_IRQ && ENABLE_IRQ_QREGS && instr_setq: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_out <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + latched_rd <= latched_rd | irqregs_offset; + latched_store <= 1; + cpu_state <= cpu_state_fetch; + end + ENABLE_IRQ && instr_retirq: begin + eoi <= 0; + irq_active <= 0; + latched_branch <= 1; + latched_store <= 1; + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_out <= CATCH_MISALIGN ? (cpuregs_rs1 & 32'h fffffffe) : cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + cpu_state <= cpu_state_fetch; + end + ENABLE_IRQ && instr_maskirq: begin + latched_store <= 1; + reg_out <= irq_mask; + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + irq_mask <= cpuregs_rs1 | MASKED_IRQ; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + cpu_state <= cpu_state_fetch; + end + ENABLE_IRQ && ENABLE_IRQ_TIMER && instr_timer: begin + latched_store <= 1; + reg_out <= timer; + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + timer <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + cpu_state <= cpu_state_fetch; + end + is_lb_lh_lw_lbu_lhu && !instr_trap: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_op1 <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + cpu_state <= cpu_state_ldmem; + mem_do_rinst <= 1; + end + is_slli_srli_srai && !BARREL_SHIFTER: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_op1 <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + reg_sh <= decoded_rs2; + cpu_state <= cpu_state_shift; + end + is_jalr_addi_slti_sltiu_xori_ori_andi, is_slli_srli_srai && BARREL_SHIFTER: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_op1 <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + reg_op2 <= is_slli_srli_srai && BARREL_SHIFTER ? decoded_rs2 : decoded_imm; + if (TWO_CYCLE_ALU) + alu_wait <= 1; + else + mem_do_rinst <= mem_do_prefetch; + cpu_state <= cpu_state_exec; + end + default: begin + `debug($display("LD_RS1: %2d 0x%08x", decoded_rs1, cpuregs_rs1);) + reg_op1 <= cpuregs_rs1; + dbg_rs1val <= cpuregs_rs1; + dbg_rs1val_valid <= 1; + if (ENABLE_REGS_DUALPORT) begin + `debug($display("LD_RS2: %2d 0x%08x", decoded_rs2, cpuregs_rs2);) + reg_sh <= cpuregs_rs2; + reg_op2 <= cpuregs_rs2; + dbg_rs2val <= cpuregs_rs2; + dbg_rs2val_valid <= 1; + (* parallel_case *) + case (1'b1) + is_sb_sh_sw: begin + cpu_state <= cpu_state_stmem; + mem_do_rinst <= 1; + end + is_sll_srl_sra && !BARREL_SHIFTER: begin + cpu_state <= cpu_state_shift; + end + default: begin + if (TWO_CYCLE_ALU || (TWO_CYCLE_COMPARE && is_beq_bne_blt_bge_bltu_bgeu)) begin + alu_wait_2 <= TWO_CYCLE_ALU && (TWO_CYCLE_COMPARE && is_beq_bne_blt_bge_bltu_bgeu); + alu_wait <= 1; + end else + mem_do_rinst <= mem_do_prefetch; + cpu_state <= cpu_state_exec; + end + endcase + end else + cpu_state <= cpu_state_ld_rs2; + end + endcase + end + + cpu_state_ld_rs2: begin + `debug($display("LD_RS2: %2d 0x%08x", decoded_rs2, cpuregs_rs2);) + reg_sh <= cpuregs_rs2; + reg_op2 <= cpuregs_rs2; + dbg_rs2val <= cpuregs_rs2; + dbg_rs2val_valid <= 1; + + (* parallel_case *) + case (1'b1) + WITH_PCPI && instr_trap: begin + pcpi_valid <= 1; + if (pcpi_int_ready) begin + mem_do_rinst <= 1; + pcpi_valid <= 0; + reg_out <= pcpi_int_rd; + latched_store <= pcpi_int_wr; + cpu_state <= cpu_state_fetch; + end else + if (CATCH_ILLINSN && (pcpi_timeout || instr_ecall_ebreak)) begin + pcpi_valid <= 0; + `debug($display("EBREAK OR UNSUPPORTED INSN AT 0x%08x", reg_pc);) + if (ENABLE_IRQ && !irq_mask[irq_ebreak] && !irq_active) begin + next_irq_pending[irq_ebreak] = 1; + cpu_state <= cpu_state_fetch; + end else + cpu_state <= cpu_state_trap; + end + end + is_sb_sh_sw: begin + cpu_state <= cpu_state_stmem; + mem_do_rinst <= 1; + end + is_sll_srl_sra && !BARREL_SHIFTER: begin + cpu_state <= cpu_state_shift; + end + default: begin + if (TWO_CYCLE_ALU || (TWO_CYCLE_COMPARE && is_beq_bne_blt_bge_bltu_bgeu)) begin + alu_wait_2 <= TWO_CYCLE_ALU && (TWO_CYCLE_COMPARE && is_beq_bne_blt_bge_bltu_bgeu); + alu_wait <= 1; + end else + mem_do_rinst <= mem_do_prefetch; + cpu_state <= cpu_state_exec; + end + endcase + end + + cpu_state_exec: begin + reg_out <= reg_pc + decoded_imm; + if ((TWO_CYCLE_ALU || TWO_CYCLE_COMPARE) && (alu_wait || alu_wait_2)) begin + mem_do_rinst <= mem_do_prefetch && !alu_wait_2; + alu_wait <= alu_wait_2; + end else + if (is_beq_bne_blt_bge_bltu_bgeu) begin + latched_rd <= 0; + latched_store <= TWO_CYCLE_COMPARE ? alu_out_0_q : alu_out_0; + latched_branch <= TWO_CYCLE_COMPARE ? alu_out_0_q : alu_out_0; + if (mem_done) + cpu_state <= cpu_state_fetch; + if (TWO_CYCLE_COMPARE ? alu_out_0_q : alu_out_0) begin + decoder_trigger <= 0; + set_mem_do_rinst = 1; + end + end else begin + latched_branch <= instr_jalr; + latched_store <= 1; + latched_stalu <= 1; + cpu_state <= cpu_state_fetch; + end + end + + cpu_state_shift: begin + latched_store <= 1; + if (reg_sh == 0) begin + reg_out <= reg_op1; + mem_do_rinst <= mem_do_prefetch; + cpu_state <= cpu_state_fetch; + end else if (TWO_STAGE_SHIFT && reg_sh >= 4) begin + (* parallel_case, full_case *) + case (1'b1) + instr_slli || instr_sll: reg_op1 <= reg_op1 << 4; + instr_srli || instr_srl: reg_op1 <= reg_op1 >> 4; + instr_srai || instr_sra: reg_op1 <= $signed(reg_op1) >>> 4; + endcase + reg_sh <= reg_sh - 4; + end else begin + (* parallel_case, full_case *) + case (1'b1) + instr_slli || instr_sll: reg_op1 <= reg_op1 << 1; + instr_srli || instr_srl: reg_op1 <= reg_op1 >> 1; + instr_srai || instr_sra: reg_op1 <= $signed(reg_op1) >>> 1; + endcase + reg_sh <= reg_sh - 1; + end + end + + cpu_state_stmem: begin + if (ENABLE_TRACE) + reg_out <= reg_op2; + if (!mem_do_prefetch || mem_done) begin + if (!mem_do_wdata) begin + (* parallel_case, full_case *) + case (1'b1) + instr_sb: mem_wordsize <= 2; + instr_sh: mem_wordsize <= 1; + instr_sw: mem_wordsize <= 0; + endcase + if (ENABLE_TRACE) begin + trace_valid <= 1; + trace_data <= (irq_active ? TRACE_IRQ : 0) | TRACE_ADDR | ((reg_op1 + decoded_imm) & 32'hffffffff); + end + reg_op1 <= reg_op1 + decoded_imm; + set_mem_do_wdata = 1; + end + if (!mem_do_prefetch && mem_done) begin + cpu_state <= cpu_state_fetch; + decoder_trigger <= 1; + decoder_pseudo_trigger <= 1; + end + end + end + + cpu_state_ldmem: begin + latched_store <= 1; + if (!mem_do_prefetch || mem_done) begin + if (!mem_do_rdata) begin + (* parallel_case, full_case *) + case (1'b1) + instr_lb || instr_lbu: mem_wordsize <= 2; + instr_lh || instr_lhu: mem_wordsize <= 1; + instr_lw: mem_wordsize <= 0; + endcase + latched_is_lu <= is_lbu_lhu_lw; + latched_is_lh <= instr_lh; + latched_is_lb <= instr_lb; + if (ENABLE_TRACE) begin + trace_valid <= 1; + trace_data <= (irq_active ? TRACE_IRQ : 0) | TRACE_ADDR | ((reg_op1 + decoded_imm) & 32'hffffffff); + end + reg_op1 <= reg_op1 + decoded_imm; + set_mem_do_rdata = 1; + end + if (!mem_do_prefetch && mem_done) begin + (* parallel_case, full_case *) + case (1'b1) + latched_is_lu: reg_out <= mem_rdata_word; + latched_is_lh: reg_out <= $signed(mem_rdata_word[15:0]); + latched_is_lb: reg_out <= $signed(mem_rdata_word[7:0]); + endcase + decoder_trigger <= 1; + decoder_pseudo_trigger <= 1; + cpu_state <= cpu_state_fetch; + end + end + end + endcase + + if (ENABLE_IRQ) begin + next_irq_pending = next_irq_pending | irq; + if(ENABLE_IRQ_TIMER && timer) + if (timer - 1 == 0) + next_irq_pending[irq_timer] = 1; + end + + if (CATCH_MISALIGN && resetn && (mem_do_rdata || mem_do_wdata)) begin + if (mem_wordsize == 0 && reg_op1[1:0] != 0) begin + `debug($display("MISALIGNED WORD: 0x%08x", reg_op1);) + if (ENABLE_IRQ && !irq_mask[irq_buserror] && !irq_active) begin + next_irq_pending[irq_buserror] = 1; + end else + cpu_state <= cpu_state_trap; + end + if (mem_wordsize == 1 && reg_op1[0] != 0) begin + `debug($display("MISALIGNED HALFWORD: 0x%08x", reg_op1);) + if (ENABLE_IRQ && !irq_mask[irq_buserror] && !irq_active) begin + next_irq_pending[irq_buserror] = 1; + end else + cpu_state <= cpu_state_trap; + end + end + if (CATCH_MISALIGN && resetn && mem_do_rinst && (COMPRESSED_ISA ? reg_pc[0] : |reg_pc[1:0])) begin + `debug($display("MISALIGNED INSTRUCTION: 0x%08x", reg_pc);) + if (ENABLE_IRQ && !irq_mask[irq_buserror] && !irq_active) begin + next_irq_pending[irq_buserror] = 1; + end else + cpu_state <= cpu_state_trap; + end + if (!CATCH_ILLINSN && decoder_trigger_q && !decoder_pseudo_trigger_q && instr_ecall_ebreak) begin + cpu_state <= cpu_state_trap; + end + + if (!resetn || mem_done) begin + mem_do_prefetch <= 0; + mem_do_rinst <= 0; + mem_do_rdata <= 0; + mem_do_wdata <= 0; + end + + if (set_mem_do_rinst) + mem_do_rinst <= 1; + if (set_mem_do_rdata) + mem_do_rdata <= 1; + if (set_mem_do_wdata) + mem_do_wdata <= 1; + + irq_pending <= next_irq_pending & ~MASKED_IRQ; + + if (!CATCH_MISALIGN) begin + if (COMPRESSED_ISA) begin + reg_pc[0] <= 0; + reg_next_pc[0] <= 0; + end else begin + reg_pc[1:0] <= 0; + reg_next_pc[1:0] <= 0; + end + end + current_pc = 'bx; + end + +`ifdef RISCV_FORMAL + reg dbg_irq_call; + reg dbg_irq_enter; + reg [31:0] dbg_irq_ret; + always @(posedge clk) begin + rvfi_valid <= resetn && (launch_next_insn || trap) && dbg_valid_insn; + rvfi_order <= resetn ? rvfi_order + rvfi_valid : 0; + + rvfi_insn <= dbg_insn_opcode; + rvfi_rs1_addr <= dbg_rs1val_valid ? dbg_insn_rs1 : 0; + rvfi_rs2_addr <= dbg_rs2val_valid ? dbg_insn_rs2 : 0; + rvfi_pc_rdata <= dbg_insn_addr; + rvfi_rs1_rdata <= dbg_rs1val_valid ? dbg_rs1val : 0; + rvfi_rs2_rdata <= dbg_rs2val_valid ? dbg_rs2val : 0; + rvfi_trap <= trap; + rvfi_halt <= trap; + rvfi_intr <= dbg_irq_enter; + rvfi_mode <= 3; + rvfi_ixl <= 1; + + if (!resetn) begin + dbg_irq_call <= 0; + dbg_irq_enter <= 0; + end else + if (rvfi_valid) begin + dbg_irq_call <= 0; + dbg_irq_enter <= dbg_irq_call; + end else + if (irq_state == 1) begin + dbg_irq_call <= 1; + dbg_irq_ret <= next_pc; + end + + if (!resetn) begin + rvfi_rd_addr <= 0; + rvfi_rd_wdata <= 0; + end else + if (cpuregs_write && !irq_state) begin +`ifdef PICORV32_TESTBUG_003 + rvfi_rd_addr <= latched_rd ^ 1; +`else + rvfi_rd_addr <= latched_rd; +`endif +`ifdef PICORV32_TESTBUG_004 + rvfi_rd_wdata <= latched_rd ? cpuregs_wrdata ^ 1 : 0; +`else + rvfi_rd_wdata <= latched_rd ? cpuregs_wrdata : 0; +`endif + end else + if (rvfi_valid) begin + rvfi_rd_addr <= 0; + rvfi_rd_wdata <= 0; + end + + casez (dbg_insn_opcode) + 32'b 0000000_?????_000??_???_?????_0001011: begin // getq + rvfi_rs1_addr <= 0; + rvfi_rs1_rdata <= 0; + end + 32'b 0000001_?????_?????_???_000??_0001011: begin // setq + rvfi_rd_addr <= 0; + rvfi_rd_wdata <= 0; + end + 32'b 0000010_?????_00000_???_00000_0001011: begin // retirq + rvfi_rs1_addr <= 0; + rvfi_rs1_rdata <= 0; + end + endcase + + if (!dbg_irq_call) begin + if (dbg_mem_instr) begin + rvfi_mem_addr <= 0; + rvfi_mem_rmask <= 0; + rvfi_mem_wmask <= 0; + rvfi_mem_rdata <= 0; + rvfi_mem_wdata <= 0; + end else + if (dbg_mem_valid && dbg_mem_ready) begin + rvfi_mem_addr <= dbg_mem_addr; + rvfi_mem_rmask <= dbg_mem_wstrb ? 0 : ~0; + rvfi_mem_wmask <= dbg_mem_wstrb; + rvfi_mem_rdata <= dbg_mem_rdata; + rvfi_mem_wdata <= dbg_mem_wdata; + end + end + end + + always @* begin +`ifdef PICORV32_TESTBUG_005 + rvfi_pc_wdata = (dbg_irq_call ? dbg_irq_ret : dbg_insn_addr) ^ 4; +`else + rvfi_pc_wdata = dbg_irq_call ? dbg_irq_ret : dbg_insn_addr; +`endif + + rvfi_csr_mcycle_rmask = 0; + rvfi_csr_mcycle_wmask = 0; + rvfi_csr_mcycle_rdata = 0; + rvfi_csr_mcycle_wdata = 0; + + rvfi_csr_minstret_rmask = 0; + rvfi_csr_minstret_wmask = 0; + rvfi_csr_minstret_rdata = 0; + rvfi_csr_minstret_wdata = 0; + + if (rvfi_valid && rvfi_insn[6:0] == 7'b 1110011 && rvfi_insn[13:12] == 3'b010) begin + if (rvfi_insn[31:20] == 12'h C00) begin + rvfi_csr_mcycle_rmask = 64'h 0000_0000_FFFF_FFFF; + rvfi_csr_mcycle_rdata = {32'h 0000_0000, rvfi_rd_wdata}; + end + if (rvfi_insn[31:20] == 12'h C80) begin + rvfi_csr_mcycle_rmask = 64'h FFFF_FFFF_0000_0000; + rvfi_csr_mcycle_rdata = {rvfi_rd_wdata, 32'h 0000_0000}; + end + if (rvfi_insn[31:20] == 12'h C02) begin + rvfi_csr_minstret_rmask = 64'h 0000_0000_FFFF_FFFF; + rvfi_csr_minstret_rdata = {32'h 0000_0000, rvfi_rd_wdata}; + end + if (rvfi_insn[31:20] == 12'h C82) begin + rvfi_csr_minstret_rmask = 64'h FFFF_FFFF_0000_0000; + rvfi_csr_minstret_rdata = {rvfi_rd_wdata, 32'h 0000_0000}; + end + end + end +`endif + + // Formal Verification +`ifdef FORMAL + reg [3:0] last_mem_nowait; + always @(posedge clk) + last_mem_nowait <= {last_mem_nowait, mem_ready || !mem_valid}; + + // stall the memory interface for max 4 cycles + restrict property (|last_mem_nowait || mem_ready || !mem_valid); + + // resetn low in first cycle, after that resetn high + restrict property (resetn != $initstate); + + // this just makes it much easier to read traces. uncomment as needed. + // assume property (mem_valid || !mem_ready); + + reg ok; + always @* begin + if (resetn) begin + // instruction fetches are read-only + if (mem_valid && mem_instr) + assert (mem_wstrb == 0); + + // cpu_state must be valid + ok = 0; + if (cpu_state == cpu_state_trap) ok = 1; + if (cpu_state == cpu_state_fetch) ok = 1; + if (cpu_state == cpu_state_ld_rs1) ok = 1; + if (cpu_state == cpu_state_ld_rs2) ok = !ENABLE_REGS_DUALPORT; + if (cpu_state == cpu_state_exec) ok = 1; + if (cpu_state == cpu_state_shift) ok = 1; + if (cpu_state == cpu_state_stmem) ok = 1; + if (cpu_state == cpu_state_ldmem) ok = 1; + assert (ok); + end + end + + reg last_mem_la_read = 0; + reg last_mem_la_write = 0; + reg [31:0] last_mem_la_addr; + reg [31:0] last_mem_la_wdata; + reg [3:0] last_mem_la_wstrb = 0; + + always @(posedge clk) begin + last_mem_la_read <= mem_la_read; + last_mem_la_write <= mem_la_write; + last_mem_la_addr <= mem_la_addr; + last_mem_la_wdata <= mem_la_wdata; + last_mem_la_wstrb <= mem_la_wstrb; + + if (last_mem_la_read) begin + assert(mem_valid); + assert(mem_addr == last_mem_la_addr); + assert(mem_wstrb == 0); + end + if (last_mem_la_write) begin + assert(mem_valid); + assert(mem_addr == last_mem_la_addr); + assert(mem_wdata == last_mem_la_wdata); + assert(mem_wstrb == last_mem_la_wstrb); + end + if (mem_la_read || mem_la_write) begin + assert(!mem_valid || mem_ready); + end + end +`endif +endmodule + +// This is a simple example implementation of PICORV32_REGS. +// Use the PICORV32_REGS mechanism if you want to use custom +// memory resources to implement the processor register file. +// Note that your implementation must match the requirements of +// the PicoRV32 configuration. (e.g. QREGS, etc) +module picorv32_regs ( + input clk, wen, + input [5:0] waddr, + input [5:0] raddr1, + input [5:0] raddr2, + input [31:0] wdata, + output [31:0] rdata1, + output [31:0] rdata2 +); + reg [31:0] regs [0:30]; + + always @(posedge clk) + if (wen) regs[~waddr[4:0]] <= wdata; + + assign rdata1 = regs[~raddr1[4:0]]; + assign rdata2 = regs[~raddr2[4:0]]; +endmodule + + +/*************************************************************** + * picorv32_pcpi_mul + ***************************************************************/ + +module picorv32_pcpi_mul #( + parameter STEPS_AT_ONCE = 1, + parameter CARRY_CHAIN = 4 +) ( + input clk, resetn, + + input pcpi_valid, + input [31:0] pcpi_insn, + input [31:0] pcpi_rs1, + input [31:0] pcpi_rs2, + output reg pcpi_wr, + output reg [31:0] pcpi_rd, + output reg pcpi_wait, + output reg pcpi_ready +); + reg instr_mul, instr_mulh, instr_mulhsu, instr_mulhu; + wire instr_any_mul = |{instr_mul, instr_mulh, instr_mulhsu, instr_mulhu}; + wire instr_any_mulh = |{instr_mulh, instr_mulhsu, instr_mulhu}; + wire instr_rs1_signed = |{instr_mulh, instr_mulhsu}; + wire instr_rs2_signed = |{instr_mulh}; + + reg pcpi_wait_q; + wire mul_start = pcpi_wait && !pcpi_wait_q; + + always @(posedge clk) begin + instr_mul <= 0; + instr_mulh <= 0; + instr_mulhsu <= 0; + instr_mulhu <= 0; + + if (resetn && pcpi_valid && pcpi_insn[6:0] == 7'b0110011 && pcpi_insn[31:25] == 7'b0000001) begin + case (pcpi_insn[14:12]) + 3'b000: instr_mul <= 1; + 3'b001: instr_mulh <= 1; + 3'b010: instr_mulhsu <= 1; + 3'b011: instr_mulhu <= 1; + endcase + end + + pcpi_wait <= instr_any_mul; + pcpi_wait_q <= pcpi_wait; + end + + reg [63:0] rs1, rs2, rd, rdx; + reg [63:0] next_rs1, next_rs2, this_rs2; + reg [63:0] next_rd, next_rdx, next_rdt; + reg [6:0] mul_counter; + reg mul_waiting; + reg mul_finish; + integer i, j; + + // carry save accumulator + always @* begin + next_rd = rd; + next_rdx = rdx; + next_rs1 = rs1; + next_rs2 = rs2; + + for (i = 0; i < STEPS_AT_ONCE; i=i+1) begin + this_rs2 = next_rs1[0] ? next_rs2 : 0; + if (CARRY_CHAIN == 0) begin + next_rdt = next_rd ^ next_rdx ^ this_rs2; + next_rdx = ((next_rd & next_rdx) | (next_rd & this_rs2) | (next_rdx & this_rs2)) << 1; + next_rd = next_rdt; + end else begin + next_rdt = 0; + for (j = 0; j < 64; j = j + CARRY_CHAIN) + {next_rdt[j+CARRY_CHAIN-1], next_rd[j +: CARRY_CHAIN]} = + next_rd[j +: CARRY_CHAIN] + next_rdx[j +: CARRY_CHAIN] + this_rs2[j +: CARRY_CHAIN]; + next_rdx = next_rdt << 1; + end + next_rs1 = next_rs1 >> 1; + next_rs2 = next_rs2 << 1; + end + end + + always @(posedge clk) begin + mul_finish <= 0; + if (!resetn) begin + mul_waiting <= 1; + end else + if (mul_waiting) begin + if (instr_rs1_signed) + rs1 <= $signed(pcpi_rs1); + else + rs1 <= $unsigned(pcpi_rs1); + + if (instr_rs2_signed) + rs2 <= $signed(pcpi_rs2); + else + rs2 <= $unsigned(pcpi_rs2); + + rd <= 0; + rdx <= 0; + mul_counter <= (instr_any_mulh ? 63 - STEPS_AT_ONCE : 31 - STEPS_AT_ONCE); + mul_waiting <= !mul_start; + end else begin + rd <= next_rd; + rdx <= next_rdx; + rs1 <= next_rs1; + rs2 <= next_rs2; + + mul_counter <= mul_counter - STEPS_AT_ONCE; + if (mul_counter[6]) begin + mul_finish <= 1; + mul_waiting <= 1; + end + end + end + + always @(posedge clk) begin + pcpi_wr <= 0; + pcpi_ready <= 0; + if (mul_finish && resetn) begin + pcpi_wr <= 1; + pcpi_ready <= 1; + pcpi_rd <= instr_any_mulh ? rd >> 32 : rd; + end + end +endmodule + +module picorv32_pcpi_fast_mul #( + parameter EXTRA_MUL_FFS = 0, + parameter EXTRA_INSN_FFS = 0, + parameter MUL_CLKGATE = 0 +) ( + input clk, resetn, + + input pcpi_valid, + input [31:0] pcpi_insn, + input [31:0] pcpi_rs1, + input [31:0] pcpi_rs2, + output pcpi_wr, + output [31:0] pcpi_rd, + output pcpi_wait, + output pcpi_ready +); + reg instr_mul, instr_mulh, instr_mulhsu, instr_mulhu; + wire instr_any_mul = |{instr_mul, instr_mulh, instr_mulhsu, instr_mulhu}; + wire instr_any_mulh = |{instr_mulh, instr_mulhsu, instr_mulhu}; + wire instr_rs1_signed = |{instr_mulh, instr_mulhsu}; + wire instr_rs2_signed = |{instr_mulh}; + + reg shift_out; + reg [3:0] active; + reg [32:0] rs1, rs2, rs1_q, rs2_q; + reg [63:0] rd, rd_q; + + wire pcpi_insn_valid = pcpi_valid && pcpi_insn[6:0] == 7'b0110011 && pcpi_insn[31:25] == 7'b0000001; + reg pcpi_insn_valid_q; + + always @* begin + instr_mul = 0; + instr_mulh = 0; + instr_mulhsu = 0; + instr_mulhu = 0; + + if (resetn && (EXTRA_INSN_FFS ? pcpi_insn_valid_q : pcpi_insn_valid)) begin + case (pcpi_insn[14:12]) + 3'b000: instr_mul = 1; + 3'b001: instr_mulh = 1; + 3'b010: instr_mulhsu = 1; + 3'b011: instr_mulhu = 1; + endcase + end + end + + always @(posedge clk) begin + pcpi_insn_valid_q <= pcpi_insn_valid; + if (!MUL_CLKGATE || active[0]) begin + rs1_q <= rs1; + rs2_q <= rs2; + end + if (!MUL_CLKGATE || active[1]) begin + rd <= $signed(EXTRA_MUL_FFS ? rs1_q : rs1) * $signed(EXTRA_MUL_FFS ? rs2_q : rs2); + end + if (!MUL_CLKGATE || active[2]) begin + rd_q <= rd; + end + end + + always @(posedge clk) begin + if (instr_any_mul && !(EXTRA_MUL_FFS ? active[3:0] : active[1:0])) begin + if (instr_rs1_signed) + rs1 <= $signed(pcpi_rs1); + else + rs1 <= $unsigned(pcpi_rs1); + + if (instr_rs2_signed) + rs2 <= $signed(pcpi_rs2); + else + rs2 <= $unsigned(pcpi_rs2); + active[0] <= 1; + end else begin + active[0] <= 0; + end + + active[3:1] <= active; + shift_out <= instr_any_mulh; + + if (!resetn) + active <= 0; + end + + assign pcpi_wr = active[EXTRA_MUL_FFS ? 3 : 1]; + assign pcpi_wait = 0; + assign pcpi_ready = active[EXTRA_MUL_FFS ? 3 : 1]; +`ifdef RISCV_FORMAL_ALTOPS + assign pcpi_rd = + instr_mul ? (pcpi_rs1 + pcpi_rs2) ^ 32'h5876063e : + instr_mulh ? (pcpi_rs1 + pcpi_rs2) ^ 32'hf6583fb7 : + instr_mulhsu ? (pcpi_rs1 - pcpi_rs2) ^ 32'hecfbe137 : + instr_mulhu ? (pcpi_rs1 + pcpi_rs2) ^ 32'h949ce5e8 : 1'bx; +`else + assign pcpi_rd = shift_out ? (EXTRA_MUL_FFS ? rd_q : rd) >> 32 : (EXTRA_MUL_FFS ? rd_q : rd); +`endif +endmodule + + +/*************************************************************** + * picorv32_pcpi_div + ***************************************************************/ + +module picorv32_pcpi_div ( + input clk, resetn, + + input pcpi_valid, + input [31:0] pcpi_insn, + input [31:0] pcpi_rs1, + input [31:0] pcpi_rs2, + output reg pcpi_wr, + output reg [31:0] pcpi_rd, + output reg pcpi_wait, + output reg pcpi_ready +); + reg instr_div, instr_divu, instr_rem, instr_remu; + wire instr_any_div_rem = |{instr_div, instr_divu, instr_rem, instr_remu}; + + reg pcpi_wait_q; + wire start = pcpi_wait && !pcpi_wait_q; + + always @(posedge clk) begin + instr_div <= 0; + instr_divu <= 0; + instr_rem <= 0; + instr_remu <= 0; + + if (resetn && pcpi_valid && !pcpi_ready && pcpi_insn[6:0] == 7'b0110011 && pcpi_insn[31:25] == 7'b0000001) begin + case (pcpi_insn[14:12]) + 3'b100: instr_div <= 1; + 3'b101: instr_divu <= 1; + 3'b110: instr_rem <= 1; + 3'b111: instr_remu <= 1; + endcase + end + + pcpi_wait <= instr_any_div_rem && resetn; + pcpi_wait_q <= pcpi_wait && resetn; + end + + reg [31:0] dividend; + reg [62:0] divisor; + reg [31:0] quotient; + reg [31:0] quotient_msk; + reg running; + reg outsign; + + always @(posedge clk) begin + pcpi_ready <= 0; + pcpi_wr <= 0; + pcpi_rd <= 'bx; + + if (!resetn) begin + running <= 0; + end else + if (start) begin + running <= 1; + dividend <= (instr_div || instr_rem) && pcpi_rs1[31] ? -pcpi_rs1 : pcpi_rs1; + divisor <= ((instr_div || instr_rem) && pcpi_rs2[31] ? -pcpi_rs2 : pcpi_rs2) << 31; + outsign <= (instr_div && (pcpi_rs1[31] != pcpi_rs2[31]) && |pcpi_rs2) || (instr_rem && pcpi_rs1[31]); + quotient <= 0; + quotient_msk <= 1 << 31; + end else + if (!quotient_msk && running) begin + running <= 0; + pcpi_ready <= 1; + pcpi_wr <= 1; +`ifdef RISCV_FORMAL_ALTOPS + case (1) + instr_div: pcpi_rd <= (pcpi_rs1 - pcpi_rs2) ^ 32'h7f8529ec; + instr_divu: pcpi_rd <= (pcpi_rs1 - pcpi_rs2) ^ 32'h10e8fd70; + instr_rem: pcpi_rd <= (pcpi_rs1 - pcpi_rs2) ^ 32'h8da68fa5; + instr_remu: pcpi_rd <= (pcpi_rs1 - pcpi_rs2) ^ 32'h3138d0e1; + endcase +`else + if (instr_div || instr_divu) + pcpi_rd <= outsign ? -quotient : quotient; + else + pcpi_rd <= outsign ? -dividend : dividend; +`endif + end else begin + if (divisor <= dividend) begin + dividend <= dividend - divisor; + quotient <= quotient | quotient_msk; + end + divisor <= divisor >> 1; +`ifdef RISCV_FORMAL_ALTOPS + quotient_msk <= quotient_msk >> 5; +`else + quotient_msk <= quotient_msk >> 1; +`endif + end + end +endmodule + + +/*************************************************************** + * picorv32_axi + ***************************************************************/ + +module picorv32_axi #( + parameter [ 0:0] ENABLE_COUNTERS = 1, + parameter [ 0:0] ENABLE_COUNTERS64 = 1, + parameter [ 0:0] ENABLE_REGS_16_31 = 1, + parameter [ 0:0] ENABLE_REGS_DUALPORT = 1, + parameter [ 0:0] TWO_STAGE_SHIFT = 1, + parameter [ 0:0] BARREL_SHIFTER = 0, + parameter [ 0:0] TWO_CYCLE_COMPARE = 0, + parameter [ 0:0] TWO_CYCLE_ALU = 0, + parameter [ 0:0] COMPRESSED_ISA = 0, + parameter [ 0:0] CATCH_MISALIGN = 1, + parameter [ 0:0] CATCH_ILLINSN = 1, + parameter [ 0:0] ENABLE_PCPI = 0, + parameter [ 0:0] ENABLE_MUL = 0, + parameter [ 0:0] ENABLE_FAST_MUL = 0, + parameter [ 0:0] ENABLE_DIV = 0, + parameter [ 0:0] ENABLE_IRQ = 0, + parameter [ 0:0] ENABLE_IRQ_QREGS = 1, + parameter [ 0:0] ENABLE_IRQ_TIMER = 1, + parameter [ 0:0] ENABLE_TRACE = 0, + parameter [ 0:0] REGS_INIT_ZERO = 0, + parameter [31:0] MASKED_IRQ = 32'h 0000_0000, + parameter [31:0] LATCHED_IRQ = 32'h ffff_ffff, + parameter [31:0] PROGADDR_RESET = 32'h 0000_0000, + parameter [31:0] PROGADDR_IRQ = 32'h 0000_0010, + parameter [31:0] STACKADDR = 32'h ffff_ffff +) ( + input clk, resetn, + output trap, + + // AXI4-lite master memory interface + + output mem_axi_awvalid, + input mem_axi_awready, + output [31:0] mem_axi_awaddr, + output [ 2:0] mem_axi_awprot, + + output mem_axi_wvalid, + input mem_axi_wready, + output [31:0] mem_axi_wdata, + output [ 3:0] mem_axi_wstrb, + + input mem_axi_bvalid, + output mem_axi_bready, + + output mem_axi_arvalid, + input mem_axi_arready, + output [31:0] mem_axi_araddr, + output [ 2:0] mem_axi_arprot, + + input mem_axi_rvalid, + output mem_axi_rready, + input [31:0] mem_axi_rdata, + + // Pico Co-Processor Interface (PCPI) + output pcpi_valid, + output [31:0] pcpi_insn, + output [31:0] pcpi_rs1, + output [31:0] pcpi_rs2, + input pcpi_wr, + input [31:0] pcpi_rd, + input pcpi_wait, + input pcpi_ready, + + // IRQ interface + input [31:0] irq, + output [31:0] eoi, + +`ifdef RISCV_FORMAL + output rvfi_valid, + output [63:0] rvfi_order, + output [31:0] rvfi_insn, + output rvfi_trap, + output rvfi_halt, + output rvfi_intr, + output [ 4:0] rvfi_rs1_addr, + output [ 4:0] rvfi_rs2_addr, + output [31:0] rvfi_rs1_rdata, + output [31:0] rvfi_rs2_rdata, + output [ 4:0] rvfi_rd_addr, + output [31:0] rvfi_rd_wdata, + output [31:0] rvfi_pc_rdata, + output [31:0] rvfi_pc_wdata, + output [31:0] rvfi_mem_addr, + output [ 3:0] rvfi_mem_rmask, + output [ 3:0] rvfi_mem_wmask, + output [31:0] rvfi_mem_rdata, + output [31:0] rvfi_mem_wdata, +`endif + + // Trace Interface + output trace_valid, + output [35:0] trace_data +); + wire mem_valid; + wire [31:0] mem_addr; + wire [31:0] mem_wdata; + wire [ 3:0] mem_wstrb; + wire mem_instr; + wire mem_ready; + wire [31:0] mem_rdata; + + picorv32_axi_adapter axi_adapter ( + .clk (clk ), + .resetn (resetn ), + .mem_axi_awvalid(mem_axi_awvalid), + .mem_axi_awready(mem_axi_awready), + .mem_axi_awaddr (mem_axi_awaddr ), + .mem_axi_awprot (mem_axi_awprot ), + .mem_axi_wvalid (mem_axi_wvalid ), + .mem_axi_wready (mem_axi_wready ), + .mem_axi_wdata (mem_axi_wdata ), + .mem_axi_wstrb (mem_axi_wstrb ), + .mem_axi_bvalid (mem_axi_bvalid ), + .mem_axi_bready (mem_axi_bready ), + .mem_axi_arvalid(mem_axi_arvalid), + .mem_axi_arready(mem_axi_arready), + .mem_axi_araddr (mem_axi_araddr ), + .mem_axi_arprot (mem_axi_arprot ), + .mem_axi_rvalid (mem_axi_rvalid ), + .mem_axi_rready (mem_axi_rready ), + .mem_axi_rdata (mem_axi_rdata ), + .mem_valid (mem_valid ), + .mem_instr (mem_instr ), + .mem_ready (mem_ready ), + .mem_addr (mem_addr ), + .mem_wdata (mem_wdata ), + .mem_wstrb (mem_wstrb ), + .mem_rdata (mem_rdata ) + ); + + picorv32 #( + .ENABLE_COUNTERS (ENABLE_COUNTERS ), + .ENABLE_COUNTERS64 (ENABLE_COUNTERS64 ), + .ENABLE_REGS_16_31 (ENABLE_REGS_16_31 ), + .ENABLE_REGS_DUALPORT(ENABLE_REGS_DUALPORT), + .TWO_STAGE_SHIFT (TWO_STAGE_SHIFT ), + .BARREL_SHIFTER (BARREL_SHIFTER ), + .TWO_CYCLE_COMPARE (TWO_CYCLE_COMPARE ), + .TWO_CYCLE_ALU (TWO_CYCLE_ALU ), + .COMPRESSED_ISA (COMPRESSED_ISA ), + .CATCH_MISALIGN (CATCH_MISALIGN ), + .CATCH_ILLINSN (CATCH_ILLINSN ), + .ENABLE_PCPI (ENABLE_PCPI ), + .ENABLE_MUL (ENABLE_MUL ), + .ENABLE_FAST_MUL (ENABLE_FAST_MUL ), + .ENABLE_DIV (ENABLE_DIV ), + .ENABLE_IRQ (ENABLE_IRQ ), + .ENABLE_IRQ_QREGS (ENABLE_IRQ_QREGS ), + .ENABLE_IRQ_TIMER (ENABLE_IRQ_TIMER ), + .ENABLE_TRACE (ENABLE_TRACE ), + .REGS_INIT_ZERO (REGS_INIT_ZERO ), + .MASKED_IRQ (MASKED_IRQ ), + .LATCHED_IRQ (LATCHED_IRQ ), + .PROGADDR_RESET (PROGADDR_RESET ), + .PROGADDR_IRQ (PROGADDR_IRQ ), + .STACKADDR (STACKADDR ) + ) picorv32_core ( + .clk (clk ), + .resetn (resetn), + .trap (trap ), + + .mem_valid(mem_valid), + .mem_addr (mem_addr ), + .mem_wdata(mem_wdata), + .mem_wstrb(mem_wstrb), + .mem_instr(mem_instr), + .mem_ready(mem_ready), + .mem_rdata(mem_rdata), + + .pcpi_valid(pcpi_valid), + .pcpi_insn (pcpi_insn ), + .pcpi_rs1 (pcpi_rs1 ), + .pcpi_rs2 (pcpi_rs2 ), + .pcpi_wr (pcpi_wr ), + .pcpi_rd (pcpi_rd ), + .pcpi_wait (pcpi_wait ), + .pcpi_ready(pcpi_ready), + + .irq(irq), + .eoi(eoi), + +`ifdef RISCV_FORMAL + .rvfi_valid (rvfi_valid ), + .rvfi_order (rvfi_order ), + .rvfi_insn (rvfi_insn ), + .rvfi_trap (rvfi_trap ), + .rvfi_halt (rvfi_halt ), + .rvfi_intr (rvfi_intr ), + .rvfi_rs1_addr (rvfi_rs1_addr ), + .rvfi_rs2_addr (rvfi_rs2_addr ), + .rvfi_rs1_rdata(rvfi_rs1_rdata), + .rvfi_rs2_rdata(rvfi_rs2_rdata), + .rvfi_rd_addr (rvfi_rd_addr ), + .rvfi_rd_wdata (rvfi_rd_wdata ), + .rvfi_pc_rdata (rvfi_pc_rdata ), + .rvfi_pc_wdata (rvfi_pc_wdata ), + .rvfi_mem_addr (rvfi_mem_addr ), + .rvfi_mem_rmask(rvfi_mem_rmask), + .rvfi_mem_wmask(rvfi_mem_wmask), + .rvfi_mem_rdata(rvfi_mem_rdata), + .rvfi_mem_wdata(rvfi_mem_wdata), +`endif + + .trace_valid(trace_valid), + .trace_data (trace_data) + ); +endmodule + + +/*************************************************************** + * picorv32_axi_adapter + ***************************************************************/ + +module picorv32_axi_adapter ( + input clk, resetn, + + // AXI4-lite master memory interface + + output mem_axi_awvalid, + input mem_axi_awready, + output [31:0] mem_axi_awaddr, + output [ 2:0] mem_axi_awprot, + + output mem_axi_wvalid, + input mem_axi_wready, + output [31:0] mem_axi_wdata, + output [ 3:0] mem_axi_wstrb, + + input mem_axi_bvalid, + output mem_axi_bready, + + output mem_axi_arvalid, + input mem_axi_arready, + output [31:0] mem_axi_araddr, + output [ 2:0] mem_axi_arprot, + + input mem_axi_rvalid, + output mem_axi_rready, + input [31:0] mem_axi_rdata, + + // Native PicoRV32 memory interface + + input mem_valid, + input mem_instr, + output mem_ready, + input [31:0] mem_addr, + input [31:0] mem_wdata, + input [ 3:0] mem_wstrb, + output [31:0] mem_rdata +); + reg ack_awvalid; + reg ack_arvalid; + reg ack_wvalid; + reg xfer_done; + + assign mem_axi_awvalid = mem_valid && |mem_wstrb && !ack_awvalid; + assign mem_axi_awaddr = mem_addr; + assign mem_axi_awprot = 0; + + assign mem_axi_arvalid = mem_valid && !mem_wstrb && !ack_arvalid; + assign mem_axi_araddr = mem_addr; + assign mem_axi_arprot = mem_instr ? 3'b100 : 3'b000; + + assign mem_axi_wvalid = mem_valid && |mem_wstrb && !ack_wvalid; + assign mem_axi_wdata = mem_wdata; + assign mem_axi_wstrb = mem_wstrb; + + assign mem_ready = mem_axi_bvalid || mem_axi_rvalid; + assign mem_axi_bready = mem_valid && |mem_wstrb; + assign mem_axi_rready = mem_valid && !mem_wstrb; + assign mem_rdata = mem_axi_rdata; + + always @(posedge clk) begin + if (!resetn) begin + ack_awvalid <= 0; + end else begin + xfer_done <= mem_valid && mem_ready; + if (mem_axi_awready && mem_axi_awvalid) + ack_awvalid <= 1; + if (mem_axi_arready && mem_axi_arvalid) + ack_arvalid <= 1; + if (mem_axi_wready && mem_axi_wvalid) + ack_wvalid <= 1; + if (xfer_done || !mem_valid) begin + ack_awvalid <= 0; + ack_arvalid <= 0; + ack_wvalid <= 0; + end + end + end +endmodule + + +/*************************************************************** + * picorv32_wb + ***************************************************************/ + +module picorv32_wb #( + parameter [ 0:0] ENABLE_COUNTERS = 1, + parameter [ 0:0] ENABLE_COUNTERS64 = 1, + parameter [ 0:0] ENABLE_REGS_16_31 = 1, + parameter [ 0:0] ENABLE_REGS_DUALPORT = 1, + parameter [ 0:0] TWO_STAGE_SHIFT = 1, + parameter [ 0:0] BARREL_SHIFTER = 0, + parameter [ 0:0] TWO_CYCLE_COMPARE = 0, + parameter [ 0:0] TWO_CYCLE_ALU = 0, + parameter [ 0:0] COMPRESSED_ISA = 0, + parameter [ 0:0] CATCH_MISALIGN = 1, + parameter [ 0:0] CATCH_ILLINSN = 1, + parameter [ 0:0] ENABLE_PCPI = 0, + parameter [ 0:0] ENABLE_MUL = 0, + parameter [ 0:0] ENABLE_FAST_MUL = 0, + parameter [ 0:0] ENABLE_DIV = 0, + parameter [ 0:0] ENABLE_IRQ = 0, + parameter [ 0:0] ENABLE_IRQ_QREGS = 1, + parameter [ 0:0] ENABLE_IRQ_TIMER = 1, + parameter [ 0:0] ENABLE_TRACE = 0, + parameter [ 0:0] REGS_INIT_ZERO = 0, + parameter [31:0] MASKED_IRQ = 32'h 0000_0000, + parameter [31:0] LATCHED_IRQ = 32'h ffff_ffff, + parameter [31:0] PROGADDR_RESET = 32'h 0000_0000, + parameter [31:0] PROGADDR_IRQ = 32'h 0000_0010, + parameter [31:0] STACKADDR = 32'h ffff_ffff +) ( + output trap, + + // Wishbone interfaces + input wb_rst_i, + input wb_clk_i, + + output reg [31:0] wbm_adr_o, + output reg [31:0] wbm_dat_o, + input [31:0] wbm_dat_i, + output reg wbm_we_o, + output reg [3:0] wbm_sel_o, + output reg wbm_stb_o, + input wbm_ack_i, + output reg wbm_cyc_o, + + // Pico Co-Processor Interface (PCPI) + output pcpi_valid, + output [31:0] pcpi_insn, + output [31:0] pcpi_rs1, + output [31:0] pcpi_rs2, + input pcpi_wr, + input [31:0] pcpi_rd, + input pcpi_wait, + input pcpi_ready, + + // IRQ interface + input [31:0] irq, + output [31:0] eoi, + +`ifdef RISCV_FORMAL + output rvfi_valid, + output [63:0] rvfi_order, + output [31:0] rvfi_insn, + output rvfi_trap, + output rvfi_halt, + output rvfi_intr, + output [ 4:0] rvfi_rs1_addr, + output [ 4:0] rvfi_rs2_addr, + output [31:0] rvfi_rs1_rdata, + output [31:0] rvfi_rs2_rdata, + output [ 4:0] rvfi_rd_addr, + output [31:0] rvfi_rd_wdata, + output [31:0] rvfi_pc_rdata, + output [31:0] rvfi_pc_wdata, + output [31:0] rvfi_mem_addr, + output [ 3:0] rvfi_mem_rmask, + output [ 3:0] rvfi_mem_wmask, + output [31:0] rvfi_mem_rdata, + output [31:0] rvfi_mem_wdata, +`endif + + // Trace Interface + output trace_valid, + output [35:0] trace_data, + + output mem_instr +); + wire mem_valid; + wire [31:0] mem_addr; + wire [31:0] mem_wdata; + wire [ 3:0] mem_wstrb; + reg mem_ready; + reg [31:0] mem_rdata; + + wire clk; + wire resetn; + + assign clk = wb_clk_i; + assign resetn = ~wb_rst_i; + + picorv32 #( + .ENABLE_COUNTERS (ENABLE_COUNTERS ), + .ENABLE_COUNTERS64 (ENABLE_COUNTERS64 ), + .ENABLE_REGS_16_31 (ENABLE_REGS_16_31 ), + .ENABLE_REGS_DUALPORT(ENABLE_REGS_DUALPORT), + .TWO_STAGE_SHIFT (TWO_STAGE_SHIFT ), + .BARREL_SHIFTER (BARREL_SHIFTER ), + .TWO_CYCLE_COMPARE (TWO_CYCLE_COMPARE ), + .TWO_CYCLE_ALU (TWO_CYCLE_ALU ), + .COMPRESSED_ISA (COMPRESSED_ISA ), + .CATCH_MISALIGN (CATCH_MISALIGN ), + .CATCH_ILLINSN (CATCH_ILLINSN ), + .ENABLE_PCPI (ENABLE_PCPI ), + .ENABLE_MUL (ENABLE_MUL ), + .ENABLE_FAST_MUL (ENABLE_FAST_MUL ), + .ENABLE_DIV (ENABLE_DIV ), + .ENABLE_IRQ (ENABLE_IRQ ), + .ENABLE_IRQ_QREGS (ENABLE_IRQ_QREGS ), + .ENABLE_IRQ_TIMER (ENABLE_IRQ_TIMER ), + .ENABLE_TRACE (ENABLE_TRACE ), + .REGS_INIT_ZERO (REGS_INIT_ZERO ), + .MASKED_IRQ (MASKED_IRQ ), + .LATCHED_IRQ (LATCHED_IRQ ), + .PROGADDR_RESET (PROGADDR_RESET ), + .PROGADDR_IRQ (PROGADDR_IRQ ), + .STACKADDR (STACKADDR ) + ) picorv32_core ( + .clk (clk ), + .resetn (resetn), + .trap (trap ), + + .mem_valid(mem_valid), + .mem_addr (mem_addr ), + .mem_wdata(mem_wdata), + .mem_wstrb(mem_wstrb), + .mem_instr(mem_instr), + .mem_ready(mem_ready), + .mem_rdata(mem_rdata), + + .pcpi_valid(pcpi_valid), + .pcpi_insn (pcpi_insn ), + .pcpi_rs1 (pcpi_rs1 ), + .pcpi_rs2 (pcpi_rs2 ), + .pcpi_wr (pcpi_wr ), + .pcpi_rd (pcpi_rd ), + .pcpi_wait (pcpi_wait ), + .pcpi_ready(pcpi_ready), + + .irq(irq), + .eoi(eoi), + +`ifdef RISCV_FORMAL + .rvfi_valid (rvfi_valid ), + .rvfi_order (rvfi_order ), + .rvfi_insn (rvfi_insn ), + .rvfi_trap (rvfi_trap ), + .rvfi_halt (rvfi_halt ), + .rvfi_intr (rvfi_intr ), + .rvfi_rs1_addr (rvfi_rs1_addr ), + .rvfi_rs2_addr (rvfi_rs2_addr ), + .rvfi_rs1_rdata(rvfi_rs1_rdata), + .rvfi_rs2_rdata(rvfi_rs2_rdata), + .rvfi_rd_addr (rvfi_rd_addr ), + .rvfi_rd_wdata (rvfi_rd_wdata ), + .rvfi_pc_rdata (rvfi_pc_rdata ), + .rvfi_pc_wdata (rvfi_pc_wdata ), + .rvfi_mem_addr (rvfi_mem_addr ), + .rvfi_mem_rmask(rvfi_mem_rmask), + .rvfi_mem_wmask(rvfi_mem_wmask), + .rvfi_mem_rdata(rvfi_mem_rdata), + .rvfi_mem_wdata(rvfi_mem_wdata), +`endif + + .trace_valid(trace_valid), + .trace_data (trace_data) + ); + + localparam IDLE = 2'b00; + localparam WBSTART = 2'b01; + localparam WBEND = 2'b10; + + reg [1:0] state; + + wire we; + assign we = (mem_wstrb[0] | mem_wstrb[1] | mem_wstrb[2] | mem_wstrb[3]); + + always @(posedge wb_clk_i) begin + if (wb_rst_i) begin + wbm_adr_o <= 0; + wbm_dat_o <= 0; + wbm_we_o <= 0; + wbm_sel_o <= 0; + wbm_stb_o <= 0; + wbm_cyc_o <= 0; + state <= IDLE; + end else begin + case (state) + IDLE: begin + if (mem_valid) begin + wbm_adr_o <= mem_addr; + wbm_dat_o <= mem_wdata; + wbm_we_o <= we; + wbm_sel_o <= mem_wstrb; + + wbm_stb_o <= 1'b1; + wbm_cyc_o <= 1'b1; + state <= WBSTART; + end else begin + mem_ready <= 1'b0; + + wbm_stb_o <= 1'b0; + wbm_cyc_o <= 1'b0; + wbm_we_o <= 1'b0; + end + end + WBSTART:begin + if (wbm_ack_i) begin + mem_rdata <= wbm_dat_i; + mem_ready <= 1'b1; + + state <= WBEND; + + wbm_stb_o <= 1'b0; + wbm_cyc_o <= 1'b0; + wbm_we_o <= 1'b0; + end + end + WBEND: begin + mem_ready <= 1'b0; + + state <= IDLE; + end + default: + state <= IDLE; + endcase + end + end +endmodule diff --git a/chips/yosys/tests/functional/picorv32_tb.v b/chips/yosys/tests/functional/picorv32_tb.v new file mode 100644 index 0000000000000000000000000000000000000000..1404c2d8c2740b50485c97138b97e8f861d46561 --- /dev/null +++ b/chips/yosys/tests/functional/picorv32_tb.v @@ -0,0 +1,62 @@ +module gold( + input wire clk, + output reg resetn, + output wire trap, + output wire mem_valid, + output wire mem_instr, + output wire mem_ready, + output wire [31:0] mem_addr, + output wire [31:0] mem_wdata, + output wire [31:0] mem_wstrb, + output wire [31:0] mem_rdata, +); + + initial resetn = 1'b0; + always @(posedge clk) resetn <= 1'b1; + + reg [31:0] rom[0:15]; + + initial begin + rom[0] = 32'h00200093; + rom[1] = 32'h00200113; + rom[2] = 32'h00111863; + rom[3] = 32'h00102023; + rom[4] = 32'h00108093; + rom[5] = 32'hfe0008e3; + rom[6] = 32'h00008193; + rom[7] = 32'h402181b3; + rom[8] = 32'hfe304ee3; + rom[9] = 32'hfe0186e3; + rom[10] = 32'h00110113; + rom[11] = 32'hfc000ee3; + end + + assign mem_ready = 1'b1; + assign mem_rdata = rom[mem_addr[5:2]]; + + wire pcpi_wr = 1'b0; + wire [31:0] pcpi_rd = 32'b0; + wire pcpi_wait = 1'b0; + wire pcpi_ready = 1'b0; + + wire [31:0] irq = 32'b0; + + picorv32 picorv32_i( + .clk(clk), + .resetn(resetn), + .trap(trap), + .mem_valid(mem_valid), + .mem_instr(mem_instr), + .mem_ready(mem_ready), + .mem_addr(mem_addr), + .mem_wdata(mem_wdata), + .mem_wstrb(mem_wstrb), + .mem_rdata(mem_rdata), + .pcpi_wr(pcpi_wr), + .pcpi_rd(pcpi_rd), + .pcpi_wait(pcpi_wait), + .pcpi_ready(pcpi_ready), + .irq(irq) + ); + +endmodule diff --git a/chips/yosys/tests/functional/rkt_vcd.py b/chips/yosys/tests/functional/rkt_vcd.py new file mode 100644 index 0000000000000000000000000000000000000000..8ce73273ff7282c512dcb6ecdbef8c15a0c7ee13 --- /dev/null +++ b/chips/yosys/tests/functional/rkt_vcd.py @@ -0,0 +1,162 @@ +from __future__ import annotations +from pathlib import Path +import re +import subprocess +from typing import Dict, List, Tuple +from random import Random + +vcd_version = "Yosys/tests/functional/rkt_vcd.py" +StepList = List[Tuple[int, str]] +SignalStepMap = Dict[str, StepList] +SignalWidthMap = Dict[str, int] + +def write_vcd(filename: Path, signals: SignalStepMap, timescale='1 ns', date='today'): + with open(filename, 'w') as f: + # Write the header + f.write(f"$date\n {date}\n$end\n") + f.write(f"$timescale {timescale} $end\n") + + # Declare signals + f.write("$scope module gold $end\n") + for signal_name, changes in signals.items(): + signal_size = len(changes[0][1]) + f.write(f"$var wire {signal_size - 1} {signal_name} {signal_name} $end\n") + f.write("$upscope $end\n") + f.write("$enddefinitions $end\n") + + # Collect all unique timestamps + timestamps = sorted(set(time for changes in signals.values() for time, _ in changes)) + + # Write initial values + f.write("#0\n") + for signal_name, changes in signals.items(): + for time, value in changes: + if time == 0: + f.write(f"{value} {signal_name}\n") + + # Write value changes + for time in timestamps: + if time != 0: + f.write(f"#{time}\n") + for signal_name, changes in signals.items(): + for change_time, value in changes: + if change_time == time: + f.write(f"{value} {signal_name}\n") + + +def simulate_rosette( + rkt_file_path: Path, + vcd_path: Path, + num_steps: int, + rnd: Random, + use_assoc_list_helpers: bool = False, +): + """ + Args: + - use_assoc_list_helpers: If True, will use the association list helpers + in the Racket file. The file should have been generated with the + -assoc-list-helpers flag in the yosys command. + """ + signals: dict[str, list[str]] = {} + inputs: SignalWidthMap = {} + outputs: SignalWidthMap = {} + + current_struct_name: str = "" + with open(rkt_file_path, 'r') as rkt_file: + for line in rkt_file: + m = re.search(r'gold_(Inputs|Outputs|State)', line) + if m: + current_struct_name = m.group(1) + if current_struct_name == "State": break + elif not current_struct_name: continue # skip lines before structs + m = re.search(r'; (.+?)\b \(bitvector (\d+)\)', line) + if not m: continue # skip non matching lines (probably closing the struct) + signal = m.group(1) + width = int(m.group(2)) + if current_struct_name == "Inputs": + inputs[signal] = width + elif current_struct_name == "Outputs": + outputs[signal] = width + + for signal, width in inputs.items(): + step_list: list[int] = [] + for step in range(num_steps): + value = rnd.getrandbits(width) + binary_string = format(value, '0{}b'.format(width)) + step_list.append(binary_string) + signals[signal] = step_list + + test_rkt_file_path = rkt_file_path.with_suffix('.tst.rkt') + with open(test_rkt_file_path, 'w') as test_rkt_file: + test_rkt_file.writelines([ + '#lang rosette\n', + f'(require "{rkt_file_path.name}")\n', + ]) + + for step in range(num_steps): + this_step = f"step_{step}" + value_list: list[str] = [] + if use_assoc_list_helpers: + # Generate inputs as a list of cons pairs making up the + # association list. + for signal, width in inputs.items(): + value = signals[signal][step] + value_list.append(f'(cons "{signal}" (bv #b{value} {width}))') + else: + # Otherwise, we generate the inputs as a list of bitvectors. + for signal, width in inputs.items(): + value = signals[signal][step] + value_list.append(f"(bv #b{value} {width})") + gold_Inputs = ( + f"(gold_inputs_helper (list {' '.join(value_list)}))" + if use_assoc_list_helpers + else f"(gold_Inputs {' '.join(value_list)})" + ) + gold_State = f"(cdr step_{step-1})" if step else "gold_initial" + get_value_expr = ( + f"(gold_outputs_helper (car {this_step}))" + if use_assoc_list_helpers + else f"(car {this_step})" + ) + test_rkt_file.write( + f"(define {this_step} (gold {gold_Inputs} {gold_State})) {get_value_expr}\n" + ) + + + cmd = ["racket", test_rkt_file_path] + status = subprocess.run(cmd, capture_output=True) + assert status.returncode == 0, f"{cmd[0]} failed" + + for signal in outputs.keys(): + signals[signal] = [] + + for line in status.stdout.decode().splitlines(): + m = ( + re.match(r"\(list( \(cons \"\S+\" \(bv \S+ \d+\)\))+\)", line) + if use_assoc_list_helpers + else re.match(r"\(gold_Outputs( \(bv \S+ \d+\))+\)", line) + ) + assert m, f"Incomplete output definition {line!r}" + outputs_values_and_widths = ( + { + output: re.findall( + r"\(cons \"" + output + r"\" \(bv (\S+) (\d+)\)\)", line + )[0] + for output in outputs.keys() + }.items() + if use_assoc_list_helpers + else zip(outputs.keys(), re.findall(r"\(bv (\S+) (\d+)\)", line)) + ) + for output, (value, width) in outputs_values_and_widths: + assert isinstance(value, str), f"Bad value {value!r}" + assert value.startswith(('#b', '#x')), f"Non-binary value {value!r}" + assert int(width) == outputs[output], f"Width mismatch for output {output!r} (got {width}, expected {outputs[output]})" + int_value = int(value[2:], 16 if value.startswith('#x') else 2) + binary_string = format(int_value, '0{}b'.format(width)) + signals[output].append(binary_string) + + vcd_signals: SignalStepMap = {} + for signal, steps in signals.items(): + vcd_signals[signal] = [(time, f"b{value}") for time, value in enumerate(steps)] + + write_vcd(vcd_path, vcd_signals) diff --git a/chips/yosys/tests/functional/rtlil_cells.py b/chips/yosys/tests/functional/rtlil_cells.py new file mode 100644 index 0000000000000000000000000000000000000000..40bc9188f217a863c3a435ceec38f6d536446d24 --- /dev/null +++ b/chips/yosys/tests/functional/rtlil_cells.py @@ -0,0 +1,381 @@ +from itertools import chain +import random + +def write_rtlil_cell(f, cell_type, inputs, outputs, parameters): + f.write('autoidx 1\n') + f.write('module \\gold\n') + idx = 1 + for name, width in inputs.items(): + f.write(f'\twire width {width} input {idx} \\{name}\n') + idx += 1 + for name, width in outputs.items(): + f.write(f'\twire width {width} output {idx} \\{name}\n') + idx += 1 + f.write(f'\tcell ${cell_type} \\UUT\n') + for (name, value) in parameters.items(): + if value >= 2**32: + f.write(f'\t\tparameter \\{name} {value.bit_length()}\'{value:b}\n') + else: + f.write(f'\t\tparameter \\{name} {value}\n') + for name in chain(inputs.keys(), outputs.keys()): + f.write(f'\t\tconnect \\{name} \\{name}\n') + f.write(f'\tend\nend\n') + +class BaseCell: + def __init__(self, name, parameters, inputs, outputs, test_values): + self.name = name + self.parameters = parameters + self.inputs = inputs + self.outputs = outputs + self.test_values = test_values + def get_port_width(self, port, parameters): + def parse_specifier(spec): + if isinstance(spec, int): + return spec + if isinstance(spec, str): + return parameters[spec] + if callable(spec): + return spec(parameters) + assert False, "expected int, str or lambda" + if port in self.inputs: + return parse_specifier(self.inputs[port]) + elif port in self.outputs: + return parse_specifier(self.outputs[port]) + else: + assert False, "expected input or output" + def generate_tests(self, rnd): + def print_parameter(v): + if isinstance(v, bool): + return "S" if v else "U" + else: + return str(v) + for values in self.test_values: + if isinstance(values, int): + values = [values] + name = '-'.join([print_parameter(v) for v in values]) + parameters = {parameter: int(values[i]) for i, parameter in enumerate(self.parameters)} + if self.is_test_valid(values): + yield (name, parameters) + def write_rtlil_file(self, path, parameters): + inputs = {port: self.get_port_width(port, parameters) for port in self.inputs} + outputs = {port: self.get_port_width(port, parameters) for port in self.outputs} + with open(path, 'w') as f: + write_rtlil_cell(f, self.name, inputs, outputs, parameters) + def is_test_valid(self, values): + return True + +class UnaryCell(BaseCell): + def __init__(self, name, values): + super().__init__(name, ['A_WIDTH', 'Y_WIDTH', 'A_SIGNED'], {'A': 'A_WIDTH'}, {'Y': 'Y_WIDTH'}, values) + +class BinaryCell(BaseCell): + def __init__(self, name, values): + super().__init__(name, ['A_WIDTH', 'B_WIDTH', 'Y_WIDTH', 'A_SIGNED', 'B_SIGNED'], {'A': 'A_WIDTH', 'B': 'B_WIDTH'}, {'Y': 'Y_WIDTH'}, values) + +class ShiftCell(BaseCell): + def __init__(self, name, values): + super().__init__(name, ['A_WIDTH', 'B_WIDTH', 'Y_WIDTH', 'A_SIGNED', 'B_SIGNED'], {'A': 'A_WIDTH', 'B': 'B_WIDTH'}, {'Y': 'Y_WIDTH'}, values) + def is_test_valid(self, values): + (a_width, b_width, y_width, a_signed, b_signed) = values + if not self.name in ('shift', 'shiftx') and b_signed: return False + if self.name == 'shiftx' and a_signed: return False + return True + +class MuxCell(BaseCell): + def __init__(self, name, values): + super().__init__(name, ['WIDTH'], {'A': 'WIDTH', 'B': 'WIDTH', 'S': 1}, {'Y': 'WIDTH'}, values) + +class BWCell(BaseCell): + def __init__(self, name, values): + inputs = {'A': 'WIDTH', 'B': 'WIDTH'} + if name == "bwmux": inputs['S'] = 'WIDTH' + super().__init__(name, ['WIDTH'], inputs, {'Y': 'WIDTH'}, values) + +class PMuxCell(BaseCell): + def __init__(self, name, values): + b_width = lambda par: par['WIDTH'] * par['S_WIDTH'] + super().__init__(name, ['WIDTH', 'S_WIDTH'], {'A': 'WIDTH', 'B': b_width, 'S': 'S_WIDTH'}, {'Y': 'WIDTH'}, values) + +class BMuxCell(BaseCell): + def __init__(self, name, values): + a_width = lambda par: par['WIDTH'] << par['S_WIDTH'] + super().__init__(name, ['WIDTH', 'S_WIDTH'], {'A': a_width, 'S': 'S_WIDTH'}, {'Y': 'WIDTH'}, values) + +class DemuxCell(BaseCell): + def __init__(self, name, values): + y_width = lambda par: par['WIDTH'] << par['S_WIDTH'] + super().__init__(name, ['WIDTH', 'S_WIDTH'], {'A': 'WIDTH', 'S': 'S_WIDTH'}, {'Y': y_width}, values) + +class LUTCell(BaseCell): + def __init__(self, name, values): + super().__init__(name, ['WIDTH', 'LUT'], {'A': 'WIDTH'}, {'Y': 1}, values) + def generate_tests(self, rnd): + for width in self.test_values: + lut = rnd(f'lut-{width}').getrandbits(2**width) + yield (f'{width}', {'WIDTH' : width, 'LUT' : lut}) + +class ConcatCell(BaseCell): + def __init__(self, name, values): + y_width = lambda par: par['A_WIDTH'] + par['B_WIDTH'] + super().__init__(name, ['A_WIDTH', 'B_WIDTH'], {'A': 'A_WIDTH', 'B': 'B_WIDTH'}, {'Y': y_width}, values) + +class SliceCell(BaseCell): + def __init__(self, name, values): + super().__init__(name, ['A_WIDTH', 'OFFSET', 'Y_WIDTH'], {'A': 'A_WIDTH'}, {'Y': 'Y_WIDTH'}, values) + +class FACell(BaseCell): + def __init__(self, name, values): + super().__init__(name, ['WIDTH'], {'A': 'WIDTH', 'B': 'WIDTH', 'C': 'WIDTH'}, {'X': 'WIDTH', 'Y': 'WIDTH'}, values) + self.sim_preprocessing = "techmap" # because FA is not implemented in yosys sim + +class LCUCell(BaseCell): + def __init__(self, name, values): + super().__init__(name, ['WIDTH'], {'P': 'WIDTH', 'G': 'WIDTH', 'CI': 1}, {'CO': 'WIDTH'}, values) + self.sim_preprocessing = "techmap" # because LCU is not implemented in yosys sim + +class ALUCell(BaseCell): + def __init__(self, name, values): + super().__init__(name, ['A_WIDTH', 'B_WIDTH', 'Y_WIDTH', 'A_SIGNED', 'B_SIGNED'], {'A': 'A_WIDTH', 'B': 'B_WIDTH', 'CI': 1, 'BI': 1}, {'X': 'Y_WIDTH', 'Y': 'Y_WIDTH', 'CO': 'Y_WIDTH'}, values) + self.sim_preprocessing = "techmap" # because ALU is not implemented in yosys sim + +class FailCell(BaseCell): + def __init__(self, name): + super().__init__(name, [], {}, {}) + def generate_tests(self, rnd): + yield ('', {}) + def write_rtlil_file(self, path, parameters): + raise Exception(f'\'{self.name}\' cell unimplemented in test generator') + +class FFCell(BaseCell): + def __init__(self, name, values): + super().__init__(name, ['WIDTH'], ['D'], ['Q'], values) + def write_rtlil_file(self, path, parameters): + from test_functional import yosys_synth + verilog_file = path.parent / 'verilog.v' + with open(verilog_file, 'w') as f: + width = parameters['WIDTH'] + f.write(f""" +module gold( + input wire clk, + input wire [{width-1}:0] D, + output reg [{width-1}:0] Q +); + initial Q = {width}'b{("101" * width)[:width]}; + always @(posedge clk) + Q <= D; +endmodule""") + yosys_synth(verilog_file, path) + +class MemCell(BaseCell): + def __init__(self, name, values): + super().__init__(name, ['DATA_WIDTH', 'ADDR_WIDTH'], {'WA': 'ADDR_WIDTH', 'RA': 'ADDR_WIDTH', 'WD': 'DATA_WIDTH'}, {'RD': 'DATA_WIDTH'}, values) + def write_rtlil_file(self, path, parameters): + from test_functional import yosys_synth + verilog_file = path.parent / 'verilog.v' + with open(verilog_file, 'w') as f: + f.write(""" +module gold( + input wire clk, + input wire [{1}:0] WA, + input wire [{0}:0] WD, + input wire [{1}:0] RA, + output reg [{0}:0] RD +); + reg [{0}:0] mem[0:{2}]; + integer i; + initial + for(i = 0; i <= {2}; i = i + 1) + mem[i] = 9192 * (i + 1); + always @(*) + RD = mem[RA]; + always @(posedge clk) + mem[WA] <= WD; +endmodule""".format(parameters['DATA_WIDTH'] - 1, parameters['ADDR_WIDTH'] - 1, 2**parameters['ADDR_WIDTH'] - 1)) + yosys_synth(verilog_file, path) + +class MemDualCell(BaseCell): + def __init__(self, name, values): + super().__init__(name, ['DATA_WIDTH', 'ADDR_WIDTH'], + {'WA1': 'ADDR_WIDTH', 'WA2': 'ADDR_WIDTH', + 'RA1': 'ADDR_WIDTH', 'RA2': 'ADDR_WIDTH', + 'WD1': 'DATA_WIDTH', 'WD2': 'DATA_WIDTH'}, + {'RD1': 'DATA_WIDTH', 'RD2': 'DATA_WIDTH'}, values) + self.sim_preprocessing = "memory_map" # issue #4496 in yosys -sim prevents this example from working without memory_map + def write_rtlil_file(self, path, parameters): + from test_functional import yosys_synth + verilog_file = path.parent / 'verilog.v' + with open(verilog_file, 'w') as f: + f.write(""" +module gold( + input wire clk, + input wire [{1}:0] WA1, + input wire [{0}:0] WD1, + input wire [{1}:0] WA2, + input wire [{0}:0] WD2, + input wire [{1}:0] RA1, + input wire [{1}:0] RA2, + output reg [{0}:0] RD1, + output reg [{0}:0] RD2 +); + reg [{0}:0] mem[0:{2}]; + integer i; + initial + for(i = 0; i <= {2}; i = i + 1) + mem[i] = 9192 * (i + 1); + always @(*) + RD1 = mem[RA1]; + always @(*) + RD2 = mem[RA2]; + always @(posedge clk) begin + mem[WA1] <= WD1; + mem[WA2] <= WD2; + end +endmodule""".format(parameters['DATA_WIDTH'] - 1, parameters['ADDR_WIDTH'] - 1, 2**parameters['ADDR_WIDTH'] - 1)) + yosys_synth(verilog_file, path) + +class PicorvCell(BaseCell): + def __init__(self): + super().__init__("picorv", [], {}, {}, [()]) + self.smt_max_steps = 50 # z3 is too slow for more steps + def write_rtlil_file(self, path, parameters): + from test_functional import yosys, base_path, quote + tb_file = base_path / 'tests/functional/picorv32_tb.v' + cpu_file = base_path / 'tests/functional/picorv32.v' + yosys(f"read_verilog {quote(tb_file)} {quote(cpu_file)}; prep -top gold; flatten; write_rtlil {quote(path)}") + +binary_widths = [ + # try to cover extending A operand, extending B operand, extending/truncating result + (16, 32, 48, True, True), + (16, 32, 48, False, False), + (32, 16, 48, True, True), + (32, 16, 48, False, False), + (32, 32, 16, True, True), + (32, 32, 16, False, False), + # have at least one test that checks small inputs, which will exercise the cornercases more + (4, 4, 8, True, True), + (4, 4, 8, False, False) +] + +unary_widths = [ + (6, 12, True), + (6, 12, False), + (32, 16, True), + (32, 16, False) +] + +# note that meaningless combinations of signednesses are eliminated, +# like e.g. most shift operations don't take signed shift amounts +shift_widths = [ + # one set of tests that definitely checks all possible shift amounts + # with a bigger result width to make sure it's not truncated + (32, 6, 64, True, False), + (32, 6, 64, False, False), + (32, 6, 64, True, True), + (32, 6, 64, False, True), + # one set that checks very oversized shifts + (32, 32, 64, True, False), + (32, 32, 64, False, False), + (32, 32, 64, True, True), + (32, 32, 64, False, True), + # at least one test where the result is going to be truncated + (32, 6, 16, False, False), + # since 1-bit shifts are special cased + (1, 4, 1, False, False), + (1, 4, 1, True, False), +] + +rtlil_cells = [ + UnaryCell("not", unary_widths), + UnaryCell("pos", unary_widths), + UnaryCell("neg", unary_widths), + BinaryCell("and", binary_widths), + BinaryCell("or", binary_widths), + BinaryCell("xor", binary_widths), + BinaryCell("xnor", binary_widths), + UnaryCell("reduce_and", unary_widths), + UnaryCell("reduce_or", unary_widths), + UnaryCell("reduce_xor", unary_widths), + UnaryCell("reduce_xnor", unary_widths), + UnaryCell("reduce_bool", unary_widths), + ShiftCell("shl", shift_widths), + ShiftCell("shr", shift_widths), + ShiftCell("sshl", shift_widths), + ShiftCell("sshr", shift_widths), + ShiftCell("shift", shift_widths), + ShiftCell("shiftx", shift_widths), + FACell("fa", [8, 20]), + LCUCell("lcu", [1, 10]), + ALUCell("alu", binary_widths), + BinaryCell("lt", binary_widths), + BinaryCell("le", binary_widths), + BinaryCell("eq", binary_widths), + BinaryCell("ne", binary_widths), + BinaryCell("eqx", binary_widths), + BinaryCell("nex", binary_widths), + BinaryCell("ge", binary_widths), + BinaryCell("gt", binary_widths), + BinaryCell("add", binary_widths), + BinaryCell("sub", binary_widths), + BinaryCell("mul", binary_widths), +# BinaryCell("macc"), + BinaryCell("div", binary_widths), + BinaryCell("mod", binary_widths), + BinaryCell("divfloor", binary_widths), + BinaryCell("modfloor", binary_widths), + BinaryCell("pow", binary_widths), + UnaryCell("logic_not", unary_widths), + BinaryCell("logic_and", binary_widths), + BinaryCell("logic_or", binary_widths), + SliceCell("slice", [(32, 10, 15), (8, 0, 4), (10, 0, 10)]), + ConcatCell("concat", [(16, 16), (8, 14), (20, 10)]), + MuxCell("mux", [10, 16, 40]), + BMuxCell("bmux", [(10, 1), (10, 2), (10, 4)]), + PMuxCell("pmux", [(10, 1), (10, 4), (20, 4)]), + DemuxCell("demux", [(10, 1), (32, 2), (16, 4)]), + LUTCell("lut", [4, 6, 8]), +# ("sop", ["A", "Y"]), +# ("tribuf", ["A", "EN", "Y"]), +# ("specify2", ["EN", "SRC", "DST"]), +# ("specify3", ["EN", "SRC", "DST", "DAT"]), +# ("specrule", ["SRC_EN", "DST_EN", "SRC", "DST"]), + BWCell("bweqx", [10, 16, 40]), + BWCell("bwmux", [10, 16, 40]), + FFCell("ff", [10, 20, 40]), + MemCell("mem", [(16, 4)]), + MemDualCell("mem-dual", [(16, 4)]), +# ("assert", ["A", "EN"]), +# ("assume", ["A", "EN"]), +# ("live", ["A", "EN"]), +# ("fair", ["A", "EN"]), +# ("cover", ["A", "EN"]), +# ("initstate", ["Y"]), +# ("anyconst", ["Y"]), +# ("anyseq", ["Y"]), +# ("anyinit", ["D", "Q"]), +# ("allconst", ["Y"]), +# ("allseq", ["Y"]), +# ("equiv", ["A", "B", "Y"]), +# ("print", ["EN", "TRG", "ARGS"]), +# ("check", ["A", "EN", "TRG", "ARGS"]), +# ("set_tag", ["A", "SET", "CLR", "Y"]), +# ("get_tag", ["A", "Y"]), +# ("overwrite_tag", ["A", "SET", "CLR"]), +# ("original_tag", ["A", "Y"]), +# ("future_ff", ["A", "Y"]), +# ("scopeinfo", []), + PicorvCell() +] + +def generate_test_cases(per_cell, rnd): + tests = [] + names = [] + for cell in rtlil_cells: + seen_names = set() + for (name, parameters) in cell.generate_tests(rnd): + if not name in seen_names: + seen_names.add(name) + tests.append((cell, parameters)) + names.append(f'{cell.name}-{name}' if name != '' else cell.name) + if per_cell is not None and len(seen_names) >= per_cell: + break + return (names, tests) diff --git a/chips/yosys/tests/functional/run-test.sh b/chips/yosys/tests/functional/run-test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8f72f7c1be62523a06a9c5b533cb0f6017c2ac25 --- /dev/null +++ b/chips/yosys/tests/functional/run-test.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) + +pytest -v -m "not smt and not rkt" "$SCRIPT_DIR" "$@" diff --git a/chips/yosys/tests/functional/smt_vcd.py b/chips/yosys/tests/functional/smt_vcd.py new file mode 100644 index 0000000000000000000000000000000000000000..162ddf094cab0fa0e6172406f6af68e6d9941b9b --- /dev/null +++ b/chips/yosys/tests/functional/smt_vcd.py @@ -0,0 +1,188 @@ +import sys +import argparse +import os +import smtio +import re + +class SExprParserError(Exception): + pass + +class SExprParser: + def __init__(self): + self.peekbuf = None + self.stack = [[]] + self.atom_pattern = re.compile(r'[a-zA-Z0-9~!@$%^&*_\-+=<>.?/#]+') + def parse_line(self, line): + ptr = 0 + while ptr < len(line): + if line[ptr].isspace(): + ptr += 1 + elif line[ptr] == ';': + break + elif line[ptr] == '(': + ptr += 1 + self.stack.append([]) + elif line[ptr] == ')': + ptr += 1 + assert len(self.stack) > 1, "too many closed parentheses" + v = self.stack.pop() + self.stack[-1].append(v) + else: + match = self.atom_pattern.match(line, ptr) + if match is None: + raise SExprParserError(f"invalid character '{line[ptr]}' in line '{line}'") + start, ptr = match.span() + self.stack[-1].append(line[start:ptr]) + def finish(self): + assert len(self.stack) == 1, "too many open parentheses" + def retrieve(self): + rv, self.stack[0] = self.stack[0], [] + return rv + +def simulate_smt_with_smtio(smt_file_path, vcd_path, smt_io, num_steps, rnd): + inputs = {} + outputs = {} + states = {} + + def handle_datatype(lst): + print(lst) + datatype_name = lst[1] + declarations = lst[2][0][1:] # Skip the first item (e.g., 'mk_inputs') + if datatype_name.endswith("_Inputs"): + for declaration in declarations: + input_name = declaration[0] + bitvec_size = declaration[1][2] + assert input_name.startswith("gold_Inputs_") + inputs[input_name[len("gold_Inputs_"):]] = int(bitvec_size) + elif datatype_name.endswith("_Outputs"): + for declaration in declarations: + output_name = declaration[0] + bitvec_size = declaration[1][2] + assert output_name.startswith("gold_Outputs_") + outputs[output_name[len("gold_Outputs_"):]] = int(bitvec_size) + elif datatype_name.endswith("_State"): + for declaration in declarations: + state_name = declaration[0] + assert state_name.startswith("gold_State_") + if declaration[1][0] == "_": + states[state_name[len("gold_State_"):]] = int(declaration[1][2]) + else: + states[state_name[len("gold_State_"):]] = (declaration[1][1][2], declaration[1][2][2]) + + parser = SExprParser() + with open(smt_file_path, 'r') as smt_file: + for line in smt_file: + parser.parse_line(line) + for expr in parser.retrieve(): + smt_io.write(smt_io.unparse(expr)) + if expr[0] == "declare-datatype": + handle_datatype(expr) + + parser.finish() + assert smt_io.check_sat() == 'sat' + + def set_step(inputs, step): + # This function assumes 'inputs' is a dictionary like {"A": 5, "B": 4} + # and 'input_values' is a dictionary like {"A": 5, "B": 13} specifying the concrete values for each input. + + mk_inputs_parts = [] + for input_name, width in inputs.items(): + value = rnd.getrandbits(width) # Generate a random number up to the maximum value for the bit size + binary_string = format(value, '0{}b'.format(width)) # Convert value to binary with leading zeros + mk_inputs_parts.append(f"#b{binary_string}") + + mk_inputs_call = "gold_Inputs " + " ".join(mk_inputs_parts) + return [ + f"(define-const test_inputs_step_n{step} gold_Inputs ({mk_inputs_call}))\n", + f"(define-const test_results_step_n{step} (Pair gold_Outputs gold_State) (gold test_inputs_step_n{step} test_state_step_n{step}))\n", + f"(define-const test_outputs_step_n{step} gold_Outputs (first test_results_step_n{step}))\n", + f"(define-const test_state_step_n{step+1} gold_State (second test_results_step_n{step}))\n", + ] + + smt_commands = [f"(define-const test_state_step_n0 gold_State gold-initial)\n"] + for step in range(num_steps): + for step_command in set_step(inputs, step): + smt_commands.append(step_command) + + for command in smt_commands: + smt_io.write(command) + + assert smt_io.check_sat() == 'sat' + + # Store signal values + signals = {name: [] for name in list(inputs.keys()) + list(outputs.keys())} + # Retrieve and print values for each state + def hex_to_bin(value): + if value.startswith('x'): + hex_value = value[1:] # Remove the 'x' prefix + bin_value = bin(int(hex_value, 16))[2:] # Convert to binary and remove the '0b' prefix + return f'b{bin_value.zfill(len(hex_value) * 4)}' # Add 'b' prefix and pad with zeros + return value + + combined_assertions = [] + for step in range(num_steps): + print(f"Values for step {step + 1}:") + for input_name, width in inputs.items(): + value = smt_io.get(f'(gold_Inputs_{input_name} test_inputs_step_n{step})') + value = hex_to_bin(value[1:]) + print(f" {input_name}: {value}") + signals[input_name].append((step, value)) + for output_name, width in outputs.items(): + value = smt_io.get(f'(gold_Outputs_{output_name} test_outputs_step_n{step})') + value = hex_to_bin(value[1:]) + print(f" {output_name}: {value}") + signals[output_name].append((step, value)) + combined_assertions.append(f'(= (gold_Outputs_{output_name} test_outputs_step_n{step}) #{value})') + # Create a single assertion covering all timesteps + combined_condition = " ".join(combined_assertions) + smt_io.write(f'(assert (not (and {combined_condition})))') + + # Check the combined assertion + assert smt_io.check_sat(["unsat"]) == "unsat" + + def write_vcd(filename, signals, timescale='1 ns', date='today'): + with open(filename, 'w') as f: + # Write the header + f.write(f"$date\n {date}\n$end\n") + f.write(f"$timescale {timescale} $end\n") + + # Declare signals + f.write("$scope module gold $end\n") + for signal_name, changes in signals.items(): + signal_size = len(changes[0][1]) + f.write(f"$var wire {signal_size - 1} {signal_name} {signal_name} $end\n") + f.write("$upscope $end\n") + f.write("$enddefinitions $end\n") + + # Collect all unique timestamps + timestamps = sorted(set(time for changes in signals.values() for time, _ in changes)) + + # Write initial values + f.write("#0\n") + for signal_name, changes in signals.items(): + for time, value in changes: + if time == 0: + f.write(f"{value} {signal_name}\n") + + # Write value changes + for time in timestamps: + if time != 0: + f.write(f"#{time}\n") + for signal_name, changes in signals.items(): + for change_time, value in changes: + if change_time == time: + f.write(f"{value} {signal_name}\n") + + + write_vcd(vcd_path, signals) + +def simulate_smt(smt_file_path, vcd_path, num_steps, rnd): + so = smtio.SmtOpts() + so.solver = "z3" + so.logic = "ABV" + so.debug_print = True + smt_io = smtio.SmtIo(opts=so) + try: + simulate_smt_with_smtio(smt_file_path, vcd_path, smt_io, num_steps, rnd) + finally: + smt_io.p_close() diff --git a/chips/yosys/tests/functional/smtio.py b/chips/yosys/tests/functional/smtio.py new file mode 100644 index 0000000000000000000000000000000000000000..e32f43c60a0037e9931500d270d3744bce3344ac --- /dev/null +++ b/chips/yosys/tests/functional/smtio.py @@ -0,0 +1,1331 @@ +# +# yosys -- Yosys Open SYnthesis Suite +# +# Copyright (C) 2012 Claire Xenia Wolf +# +# Permission to use, copy, modify, and/or distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# + +import sys, re, os, signal, json +import subprocess +if os.name == "posix": + import resource +from copy import copy +from select import select +from time import time +from queue import Queue, Empty +from threading import Thread + + +# This is needed so that the recursive SMT2 S-expression parser +# does not run out of stack frames when parsing large expressions +if os.name == "posix": + smtio_reclimit = 64 * 1024 + if sys.getrecursionlimit() < smtio_reclimit: + sys.setrecursionlimit(smtio_reclimit) + + current_rlimit_stack = resource.getrlimit(resource.RLIMIT_STACK) + if current_rlimit_stack[0] != resource.RLIM_INFINITY: + smtio_stacksize = 128 * 1024 * 1024 + if os.uname().sysname == "Darwin": + # MacOS has rather conservative stack limits + smtio_stacksize = 8 * 1024 * 1024 + if current_rlimit_stack[1] != resource.RLIM_INFINITY: + smtio_stacksize = min(smtio_stacksize, current_rlimit_stack[1]) + if current_rlimit_stack[0] < smtio_stacksize: + try: + resource.setrlimit(resource.RLIMIT_STACK, (smtio_stacksize, current_rlimit_stack[1])) + except ValueError: + # couldn't get more stack, just run with what we have + pass + + +# currently running solvers (so we can kill them) +running_solvers = dict() +forced_shutdown = False +solvers_index = 0 + +def force_shutdown(signum, frame): + global forced_shutdown + if not forced_shutdown: + forced_shutdown = True + if signum is not None: + print("<%s>" % signal.Signals(signum).name) + for p in running_solvers.values(): + # os.killpg(os.getpgid(p.pid), signal.SIGTERM) + os.kill(p.pid, signal.SIGTERM) + sys.exit(1) + +if os.name == "posix": + signal.signal(signal.SIGHUP, force_shutdown) +signal.signal(signal.SIGINT, force_shutdown) +signal.signal(signal.SIGTERM, force_shutdown) + +def except_hook(exctype, value, traceback): + if not forced_shutdown: + sys.__excepthook__(exctype, value, traceback) + force_shutdown(None, None) + +sys.excepthook = except_hook + + +def recursion_helper(iteration, *request): + stack = [iteration(*request)] + + while stack: + top = stack.pop() + try: + request = next(top) + except StopIteration: + continue + + stack.append(top) + stack.append(iteration(*request)) + + +hex_dict = { + "0": "0000", "1": "0001", "2": "0010", "3": "0011", + "4": "0100", "5": "0101", "6": "0110", "7": "0111", + "8": "1000", "9": "1001", "A": "1010", "B": "1011", + "C": "1100", "D": "1101", "E": "1110", "F": "1111", + "a": "1010", "b": "1011", "c": "1100", "d": "1101", + "e": "1110", "f": "1111" +} + + +class SmtModInfo: + def __init__(self): + self.inputs = set() + self.outputs = set() + self.registers = set() + self.memories = dict() + self.wires = set() + self.wsize = dict() + self.clocks = dict() + self.cells = dict() + self.asserts = dict() + self.assumes = dict() + self.covers = dict() + self.maximize = set() + self.minimize = set() + self.anyconsts = dict() + self.anyseqs = dict() + self.allconsts = dict() + self.allseqs = dict() + self.asize = dict() + self.witness = [] + + +class SmtIo: + def __init__(self, opts=None): + global solvers_index + + self.logic = None + self.logic_qf = True + self.logic_ax = True + self.logic_uf = True + self.logic_bv = True + self.logic_dt = False + self.forall = False + self.timeout = 0 + self.produce_models = True + self.recheck = False + self.smt2cache = [list()] + self.smt2_options = dict() + self.smt2_assumptions = dict() + self.p = None + self.p_index = solvers_index + solvers_index += 1 + + if opts is not None: + self.logic = opts.logic + self.solver = opts.solver + self.solver_opts = opts.solver_opts + self.debug_print = opts.debug_print + self.debug_file = opts.debug_file + self.dummy_file = opts.dummy_file + self.timeinfo = opts.timeinfo + self.timeout = opts.timeout + self.unroll = opts.unroll + self.noincr = opts.noincr + self.info_stmts = opts.info_stmts + self.nocomments = opts.nocomments + + else: + self.solver = "yices" + self.solver_opts = list() + self.debug_print = False + self.debug_file = None + self.dummy_file = None + self.timeinfo = os.name != "nt" + self.timeout = 0 + self.unroll = False + self.noincr = False + self.info_stmts = list() + self.nocomments = False + + self.start_time = time() + + self.modinfo = dict() + self.curmod = None + self.topmod = None + self.setup_done = False + + def __del__(self): + if self.p is not None and not forced_shutdown: + os.killpg(os.getpgid(self.p.pid), signal.SIGTERM) + if running_solvers is not None: + del running_solvers[self.p_index] + + def setup(self): + assert not self.setup_done + + if self.forall: + self.unroll = False + + if self.solver == "yices": + if self.forall: + self.noincr = True + + if self.noincr: + self.popen_vargs = ['yices-smt2'] + self.solver_opts + else: + self.popen_vargs = ['yices-smt2', '--incremental'] + self.solver_opts + if self.timeout != 0: + self.popen_vargs.append('-t') + self.popen_vargs.append('%d' % self.timeout); + + if self.solver == "z3": + self.popen_vargs = ['z3', '-smt2', '-in'] + self.solver_opts + if self.timeout != 0: + self.popen_vargs.append('-T:%d' % self.timeout); + + if self.solver in ["cvc4", "cvc5"]: + self.recheck = True + if self.noincr: + self.popen_vargs = [self.solver, '--lang', 'smt2.6' if self.logic_dt else 'smt2'] + self.solver_opts + else: + self.popen_vargs = [self.solver, '--incremental', '--lang', 'smt2.6' if self.logic_dt else 'smt2'] + self.solver_opts + if self.timeout != 0: + self.popen_vargs.append('--tlimit=%d000' % self.timeout); + + if self.solver == "mathsat": + self.popen_vargs = ['mathsat'] + self.solver_opts + if self.timeout != 0: + print('timeout option is not supported for mathsat.') + sys.exit(1) + + if self.solver in ["boolector", "bitwuzla"]: + if self.noincr: + self.popen_vargs = [self.solver, '--smt2'] + self.solver_opts + else: + self.popen_vargs = [self.solver, '--smt2', '-i'] + self.solver_opts + self.unroll = True + if self.timeout != 0: + print('timeout option is not supported for %s.' % self.solver) + sys.exit(1) + + if self.solver == "abc": + if len(self.solver_opts) > 0: + self.popen_vargs = ['yosys-abc', '-S', '; '.join(self.solver_opts)] + else: + self.popen_vargs = ['yosys-abc', '-S', '%blast; &sweep -C 5000; &syn4; &cec -s -m -C 2000'] + self.logic_ax = False + self.unroll = True + self.noincr = True + if self.timeout != 0: + print('timeout option is not supported for abc.') + sys.exit(1) + + if self.solver == "dummy": + assert self.dummy_file is not None + self.dummy_fd = open(self.dummy_file, "r") + else: + if self.dummy_file is not None: + self.dummy_fd = open(self.dummy_file, "w") + if not self.noincr: + self.p_open() + + if self.unroll: + assert not self.forall + self.logic_uf = False + self.unroll_idcnt = 0 + self.unroll_buffer = "" + self.unroll_level = 0 + self.unroll_sorts = set() + self.unroll_objs = set() + self.unroll_decls = dict() + self.unroll_cache = dict() + self.unroll_stack = list() + + if self.logic is None: + self.logic = "" + if self.logic_qf: self.logic += "QF_" + if self.logic_ax: self.logic += "A" + if self.logic_uf: self.logic += "UF" + if self.logic_bv: self.logic += "BV" + if self.logic_dt: self.logic = "ALL" + if self.solver == "yices" and self.forall: self.logic = "BV" + + self.setup_done = True + + for stmt in self.info_stmts: + self.write(stmt) + + if self.produce_models: + self.write("(set-option :produce-models true)") + + #See the SMT-LIB Standard, Section 4.1.7 + modestart_options = [":global-declarations", ":interactive-mode", ":produce-assertions", ":produce-assignments", ":produce-models", ":produce-proofs", ":produce-unsat-assumptions", ":produce-unsat-cores", ":random-seed"] + for key, val in self.smt2_options.items(): + if key in modestart_options: + self.write("(set-option {} {})".format(key, val)) + + self.write("(set-logic %s)" % self.logic) + + if self.forall and self.solver == "yices": + self.write("(set-option :yices-ef-max-iters 1000000000)") + + for key, val in self.smt2_options.items(): + if key not in modestart_options: + self.write("(set-option {} {})".format(key, val)) + + def timestamp(self): + secs = int(time() - self.start_time) + return "## %3d:%02d:%02d " % (secs // (60*60), (secs // 60) % 60, secs % 60) + + def replace_in_stmt(self, stmt, pat, repl): + if stmt == pat: + return repl + + if isinstance(stmt, list): + return [self.replace_in_stmt(s, pat, repl) for s in stmt] + + return stmt + + def unroll_stmt(self, stmt): + result = [] + recursion_helper(self._unroll_stmt_into, stmt, result) + return result.pop() + + def _unroll_stmt_into(self, stmt, output, depth=128): + if not isinstance(stmt, list): + output.append(stmt) + return + + new_stmt = [] + for s in stmt: + if depth: + yield from self._unroll_stmt_into(s, new_stmt, depth - 1) + else: + yield s, new_stmt + stmt = new_stmt + + if len(stmt) >= 2 and not isinstance(stmt[0], list) and stmt[0] in self.unroll_decls: + assert stmt[1] in self.unroll_objs + + key = tuple(stmt) + if key not in self.unroll_cache: + decl = copy(self.unroll_decls[key[0]]) + + self.unroll_cache[key] = "|UNROLL#%d|" % self.unroll_idcnt + decl[1] = self.unroll_cache[key] + self.unroll_idcnt += 1 + + if decl[0] == "declare-fun": + if isinstance(decl[3], list) or decl[3] not in self.unroll_sorts: + self.unroll_objs.add(decl[1]) + decl[2] = list() + else: + self.unroll_objs.add(decl[1]) + decl = list() + + elif decl[0] == "define-fun": + arg_index = 1 + for arg_name, arg_sort in decl[2]: + decl[4] = self.replace_in_stmt(decl[4], arg_name, key[arg_index]) + arg_index += 1 + decl[2] = list() + + if len(decl) > 0: + tmp = [] + if depth: + yield from self._unroll_stmt_into(decl, tmp, depth - 1) + else: + yield decl, tmp + + decl = tmp.pop() + self.write(self.unparse(decl), unroll=False) + + output.append(self.unroll_cache[key]) + return + + output.append(stmt) + + def p_thread_main(self): + while True: + data = self.p.stdout.readline().decode("utf-8") + if data == "": break + self.p_queue.put(data) + self.p_queue.put("") + self.p_running = False + + def p_open(self): + assert self.p is None + try: + self.p = subprocess.Popen(self.popen_vargs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + except FileNotFoundError: + print("%s SMT Solver '%s' not found in path." % (self.timestamp(), self.popen_vargs[0]), flush=True) + sys.exit(1) + running_solvers[self.p_index] = self.p + self.p_running = True + self.p_next = None + self.p_queue = Queue() + self.p_thread = Thread(target=self.p_thread_main) + self.p_thread.start() + + def p_write(self, data, flush): + assert self.p is not None + self.p.stdin.write(bytes(data, "utf-8")) + if flush: self.p.stdin.flush() + + def p_read(self): + assert self.p is not None + if self.p_next is not None: + data = self.p_next + self.p_next = None + return data + if not self.p_running: + return "" + return self.p_queue.get() + + def p_poll(self, timeout=0.1): + assert self.p is not None + assert self.p_running + if self.p_next is not None: + return False + try: + self.p_next = self.p_queue.get(True, timeout) + return False + except Empty: + return True + + def p_close(self): + assert self.p is not None + self.p.stdin.close() + self.p_thread.join() + assert not self.p_running + del running_solvers[self.p_index] + self.p = None + self.p_next = None + self.p_queue = None + self.p_thread = None + + def write(self, stmt, unroll=True): + if stmt.startswith(";"): + self.info(stmt) + if not self.setup_done: + self.info_stmts.append(stmt) + return + elif not self.setup_done: + self.setup() + + stmt = stmt.strip() + + if self.nocomments or self.unroll: + stmt = re.sub(r" *;.*", "", stmt) + if stmt == "": return + + recheck = None + + if self.solver != "dummy": + if self.noincr: + # Don't close the solver yet, if we're just unrolling definitions + # required for a (get-...) statement + if self.p is not None and not stmt.startswith("(get-") and unroll: + self.p_close() + + if unroll and self.unroll: + s = re.sub(r"\|[^|]*\|", "", stmt) + self.unroll_level += s.count("(") - s.count(")") + if self.unroll_level > 0: + self.unroll_buffer += stmt + self.unroll_buffer += " " + return + else: + stmt = self.unroll_buffer + stmt + self.unroll_buffer = "" + + s = self.parse(stmt) + + if self.recheck and s and s[0].startswith("get-"): + recheck = self.unroll_idcnt + + if self.debug_print: + print("-> %s" % s) + + if len(s) == 3 and s[0] == "declare-sort" and s[2] == "0": + self.unroll_sorts.add(s[1]) + return + + elif len(s) == 4 and s[0] == "declare-fun" and s[2] == [] and s[3] in self.unroll_sorts: + self.unroll_objs.add(s[1]) + return + + elif len(s) >= 4 and s[0] == "declare-fun": + for arg_sort in s[2]: + if arg_sort in self.unroll_sorts: + self.unroll_decls[s[1]] = s + return + + elif len(s) >= 4 and s[0] == "define-fun": + for arg_name, arg_sort in s[2]: + if arg_sort in self.unroll_sorts: + self.unroll_decls[s[1]] = s + return + + stmt = self.unparse(self.unroll_stmt(s)) + + if recheck is not None and recheck != self.unroll_idcnt: + self.check_sat(["sat"]) + + if stmt == "(push 1)": + self.unroll_stack.append(( + copy(self.unroll_sorts), + copy(self.unroll_objs), + copy(self.unroll_decls), + copy(self.unroll_cache), + )) + + if stmt == "(pop 1)": + self.unroll_sorts, self.unroll_objs, self.unroll_decls, self.unroll_cache = self.unroll_stack.pop() + + if self.debug_print: + print("> %s" % stmt) + + if self.debug_file: + print(stmt, file=self.debug_file) + self.debug_file.flush() + + if self.solver != "dummy": + if self.noincr: + if stmt == "(push 1)": + self.smt2cache.append(list()) + elif stmt == "(pop 1)": + self.smt2cache.pop() + else: + if self.p is not None: + self.p_write(stmt + "\n", True) + self.smt2cache[-1].append(stmt) + else: + self.p_write(stmt + "\n", True) + + def info(self, stmt): + if not stmt.startswith("; yosys-smt2-"): + return + + fields = stmt.split() + + if fields[1] == "yosys-smt2-solver-option": + self.smt2_options[fields[2]] = fields[3] + + if fields[1] == "yosys-smt2-nomem": + if self.logic is None: + self.logic_ax = False + + if fields[1] == "yosys-smt2-nobv": + if self.logic is None: + self.logic_bv = False + + if fields[1] == "yosys-smt2-stdt": + if self.logic is None: + self.logic_dt = True + + if fields[1] == "yosys-smt2-forall": + if self.logic is None: + self.logic_qf = False + self.forall = True + + if fields[1] == "yosys-smt2-module": + self.curmod = fields[2] + self.modinfo[self.curmod] = SmtModInfo() + + if fields[1] == "yosys-smt2-cell": + self.modinfo[self.curmod].cells[fields[3]] = fields[2] + + if fields[1] == "yosys-smt2-topmod": + self.topmod = fields[2] + + if fields[1] == "yosys-smt2-input": + self.modinfo[self.curmod].inputs.add(fields[2]) + self.modinfo[self.curmod].wsize[fields[2]] = int(fields[3]) + + if fields[1] == "yosys-smt2-output": + self.modinfo[self.curmod].outputs.add(fields[2]) + self.modinfo[self.curmod].wsize[fields[2]] = int(fields[3]) + + if fields[1] == "yosys-smt2-register": + self.modinfo[self.curmod].registers.add(fields[2]) + self.modinfo[self.curmod].wsize[fields[2]] = int(fields[3]) + + if fields[1] == "yosys-smt2-memory": + self.modinfo[self.curmod].memories[fields[2]] = (int(fields[3]), int(fields[4]), int(fields[5]), int(fields[6]), fields[7] == "async") + + if fields[1] == "yosys-smt2-wire": + self.modinfo[self.curmod].wires.add(fields[2]) + self.modinfo[self.curmod].wsize[fields[2]] = int(fields[3]) + + if fields[1] == "yosys-smt2-clock": + for edge in fields[3:]: + if fields[2] not in self.modinfo[self.curmod].clocks: + self.modinfo[self.curmod].clocks[fields[2]] = edge + elif self.modinfo[self.curmod].clocks[fields[2]] != edge: + self.modinfo[self.curmod].clocks[fields[2]] = "event" + + if fields[1] == "yosys-smt2-assert": + if len(fields) > 4: + self.modinfo[self.curmod].asserts["%s_a %s" % (self.curmod, fields[2])] = f'{fields[4]} ({fields[3]})' + else: + self.modinfo[self.curmod].asserts["%s_a %s" % (self.curmod, fields[2])] = fields[3] + + if fields[1] == "yosys-smt2-cover": + if len(fields) > 4: + self.modinfo[self.curmod].covers["%s_c %s" % (self.curmod, fields[2])] = f'{fields[4]} ({fields[3]})' + else: + self.modinfo[self.curmod].covers["%s_c %s" % (self.curmod, fields[2])] = fields[3] + + if fields[1] == "yosys-smt2-assume": + if len(fields) > 4: + self.modinfo[self.curmod].assumes["%s_u %s" % (self.curmod, fields[2])] = f'{fields[4]} ({fields[3]})' + else: + self.modinfo[self.curmod].assumes["%s_u %s" % (self.curmod, fields[2])] = fields[3] + + if fields[1] == "yosys-smt2-maximize": + self.modinfo[self.curmod].maximize.add(fields[2]) + + if fields[1] == "yosys-smt2-minimize": + self.modinfo[self.curmod].minimize.add(fields[2]) + + if fields[1] == "yosys-smt2-anyconst": + self.modinfo[self.curmod].anyconsts[fields[2]] = (fields[4], None if len(fields) <= 5 else fields[5]) + self.modinfo[self.curmod].asize[fields[2]] = int(fields[3]) + + if fields[1] == "yosys-smt2-anyseq": + self.modinfo[self.curmod].anyseqs[fields[2]] = (fields[4], None if len(fields) <= 5 else fields[5]) + self.modinfo[self.curmod].asize[fields[2]] = int(fields[3]) + + if fields[1] == "yosys-smt2-allconst": + self.modinfo[self.curmod].allconsts[fields[2]] = (fields[4], None if len(fields) <= 5 else fields[5]) + self.modinfo[self.curmod].asize[fields[2]] = int(fields[3]) + + if fields[1] == "yosys-smt2-allseq": + self.modinfo[self.curmod].allseqs[fields[2]] = (fields[4], None if len(fields) <= 5 else fields[5]) + self.modinfo[self.curmod].asize[fields[2]] = int(fields[3]) + + if fields[1] == "yosys-smt2-witness": + data = json.loads(stmt.split(None, 2)[2]) + if data.get("type") in ["cell", "mem", "posedge", "negedge", "input", "reg", "init", "seq", "blackbox"]: + self.modinfo[self.curmod].witness.append(data) + + def hiernets(self, top, regs_only=False): + def hiernets_worker(nets, mod, cursor): + for netname in sorted(self.modinfo[mod].wsize.keys()): + if not regs_only or netname in self.modinfo[mod].registers: + nets.append(cursor + [netname]) + for cellname, celltype in sorted(self.modinfo[mod].cells.items()): + hiernets_worker(nets, celltype, cursor + [cellname]) + + nets = list() + hiernets_worker(nets, top, []) + return nets + + def hieranyconsts(self, top): + def worker(results, mod, cursor): + for name, value in sorted(self.modinfo[mod].anyconsts.items()): + width = self.modinfo[mod].asize[name] + results.append((cursor, name, value[0], value[1], width)) + for cellname, celltype in sorted(self.modinfo[mod].cells.items()): + worker(results, celltype, cursor + [cellname]) + + results = list() + worker(results, top, []) + return results + + def hieranyseqs(self, top): + def worker(results, mod, cursor): + for name, value in sorted(self.modinfo[mod].anyseqs.items()): + width = self.modinfo[mod].asize[name] + results.append((cursor, name, value[0], value[1], width)) + for cellname, celltype in sorted(self.modinfo[mod].cells.items()): + worker(results, celltype, cursor + [cellname]) + + results = list() + worker(results, top, []) + return results + + def hierallconsts(self, top): + def worker(results, mod, cursor): + for name, value in sorted(self.modinfo[mod].allconsts.items()): + width = self.modinfo[mod].asize[name] + results.append((cursor, name, value[0], value[1], width)) + for cellname, celltype in sorted(self.modinfo[mod].cells.items()): + worker(results, celltype, cursor + [cellname]) + + results = list() + worker(results, top, []) + return results + + def hierallseqs(self, top): + def worker(results, mod, cursor): + for name, value in sorted(self.modinfo[mod].allseqs.items()): + width = self.modinfo[mod].asize[name] + results.append((cursor, name, value[0], value[1], width)) + for cellname, celltype in sorted(self.modinfo[mod].cells.items()): + worker(results, celltype, cursor + [cellname]) + + results = list() + worker(results, top, []) + return results + + def hiermems(self, top): + def hiermems_worker(mems, mod, cursor): + for memname in sorted(self.modinfo[mod].memories.keys()): + mems.append(cursor + [memname]) + for cellname, celltype in sorted(self.modinfo[mod].cells.items()): + hiermems_worker(mems, celltype, cursor + [cellname]) + + mems = list() + hiermems_worker(mems, top, []) + return mems + + def hierwitness(self, top, allregs=False, blackbox=True): + init_witnesses = [] + seq_witnesses = [] + clk_witnesses = [] + mem_witnesses = [] + + def absolute(path, cursor, witness): + return { + **witness, + "path": path + tuple(witness["path"]), + "smtpath": cursor + [witness["smtname"]], + } + + for witness in self.modinfo[top].witness: + if witness["type"] == "input": + seq_witnesses.append(absolute((), [], witness)) + if witness["type"] in ("posedge", "negedge"): + clk_witnesses.append(absolute((), [], witness)) + + init_types = ["init"] + if allregs: + init_types.append("reg") + + seq_types = ["seq"] + if blackbox: + seq_types.append("blackbox") + + def worker(mod, path, cursor): + cell_paths = {} + for witness in self.modinfo[mod].witness: + if witness["type"] in init_types: + init_witnesses.append(absolute(path, cursor, witness)) + if witness["type"] in seq_types: + seq_witnesses.append(absolute(path, cursor, witness)) + if witness["type"] == "mem": + if allregs and not witness["rom"]: + width, size = witness["width"], witness["size"] + witness = {**witness, "uninitialized": [{"width": width * size, "offset": 0}]} + if not witness["uninitialized"]: + continue + + mem_witnesses.append(absolute(path, cursor, witness)) + if witness["type"] == "cell": + cell_paths[witness["smtname"]] = tuple(witness["path"]) + + for cellname, celltype in sorted(self.modinfo[mod].cells.items()): + worker(celltype, path + cell_paths.get(cellname, ("?" + cellname,)), cursor + [cellname]) + + worker(top, (), []) + return init_witnesses, seq_witnesses, clk_witnesses, mem_witnesses + + def read(self): + stmt = [] + count_brackets = 0 + + while True: + if self.solver == "dummy": + line = self.dummy_fd.readline().strip() + else: + line = self.p_read().strip() + if self.dummy_file is not None: + self.dummy_fd.write(line + "\n") + + count_brackets += line.count("(") + count_brackets -= line.count(")") + stmt.append(line) + + if self.debug_print: + print("< %s" % line) + if count_brackets == 0: + break + if self.solver != "dummy" and self.p.poll(): + print("%s Solver terminated unexpectedly: %s" % (self.timestamp(), "".join(stmt)), flush=True) + sys.exit(1) + + stmt = "".join(stmt) + if stmt.startswith("(error"): + print("%s Solver Error: %s" % (self.timestamp(), stmt), flush=True) + if self.solver != "dummy": + self.p_close() + sys.exit(1) + + return stmt + + def check_sat(self, expected=["sat", "unsat", "unknown", "timeout", "interrupted"]): + if self.smt2_assumptions: + assume_exprs = " ".join(self.smt2_assumptions.values()) + check_stmt = f"(check-sat-assuming ({assume_exprs}))" + else: + check_stmt = "(check-sat)" + if self.debug_print: + print(f"> {check_stmt}") + if self.debug_file and not self.nocomments: + print("; running check-sat..", file=self.debug_file) + self.debug_file.flush() + + if self.solver != "dummy": + if self.noincr: + if self.p is not None: + self.p_close() + self.p_open() + for cache_ctx in self.smt2cache: + for cache_stmt in cache_ctx: + self.p_write(cache_stmt + "\n", False) + + self.p_write(f"{check_stmt}\n", True) + + if self.timeinfo: + i = 0 + s = r"/-\|" + + count = 0 + num_bs = 0 + while self.p_poll(): + count += 1 + + if count < 25: + continue + + if count % 10 == 0 or count == 25: + secs = count // 10 + + if secs < 60: + m = "(%d seconds)" % secs + elif secs < 60*60: + m = "(%d seconds -- %d:%02d)" % (secs, secs // 60, secs % 60) + else: + m = "(%d seconds -- %d:%02d:%02d)" % (secs, secs // (60*60), (secs // 60) % 60, secs % 60) + + print("%s %s %c" % ("\b \b" * num_bs, m, s[i]), end="", file=sys.stderr) + num_bs = len(m) + 3 + + else: + print("\b" + s[i], end="", file=sys.stderr) + + sys.stderr.flush() + i = (i + 1) % len(s) + + if num_bs != 0: + print("\b \b" * num_bs, end="", file=sys.stderr) + sys.stderr.flush() + + else: + count = 0 + while self.p_poll(60): + count += 1 + msg = None + + if count == 1: + msg = "1 minute" + + elif count in [5, 10, 15, 30]: + msg = "%d minutes" % count + + elif count == 60: + msg = "1 hour" + + elif count % 60 == 0: + msg = "%d hours" % (count // 60) + + if msg is not None: + print("%s waiting for solver (%s)" % (self.timestamp(), msg), flush=True) + + if self.forall: + result = self.read() + while result not in ["sat", "unsat", "unknown", "timeout", "interrupted", ""]: + print("%s %s: %s" % (self.timestamp(), self.solver, result)) + result = self.read() + else: + result = self.read() + + if self.debug_file: + print("(set-info :status %s)" % result, file=self.debug_file) + print(check_stmt, file=self.debug_file) + self.debug_file.flush() + + if result not in expected: + if result == "": + print("%s Unexpected EOF response from solver." % (self.timestamp()), flush=True) + else: + print("%s Unexpected response from solver: %s" % (self.timestamp(), result), flush=True) + if self.solver != "dummy": + self.p_close() + sys.exit(1) + + return result + + def parse(self, stmt): + def worker(stmt, cursor=0): + while stmt[cursor] in [" ", "\t", "\r", "\n"]: + cursor += 1 + + if stmt[cursor] == '(': + expr = [] + cursor += 1 + while stmt[cursor] != ')': + el, cursor = worker(stmt, cursor) + expr.append(el) + return expr, cursor+1 + + if stmt[cursor] == '|': + expr = "|" + cursor += 1 + while stmt[cursor] != '|': + expr += stmt[cursor] + cursor += 1 + expr += "|" + return expr, cursor+1 + + expr = "" + while stmt[cursor] not in ["(", ")", "|", " ", "\t", "\r", "\n"]: + expr += stmt[cursor] + cursor += 1 + return expr, cursor + return worker(stmt)[0] + + def unparse(self, stmt): + if isinstance(stmt, list): + return "(" + " ".join([self.unparse(s) for s in stmt]) + ")" + return stmt + + def bv2hex(self, v): + h = "" + v = self.bv2bin(v) + while len(v) > 0: + d = 0 + if len(v) > 0 and v[-1] == "1": d += 1 + if len(v) > 1 and v[-2] == "1": d += 2 + if len(v) > 2 and v[-3] == "1": d += 4 + if len(v) > 3 and v[-4] == "1": d += 8 + h = hex(d)[2:] + h + if len(v) < 4: break + v = v[:-4] + return h + + def bv2bin(self, v): + if type(v) is list and len(v) == 3 and v[0] == "_" and v[1].startswith("bv"): + x, n = int(v[1][2:]), int(v[2]) + return "".join("1" if (x & (1 << i)) else "0" for i in range(n-1, -1, -1)) + if v == "true": return "1" + if v == "false": return "0" + if v.startswith("#b"): + return v[2:] + if v.startswith("#x"): + return "".join(hex_dict.get(x) for x in v[2:]) + assert False + + def bv2int(self, v): + return int(self.bv2bin(v), 2) + + def get_raw_unsat_assumptions(self): + self.write("(get-unsat-assumptions)") + exprs = set(self.unparse(part) for part in self.parse(self.read())) + unsat_assumptions = [] + for key, value in self.smt2_assumptions.items(): + # normalize expression + value = self.unparse(self.parse(value)) + if value in exprs: + exprs.remove(value) + unsat_assumptions.append(key) + return unsat_assumptions + + def get_unsat_assumptions(self, minimize=False): + if not minimize: + return self.get_raw_unsat_assumptions() + required_assumptions = {} + + while True: + candidate_assumptions = {} + for key in self.get_raw_unsat_assumptions(): + if key not in required_assumptions: + candidate_assumptions[key] = self.smt2_assumptions[key] + + while candidate_assumptions: + + candidate_key, candidate_assume = candidate_assumptions.popitem() + + self.smt2_assumptions = {} + for key, assume in candidate_assumptions.items(): + self.smt2_assumptions[key] = assume + for key, assume in required_assumptions.items(): + self.smt2_assumptions[key] = assume + result = self.check_sat() + + if result == 'unsat': + candidate_assumptions = None + else: + required_assumptions[candidate_key] = candidate_assume + + if candidate_assumptions is not None: + return list(required_assumptions) + + def get(self, expr): + self.write("(get-value (%s))" % (expr)) + return self.parse(self.read())[0][1] + + def get_list(self, expr_list): + if len(expr_list) == 0: + return [] + self.write("(get-value (%s))" % " ".join(expr_list)) + return [n[1] for n in self.parse(self.read()) if n] + + def get_path(self, mod, path): + assert mod in self.modinfo + path = path.replace("\\", "/").split(".") + + for i in range(len(path)-1): + first = ".".join(path[0:i+1]) + second = ".".join(path[i+1:]) + + if first in self.modinfo[mod].cells: + nextmod = self.modinfo[mod].cells[first] + return [first] + self.get_path(nextmod, second) + + return [".".join(path)] + + def net_expr(self, mod, base, path): + if len(path) == 0: + return base + + if len(path) == 1: + assert mod in self.modinfo + if path[0] == "": + return base + if isinstance(path[0], int): + return "(|%s#%d| %s)" % (mod, path[0], base) + if path[0] in self.modinfo[mod].cells: + return "(|%s_h %s| %s)" % (mod, path[0], base) + if path[0] in self.modinfo[mod].wsize: + return "(|%s_n %s| %s)" % (mod, path[0], base) + if path[0] in self.modinfo[mod].memories: + return "(|%s_m %s| %s)" % (mod, path[0], base) + assert 0 + + assert mod in self.modinfo + assert path[0] in self.modinfo[mod].cells + + nextmod = self.modinfo[mod].cells[path[0]] + nextbase = "(|%s_h %s| %s)" % (mod, path[0], base) + return self.net_expr(nextmod, nextbase, path[1:]) + + def witness_net_expr(self, mod, base, witness): + net = self.net_expr(mod, base, witness["smtpath"]) + is_bool = self.net_width(mod, witness["smtpath"]) == 1 + if is_bool: + assert witness["width"] == 1 + assert witness["smtoffset"] == 0 + return net + return "((_ extract %d %d) %s)" % (witness["smtoffset"] + witness["width"] - 1, witness["smtoffset"], net) + + def net_width(self, mod, net_path): + for i in range(len(net_path)-1): + assert mod in self.modinfo + assert net_path[i] in self.modinfo[mod].cells + mod = self.modinfo[mod].cells[net_path[i]] + + assert mod in self.modinfo + if isinstance(net_path[-1], int): + return None + assert net_path[-1] in self.modinfo[mod].wsize + return self.modinfo[mod].wsize[net_path[-1]] + + def net_clock(self, mod, net_path): + for i in range(len(net_path)-1): + assert mod in self.modinfo + assert net_path[i] in self.modinfo[mod].cells + mod = self.modinfo[mod].cells[net_path[i]] + + assert mod in self.modinfo + if net_path[-1] not in self.modinfo[mod].clocks: + return None + return self.modinfo[mod].clocks[net_path[-1]] + + def net_exists(self, mod, net_path): + for i in range(len(net_path)-1): + if mod not in self.modinfo: return False + if net_path[i] not in self.modinfo[mod].cells: return False + mod = self.modinfo[mod].cells[net_path[i]] + + if mod not in self.modinfo: return False + if net_path[-1] not in self.modinfo[mod].wsize: return False + return True + + def mem_exists(self, mod, mem_path): + for i in range(len(mem_path)-1): + if mod not in self.modinfo: return False + if mem_path[i] not in self.modinfo[mod].cells: return False + mod = self.modinfo[mod].cells[mem_path[i]] + + if mod not in self.modinfo: return False + if mem_path[-1] not in self.modinfo[mod].memories: return False + return True + + def mem_expr(self, mod, base, path, port=None, infomode=False): + if len(path) == 1: + assert mod in self.modinfo + assert path[0] in self.modinfo[mod].memories + if infomode: + return self.modinfo[mod].memories[path[0]] + return "(|%s_m%s %s| %s)" % (mod, "" if port is None else ":%s" % port, path[0], base) + + assert mod in self.modinfo + assert path[0] in self.modinfo[mod].cells + + nextmod = self.modinfo[mod].cells[path[0]] + nextbase = "(|%s_h %s| %s)" % (mod, path[0], base) + return self.mem_expr(nextmod, nextbase, path[1:], port=port, infomode=infomode) + + def mem_info(self, mod, path): + return self.mem_expr(mod, "", path, infomode=True) + + def get_net(self, mod_name, net_path, state_name): + return self.get(self.net_expr(mod_name, state_name, net_path)) + + def get_net_list(self, mod_name, net_path_list, state_name): + return self.get_list([self.net_expr(mod_name, state_name, n) for n in net_path_list]) + + def get_net_hex(self, mod_name, net_path, state_name): + return self.bv2hex(self.get_net(mod_name, net_path, state_name)) + + def get_net_hex_list(self, mod_name, net_path_list, state_name): + return [self.bv2hex(v) for v in self.get_net_list(mod_name, net_path_list, state_name)] + + def get_net_bin(self, mod_name, net_path, state_name): + return self.bv2bin(self.get_net(mod_name, net_path, state_name)) + + def get_net_bin_list(self, mod_name, net_path_list, state_name): + return [self.bv2bin(v) for v in self.get_net_list(mod_name, net_path_list, state_name)] + + def wait(self): + if self.p is not None: + self.p.wait() + self.p_close() + + +class SmtOpts: + def __init__(self): + self.shortopts = "s:S:v" + self.longopts = ["unroll", "noincr", "noprogress", "timeout=", "dump-smt2=", "logic=", "dummy=", "info=", "nocomments"] + self.solver = "yices" + self.solver_opts = list() + self.debug_print = False + self.debug_file = None + self.dummy_file = None + self.unroll = False + self.noincr = False + self.timeinfo = os.name != "nt" + self.timeout = 0 + self.logic = None + self.info_stmts = list() + self.nocomments = False + + def handle(self, o, a): + if o == "-s": + self.solver = a + elif o == "-S": + self.solver_opts.append(a) + elif o == "--timeout": + self.timeout = int(a) + elif o == "-v": + self.debug_print = True + elif o == "--unroll": + self.unroll = True + elif o == "--noincr": + self.noincr = True + elif o == "--noprogress": + self.timeinfo = False + elif o == "--dump-smt2": + self.debug_file = open(a, "w") + elif o == "--logic": + self.logic = a + elif o == "--dummy": + self.dummy_file = a + elif o == "--info": + self.info_stmts.append(a) + elif o == "--nocomments": + self.nocomments = True + else: + return False + return True + + def helpmsg(self): + return """ + -s + set SMT solver: z3, yices, boolector, bitwuzla, cvc4, mathsat, dummy + default: yices + + -S + pass as command line argument to the solver + + --timeout + set the solver timeout to the specified value (in seconds). + + --logic + use the specified SMT2 logic (e.g. QF_AUFBV) + + --dummy + if solver is "dummy", read solver output from that file + otherwise: write solver output to that file + + -v + enable debug output + + --unroll + unroll uninterpreted functions + + --noincr + don't use incremental solving, instead restart solver for + each (check-sat). This also avoids (push) and (pop). + + --noprogress + disable timer display during solving + (this option is set implicitly on Windows) + + --dump-smt2 + write smt2 statements to file + + --info + include the specified smt2 info statement in the smt2 output + + --nocomments + strip all comments from the generated smt2 code +""" + + +class MkVcd: + def __init__(self, f): + self.f = f + self.t = -1 + self.nets = dict() + self.clocks = dict() + + def add_net(self, path, width): + path = tuple(path) + assert self.t == -1 + key = "n%d" % len(self.nets) + self.nets[path] = (key, width) + + def add_clock(self, path, edge): + path = tuple(path) + assert self.t == -1 + key = "n%d" % len(self.nets) + self.nets[path] = (key, 1) + self.clocks[path] = (key, edge) + + def set_net(self, path, bits): + path = tuple(path) + assert self.t >= 0 + assert path in self.nets + if path not in self.clocks: + print("b%s %s" % (bits, self.nets[path][0]), file=self.f) + + def escape_name(self, name): + name = re.sub(r"\[([0-9a-zA-Z_]*[a-zA-Z_][0-9a-zA-Z_]*)\]", r"<\1>", name) + if re.match(r"[\[\]]", name) and name[0] != "\\": + name = "\\" + name + return name + + def set_time(self, t): + assert t >= self.t + if t != self.t: + if self.t == -1: + print("$version Generated by Yosys-SMTBMC $end", file=self.f) + print("$timescale 1ns $end", file=self.f) + print("$var integer 32 t smt_step $end", file=self.f) + print("$var event 1 ! smt_clock $end", file=self.f) + + def vcdescape(n): + if n.startswith("$") or ":" in n: + return "\\" + n + return n + + scope = [] + for path in sorted(self.nets): + key, width = self.nets[path] + + uipath = list(path) + if "." in uipath[-1] and not uipath[-1].startswith("$"): + uipath = uipath[0:-1] + uipath[-1].split(".") + for i in range(len(uipath)): + uipath[i] = re.sub(r"\[([^\]]*)\]", r"<\1>", uipath[i]) + + while uipath[:len(scope)] != scope: + print("$upscope $end", file=self.f) + scope = scope[:-1] + + while uipath[:-1] != scope: + scopename = uipath[len(scope)] + print("$scope module %s $end" % vcdescape(scopename), file=self.f) + scope.append(uipath[len(scope)]) + + if path in self.clocks and self.clocks[path][1] == "event": + print("$var event 1 %s %s $end" % (key, vcdescape(uipath[-1])), file=self.f) + else: + print("$var wire %d %s %s $end" % (width, key, vcdescape(uipath[-1])), file=self.f) + + for i in range(len(scope)): + print("$upscope $end", file=self.f) + + print("$enddefinitions $end", file=self.f) + + self.t = t + assert self.t >= 0 + + if self.t > 0: + print("#%d" % (10 * self.t - 5), file=self.f) + for path in sorted(self.clocks.keys()): + if self.clocks[path][1] == "posedge": + print("b0 %s" % self.nets[path][0], file=self.f) + elif self.clocks[path][1] == "negedge": + print("b1 %s" % self.nets[path][0], file=self.f) + + print("#%d" % (10 * self.t), file=self.f) + print("1!", file=self.f) + print("b%s t" % format(self.t, "032b"), file=self.f) + + for path in sorted(self.clocks.keys()): + if self.clocks[path][1] == "negedge": + print("b0 %s" % self.nets[path][0], file=self.f) + else: + print("b1 %s" % self.nets[path][0], file=self.f) diff --git a/chips/yosys/tests/functional/test_functional.py b/chips/yosys/tests/functional/test_functional.py new file mode 100644 index 0000000000000000000000000000000000000000..9df83286478b139ad42ec93da106d32f586bf13c --- /dev/null +++ b/chips/yosys/tests/functional/test_functional.py @@ -0,0 +1,96 @@ +import subprocess +import pytest +import os +import shlex +from pathlib import Path + +base_path = Path(__file__).resolve().parent.parent.parent + +# quote a string or pathlib path so that it can be used by bash or yosys +# TODO: is this really appropriate for yosys? +def quote(path): + return shlex.quote(str(path)) + +# run a shell command and require the return code to be 0 +def run(cmd, **kwargs): + print(' '.join([quote(x) for x in cmd])) + status = subprocess.run(cmd, **kwargs) + assert status.returncode == 0, f"{cmd[0]} failed" + +def yosys(script): + run([os.environ.get("YOSYS", "../../yosys"), '-Q', '-p', script]) + +def compile_cpp(in_path, out_path, args): + run(['g++', '-g', '-std=c++20'] + args + [str(in_path), '-o', str(out_path)]) + +def yosys_synth(verilog_file, rtlil_file): + yosys(f"read_verilog {quote(verilog_file)} ; prep ; setundef -undriven -undef ; write_rtlil {quote(rtlil_file)}") + +# simulate an rtlil file with yosys, comparing with a given vcd file, and writing out the yosys simulation results into a second vcd file +def yosys_sim(rtlil_file, vcd_reference_file, vcd_out_file, preprocessing = ""): + try: + yosys(f"read_rtlil {quote(rtlil_file)}; {preprocessing}; sim -r {quote(vcd_reference_file)} -scope gold -vcd {quote(vcd_out_file)} -timescale 1us -sim-gold -fst-noinit") + except: + # if yosys sim fails it's probably because of a simulation mismatch + # since yosys sim aborts on simulation mismatch to generate vcd output + # we have to re-run with a different set of flags + # on this run we ignore output and return code, we just want a best-effort attempt to get a vcd + subprocess.run([os.environ.get("YOSYS", "../../yosys"), '-Q', '-p', + f'read_rtlil {quote(rtlil_file)}; sim -vcd {quote(vcd_out_file)} -a -r {quote(vcd_reference_file)} -scope gold -timescale 1us -fst-noinit'], + capture_output=True, check=False) + raise + +def test_cxx(cell, parameters, tmp_path, num_steps, rnd): + rtlil_file = tmp_path / 'rtlil.il' + vcdharness_cc_file = base_path / 'tests/functional/vcd_harness.cc' + cc_file = tmp_path / 'my_module_functional_cxx.cc' + vcdharness_exe_file = tmp_path / 'a.out' + vcd_functional_file = tmp_path / 'functional.vcd' + vcd_yosys_sim_file = tmp_path / 'yosys.vcd' + + cell.write_rtlil_file(rtlil_file, parameters) + yosys(f"read_rtlil {quote(rtlil_file)} ; clk2fflogic ; write_functional_cxx {quote(cc_file)}") + compile_cpp(vcdharness_cc_file, vcdharness_exe_file, ['-I', tmp_path, '-I', str(base_path / 'backends/functional/cxx_runtime')]) + seed = str(rnd(cell.name + "-cxx").getrandbits(32)) + run([str(vcdharness_exe_file.resolve()), str(vcd_functional_file), str(num_steps), str(seed)]) + yosys_sim(rtlil_file, vcd_functional_file, vcd_yosys_sim_file, getattr(cell, 'sim_preprocessing', '')) + +@pytest.mark.smt +def test_smt(cell, parameters, tmp_path, num_steps, rnd): + import smt_vcd + + rtlil_file = tmp_path / 'rtlil.il' + smt_file = tmp_path / 'smtlib.smt' + vcd_functional_file = tmp_path / 'functional.vcd' + vcd_yosys_sim_file = tmp_path / 'yosys.vcd' + + if hasattr(cell, 'smt_max_steps'): + num_steps = min(num_steps, cell.smt_max_steps) + + cell.write_rtlil_file(rtlil_file, parameters) + yosys(f"read_rtlil {quote(rtlil_file)} ; clk2fflogic ; write_functional_smt2 {quote(smt_file)}") + run(['z3', smt_file]) # check if output is valid smtlib before continuing + smt_vcd.simulate_smt(smt_file, vcd_functional_file, num_steps, rnd(cell.name + "-smt")) + yosys_sim(rtlil_file, vcd_functional_file, vcd_yosys_sim_file, getattr(cell, 'sim_preprocessing', '')) + +@pytest.mark.rkt +@pytest.mark.parametrize("use_assoc_list_helpers", [True, False]) +def test_rkt(cell, parameters, tmp_path, num_steps, rnd, use_assoc_list_helpers): + import rkt_vcd + + rtlil_file = tmp_path / 'rtlil.il' + rkt_file = tmp_path / 'smtlib.rkt' + vcd_functional_file = tmp_path / 'functional.vcd' + vcd_yosys_sim_file = tmp_path / 'yosys.vcd' + + cell.write_rtlil_file(rtlil_file, parameters) + use_assoc_helpers_flag = '-assoc-list-helpers' if use_assoc_list_helpers else '' + yosys(f"read_rtlil {quote(rtlil_file)} ; clk2fflogic ; write_functional_rosette -provides {use_assoc_helpers_flag} {quote(rkt_file)}") + rkt_vcd.simulate_rosette(rkt_file, vcd_functional_file, num_steps, rnd(cell.name + "-rkt"), use_assoc_list_helpers=use_assoc_list_helpers) + yosys_sim(rtlil_file, vcd_functional_file, vcd_yosys_sim_file, getattr(cell, 'sim_preprocessing', '')) + +def test_print_graph(tmp_path): + tb_file = base_path / 'tests/functional/picorv32_tb.v' + cpu_file = base_path / 'tests/functional/picorv32.v' + # currently we only check that we can print the graph without getting an error, not that it prints anything sensibl + yosys(f"read_verilog {quote(tb_file)} {quote(cpu_file)}; prep -top gold; setundef -undriven -undef ; flatten; clk2fflogic; test_generic") diff --git a/chips/yosys/tests/functional/test_smtbmc_witness_mismatch.py b/chips/yosys/tests/functional/test_smtbmc_witness_mismatch.py new file mode 100644 index 0000000000000000000000000000000000000000..60cd87073e91d0566416575bc582c0d84d459ee9 --- /dev/null +++ b/chips/yosys/tests/functional/test_smtbmc_witness_mismatch.py @@ -0,0 +1,191 @@ +import os +import json +import shutil +import subprocess +from pathlib import Path + +import pytest + +base_path = Path(__file__).resolve().parent.parent.parent + +pytestmark = pytest.mark.skipif(shutil.which("z3") is None, reason="z3 not available") + +def run(cmd, **kwargs): + """Run a command and assert it succeeds.""" + status = subprocess.run(cmd, **kwargs) + assert status.returncode == 0, f"{cmd[0]} failed" + return status + + +def write_smt2(tmp_path, verilog_text): + """Write Verilog to temp and emit SMT2 via yosys.""" + vfile = tmp_path / "design.v" + smt2 = tmp_path / "design.smt2" + vfile.write_text(verilog_text) + run([os.environ.get("YOSYS", "../../yosys"), "-Q", "-p", + f"read_verilog {vfile}; prep -top top; write_smt2 {smt2}"]) + return smt2 + + +def witness_entries(smt2_path): + """Parse yosys-smt2-witness JSON records from an SMT2 file.""" + entries = [] + marker = "yosys-smt2-witness" + with open(smt2_path, "r") as f: + for line in f: + if marker not in line: + continue + payload = line.split(marker, 1)[1].strip() + entries.append(json.loads(payload)) + return entries + + +def find_entry(entries, entry_type): + """Return the first witness entry of the given type.""" + for entry in entries: + if entry.get("type") == entry_type: + return entry + return None + + +def write_yw(yw_path, signals, bits): + """Write a minimal Yosys witness file with one step of bits.""" + data = { + "format": "Yosys Witness Trace", + "clocks": [], + "signals": signals, + "steps": [{"bits": bits}], + } + yw_path.write_text(json.dumps(data)) + + +def run_smtbmc(smt2_path, yw_path): + """Run yosys-smtbmc on the SMT2 file with a witness trace.""" + cmd = [ + os.environ.get("YOSYS_SMTBMC", "../../yosys-smtbmc"), + "-s", "z3", + "-m", "top", + "--check-witness", + "--yw", yw_path, + "-t", "1", + smt2_path, + ] + return subprocess.run(cmd, capture_output=True, text=True) + + +def assert_no_mismatch_message(result): + """Assert the mismatch error prefix is absent from outputs.""" + combined = (result.stderr or "") + (result.stdout or "") + assert "Yosys witness signal mismatch" not in combined + + +def assert_has_mismatch_message(result, msg): + """Assert the mismatch error prefix and substring are present.""" + combined = (result.stderr or "") + (result.stdout or "") + assert "Yosys witness signal mismatch" in combined + assert msg in combined + + +def test_missing_signal_path(tmp_path): + smt2 = write_smt2(tmp_path, "module top(input ok, output out); assign out = ok; endmodule") + yw_path = tmp_path / "trace.yw" + signals = [{"path": ["\\missing"], "offset": 0, "width": 1, "init_only": False}] + write_yw(yw_path, signals, "1") + result = run_smtbmc(smt2, yw_path) + assert result.returncode != 0 + assert_has_mismatch_message(result, "signal not found in design") + + +def test_width_mismatch(tmp_path): + smt2 = write_smt2(tmp_path, "module top(input ok, output out); assign out = ok; endmodule") + entries = witness_entries(smt2) + input_entry = find_entry(entries, "input") + assert input_entry is not None + yw_path = tmp_path / "trace.yw" + signals = [{ + "path": input_entry["path"], + "offset": 0, + "width": 2, + "init_only": False, + }] + write_yw(yw_path, signals, "10") + result = run_smtbmc(smt2, yw_path) + assert result.returncode != 0 + assert_has_mismatch_message(result, "signal width/offset mismatch") + + +def test_memory_address_oob(tmp_path): + verilog = """ +module top(input ok, output [7:0] mem_out); + reg [7:0] mem [0:1]; + assign mem_out = mem[0] ^ {8{ok}}; +endmodule +""" + smt2 = write_smt2(tmp_path, verilog) + entries = witness_entries(smt2) + mem_entry = find_entry(entries, "mem") + assert mem_entry is not None + addr = mem_entry["size"] + yw_path = tmp_path / "trace.yw" + signals = [{ + "path": mem_entry["path"] + [f"\\[{addr}]"], + "offset": 0, + "width": mem_entry["width"], + "init_only": False, + }] + bits = "0" * mem_entry["width"] + write_yw(yw_path, signals, bits) + result = run_smtbmc(smt2, yw_path) + assert result.returncode != 0 + assert_has_mismatch_message(result, "memory address out of bounds") + + +def test_allowed_extra_signal_in_design(tmp_path): + verilog = """ +module top(input ok, input extra, output [1:0] out); + assign out = {ok, extra}; +endmodule +""" + smt2 = write_smt2(tmp_path, verilog) + entries = witness_entries(smt2) + input_entry = find_entry(entries, "input") + assert input_entry is not None + yw_path = tmp_path / "trace.yw" + signals = [{ + "path": input_entry["path"], + "offset": 0, + "width": input_entry["width"], + "init_only": False, + }] + bits = "0" * input_entry["width"] + write_yw(yw_path, signals, bits) + result = run_smtbmc(smt2, yw_path) + # With --check-witness and no assertions, smtbmc can still exit non-zero. + # Thus we don't check the result.returncode here and in the other success + # cases. + assert_no_mismatch_message(result) + + +def test_allowed_extra_memory_in_design(tmp_path): + verilog = """ +module top(input ok, output [7:0] out); + reg [7:0] mem0 [0:1]; + reg [7:0] mem1 [0:3]; + assign out = mem0[0] ^ mem1[0]; +endmodule +""" + smt2 = write_smt2(tmp_path, verilog) + entries = witness_entries(smt2) + input_entry = find_entry(entries, "input") + assert input_entry is not None + yw_path = tmp_path / "trace.yw" + signals = [{ + "path": input_entry["path"], + "offset": 0, + "width": input_entry["width"], + "init_only": False, + }] + bits = "1" * input_entry["width"] + write_yw(yw_path, signals, bits) + result = run_smtbmc(smt2, yw_path) + assert_no_mismatch_message(result) diff --git a/chips/yosys/tests/functional/vcd_harness.cc b/chips/yosys/tests/functional/vcd_harness.cc new file mode 100644 index 0000000000000000000000000000000000000000..30238429b6e9660b33fd8bebe0b9c9cd4d13a439 --- /dev/null +++ b/chips/yosys/tests/functional/vcd_harness.cc @@ -0,0 +1,146 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "my_module_functional_cxx.cc" + +class VcdFile { + std::ofstream &ofs; + std::string code_alloc = "!"; + std::unordered_map codes; + std::string name_mangle(std::string name) { + std::string ret = name; + bool escape = ret.empty() || !isalpha(ret[0]) && ret[0] != '_'; + for(size_t i = 0; i < ret.size(); i++) { + if(isspace(ret[i])) ret[i] = '_'; + if(!isalnum(ret[i]) && ret[i] != '_' && ret[i] != '$') + escape = true; + } + if(escape) + return "\\" + ret; + else + return ret; + } + std::string allocate_code() { + std::string ret = code_alloc; + for (size_t i = 0; i < code_alloc.size(); i++) + if (code_alloc[i]++ == '~') + code_alloc[i] = '!'; + else + return ret; + code_alloc.push_back('!'); + return ret; + } +public: + VcdFile(std::ofstream &ofs) : ofs(ofs) {} + struct DumpHeader { + VcdFile *file; + explicit DumpHeader(VcdFile *file) : file(file) {} + template void operator()(const char *name, Signal value) + { + auto it = file->codes.find(name); + if(it == file->codes.end()) + it = file->codes.emplace(name, file->allocate_code()).first; + file->ofs << "$var wire " << n << " " << it->second << " " << file->name_mangle(name) << " $end\n"; + } + template void operator()(const char *name, Memory value) {} + }; + struct Dump { + VcdFile *file; + explicit Dump(VcdFile *file) : file(file) {} + template void operator()(const char *name, Signal value) + { + if (n == 1) { + file->ofs << (value[0] ? '1' : '0'); + file->ofs << file->codes.at(name) << "\n"; + } else { + file->ofs << "b"; + for (size_t i = n; i-- > 0;) + file->ofs << (value[i] ? '1' : '0'); + file->ofs << " " << file->codes.at(name) << "\n"; + } + } + template void operator()(const char *name, Memory value) {} + }; + void begin_header() { + constexpr int number_timescale = 1; + const std::string units_timescale = "us"; + ofs << "$timescale " << number_timescale << " " << units_timescale << " $end\n"; + ofs << "$scope module gold $end\n"; + } + void end_header() { + ofs << "$enddefinitions $end\n$dumpvars\n"; + } + template void header(Args ...args) { + begin_header(); + DumpHeader d(this); + (args.visit(d), ...); + end_header(); + } + void begin_data(int step) { + ofs << "#" << step << "\n"; + } + template void data(int step, Args ...args) { + begin_data(step); + Dump d(this); + (args.visit(d), ...); + } + DumpHeader dump_header() { return DumpHeader(this); } + Dump dump() { return Dump(this); } +}; + +template Signal random_signal(std::mt19937 &gen) +{ + std::uniform_int_distribution dist; + std::array words; + for (auto &w : words) + w = dist(gen); + return Signal::from_array(words); +} + +struct Randomize { + std::mt19937 &gen; + Randomize(std::mt19937 &gen) : gen(gen) {} + + template void operator()(const char *, Signal &signal) { signal = random_signal(gen); } +}; + +int main(int argc, char **argv) +{ + if (argc != 4) { + std::cerr << "Usage: " << argv[0] << " \n"; + return 1; + } + + const std::string functional_vcd_filename = argv[1]; + const int steps = atoi(argv[2]); + const uint32_t seed = atoi(argv[3]); + + gold::Inputs inputs; + gold::Outputs outputs; + gold::State state; + gold::State next_state; + + std::ofstream vcd_file(functional_vcd_filename); + VcdFile vcd(vcd_file); + vcd.header(inputs, outputs, state); + + std::mt19937 gen(seed); + + gold::initialize(state); + + for (int step = 0; step < steps; ++step) { + inputs.visit(Randomize(gen)); + + gold::eval(inputs, outputs, state, next_state); + vcd.data(step, inputs, outputs, state); + + state = next_state; + } + + return 0; +} diff --git a/chips/yosys/tests/gen_tests_makefile.py b/chips/yosys/tests/gen_tests_makefile.py new file mode 100644 index 0000000000000000000000000000000000000000..147cc04777598d5854c5ddd4ea17c5508c0498ac --- /dev/null +++ b/chips/yosys/tests/gen_tests_makefile.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python3 + +import glob +import os +import sys +import argparse +from contextlib import contextmanager + +yosys_basedir = os.path.relpath(os.path.join(os.path.dirname(__file__), "..")) +common_mk = os.path.relpath(os.path.join(os.path.dirname(__file__), "common.mk")) + +def remove_generated(pattern): + for f in glob.glob(pattern): + if os.path.isfile(f): + os.remove(f) + +def _cwd_base(): + return os.path.basename(os.getcwd()) + +def generate_target(name, command, deps = None): + #target = f"{_cwd_base()}-{name}" + target = f"{name}" + print(f"all: {target}") + print(f".PHONY: {target}") + print(f"{target}_cmd={command}") + if deps: + print(f"{target}: {' '.join(deps)}") + else: + print(f"{target}:") + + print(f"\t@$(call run_test,{target}, $({target}_cmd))") + +def generate_ys_test(ys_file, yosys_args="", commands=""): + cmd = f'$(YOSYS) -l {ys_file}.err {yosys_args} {ys_file} && mv {ys_file}.err {ys_file}.log' + if commands: + cmd += f"; \\\n{commands}" + generate_target(ys_file, cmd) + +def generate_tcl_test(tcl_file, yosys_args="", commands=""): + cmd = f'$(YOSYS) -l {tcl_file}.err {yosys_args} {tcl_file} && mv {tcl_file}.err {tcl_file}.log' + if commands: + cmd += f"; \\\n{commands}" + generate_target(tcl_file, cmd) + +def generate_sv_check(sv_file, yosys_args="", yosys_cmds=""): + yosys_cmd = f'read -sv {sv_file}; {yosys_cmds}' + cmd = f'$(YOSYS) -l {sv_file}.err -p "{yosys_cmd}" {yosys_args} && mv {sv_file}.err {sv_file}.log' + generate_target(sv_file, cmd) + +def generate_sv_test(sv_file, yosys_args="", commands=""): + base = os.path.splitext(sv_file)[0] + if not os.path.exists(base + ".ys"): + yosys_cmd = '-p "prep -top top; async2sync; sat -enable_undef -verify -prove-asserts"' + cmd = f'$(YOSYS) -l {sv_file}.err {yosys_cmd} {yosys_args} {sv_file} && mv {sv_file}.err {sv_file}.log' + if commands: + cmd += f"; \\\n{commands}" + generate_target(sv_file, cmd) + +def generate_bash_test(sh_file, commands=""): + cmd = f"bash -v {sh_file} >{sh_file}.err 2>&1 && mv {sh_file}.err {sh_file}.log" + if commands: + cmd += f"; \\\n{commands}" + generate_target(sh_file, cmd) + +def unpack_cmd(cmd): + if isinstance(cmd, str): + return cmd + if isinstance(cmd, (list, tuple)): + return " && \\\n".join(cmd) + raise TypeError("cmd must be a string or a list/tuple of strings") + +def generate_cmd_test(test_name, cmd, yosys_args="", deps = None): + generate_target(test_name, unpack_cmd(cmd), deps) + +def generate_tests(argv, cmds, yosys_cmds=""): + parser = argparse.ArgumentParser(add_help=False) + parser.add_argument("-y", "--yosys-scripts", action="store_true") + parser.add_argument("-t", "--tcl-scripts", action="store_true") + parser.add_argument("-c", "--check-sv", action="store_true") + parser.add_argument("-s", "--prove-sv", action="store_true") + parser.add_argument("-b", "--bash", action="store_true") + parser.add_argument("-a", "--yosys-args", default="") + + args = parser.parse_args(argv) + + if not (args.yosys_scripts or args.tcl_scripts or args.check_sv or args.prove_sv or args.bash): + raise RuntimeError("No file types selected") + + if args.check_sv and args.prove_sv: + raise RuntimeError("Unable to use --check-sv and --prove-sv together") + + if args.yosys_scripts: + for f in sorted(glob.glob("*.ys")): + generate_ys_test(f, args.yosys_args, cmds) + + if args.tcl_scripts: + for f in sorted(glob.glob("*.tcl")): + generate_tcl_test(f, args.yosys_args, cmds) + + if args.check_sv: + for f in sorted(glob.glob("*.sv")): + generate_sv_check(f, args.yosys_args, yosys_cmds) + + if args.prove_sv: + for f in sorted(glob.glob("*.sv")): + generate_sv_test(f, args.yosys_args, cmds) + + if args.bash: + for f in sorted(glob.glob("*.sh")): + if f != "run-test.sh": + generate_bash_test(f, cmds) + +def print_header(extra=None): + print(f"include {common_mk}") + if extra: + for line in extra: + print(line) + print("") + print(".PHONY: all") + print("all:") + +@contextmanager +def redirect_stdout(new_target): + old_target, sys.stdout = sys.stdout, new_target + try: + yield new_target + finally: + sys.stdout = old_target + +def generate(argv, extra=None, cmds="", yosys_cmds=""): + with open("Makefile", "w") as f: + with redirect_stdout(f): + print_header(extra) + generate_tests(argv, cmds, yosys_cmds) + +def generate_custom(callback, extra=None): + with open("Makefile", "w") as f: + with redirect_stdout(f): + print_header(extra) + callback() + +def generate_autotest_file(test_file, commands): + cmd = f"../tools/autotest.sh -G -j ${{SEEDOPT}} -Y ${{YOSYS}} ${{EXTRA_FLAGS}} {test_file} || exit $$?; \\\n{commands}" + generate_target(test_file, cmd) + +def generate_autotest(pattern, extra_flags, cmds=""): + with open("Makefile", "w") as f: + with redirect_stdout(f): + print_header([ f"EXTRA_FLAGS = {extra_flags}", + "SEED ?=", + "ifneq ($(strip $(SEED)),)", + " SEEDOPT=-S$(SEED)", + "endif", + ]) + for fn in sorted(glob.glob(pattern)): + generate_autotest_file(fn, cmds) diff --git a/chips/yosys/tests/hana/README b/chips/yosys/tests/hana/README new file mode 100644 index 0000000000000000000000000000000000000000..0ff6855cf51176bacfde0901e66b14f0d973ca8e --- /dev/null +++ b/chips/yosys/tests/hana/README @@ -0,0 +1,3 @@ + +These test cases are copied from the hana project: +https://sourceforge.net/projects/sim-sim/ diff --git a/chips/yosys/tests/hana/generate_mk.py b/chips/yosys/tests/hana/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..0068c590aae8edce41cfff101405f653febe44bb --- /dev/null +++ b/chips/yosys/tests/hana/generate_mk.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile + +gen_tests_makefile.generate_autotest("test_*.v", "-l hana_vlib.v -n 300 -e") diff --git a/chips/yosys/tests/hana/hana_vlib.v b/chips/yosys/tests/hana/hana_vlib.v new file mode 100644 index 0000000000000000000000000000000000000000..1b3d1819168a84608c3ff7bf688a719105118879 --- /dev/null +++ b/chips/yosys/tests/hana/hana_vlib.v @@ -0,0 +1,1138 @@ +/* +Copyright (C) 2009-2010 Parvez Ahmad +Written by Parvez Ahmad . + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . */ + + +module BUF (input in, output out); + +assign out = in; + +endmodule + +module TRIBUF(input in, enable, output out); + +assign out = enable ? in : 1'bz; + +endmodule + +module INV(input in, output out); + +assign out = ~in; + +endmodule + +module AND2 #(parameter SIZE = 2) (input [SIZE-1:0] in, output out); + +assign out = ∈ + +endmodule + +module AND3 #(parameter SIZE = 3) (input [SIZE-1:0] in, output out); + +assign out = ∈ + +endmodule + +module AND4 #(parameter SIZE = 4) (input [SIZE-1:0] in, output out); + +assign out = ∈ + +endmodule + +module OR2 #(parameter SIZE = 2) (input [SIZE-1:0] in, output out); + +assign out = |in; + +endmodule + +module OR3 #(parameter SIZE = 3) (input [SIZE-1:0] in, output out); + +assign out = |in; + +endmodule + +module OR4 #(parameter SIZE = 4) (input [SIZE-1:0] in, output out); + +assign out = |in; + +endmodule + + +module NAND2 #(parameter SIZE = 2) (input [SIZE-1:0] in, output out); + +assign out = ~∈ + +endmodule + +module NAND3 #(parameter SIZE = 3) (input [SIZE-1:0] in, output out); + +assign out = ~∈ + +endmodule + +module NAND4 #(parameter SIZE = 4) (input [SIZE-1:0] in, output out); + +assign out = ~∈ + +endmodule + +module NOR2 #(parameter SIZE = 2) (input [SIZE-1:0] in, output out); + +assign out = ~|in; + +endmodule + +module NOR3 #(parameter SIZE = 3) (input [SIZE-1:0] in, output out); + +assign out = ~|in; + +endmodule + +module NOR4 #(parameter SIZE = 4) (input [SIZE-1:0] in, output out); + +assign out = ~|in; + +endmodule + + +module XOR2 #(parameter SIZE = 2) (input [SIZE-1:0] in, output out); + +assign out = ^in; + +endmodule + +module XOR3 #(parameter SIZE = 3) (input [SIZE-1:0] in, output out); + +assign out = ^in; + +endmodule + +module XOR4 #(parameter SIZE = 4) (input [SIZE-1:0] in, output out); + +assign out = ^in; + +endmodule + + +module XNOR2 #(parameter SIZE = 2) (input [SIZE-1:0] in, output out); + +assign out = ~^in; + +endmodule + +module XNOR3 #(parameter SIZE = 3) (input [SIZE-1:0] in, output out); + +assign out = ~^in; + +endmodule + +module XNOR4 #(parameter SIZE = 4) (input [SIZE-1:0] in, output out); + +assign out = ~^in; + +endmodule + +module DEC1 (input in, enable, output reg [1:0] out); + +always @(in or enable) + if(!enable) + out = 2'b00; + else begin + case (in) + 1'b0 : out = 2'b01; + 1'b1 : out = 2'b10; + endcase + end +endmodule + +module DEC2 (input [1:0] in, input enable, output reg [3:0] out); + +always @(in or enable) + if(!enable) + out = 4'b0000; + else begin + case (in) + 2'b00 : out = 4'b0001; + 2'b01 : out = 4'b0010; + 2'b10 : out = 4'b0100; + 2'b11 : out = 4'b1000; + endcase + end +endmodule + +module DEC3 (input [2:0] in, input enable, output reg [7:0] out); + +always @(in or enable) + if(!enable) + out = 8'b00000000; + else begin + case (in) + 3'b000 : out = 8'b00000001; + 3'b001 : out = 8'b00000010; + 3'b010 : out = 8'b00000100; + 3'b011 : out = 8'b00001000; + 3'b100 : out = 8'b00010000; + 3'b101 : out = 8'b00100000; + 3'b110 : out = 8'b01000000; + 3'b111 : out = 8'b10000000; + endcase + end +endmodule + +module DEC4 (input [3:0] in, input enable, output reg [15:0] out); + +always @(in or enable) + if(!enable) + out = 16'b0000000000000000; + else begin + case (in) + 4'b0000 : out = 16'b0000000000000001; + 4'b0001 : out = 16'b0000000000000010; + 4'b0010 : out = 16'b0000000000000100; + 4'b0011 : out = 16'b0000000000001000; + 4'b0100 : out = 16'b0000000000010000; + 4'b0101 : out = 16'b0000000000100000; + 4'b0110 : out = 16'b0000000001000000; + 4'b0111 : out = 16'b0000000010000000; + 4'b1000 : out = 16'b0000000100000000; + 4'b1001 : out = 16'b0000001000000000; + 4'b1010 : out = 16'b0000010000000000; + 4'b1011 : out = 16'b0000100000000000; + 4'b1100 : out = 16'b0001000000000000; + 4'b1101 : out = 16'b0010000000000000; + 4'b1110 : out = 16'b0100000000000000; + 4'b1111 : out = 16'b1000000000000000; + endcase + end +endmodule +module DEC5 (input [4:0] in, input enable, output reg [31:0] out); + +always @(in or enable) + if(!enable) + out = 32'b00000000000000000000000000000000; + else begin + case (in) + 5'b00000 : out = 32'b00000000000000000000000000000001; + 5'b00001 : out = 32'b00000000000000000000000000000010; + 5'b00010 : out = 32'b00000000000000000000000000000100; + 5'b00011 : out = 32'b00000000000000000000000000001000; + 5'b00100 : out = 32'b00000000000000000000000000010000; + 5'b00101 : out = 32'b00000000000000000000000000100000; + 5'b00110 : out = 32'b00000000000000000000000001000000; + 5'b00111 : out = 32'b00000000000000000000000010000000; + 5'b01000 : out = 32'b00000000000000000000000100000000; + 5'b01001 : out = 32'b00000000000000000000001000000000; + 5'b01010 : out = 32'b00000000000000000000010000000000; + 5'b01011 : out = 32'b00000000000000000000100000000000; + 5'b01100 : out = 32'b00000000000000000001000000000000; + 5'b01101 : out = 32'b00000000000000000010000000000000; + 5'b01110 : out = 32'b00000000000000000100000000000000; + 5'b01111 : out = 32'b00000000000000001000000000000000; + 5'b10000 : out = 32'b00000000000000010000000000000000; + 5'b10001 : out = 32'b00000000000000100000000000000000; + 5'b10010 : out = 32'b00000000000001000000000000000000; + 5'b10011 : out = 32'b00000000000010000000000000000000; + 5'b10100 : out = 32'b00000000000100000000000000000000; + 5'b10101 : out = 32'b00000000001000000000000000000000; + 5'b10110 : out = 32'b00000000010000000000000000000000; + 5'b10111 : out = 32'b00000000100000000000000000000000; + 5'b11000 : out = 32'b00000001000000000000000000000000; + 5'b11001 : out = 32'b00000010000000000000000000000000; + 5'b11010 : out = 32'b00000100000000000000000000000000; + 5'b11011 : out = 32'b00001000000000000000000000000000; + 5'b11100 : out = 32'b00010000000000000000000000000000; + 5'b11101 : out = 32'b00100000000000000000000000000000; + 5'b11110 : out = 32'b01000000000000000000000000000000; + 5'b11111 : out = 32'b10000000000000000000000000000000; + endcase + end +endmodule + +module DEC6 (input [5:0] in, input enable, output reg [63:0] out); + +always @(in or enable) + if(!enable) + out = 64'b0000000000000000000000000000000000000000000000000000000000000000; + else begin + case (in) + 6'b000000 : out = 64'b0000000000000000000000000000000000000000000000000000000000000001; + 6'b000001 : out = 64'b0000000000000000000000000000000000000000000000000000000000000010; + 6'b000010 : out = 64'b0000000000000000000000000000000000000000000000000000000000000100; + 6'b000011 : out = 64'b0000000000000000000000000000000000000000000000000000000000001000; + 6'b000100 : out = 64'b0000000000000000000000000000000000000000000000000000000000010000; + 6'b000101 : out = 64'b0000000000000000000000000000000000000000000000000000000000100000; + 6'b000110 : out = 64'b0000000000000000000000000000000000000000000000000000000001000000; + 6'b000111 : out = 64'b0000000000000000000000000000000000000000000000000000000010000000; + 6'b001000 : out = 64'b0000000000000000000000000000000000000000000000000000000100000000; + 6'b001001 : out = 64'b0000000000000000000000000000000000000000000000000000001000000000; + 6'b001010 : out = 64'b0000000000000000000000000000000000000000000000000000010000000000; + 6'b001011 : out = 64'b0000000000000000000000000000000000000000000000000000100000000000; + 6'b001100 : out = 64'b0000000000000000000000000000000000000000000000000001000000000000; + 6'b001101 : out = 64'b0000000000000000000000000000000000000000000000000010000000000000; + 6'b001110 : out = 64'b0000000000000000000000000000000000000000000000000100000000000000; + 6'b001111 : out = 64'b0000000000000000000000000000000000000000000000001000000000000000; + 6'b010000 : out = 64'b0000000000000000000000000000000000000000000000010000000000000000; + 6'b010001 : out = 64'b0000000000000000000000000000000000000000000000100000000000000000; + 6'b010010 : out = 64'b0000000000000000000000000000000000000000000001000000000000000000; + 6'b010011 : out = 64'b0000000000000000000000000000000000000000000010000000000000000000; + 6'b010100 : out = 64'b0000000000000000000000000000000000000000000100000000000000000000; + 6'b010101 : out = 64'b0000000000000000000000000000000000000000001000000000000000000000; + 6'b010110 : out = 64'b0000000000000000000000000000000000000000010000000000000000000000; + 6'b010111 : out = 64'b0000000000000000000000000000000000000000100000000000000000000000; + 6'b011000 : out = 64'b0000000000000000000000000000000000000001000000000000000000000000; + 6'b011001 : out = 64'b0000000000000000000000000000000000000010000000000000000000000000; + 6'b011010 : out = 64'b0000000000000000000000000000000000000100000000000000000000000000; + 6'b011011 : out = 64'b0000000000000000000000000000000000001000000000000000000000000000; + 6'b011100 : out = 64'b0000000000000000000000000000000000010000000000000000000000000000; + 6'b011101 : out = 64'b0000000000000000000000000000000000100000000000000000000000000000; + 6'b011110 : out = 64'b0000000000000000000000000000000001000000000000000000000000000000; + 6'b011111 : out = 64'b0000000000000000000000000000000010000000000000000000000000000000; + + 6'b100000 : out = 64'b0000000000000000000000000000000100000000000000000000000000000000; + 6'b100001 : out = 64'b0000000000000000000000000000001000000000000000000000000000000000; + 6'b100010 : out = 64'b0000000000000000000000000000010000000000000000000000000000000000; + 6'b100011 : out = 64'b0000000000000000000000000000100000000000000000000000000000000000; + 6'b100100 : out = 64'b0000000000000000000000000001000000000000000000000000000000000000; + 6'b100101 : out = 64'b0000000000000000000000000010000000000000000000000000000000000000; + 6'b100110 : out = 64'b0000000000000000000000000100000000000000000000000000000000000000; + 6'b100111 : out = 64'b0000000000000000000000001000000000000000000000000000000000000000; + 6'b101000 : out = 64'b0000000000000000000000010000000000000000000000000000000000000000; + 6'b101001 : out = 64'b0000000000000000000000100000000000000000000000000000000000000000; + 6'b101010 : out = 64'b0000000000000000000001000000000000000000000000000000000000000000; + 6'b101011 : out = 64'b0000000000000000000010000000000000000000000000000000000000000000; + 6'b101100 : out = 64'b0000000000000000000100000000000000000000000000000000000000000000; + 6'b101101 : out = 64'b0000000000000000001000000000000000000000000000000000000000000000; + 6'b101110 : out = 64'b0000000000000000010000000000000000000000000000000000000000000000; + 6'b101111 : out = 64'b0000000000000000100000000000000000000000000000000000000000000000; + 6'b110000 : out = 64'b0000000000000001000000000000000000000000000000000000000000000000; + 6'b110001 : out = 64'b0000000000000010000000000000000000000000000000000000000000000000; + 6'b110010 : out = 64'b0000000000000100000000000000000000000000000000000000000000000000; + 6'b110011 : out = 64'b0000000000001000000000000000000000000000000000000000000000000000; + 6'b110100 : out = 64'b0000000000010000000000000000000000000000000000000000000000000000; + 6'b110101 : out = 64'b0000000000100000000000000000000000000000000000000000000000000000; + 6'b110110 : out = 64'b0000000001000000000000000000000000000000000000000000000000000000; + 6'b110111 : out = 64'b0000000010000000000000000000000000000000000000000000000000000000; + 6'b111000 : out = 64'b0000000100000000000000000000000000000000000000000000000000000000; + 6'b111001 : out = 64'b0000001000000000000000000000000000000000000000000000000000000000; + 6'b111010 : out = 64'b0000010000000000000000000000000000000000000000000000000000000000; + 6'b111011 : out = 64'b0000100000000000000000000000000000000000000000000000000000000000; + 6'b111100 : out = 64'b0001000000000000000000000000000000000000000000000000000000000000; + 6'b111101 : out = 64'b0010000000000000000000000000000000000000000000000000000000000000; + 6'b111110 : out = 64'b0100000000000000000000000000000000000000000000000000000000000000; + 6'b111111 : out = 64'b1000000000000000000000000000000000000000000000000000000000000000; + endcase + end +endmodule + + +module MUX2(input [1:0] in, input select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + endcase +endmodule + + +module MUX4(input [3:0] in, input [1:0] select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + 2: out = in[2]; + 3: out = in[3]; + endcase +endmodule + + +module MUX8(input [7:0] in, input [2:0] select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + 2: out = in[2]; + 3: out = in[3]; + 4: out = in[4]; + 5: out = in[5]; + 6: out = in[6]; + 7: out = in[7]; + endcase +endmodule + +module MUX16(input [15:0] in, input [3:0] select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + 2: out = in[2]; + 3: out = in[3]; + 4: out = in[4]; + 5: out = in[5]; + 6: out = in[6]; + 7: out = in[7]; + 8: out = in[8]; + 9: out = in[9]; + 10: out = in[10]; + 11: out = in[11]; + 12: out = in[12]; + 13: out = in[13]; + 14: out = in[14]; + 15: out = in[15]; + endcase +endmodule + +module MUX32(input [31:0] in, input [4:0] select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + 2: out = in[2]; + 3: out = in[3]; + 4: out = in[4]; + 5: out = in[5]; + 6: out = in[6]; + 7: out = in[7]; + 8: out = in[8]; + 9: out = in[9]; + 10: out = in[10]; + 11: out = in[11]; + 12: out = in[12]; + 13: out = in[13]; + 14: out = in[14]; + 15: out = in[15]; + 16: out = in[16]; + 17: out = in[17]; + 18: out = in[18]; + 19: out = in[19]; + 20: out = in[20]; + 21: out = in[21]; + 22: out = in[22]; + 23: out = in[23]; + 24: out = in[24]; + 25: out = in[25]; + 26: out = in[26]; + 27: out = in[27]; + 28: out = in[28]; + 29: out = in[29]; + 30: out = in[30]; + 31: out = in[31]; + endcase +endmodule + +module MUX64(input [63:0] in, input [5:0] select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + 2: out = in[2]; + 3: out = in[3]; + 4: out = in[4]; + 5: out = in[5]; + 6: out = in[6]; + 7: out = in[7]; + 8: out = in[8]; + 9: out = in[9]; + 10: out = in[10]; + 11: out = in[11]; + 12: out = in[12]; + 13: out = in[13]; + 14: out = in[14]; + 15: out = in[15]; + 16: out = in[16]; + 17: out = in[17]; + 18: out = in[18]; + 19: out = in[19]; + 20: out = in[20]; + 21: out = in[21]; + 22: out = in[22]; + 23: out = in[23]; + 24: out = in[24]; + 25: out = in[25]; + 26: out = in[26]; + 27: out = in[27]; + 28: out = in[28]; + 29: out = in[29]; + 30: out = in[30]; + 31: out = in[31]; + 32: out = in[32]; + 33: out = in[33]; + 34: out = in[34]; + 35: out = in[35]; + 36: out = in[36]; + 37: out = in[37]; + 38: out = in[38]; + 39: out = in[39]; + 40: out = in[40]; + 41: out = in[41]; + 42: out = in[42]; + 43: out = in[43]; + 44: out = in[44]; + 45: out = in[45]; + 46: out = in[46]; + 47: out = in[47]; + 48: out = in[48]; + 49: out = in[49]; + 50: out = in[50]; + 51: out = in[51]; + 52: out = in[52]; + 53: out = in[53]; + 54: out = in[54]; + 55: out = in[55]; + 56: out = in[56]; + 57: out = in[57]; + 58: out = in[58]; + 59: out = in[59]; + 60: out = in[60]; + 61: out = in[61]; + 62: out = in[62]; + 63: out = in[63]; + endcase +endmodule + +module ADD1(input in1, in2, cin, output out, cout); + +assign {cout, out} = in1 + in2 + cin; + +endmodule + +module ADD2 #(parameter SIZE = 2)(input [SIZE-1:0] in1, in2, + input cin, output [SIZE-1:0] out, output cout); + +assign {cout, out} = in1 + in2 + cin; + +endmodule + +module ADD4 #(parameter SIZE = 4)(input [SIZE-1:0] in1, in2, + input cin, output [SIZE-1:0] out, output cout); + +assign {cout, out} = in1 + in2 + cin; + +endmodule + +module ADD8 #(parameter SIZE = 8)(input [SIZE-1:0] in1, in2, + input cin, output [SIZE-1:0] out, output cout); + +assign {cout, out} = in1 + in2 + cin; + +endmodule + +module ADD16 #(parameter SIZE = 16)(input [SIZE-1:0] in1, in2, + input cin, output [SIZE-1:0] out, output cout); + +assign {cout, out} = in1 + in2 + cin; + +endmodule + +module ADD32 #(parameter SIZE = 32)(input [SIZE-1:0] in1, in2, + input cin, output [SIZE-1:0] out, output cout); + +assign {cout, out} = in1 + in2 + cin; + +endmodule +module ADD64 #(parameter SIZE = 64)(input [SIZE-1:0] in1, in2, + input cin, output [SIZE-1:0] out, output cout); + +assign {cout, out} = in1 + in2 + cin; + +endmodule + +module SUB1(input in1, in2, cin, output out, cout); + +assign {cout, out} = in1 - in2 - cin; + +endmodule + +module SUB2 #(parameter SIZE = 2)(input [SIZE-1:0] in1, in2, + input cin, output [SIZE-1:0] out, output cout); + +assign {cout, out} = in1 - in2 - cin; + +endmodule + +module SUB4 #(parameter SIZE = 4)(input [SIZE-1:0] in1, in2, + input cin, output [SIZE-1:0] out, output cout); + +assign {cout, out} = in1 - in2 - cin; + +endmodule + +module SUB8 #(parameter SIZE = 8)(input [SIZE-1:0] in1, in2, + input cin, output [SIZE-1:0] out, output cout); + +assign {cout, out} = in1 - in2 - cin; + +endmodule + +module SUB16 #(parameter SIZE = 16)(input [SIZE-1:0] in1, in2, + input cin, output [SIZE-1:0] out, output cout); + +assign {cout, out} = in1 - in2 - cin; + +endmodule + +module SUB32 #(parameter SIZE = 32)(input [SIZE-1:0] in1, in2, + input cin, output [SIZE-1:0] out, output cout); + +assign {cout, out} = in1 - in2 - cin; + +endmodule +module SUB64 #(parameter SIZE = 64)(input [SIZE-1:0] in1, in2, + input cin, output [SIZE-1:0] out, output cout); + +assign {cout, out} = in1 - in2 - cin; + +endmodule + +module MUL1 #(parameter SIZE = 1)(input in1, in2, output [2*SIZE-1:0] out); + +assign out = in1*in2; + +endmodule + +module MUL2 #(parameter SIZE = 2)(input [SIZE-1:0] in1, in2, output [2*SIZE-1:0] out); + +assign out = in1*in2; + +endmodule + +module MUL4 #(parameter SIZE = 4)(input [SIZE-1:0] in1, in2, output [2*SIZE-1:0] out); + +assign out = in1*in2; + +endmodule + +module MUL8 #(parameter SIZE = 8)(input [SIZE-1:0] in1, in2, output [2*SIZE-1:0] out); + +assign out = in1*in2; + +endmodule + +module MUL16 #(parameter SIZE = 16)(input [SIZE-1:0] in1, in2, output [2*SIZE-1:0] out); + +assign out = in1*in2; + +endmodule + +module MUL32 #(parameter SIZE = 32)(input [SIZE-1:0] in1, in2, output [2*SIZE-1:0] out); + +assign out = in1*in2; + +endmodule + +module MUL64 #(parameter SIZE = 64)(input [SIZE-1:0] in1, in2, output [2*SIZE-1:0] out); + +assign out = in1*in2; + +endmodule + +module DIV1 #(parameter SIZE = 1)(input in1, in2, output out, rem); + +assign out = in1/in2; +assign rem = in1%in2; + +endmodule + +module DIV2 #(parameter SIZE = 2)(input [SIZE-1:0] in1, in2, + output [SIZE-1:0] out, rem); + +assign out = in1/in2; +assign rem = in1%in2; + +endmodule + +module DIV4 #(parameter SIZE = 4)(input [SIZE-1:0] in1, in2, + output [SIZE-1:0] out, rem); + +assign out = in1/in2; +assign rem = in1%in2; + +endmodule + +module DIV8 #(parameter SIZE = 8)(input [SIZE-1:0] in1, in2, + output [SIZE-1:0] out, rem); + +assign out = in1/in2; +assign rem = in1%in2; + +endmodule + +module DIV16 #(parameter SIZE = 16)(input [SIZE-1:0] in1, in2, + output [SIZE-1:0] out, rem); + +assign out = in1/in2; +assign rem = in1%in2; + +endmodule + +module DIV32 #(parameter SIZE = 32)(input [SIZE-1:0] in1, in2, + output [SIZE-1:0] out, rem); + +assign out = in1/in2; +assign rem = in1%in2; + +endmodule + +module DIV64 #(parameter SIZE = 64)(input [SIZE-1:0] in1, in2, + output [SIZE-1:0] out, rem); + +assign out = in1/in2; +assign rem = in1%in2; + +endmodule + +module FF (input d, clk, output reg q); +always @( posedge clk) + q <= d; +endmodule + + +module RFF(input d, clk, reset, output reg q); +always @(posedge clk or posedge reset) + if(reset) + q <= 0; + else + q <= d; +endmodule + +module SFF(input d, clk, set, output reg q); +always @(posedge clk or posedge set) + if(set) + q <= 1; + else + q <= d; +endmodule + +module RSFF(input d, clk, set, reset, output reg q); +always @(posedge clk or posedge reset or posedge set) + if(reset) + q <= 0; + else if(set) + q <= 1; + else + q <= d; +endmodule + +module SRFF(input d, clk, set, reset, output reg q); +always @(posedge clk or posedge set or posedge reset) + if(set) + q <= 1; + else if(reset) + q <= 0; + else + q <= d; +endmodule + +module LATCH(input d, enable, output reg q); +always @( d or enable) + if(enable) + q <= d; +endmodule + +module RLATCH(input d, reset, enable, output reg q); +always @( d or enable or reset) + if(enable) + if(reset) + q <= 0; + else + q <= d; +endmodule + +module LSHIFT1 #(parameter SIZE = 1)(input in, shift, val, output reg out); + +always @ (in, shift, val) begin + if(shift) + out = val; + else + out = in; +end + +endmodule + + +module LSHIFT2 #(parameter SIZE = 2)(input [SIZE-1:0] in, + input [SIZE-1:0] shift, input val, + output reg [SIZE-1:0] out); + +always @(in or shift or val) begin + out = in << shift; + if(val) + out = out | ({SIZE-1 {1'b1} } >> (SIZE-1-shift)); +end +endmodule + +module LSHIFT4 #(parameter SIZE = 4)(input [SIZE-1:0] in, + input [2:0] shift, input val, output reg [SIZE-1:0] out); + +always @(in or shift or val) begin + out = in << shift; + if(val) + out = out | ({SIZE-1 {1'b1} } >> (SIZE-1-shift)); +end +endmodule + + +module LSHIFT8 #(parameter SIZE = 8)(input [SIZE-1:0] in, + input [3:0] shift, input val, output reg [SIZE-1:0] out); + +always @(in or shift or val) begin + out = in << shift; + if(val) + out = out | ({SIZE-1 {1'b1} } >> (SIZE-1-shift)); +end +endmodule + +module LSHIFT16 #(parameter SIZE = 16)(input [SIZE-1:0] in, + input [4:0] shift, input val, output reg [SIZE-1:0] out); + +always @(in or shift or val) begin + out = in << shift; + if(val) + out = out | ({SIZE-1 {1'b1} } >> (SIZE-1-shift)); +end +endmodule + +module LSHIFT32 #(parameter SIZE = 32)(input [SIZE-1:0] in, + input [5:0] shift, input val, output reg [SIZE-1:0] out); + +always @(in or shift or val) begin + out = in << shift; + if(val) + out = out | ({SIZE-1 {1'b1} } >> (SIZE-1-shift)); +end +endmodule + +module LSHIFT64 #(parameter SIZE = 64)(input [SIZE-1:0] in, + input [6:0] shift, input val, output reg [SIZE-1:0] out); + +always @(in or shift or val) begin + out = in << shift; + if(val) + out = out | ({SIZE-1 {1'b1} } >> (SIZE-1-shift)); +end +endmodule + +module RSHIFT1 #(parameter SIZE = 1)(input in, shift, val, output reg out); + +always @ (in, shift, val) begin + if(shift) + out = val; + else + out = in; +end + +endmodule + +module RSHIFT2 #(parameter SIZE = 2)(input [SIZE-1:0] in, + input [SIZE-1:0] shift, input val, + output reg [SIZE-1:0] out); + +always @(in or shift or val) begin + out = in >> shift; + if(val) + out = out | ({SIZE-1 {1'b1} } << (SIZE-1-shift)); +end + +endmodule + + +module RSHIFT4 #(parameter SIZE = 4)(input [SIZE-1:0] in, + input [2:0] shift, input val, + output reg [SIZE-1:0] out); + +always @(in or shift or val) begin + out = in >> shift; + if(val) + out = out | ({SIZE-1 {1'b1} } << (SIZE-1-shift)); +end +endmodule + +module RSHIFT8 #(parameter SIZE = 8)(input [SIZE-1:0] in, + input [3:0] shift, input val, + output reg [SIZE-1:0] out); + +always @(in or shift or val) begin + out = in >> shift; + if(val) + out = out | ({SIZE-1 {1'b1} } << (SIZE-1-shift)); +end + +endmodule + +module RSHIFT16 #(parameter SIZE = 16)(input [SIZE-1:0] in, + input [4:0] shift, input val, + output reg [SIZE-1:0] out); + +always @(in or shift or val) begin + out = in >> shift; + if(val) + out = out | ({SIZE-1 {1'b1} } << (SIZE-1-shift)); +end +endmodule + + +module RSHIFT32 #(parameter SIZE = 32)(input [SIZE-1:0] in, + input [5:0] shift, input val, + output reg [SIZE-1:0] out); + +always @(in or shift or val) begin + out = in >> shift; + if(val) + out = out | ({SIZE-1 {1'b1} } << (SIZE-1-shift)); +end +endmodule + +module RSHIFT64 #(parameter SIZE = 64)(input [SIZE-1:0] in, + input [6:0] shift, input val, + output reg [SIZE-1:0] out); + +always @(in or shift or val) begin + out = in >> shift; + if(val) + out = out | ({SIZE-1 {1'b1} } << (SIZE-1-shift)); +end +endmodule + +module CMP1 #(parameter SIZE = 1) (input in1, in2, + output reg equal, unequal, greater, lesser); + +always @ (in1 or in2) begin + if(in1 == in2) begin + equal = 1; + unequal = 0; + greater = 0; + lesser = 0; + end + else begin + equal = 0; + unequal = 1; + + if(in1 < in2) begin + greater = 0; + lesser = 1; + end + else begin + greater = 1; + lesser = 0; + end + end +end +endmodule + + +module CMP2 #(parameter SIZE = 2) (input [SIZE-1:0] in1, in2, + output reg equal, unequal, greater, lesser); + +always @ (in1 or in2) begin + if(in1 == in2) begin + equal = 1; + unequal = 0; + greater = 0; + lesser = 0; + end + else begin + equal = 0; + unequal = 1; + + if(in1 < in2) begin + greater = 0; + lesser = 1; + end + else begin + greater = 1; + lesser = 0; + end + end +end +endmodule + +module CMP4 #(parameter SIZE = 4) (input [SIZE-1:0] in1, in2, + output reg equal, unequal, greater, lesser); + +always @ (in1 or in2) begin + if(in1 == in2) begin + equal = 1; + unequal = 0; + greater = 0; + lesser = 0; + end + else begin + equal = 0; + unequal = 1; + + if(in1 < in2) begin + greater = 0; + lesser = 1; + end + else begin + greater = 1; + lesser = 0; + end + end +end +endmodule + +module CMP8 #(parameter SIZE = 8) (input [SIZE-1:0] in1, in2, + output reg equal, unequal, greater, lesser); + +always @ (in1 or in2) begin + if(in1 == in2) begin + equal = 1; + unequal = 0; + greater = 0; + lesser = 0; + end + else begin + equal = 0; + unequal = 1; + + if(in1 < in2) begin + greater = 0; + lesser = 1; + end + else begin + greater = 1; + lesser = 0; + end + end +end +endmodule + +module CMP16 #(parameter SIZE = 16) (input [SIZE-1:0] in1, in2, + output reg equal, unequal, greater, lesser); + +always @ (in1 or in2) begin + if(in1 == in2) begin + equal = 1; + unequal = 0; + greater = 0; + lesser = 0; + end + else begin + equal = 0; + unequal = 1; + + if(in1 < in2) begin + greater = 0; + lesser = 1; + end + else begin + greater = 1; + lesser = 0; + end + end +end +endmodule + +module CMP32 #(parameter SIZE = 32) (input [SIZE-1:0] in1, in2, + output reg equal, unequal, greater, lesser); + +always @ (in1 or in2) begin + if(in1 == in2) begin + equal = 1; + unequal = 0; + greater = 0; + lesser = 0; + end + else begin + equal = 0; + unequal = 1; + + if(in1 < in2) begin + greater = 0; + lesser = 1; + end + else begin + greater = 1; + lesser = 0; + end + end +end +endmodule + +module CMP64 #(parameter SIZE = 64) (input [SIZE-1:0] in1, in2, + output reg equal, unequal, greater, lesser); + +always @ (in1 or in2) begin + if(in1 == in2) begin + equal = 1; + unequal = 0; + greater = 0; + lesser = 0; + end + else begin + equal = 0; + unequal = 1; + + if(in1 < in2) begin + greater = 0; + lesser = 1; + end + else begin + greater = 1; + lesser = 0; + end + end +end +endmodule + +module VCC (output supply1 out); +endmodule + +module GND (output supply0 out); +endmodule + + +module INC1 #(parameter SIZE = 1) (input in, output [SIZE:0] out); + +assign out = in + 1; + +endmodule + +module INC2 #(parameter SIZE = 2) (input [SIZE-1:0] in, output [SIZE:0] out); + +assign out = in + 1; + +endmodule + +module INC4 #(parameter SIZE = 4) (input [SIZE-1:0] in, output [SIZE:0] out); +assign out = in + 1; + +endmodule + +module INC8 #(parameter SIZE = 8) (input [SIZE-1:0] in, output [SIZE:0] out); +assign out = in + 1; + +endmodule + +module INC16 #(parameter SIZE = 16) (input [SIZE-1:0] in, output [SIZE:0] out); +assign out = in + 1; + +endmodule + +module INC32 #(parameter SIZE = 32) (input [SIZE-1:0] in, output [SIZE:0] out); +assign out = in + 1; + +endmodule +module INC64 #(parameter SIZE = 64) (input [SIZE-1:0] in, output [SIZE:0] out); +assign out = in + 1; + +endmodule diff --git a/chips/yosys/tests/hana/test_intermout.v b/chips/yosys/tests/hana/test_intermout.v new file mode 100644 index 0000000000000000000000000000000000000000..649f78a0d61839660475798c2397b8c59e6a5657 --- /dev/null +++ b/chips/yosys/tests/hana/test_intermout.v @@ -0,0 +1,418 @@ + +// test_intermout_always_comb_1_test.v +module f1_test(a, b, c, d, z); +input a, b, c, d; +output z; +reg z, temp1, temp2; + +always @(a or b or c or d) +begin + temp1 = a ^ b; + temp2 = c ^ d; + z = temp1 ^ temp2; +end + +endmodule + +// test_intermout_always_comb_3_test.v +module f2_test (in1, in2, out); +input in1, in2; +output reg out; + +always @ ( in1 or in2) + if(in1 > in2) + out = in1; + else + out = in2; +endmodule + +// test_intermout_always_comb_4_test.v +module f3_test(a, b, c); +input b, c; +output reg a; + +always @(b or c) begin +a = b; +a = c; +end +endmodule + +// test_intermout_always_comb_5_test.v +module f4_test(ctrl, in1, in2, out); +input ctrl; +input in1, in2; +output reg out; + +always @ (ctrl or in1 or in2) + if(ctrl) + out = in1 & in2; + else + out = in1 | in2; +endmodule + +// test_intermout_always_ff_3_test.v +module f5_NonBlockingEx(clk, merge, er, xmit, fddi, claim); +input clk, merge, er, xmit, fddi; +output reg claim; +reg fcr; + +always @(posedge clk) +begin + fcr = er | xmit; + + if(merge) + claim = fcr & fddi; + else + claim = fddi; +end +endmodule + +// test_intermout_always_ff_4_test.v +module f6_FlipFlop(clk, cs, ns); +input clk; +input [31:0] cs; +output [31:0] ns; +integer is; + +always @(posedge clk) + is <= cs; + +assign ns = is; +endmodule + +// test_intermout_always_ff_5_test.v +module f7_FlipFlop(clock, cs, ns); +input clock; +input [3:0] cs; +output reg [3:0] ns; +reg [3:0] temp; + +always @(posedge clock) +begin + temp = cs; + ns = temp; +end + +endmodule + +// test_intermout_always_ff_6_test.v +module f8_inc(clock, counter); + +input clock; +output reg [3:0] counter; +always @(posedge clock) + counter <= counter + 1; +endmodule + +// test_intermout_always_ff_8_test.v +module f9_NegEdgeClock(q, d, clk, reset); +input d, clk, reset; +output reg q; + +always @(negedge clk or negedge reset) + if(!reset) + q <= 1'b0; + else + q <= d; + +endmodule + +// test_intermout_always_ff_9_test.v +module f10_MyCounter (clock, preset, updown, presetdata, counter); +input clock, preset, updown; +input [1: 0] presetdata; +output reg [1:0] counter; + +always @(posedge clock) + if(preset) + counter <= presetdata; + else + if(updown) + counter <= counter + 1; + else + counter <= counter - 1; +endmodule + +// test_intermout_always_latch_1_test.v +module f11_test(en, in, out); +input en; +input [1:0] in; +output reg [2:0] out; + +always @ (en or in) + if(en) + out = in + 1; +endmodule + +// test_intermout_bufrm_1_test.v +module f12_test(input in, output out); +//no buffer removal +assign out = in; +endmodule + +// test_intermout_bufrm_2_test.v +module f13_test(input in, output out); +//intermediate buffers should be removed +wire w1, w2; +assign w1 = in; +assign w2 = w1; +assign out = w2; +endmodule + +// test_intermout_bufrm_6_test.v +module f14_test(in, out); +input in; +output out; + +wire w1, w2, w3, w4; +assign w1 = in; +assign w2 = w1; +assign w4 = w3; +assign out = w4; +f14_mybuf _f14_mybuf(w2, w3); +endmodule + +module f14_mybuf(in, out); +input in; +output out; +wire w1, w2, w3, w4; + +assign w1 = in; +assign w2 = w1; +assign out = w2; +endmodule + + +// test_intermout_bufrm_7_test.v +module f15_test(in1, in2, out); +input in1, in2; +output out; +// Y with cluster of f15_mybuf instances at the junction + +wire w1, w2, w3, w4, w5, w6, w7, w8, w9, w10; +assign w1 = in1; +assign w2 = w1; +assign w5 = in2; +assign w6 = w5; +assign w10 = w9; +assign out = w10; + +f15_mybuf _f15_mybuf0(w2, w3); +f15_mybuf _f15_mybuf1(w3, w4); + +f15_mybuf _f15_mybuf2(w6, w7); +f15_mybuf _f15_mybuf3(w7, w4); + +f15_mybuf _f15_mybuf4(w4, w8); +f15_mybuf _f15_mybuf5(w8, w9); +endmodule + +module f15_mybuf(in, out); +input in; +output out; +wire w1, w2, w3, w4; + +assign w1 = in; +assign w2 = w1; +assign out = w2; +endmodule + + +// test_intermout_exprs_add_test.v +module f16_test(out, in1, in2, vin1, vin2, vout1); +output out; +input in1, in2; +input [1:0] vin1; +input [2:0] vin2; +output [3:0] vout1; + +assign out = in1 + in2; +assign vout1 = vin1 + vin2; +endmodule + +// test_intermout_exprs_binlogic_test.v +module f17_test(in1, in2, vin1, vin2, out, vout, vin3, vin4, vout1 ); +input in1, in2; +input [1:0] vin1; +input [3:0] vin2; +input [1:0] vin3; +input [3:0] vin4; +output vout, vout1; +output out; + +assign out = in1 && in2; +assign vout = vin1 && vin2; +assign vout1 = vin3 || vin4; +endmodule + +// test_intermout_exprs_bitwiseneg_test.v +module f18_test(output out, input in, output [1:0] vout, input [1:0] vin); + +assign out = ~in; +assign vout = ~vin; +endmodule + +// test_intermout_exprs_buffer_test.v +module f19_buffer(in, out, vin, vout); +input in; +output out; +input [1:0] vin; +output [1:0] vout; + +assign out = in; +assign vout = vin; +endmodule + +// test_intermout_exprs_condexpr_mux_test.v +module f20_test(in1, in2, out, vin1, vin2, vin3, vin4, vout1, vout2, en1, ven1, ven2); +input in1, in2, en1, ven1; +input [1:0] ven2; +output out; +input [1:0] vin1, vin2, vin3, vin4; +output [1:0] vout1, vout2; + +assign out = en1 ? in1 : in2; +assign vout1 = ven1 ? vin1 : vin2; +assign vout2 = ven2 ? vin3 : vin4; +endmodule + +// test_intermout_exprs_condexpr_tribuf_test.v +module f21_test(in, out, en, vin1, vout1, en1); +input in, en, en1; +output out; +input [1:0] vin1; +output [1:0] vout1; + +assign out = en ? in : 1'bz; +assign vout1 = en1 ? vin1 : 2'bzz; +endmodule + +// test_intermout_exprs_constshift_test.v +module f22_test(in, out, vin, vout, vin1, vout1, vin2, vout2); + +input in; +input [3:0] vin, vin1, vin2; +output [3:0] vout, vout1, vout2; +output out; + +assign out = in << 1; +assign vout = vin << 2; +assign vout1 = vin1 >> 2; +assign vout2 = vin2 >>> 2; +endmodule + +// test_intermout_exprs_const_test.v +module f23_test (out, vout); +output out; +output [7:0] vout; + +assign out = 1'b1; +assign vout = 9; +endmodule + +// test_intermout_exprs_div_test.v +module f24_test(out, in1, in2, vin1, vin2, vout1); +output out; +input in1, in2; +input [1:0] vin1; +input [2:0] vin2; +output [3:0] vout1; + +assign out = in1 / in2; +assign vout1 = vin1 / vin2; +endmodule + +// test_intermout_exprs_logicneg_test.v +module f25_test(out, vout, in, vin); +output out, vout; +input in; +input [3:0] vin; +assign out = !in; +assign vout = !vin; +endmodule + +// test_intermout_exprs_mod_test.v +module f26_test(out, in1, in2, vin1, vin2, vout1); +output out; +input in1, in2; +input [1:0] vin1; +input [2:0] vin2; +output [3:0] vout1; + +assign out = in1 % in2; +assign vout1 = vin1 % vin2; +endmodule + +// test_intermout_exprs_mul_test.v +module f27_test(out, in1, in2, vin1, vin2, vout1); +output out; +input in1, in2; +input [1:0] vin1; +input [2:0] vin2; +output [3:0] vout1; + +assign out = in1 * in2; +assign vout1 = vin1 * vin2; +endmodule + +// test_intermout_exprs_redand_test.v +module f28_test(output out, input [1:0] vin, output out1, input [3:0] vin1); + +assign out = &vin; +assign out1 = &vin1; +endmodule + +// test_intermout_exprs_redop_test.v +module f29_Reduction (A1, A2, A3, A4, A5, A6, Y1, Y2, Y3, Y4, Y5, Y6); +input [1:0] A1; +input [1:0] A2; +input [1:0] A3; +input [1:0] A4; +input [1:0] A5; +input [1:0] A6; +output Y1, Y2, Y3, Y4, Y5, Y6; +//reg Y1, Y2, Y3, Y4, Y5, Y6; +assign Y1=&A1; //reduction AND +assign Y2=|A2; //reduction OR +assign Y3=~&A3; //reduction NAND +assign Y4=~|A4; //reduction NOR +assign Y5=^A5; //reduction XOR +assign Y6=~^A6; //reduction XNOR +endmodule + +// test_intermout_exprs_sub_test.v +module f30_test(out, in1, in2, vin1, vin2, vout1); +output out; +input in1, in2; +input [1:0] vin1; +input [2:0] vin2; +output [3:0] vout1; + +assign out = in1 - in2; +assign vout1 = vin1 - vin2; +endmodule + +// test_intermout_exprs_unaryminus_test.v +module f31_test(output out, input in, output [31:0] vout, input [31:0] vin); + +assign out = -in; +assign vout = -vin; +endmodule + +// test_intermout_exprs_unaryplus_test.v +module f32_test(output out, input in); + +assign out = +in; +endmodule + +// test_intermout_exprs_varshift_test.v +module f33_test(vin0, vout0); +input [2:0] vin0; +output reg [7:0] vout0; + +wire [7:0] myreg0, myreg1, myreg2; +integer i; +assign myreg0 = vout0 << vin0; + +assign myreg1 = myreg2 >> i; +endmodule diff --git a/chips/yosys/tests/hana/test_parse2synthtrans.v b/chips/yosys/tests/hana/test_parse2synthtrans.v new file mode 100644 index 0000000000000000000000000000000000000000..7185065fbf9fb7f009e7260f2de7e4859f344a81 --- /dev/null +++ b/chips/yosys/tests/hana/test_parse2synthtrans.v @@ -0,0 +1,91 @@ + +// test_parse2synthtrans_behavopt_1_test.v +module f1_test(in, out, clk, reset); +input in, reset; +output reg out; +input clk; +reg signed [3:0] a; +reg signed [3:0] b; +reg signed [3:0] c; +reg [5:0] d; +reg [5:0] e; + +always @(clk or reset) begin + a = -4; + b = 2; + c = a + b; + d = a + b + c; + d = d*d; + if(b) + e = d*d; + else + e = d + d; +end +endmodule + +// test_parse2synthtrans_case_1_test.v module f2_demultiplexer1_to_4 - REMOVED, multiple drivers + +// test_parse2synthtrans_contassign_1_test.v +module f3_test(in, out); + +input wire in; +output out; +assign out = (in+in); +assign out = 74; +endmodule + +// test_parse2synthtrans_module_basic0_test.v +module f4_test; +endmodule + +// test_parse2synthtrans_operators_1_test.v +module f5_test(in, out); +input in; +output out; +parameter p1 = 10; +parameter p2 = 5; + +assign out = +p1; +assign out = -p2; +assign out = p1 + p2; +assign out = p1 - p2; +endmodule + +// test_parse2synthtrans_param_1_test.v +module f6_test(in, out); +input in; +output out; +parameter p = 10; + +assign out = p; +endmodule + +// test_parse2synthtrans_port_scalar_1_test.v +module f7_test(in, out, io); +inout io; +output out; +input in; + +endmodule + +// test_parse2synthtrans_port_vector_1_test.v +module f8_test(in1, in2, out1, out2, io1, io2); +inout [1:0] io1; +inout [0:1] io2; +output [1:0] out1; +output [0:1] out2; +input [1:0] in1; +input [0:1] in2; + +endmodule + +// test_parse2synthtrans_v2k_comb_logic_sens_list_test.v +module f9_test(q, d, clk, reset); +output reg q; +input d, clk, reset; + +always @ (posedge clk, negedge reset) + if(!reset) q <= 0; + else q <= d; + +endmodule diff --git a/chips/yosys/tests/hana/test_parser.v b/chips/yosys/tests/hana/test_parser.v new file mode 100644 index 0000000000000000000000000000000000000000..c7305356a4ba0bfaf8a0c8a5af64484d7eb0542a --- /dev/null +++ b/chips/yosys/tests/hana/test_parser.v @@ -0,0 +1,87 @@ + +// test_parser_constructs_module_basic1_test.v +module f1_test; +endmodule + +// test_parser_constructs_param_basic0_test.v +module f2_test #( parameter v2kparam = 5) +(in, out, io, vin, vout, vio); +input in; +output out; +inout io; +input [3:0] vin; +output [v2kparam:0] vout; +inout [0:3] vio; +parameter myparam = 10; +endmodule + +// test_parser_constructs_port_basic0_test.v +module f3_test(in, out, io, vin, vout, vio); +input in; +output out; +inout io; +input [3:0] vin; +output [3:0] vout; +inout [0:3] vio; +endmodule + +// test_parser_directives_define_simpledef_test.v +`define parvez ahmad +`define WIRE wire +`define TEN 10 + +module f4_`parvez(); +parameter param = `TEN; +`WIRE w; +assign w = `TEN; +endmodule + +// test_parser_misc_operators_test.v +module f5_test(out, i0, i1, i2, i3, s1, s0); +output out; +input i0, i1, i2, i3; +input s1, s0; + +assign out = (~s1 & s0 & i0) | + (~s1 & s0 & i1) | + (s1 & ~s0 & i2) | + (s1 & s0 & i3); + +endmodule + +module f5_ternaryop(out, i0, i1, i2, i3, s1, s0); +output out; +input i0, i1, i2, i3; +input s1, s0; + +assign out = s1 ? (s0 ? i3 : i2) : (s0 ? i1 : i0); + +endmodule + +module f5_fulladd4(sum, c_out, a, b, c_in); +output [3:0] sum; +output c_out; +input [3:0] a, b; +input c_in; + +assign {c_out, sum} = a + b + c_in; +endmodule + +// test_parser_v2k_comb_port_data_type_test.v +module f6_adder(sum , co, a, b, ci); +output reg [31:0] sum; +output reg co; +input wire [31:0] a, b; +input wire ci; +endmodule + +// test_parser_v2k_comma_sep_sens_list_test.v +module f7_test(q, d, clk, reset); +output reg q; +input d, clk, reset; + +always @ (posedge clk, negedge reset) + if(!reset) q <= 0; + else q <= d; + +endmodule diff --git a/chips/yosys/tests/hana/test_simulation_always.v b/chips/yosys/tests/hana/test_simulation_always.v new file mode 100644 index 0000000000000000000000000000000000000000..0da8e43bd26a511fe340d99e8118eacb7fec64b4 --- /dev/null +++ b/chips/yosys/tests/hana/test_simulation_always.v @@ -0,0 +1,135 @@ + +// test_simulation_always_15_test.v +module f1_test(input [1:0] in, output reg [1:0] out); + +always @(in) + out = in; +endmodule + +// test_simulation_always_17_test.v +module f2_test(a, b, c, d, z); +input a, b, c, d; +output z; +reg z, temp1, temp2; + +always @(a or b or c or d) +begin + temp1 = a ^ b; + temp2 = c ^ d; + z = temp1 ^ temp2; +end + +endmodule + +// test_simulation_always_18_test.v +module f3_test (in1, in2, out); +input in1, in2; +output reg out; + +always @ ( in1 or in2) + if(in1 > in2) + out = in1; + else + out = in2; +endmodule + +// test_simulation_always_19_test.v +module f4_test(ctrl, in1, in2, out); +input ctrl; +input in1, in2; +output reg out; + +always @ (ctrl or in1 or in2) + if(ctrl) + out = in1 & in2; + else + out = in1 | in2; +endmodule + +// test_simulation_always_1_test.v +module f5_test(input in, output reg out); + +always @(in) + out = in; +endmodule + +// test_simulation_always_20_test.v +module f6_NonBlockingEx(clk, merge, er, xmit, fddi, claim); +input clk, merge, er, xmit, fddi; +output reg claim; +reg fcr; + +always @(posedge clk) +begin + fcr <= er | xmit; + + if(merge) + claim <= fcr & fddi; + else + claim <= fddi; +end +endmodule + +// test_simulation_always_21_test.v +module f7_FlipFlop(clk, cs, ns); +input clk; +input [7:0] cs; +output [7:0] ns; +integer is; + +always @(posedge clk) + is <= cs; + +assign ns = is; +endmodule + +// test_simulation_always_22_test.v +module f8_inc(clock, counter); + +input clock; +output reg [7:0] counter; +always @(posedge clock) + counter <= counter + 1; +endmodule + +// test_simulation_always_23_test.v +module f9_MyCounter (clock, preset, updown, presetdata, counter); +input clock, preset, updown; +input [1: 0] presetdata; +output reg [1:0] counter; + +always @(posedge clock) + if(preset) + counter <= presetdata; + else + if(updown) + counter <= counter + 1; + else + counter <= counter - 1; +endmodule + +// test_simulation_always_27_test.v +module f10_FlipFlop(clock, cs, ns); +input clock; +input cs; +output reg ns; +reg temp; + +always @(posedge clock) +begin + temp <= cs; + ns <= temp; +end + +endmodule + +// test_simulation_always_29_test.v +module f11_test(input in, output reg [1:0] out); + + always @(in) + begin + out = in; + out = out + in; + end + +endmodule diff --git a/chips/yosys/tests/hana/test_simulation_and.v b/chips/yosys/tests/hana/test_simulation_and.v new file mode 100644 index 0000000000000000000000000000000000000000..480e733d13e6ad1d574d1757b7b20e24c039c174 --- /dev/null +++ b/chips/yosys/tests/hana/test_simulation_and.v @@ -0,0 +1,35 @@ + +// test_simulation_and_1_test.v +module f1_test(input [1:0] in, output out); +assign out = in[0] & in[1]; +endmodule + +// test_simulation_and_2_test.v +module f2_test(input [1:0] in, output out); +assign out = in[0] && in[1]; +endmodule + +// test_simulation_and_3_test.v +module f3_test(input [2:0] in, output out); +assign out = in[0] & in[1] & in[2]; +endmodule + +// test_simulation_and_4_test.v +module f4_test(input [2:0] in, output out); +assign out = in[0] && in[1] && in[2]; +endmodule + +// test_simulation_and_5_test.v +module f5_test(input [3:0] in, output out); +assign out = in[0] & in[1] & in[2] & in[3]; +endmodule + +// test_simulation_and_6_test.v +module f6_test(input [3:0] in, output out); +assign out = in[0] && in[1] && in[2] && in[3]; +endmodule + +// test_simulation_and_7_test.v +module f7_test(input [3:0] in, output out); +and myand(out, in[0], in[1], in[2], in[3]); +endmodule diff --git a/chips/yosys/tests/hana/test_simulation_buffer.v b/chips/yosys/tests/hana/test_simulation_buffer.v new file mode 100644 index 0000000000000000000000000000000000000000..d674b05cafa69a6b96a87d15fcda2869122d9f15 --- /dev/null +++ b/chips/yosys/tests/hana/test_simulation_buffer.v @@ -0,0 +1,17 @@ + +// test_simulation_buffer_1_test.v +module f1_test(input in, output out); +assign out = in; +endmodule + +// test_simulation_buffer_2_test.v +module f2_test(input [1:0] in, output [1:0] out); +assign out[0] = in[0]; +assign out[1] = in[1]; +endmodule + +// test_simulation_buffer_3_test.v +module f3_test(input in, output [1:0] out); +assign out[0] = in; +assign out[1] = in; +endmodule diff --git a/chips/yosys/tests/hana/test_simulation_decoder.v b/chips/yosys/tests/hana/test_simulation_decoder.v new file mode 100644 index 0000000000000000000000000000000000000000..311d425c8e267d25a21cc1d5e267ec7791614a42 --- /dev/null +++ b/chips/yosys/tests/hana/test_simulation_decoder.v @@ -0,0 +1,218 @@ + +// test_simulation_decoder_2_test.v +module f1_test (input [1:0] in, input enable, output reg out); + +always @(in or enable) + if(!enable) + out = 4'b0000; + else begin + case (in) + 2'b00 : out = 0 ; + 2'b01 : out = 1; + 2'b10 : out = 0; + 2'b11 : out = 1; + endcase + end +endmodule + +// test_simulation_decoder_3_test.v +module f2_test (input [1:0] in, input enable, output reg [2:0] out); + +always @(in or enable) + if(!enable) + out = 3'b000; + else begin + case (in) + 2'b00 : out = 3'b001 ; + 2'b01 : out = 3'b010; + 2'b10 : out = 3'b010; + 2'b11 : out = 3'b100; + endcase + end +endmodule + +// test_simulation_decoder_4_test.v +module f3_test (input [2:0] in, output reg [7:0] out); + +always @(in ) + case (in) + 3'b000 : out = 8'b00000001; + 3'b001 : out = 8'b00000010; + 3'b010 : out = 8'b00000100; + 3'b011 : out = 8'b00001000; + 3'b100 : out = 8'b00010000; + 3'b101 : out = 8'b00100000; + 3'b110 : out = 8'b01000000; + 3'b111 : out = 8'b10000000; + endcase +endmodule + +// test_simulation_decoder_5_test.v +module f4_test (input [2:0] in, input enable, output reg [7:0] out); + +always @(in or enable ) + if(!enable) + out = 8'b00000000; + else + case (in) + 3'b000 : out = 8'b00000001; + 3'b001 : out = 8'b00000010; + 3'b010 : out = 8'b00000100; + 3'b011 : out = 8'b00001000; + 3'b100 : out = 8'b00010000; + 3'b101 : out = 8'b00100000; + 3'b110 : out = 8'b01000000; + 3'b111 : out = 8'b10000000; + endcase +endmodule + +// test_simulation_decoder_6_test.v +module f5_test (input [3:0] in, input enable, output reg [15:0] out); + +always @(in or enable) + if(!enable) + out = 16'b0000000000000000; + else begin + case (in) + 4'b0000 : out = 16'b0000000000000001; + 4'b0001 : out = 16'b0000000000000010; + 4'b0010 : out = 16'b0000000000000100; + 4'b0011 : out = 16'b0000000000001000; + 4'b0100 : out = 16'b0000000000010000; + 4'b0101 : out = 16'b0000000000100000; + 4'b0110 : out = 16'b0000000001000000; + 4'b0111 : out = 16'b0000000010000000; + 4'b1000 : out = 16'b0000000100000000; + 4'b1001 : out = 16'b0000001000000000; + 4'b1010 : out = 16'b0000010000000000; + 4'b1011 : out = 16'b0000100000000000; + 4'b1100 : out = 16'b0001000000000000; + 4'b1101 : out = 16'b0010000000000000; + 4'b1110 : out = 16'b0100000000000000; + 4'b1111 : out = 16'b1000000000000000; + endcase + end +endmodule + + +// test_simulation_decoder_7_test.v +module f6_test (input [4:0] in, input enable, output reg [31:0] out); + +always @(in or enable) + if(!enable) + out = 32'b00000000000000000000000000000000; + else begin + case (in) + 5'b00000 : out = 32'b00000000000000000000000000000001; + 5'b00001 : out = 32'b00000000000000000000000000000010; + 5'b00010 : out = 32'b00000000000000000000000000000100; + 5'b00011 : out = 32'b00000000000000000000000000001000; + 5'b00100 : out = 32'b00000000000000000000000000010000; + 5'b00101 : out = 32'b00000000000000000000000000100000; + 5'b00110 : out = 32'b00000000000000000000000001000000; + 5'b00111 : out = 32'b00000000000000000000000010000000; + 5'b01000 : out = 32'b00000000000000000000000100000000; + 5'b01001 : out = 32'b00000000000000000000001000000000; + 5'b01010 : out = 32'b00000000000000000000010000000000; + 5'b01011 : out = 32'b00000000000000000000100000000000; + 5'b01100 : out = 32'b00000000000000000001000000000000; + 5'b01101 : out = 32'b00000000000000000010000000000000; + 5'b01110 : out = 32'b00000000000000000100000000000000; + 5'b01111 : out = 32'b00000000000000001000000000000000; + 5'b10000 : out = 32'b00000000000000010000000000000000; + 5'b10001 : out = 32'b00000000000000100000000000000000; + 5'b10010 : out = 32'b00000000000001000000000000000000; + 5'b10011 : out = 32'b00000000000010000000000000000000; + 5'b10100 : out = 32'b00000000000100000000000000000000; + 5'b10101 : out = 32'b00000000001000000000000000000000; + 5'b10110 : out = 32'b00000000010000000000000000000000; + 5'b10111 : out = 32'b00000000100000000000000000000000; + 5'b11000 : out = 32'b00000001000000000000000000000000; + 5'b11001 : out = 32'b00000010000000000000000000000000; + 5'b11010 : out = 32'b00000100000000000000000000000000; + 5'b11011 : out = 32'b00001000000000000000000000000000; + 5'b11100 : out = 32'b00010000000000000000000000000000; + 5'b11101 : out = 32'b00100000000000000000000000000000; + 5'b11110 : out = 32'b01000000000000000000000000000000; + 5'b11111 : out = 32'b10000000000000000000000000000000; + endcase + end +endmodule + + +// test_simulation_decoder_8_test.v +module f7_test (input [5:0] in, input enable, output reg [63:0] out); + +always @(in or enable) + if(!enable) + out = 64'b0000000000000000000000000000000000000000000000000000000000000000; + else begin + case (in) + 6'b000000 : out = 64'b0000000000000000000000000000000000000000000000000000000000000001; + 6'b000001 : out = 64'b0000000000000000000000000000000000000000000000000000000000000010; + 6'b000010 : out = 64'b0000000000000000000000000000000000000000000000000000000000000100; + 6'b000011 : out = 64'b0000000000000000000000000000000000000000000000000000000000001000; + 6'b000100 : out = 64'b0000000000000000000000000000000000000000000000000000000000010000; + 6'b000101 : out = 64'b0000000000000000000000000000000000000000000000000000000000100000; + 6'b000110 : out = 64'b0000000000000000000000000000000000000000000000000000000001000000; + 6'b000111 : out = 64'b0000000000000000000000000000000000000000000000000000000010000000; + 6'b001000 : out = 64'b0000000000000000000000000000000000000000000000000000000100000000; + 6'b001001 : out = 64'b0000000000000000000000000000000000000000000000000000001000000000; + 6'b001010 : out = 64'b0000000000000000000000000000000000000000000000000000010000000000; + 6'b001011 : out = 64'b0000000000000000000000000000000000000000000000000000100000000000; + 6'b001100 : out = 64'b0000000000000000000000000000000000000000000000000001000000000000; + 6'b001101 : out = 64'b0000000000000000000000000000000000000000000000000010000000000000; + 6'b001110 : out = 64'b0000000000000000000000000000000000000000000000000100000000000000; + 6'b001111 : out = 64'b0000000000000000000000000000000000000000000000001000000000000000; + 6'b010000 : out = 64'b0000000000000000000000000000000000000000000000010000000000000000; + 6'b010001 : out = 64'b0000000000000000000000000000000000000000000000100000000000000000; + 6'b010010 : out = 64'b0000000000000000000000000000000000000000000001000000000000000000; + 6'b010011 : out = 64'b0000000000000000000000000000000000000000000010000000000000000000; + 6'b010100 : out = 64'b0000000000000000000000000000000000000000000100000000000000000000; + 6'b010101 : out = 64'b0000000000000000000000000000000000000000001000000000000000000000; + 6'b010110 : out = 64'b0000000000000000000000000000000000000000010000000000000000000000; + 6'b010111 : out = 64'b0000000000000000000000000000000000000000100000000000000000000000; + 6'b011000 : out = 64'b0000000000000000000000000000000000000001000000000000000000000000; + 6'b011001 : out = 64'b0000000000000000000000000000000000000010000000000000000000000000; + 6'b011010 : out = 64'b0000000000000000000000000000000000000100000000000000000000000000; + 6'b011011 : out = 64'b0000000000000000000000000000000000001000000000000000000000000000; + 6'b011100 : out = 64'b0000000000000000000000000000000000010000000000000000000000000000; + 6'b011101 : out = 64'b0000000000000000000000000000000000100000000000000000000000000000; + 6'b011110 : out = 64'b0000000000000000000000000000000001000000000000000000000000000000; + 6'b011111 : out = 64'b0000000000000000000000000000000010000000000000000000000000000000; + + 6'b100000 : out = 64'b0000000000000000000000000000000100000000000000000000000000000000; + 6'b100001 : out = 64'b0000000000000000000000000000001000000000000000000000000000000000; + 6'b100010 : out = 64'b0000000000000000000000000000010000000000000000000000000000000000; + 6'b100011 : out = 64'b0000000000000000000000000000100000000000000000000000000000000000; + 6'b100100 : out = 64'b0000000000000000000000000001000000000000000000000000000000000000; + 6'b100101 : out = 64'b0000000000000000000000000010000000000000000000000000000000000000; + 6'b100110 : out = 64'b0000000000000000000000000100000000000000000000000000000000000000; + 6'b100111 : out = 64'b0000000000000000000000001000000000000000000000000000000000000000; + 6'b101000 : out = 64'b0000000000000000000000010000000000000000000000000000000000000000; + 6'b101001 : out = 64'b0000000000000000000000100000000000000000000000000000000000000000; + 6'b101010 : out = 64'b0000000000000000000001000000000000000000000000000000000000000000; + 6'b101011 : out = 64'b0000000000000000000010000000000000000000000000000000000000000000; + 6'b101100 : out = 64'b0000000000000000000100000000000000000000000000000000000000000000; + 6'b101101 : out = 64'b0000000000000000001000000000000000000000000000000000000000000000; + 6'b101110 : out = 64'b0000000000000000010000000000000000000000000000000000000000000000; + 6'b101111 : out = 64'b0000000000000000100000000000000000000000000000000000000000000000; + 6'b110000 : out = 64'b0000000000000001000000000000000000000000000000000000000000000000; + 6'b110001 : out = 64'b0000000000000010000000000000000000000000000000000000000000000000; + 6'b110010 : out = 64'b0000000000000100000000000000000000000000000000000000000000000000; + 6'b110011 : out = 64'b0000000000001000000000000000000000000000000000000000000000000000; + 6'b110100 : out = 64'b0000000000010000000000000000000000000000000000000000000000000000; + 6'b110101 : out = 64'b0000000000100000000000000000000000000000000000000000000000000000; + 6'b110110 : out = 64'b0000000001000000000000000000000000000000000000000000000000000000; + 6'b110111 : out = 64'b0000000010000000000000000000000000000000000000000000000000000000; + 6'b111000 : out = 64'b0000000100000000000000000000000000000000000000000000000000000000; + 6'b111001 : out = 64'b0000001000000000000000000000000000000000000000000000000000000000; + 6'b111010 : out = 64'b0000010000000000000000000000000000000000000000000000000000000000; + 6'b111011 : out = 64'b0000100000000000000000000000000000000000000000000000000000000000; + 6'b111100 : out = 64'b0001000000000000000000000000000000000000000000000000000000000000; + 6'b111101 : out = 64'b0010000000000000000000000000000000000000000000000000000000000000; + 6'b111110 : out = 64'b0100000000000000000000000000000000000000000000000000000000000000; + 6'b111111 : out = 64'b1000000000000000000000000000000000000000000000000000000000000000; + endcase + end +endmodule diff --git a/chips/yosys/tests/hana/test_simulation_inc.v b/chips/yosys/tests/hana/test_simulation_inc.v new file mode 100644 index 0000000000000000000000000000000000000000..f8f5487055d01ce00e96cc2d529168b0502329e1 --- /dev/null +++ b/chips/yosys/tests/hana/test_simulation_inc.v @@ -0,0 +1,42 @@ + +// test_simulation_inc_16_test.v +module f1_test(input [15:0] in, output [15:0] out); + +assign out = -in; + +endmodule + +// test_simulation_inc_1_test.v +module f2_test(input in, output out); + +assign out = -in; + +endmodule + +// test_simulation_inc_2_test.v +module f3_test(input [1:0] in, output [1:0] out); + +assign out = -in; + +endmodule + +// test_simulation_inc_32_test.v +module f4_test(input [31:0] in, output [31:0] out); + +assign out = -in; + +endmodule + +// test_simulation_inc_4_test.v +module f5_test(input [3:0] in, output [3:0] out); + +assign out = -in; + +endmodule + +// test_simulation_inc_8_test.v +module f6_test(input [7:0] in, output [7:0] out); + +assign out = -in; + +endmodule diff --git a/chips/yosys/tests/hana/test_simulation_mux.v b/chips/yosys/tests/hana/test_simulation_mux.v new file mode 100644 index 0000000000000000000000000000000000000000..6fc91289393098f1e268ca009b66f67c404ba48b --- /dev/null +++ b/chips/yosys/tests/hana/test_simulation_mux.v @@ -0,0 +1,176 @@ + +// test_simulation_mux_16_test.v +module f1_test(input [15:0] in, input [3:0] select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + 2: out = in[2]; + 3: out = in[3]; + 4: out = in[4]; + 5: out = in[5]; + 6: out = in[6]; + 7: out = in[7]; + 8: out = in[8]; + 9: out = in[9]; + 10: out = in[10]; + 11: out = in[11]; + 12: out = in[12]; + 13: out = in[13]; + 14: out = in[14]; + 15: out = in[15]; + endcase +endmodule + +// test_simulation_mux_2_test.v +module f2_test(input [1:0] in, input select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + endcase +endmodule + +// test_simulation_mux_32_test.v +module f3_test(input [31:0] in, input [4:0] select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + 2: out = in[2]; + 3: out = in[3]; + 4: out = in[4]; + 5: out = in[5]; + 6: out = in[6]; + 7: out = in[7]; + 8: out = in[8]; + 9: out = in[9]; + 10: out = in[10]; + 11: out = in[11]; + 12: out = in[12]; + 13: out = in[13]; + 14: out = in[14]; + 15: out = in[15]; + 16: out = in[16]; + 17: out = in[17]; + 18: out = in[18]; + 19: out = in[19]; + 20: out = in[20]; + 21: out = in[21]; + 22: out = in[22]; + 23: out = in[23]; + 24: out = in[24]; + 25: out = in[25]; + 26: out = in[26]; + 27: out = in[27]; + 28: out = in[28]; + 29: out = in[29]; + 30: out = in[30]; + 31: out = in[31]; + endcase +endmodule + + +// test_simulation_mux_4_test.v +module f4_test(input [3:0] in, input [1:0] select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + 2: out = in[2]; + 3: out = in[3]; + endcase +endmodule + +// test_simulation_mux_64_test.v +module f5_test(input [63:0] in, input [5:0] select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + 2: out = in[2]; + 3: out = in[3]; + 4: out = in[4]; + 5: out = in[5]; + 6: out = in[6]; + 7: out = in[7]; + 8: out = in[8]; + 9: out = in[9]; + 10: out = in[10]; + 11: out = in[11]; + 12: out = in[12]; + 13: out = in[13]; + 14: out = in[14]; + 15: out = in[15]; + 16: out = in[16]; + 17: out = in[17]; + 18: out = in[18]; + 19: out = in[19]; + 20: out = in[20]; + 21: out = in[21]; + 22: out = in[22]; + 23: out = in[23]; + 24: out = in[24]; + 25: out = in[25]; + 26: out = in[26]; + 27: out = in[27]; + 28: out = in[28]; + 29: out = in[29]; + 30: out = in[30]; + 31: out = in[31]; + 32: out = in[32]; + 33: out = in[33]; + 34: out = in[34]; + 35: out = in[35]; + 36: out = in[36]; + 37: out = in[37]; + 38: out = in[38]; + 39: out = in[39]; + 40: out = in[40]; + 41: out = in[41]; + 42: out = in[42]; + 43: out = in[43]; + 44: out = in[44]; + 45: out = in[45]; + 46: out = in[46]; + 47: out = in[47]; + 48: out = in[48]; + 49: out = in[49]; + 50: out = in[50]; + 51: out = in[51]; + 52: out = in[52]; + 53: out = in[53]; + 54: out = in[54]; + 55: out = in[55]; + 56: out = in[56]; + 57: out = in[57]; + 58: out = in[58]; + 59: out = in[59]; + 60: out = in[60]; + 61: out = in[61]; + 62: out = in[62]; + 63: out = in[63]; + endcase +endmodule + + +// test_simulation_mux_8_test.v +module f6_test(input [7:0] in, input [2:0] select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + 2: out = in[2]; + 3: out = in[3]; + 4: out = in[4]; + 5: out = in[5]; + 6: out = in[6]; + 7: out = in[7]; + endcase +endmodule diff --git a/chips/yosys/tests/hana/test_simulation_nand.v b/chips/yosys/tests/hana/test_simulation_nand.v new file mode 100644 index 0000000000000000000000000000000000000000..5e6e0f1f5bf63dc1e121c9d281f7cb8d708aec39 --- /dev/null +++ b/chips/yosys/tests/hana/test_simulation_nand.v @@ -0,0 +1,25 @@ + +// test_simulation_nand_1_test.v +module f1_test(input [1:0] in, output out); +assign out = ~(in[0] & in[1]); +endmodule + +// test_simulation_nand_3_test.v +module f2_test(input [2:0] in, output out); +assign out = !(in[0] & in[1] & in[2]); +endmodule + +// test_simulation_nand_4_test.v +module f3_test(input [2:0] in, output out); +assign out = ~(in[0] && in[1] && in[2]); +endmodule + +// test_simulation_nand_5_test.v +module f4_test(input [3:0] in, output out); +assign out = !(in[0] & in[1] & in[2] & in[3]); +endmodule + +// test_simulation_nand_6_test.v +module f5_test(input [3:0] in, output out); +assign out = !(in[0] && in[1] && in[2] && in[3]); +endmodule diff --git a/chips/yosys/tests/hana/test_simulation_nor.v b/chips/yosys/tests/hana/test_simulation_nor.v new file mode 100644 index 0000000000000000000000000000000000000000..d7d2bc0ec3505f98dcd2392134fd372fe8f942fd --- /dev/null +++ b/chips/yosys/tests/hana/test_simulation_nor.v @@ -0,0 +1,20 @@ + +// test_simulation_nor_1_test.v +module f1_test(input [1:0] in, output out); +assign out = ~(in[0] | in[1]); +endmodule + +// test_simulation_nor_2_test.v +module f2_test(input [2:0] in, output out); +assign out = ~(in[0] | in[1] | in[2]); +endmodule + +// test_simulation_nor_3_test.v +module f3_test(input [3:0] in, output out); +assign out = ~(in[0] | in[1] | in[2] | in[3]); +endmodule + +// test_simulation_nor_4_test.v +module f4_test(input [3:0] in, output out); +nor mynor(out, in[0], in[1], in[2], in[3]); +endmodule diff --git a/chips/yosys/tests/hana/test_simulation_or.v b/chips/yosys/tests/hana/test_simulation_or.v new file mode 100644 index 0000000000000000000000000000000000000000..9217db80891bf8f50530288812b17bf527a0c5eb --- /dev/null +++ b/chips/yosys/tests/hana/test_simulation_or.v @@ -0,0 +1,30 @@ + +// test_simulation_or_1_test.v +module f1_test(input [1:0] in, output out); +assign out = in[0] | in[1]; +endmodule + +// test_simulation_or_2_test.v +module f2_test(input [1:0] in, output out); +assign out = in[0] || in[1]; +endmodule + +// test_simulation_or_3_test.v +module f3_test(input [2:0] in, output out); +assign out = in[0] | in[1] | in[2]; +endmodule + +// test_simulation_or_4_test.v +module f4_test(input [2:0] in, output out); +assign out = in[0] || in[1] || in[2]; +endmodule + +// test_simulation_or_5_test.v +module f5_test(input [3:0] in, output out); +assign out = in[0] | in[1] | in[2] | in[3]; +endmodule + +// test_simulation_or_6_test.v +module f6_test(input [3:0] in, output out); +assign out = in[0] || in[1] || in[2] || in[3]; +endmodule diff --git a/chips/yosys/tests/hana/test_simulation_seq.v b/chips/yosys/tests/hana/test_simulation_seq.v new file mode 100644 index 0000000000000000000000000000000000000000..d5069bb7624fa3da980ad216b8249ee719cc51cc --- /dev/null +++ b/chips/yosys/tests/hana/test_simulation_seq.v @@ -0,0 +1,12 @@ + +// test_simulation_seq_ff_1_test.v +module f1_test(input in, input clk, output reg out); +always @(posedge clk) + out <= in; +endmodule + +// test_simulation_seq_ff_2_test.v +module f2_test(input in, input clk, output reg out); +always @(negedge clk) + out <= in; +endmodule diff --git a/chips/yosys/tests/hana/test_simulation_shifter.v b/chips/yosys/tests/hana/test_simulation_shifter.v new file mode 100644 index 0000000000000000000000000000000000000000..8864fb0e78875be8c7c18cd3fb68a41d498396fc --- /dev/null +++ b/chips/yosys/tests/hana/test_simulation_shifter.v @@ -0,0 +1,60 @@ + +// test_simulation_shifter_left_16_test.v +module f1_test(input [15:0] IN, input [4:0] SHIFT, output [15:0] OUT); + +assign OUT = IN << SHIFT; +endmodule + +// test_simulation_shifter_left_32_test.v +module f2_test(input [31:0] IN, input [5:0] SHIFT, output [31:0] OUT); + +assign OUT = IN << SHIFT; +endmodule + +// test_simulation_shifter_left_4_test.v +module f3_test(input [3:0] IN, input [2:0] SHIFT, output [3:0] OUT); + +assign OUT = IN << SHIFT; +endmodule + +// test_simulation_shifter_left_64_test.v +module f4_test(input [63:0] IN, input [6:0] SHIFT, output [63:0] OUT); + +assign OUT = IN << SHIFT; +endmodule + +// test_simulation_shifter_left_8_test.v +module f5_test(input [7:0] IN, input [3:0] SHIFT, output [7:0] OUT); + +assign OUT = IN << SHIFT; +endmodule + +// test_simulation_shifter_right_16_test.v +module f6_test(input [15:0] IN, input [4:0] SHIFT, output [15:0] OUT); + +assign OUT = IN >> SHIFT; +endmodule + +// test_simulation_shifter_right_32_test.v +module f7_test(input [31:0] IN, input [5:0] SHIFT, output [31:0] OUT); + +assign OUT = IN >> SHIFT; +endmodule + +// test_simulation_shifter_right_4_test.v +module f8_test(input [3:0] IN, input [2:0] SHIFT, output [3:0] OUT); + +assign OUT = IN >> SHIFT; +endmodule + +// test_simulation_shifter_right_64_test.v +module f9_test(input [63:0] IN, input [6:0] SHIFT, output [63:0] OUT); + +assign OUT = IN >> SHIFT; +endmodule + +// test_simulation_shifter_right_8_test.v +module f10_test(input [7:0] IN, input [3:0] SHIFT, output [7:0] OUT); + +assign OUT = IN >> SHIFT; +endmodule diff --git a/chips/yosys/tests/hana/test_simulation_sop.v b/chips/yosys/tests/hana/test_simulation_sop.v new file mode 100644 index 0000000000000000000000000000000000000000..9373ea085cb4fbaa24b75267b6118e2db7ba54ff --- /dev/null +++ b/chips/yosys/tests/hana/test_simulation_sop.v @@ -0,0 +1,65 @@ + +// test_simulation_sop_basic_10_test.v +module f1_test(input [1:0] in, input select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + endcase +endmodule + +// test_simulation_sop_basic_11_test.v +module f2_test(input [3:0] in, input [1:0] select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + 2: out = in[2]; + 3: out = in[3]; + endcase +endmodule + +// test_simulation_sop_basic_12_test.v +module f3_test(input [7:0] in, input [2:0] select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + 2: out = in[2]; + 3: out = in[3]; + 4: out = in[4]; + 5: out = in[5]; + 6: out = in[6]; + 7: out = in[7]; + endcase +endmodule + +// test_simulation_sop_basic_18_test.v +module f4_test(input [7:0] in, output out); + +assign out = ~^in; + +endmodule + +// test_simulation_sop_basic_3_test.v +module f5_test(input in, output out); +assign out = ~in; +endmodule + +// test_simulation_sop_basic_7_test.v +module f6_test(input in, output out); +assign out = in; +endmodule + +// test_simulation_sop_basic_8_test.v +module f7_test(output out); +assign out = 1'b0; +endmodule + +// test_simulation_sop_basic_9_test.v +module f8_test(input in, output out); +assign out = ~in; +endmodule diff --git a/chips/yosys/tests/hana/test_simulation_techmap.v b/chips/yosys/tests/hana/test_simulation_techmap.v new file mode 100644 index 0000000000000000000000000000000000000000..65dd88d867abb3457b898ab0436599481306313f --- /dev/null +++ b/chips/yosys/tests/hana/test_simulation_techmap.v @@ -0,0 +1,172 @@ + +// test_simulation_techmap_buf_test.v +module f1_test(input in, output out); +assign out = in; +endmodule + +// test_simulation_techmap_inv_test.v +module f2_test(input in, output out); +assign out = ~in; +endmodule + +// test_simulation_techmap_mux_0_test.v +module f3_test(input [1:0] in, input select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + endcase +endmodule + +// test_simulation_techmap_mux_128_test.v +module f4_test(input [127:0] in, input [6:0] select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + 2: out = in[2]; + 3: out = in[3]; + 4: out = in[4]; + 5: out = in[5]; + 6: out = in[6]; + 7: out = in[7]; + 8: out = in[8]; + 9: out = in[9]; + 10: out = in[10]; + 11: out = in[11]; + 12: out = in[12]; + 13: out = in[13]; + 14: out = in[14]; + 15: out = in[15]; + 16: out = in[16]; + 17: out = in[17]; + 18: out = in[18]; + 19: out = in[19]; + 20: out = in[20]; + 21: out = in[21]; + 22: out = in[22]; + 23: out = in[23]; + 24: out = in[24]; + 25: out = in[25]; + 26: out = in[26]; + 27: out = in[27]; + 28: out = in[28]; + 29: out = in[29]; + 30: out = in[30]; + 31: out = in[31]; + 32: out = in[32]; + 33: out = in[33]; + 34: out = in[34]; + 35: out = in[35]; + 36: out = in[36]; + 37: out = in[37]; + 38: out = in[38]; + 39: out = in[39]; + 40: out = in[40]; + 41: out = in[41]; + 42: out = in[42]; + 43: out = in[43]; + 44: out = in[44]; + 45: out = in[45]; + 46: out = in[46]; + 47: out = in[47]; + 48: out = in[48]; + 49: out = in[49]; + 50: out = in[50]; + 51: out = in[51]; + 52: out = in[52]; + 53: out = in[53]; + 54: out = in[54]; + 55: out = in[55]; + 56: out = in[56]; + 57: out = in[57]; + 58: out = in[58]; + 59: out = in[59]; + 60: out = in[60]; + 61: out = in[61]; + 62: out = in[62]; + 63: out = in[63]; + 64: out = in[64]; + 65: out = in[65]; + 66: out = in[66]; + 67: out = in[67]; + 68: out = in[68]; + 69: out = in[69]; + 70: out = in[70]; + 71: out = in[71]; + 72: out = in[72]; + 73: out = in[73]; + 74: out = in[74]; + 75: out = in[75]; + 76: out = in[76]; + 77: out = in[77]; + 78: out = in[78]; + 79: out = in[79]; + 80: out = in[80]; + 81: out = in[81]; + 82: out = in[82]; + 83: out = in[83]; + 84: out = in[84]; + 85: out = in[85]; + 86: out = in[86]; + 87: out = in[87]; + 88: out = in[88]; + 89: out = in[89]; + 90: out = in[90]; + 91: out = in[91]; + 92: out = in[92]; + 93: out = in[93]; + 94: out = in[94]; + 95: out = in[95]; + 96: out = in[96]; + 97: out = in[97]; + 98: out = in[98]; + 99: out = in[99]; + 100: out = in[100]; + 101: out = in[101]; + 102: out = in[102]; + 103: out = in[103]; + 104: out = in[104]; + 105: out = in[105]; + 106: out = in[106]; + 107: out = in[107]; + 108: out = in[108]; + 109: out = in[109]; + 110: out = in[110]; + 111: out = in[111]; + 112: out = in[112]; + 113: out = in[113]; + 114: out = in[114]; + 115: out = in[115]; + 116: out = in[116]; + 117: out = in[117]; + 118: out = in[118]; + 119: out = in[119]; + 120: out = in[120]; + 121: out = in[121]; + 122: out = in[122]; + 123: out = in[123]; + 124: out = in[124]; + 125: out = in[125]; + 126: out = in[126]; + 127: out = in[127]; + endcase +endmodule + +// test_simulation_techmap_mux_8_test.v +module f5_test(input [7:0] in, input [2:0] select, output reg out); + +always @( in or select) + case (select) + 0: out = in[0]; + 1: out = in[1]; + 2: out = in[2]; + 3: out = in[3]; + 4: out = in[4]; + 5: out = in[5]; + 6: out = in[6]; + 7: out = in[7]; + endcase +endmodule diff --git a/chips/yosys/tests/hana/test_simulation_techmap_tech.v b/chips/yosys/tests/hana/test_simulation_techmap_tech.v new file mode 100644 index 0000000000000000000000000000000000000000..60aeca5c12a606c4db525f3240b6321d16e19d1d --- /dev/null +++ b/chips/yosys/tests/hana/test_simulation_techmap_tech.v @@ -0,0 +1,143 @@ + +// test_simulation_techmap_and_19_tech.v +module f1_TECH_AND18(input [17:0] in, output out); +assign out = ∈ +endmodule + +module f1_TECH_AND4(input [3:0] in, output out); +assign out = ∈ +endmodule + +// test_simulation_techmap_and_5_tech.v +module f2_TECH_AND5(input [4:0] in, output out); +assign out = ∈ +endmodule + +// test_simulation_techmap_nand_19_tech.v +module f3_TECH_NAND18(input [17:0] in, output out); +assign out = ~(&in); +endmodule + +module f3_TECH_NAND4(input [3:0] in, output out); +assign out = ~(&in); +endmodule + +module f3_TECH_NAND2(input [1:0] in, output out); +assign out = ~(&in); +endmodule + +// test_simulation_techmap_nand_2_tech.v +module f4_TECH_NAND18(input [17:0] in, output out); +assign out = ~(&in); +endmodule + +module f4_TECH_NAND4(input [3:0] in, output out); +assign out = ~(&in); +endmodule + +module f4_TECH_NAND2(input [1:0] in, output out); +assign out = ~(&in); +endmodule + +// test_simulation_techmap_nand_5_tech.v +module f5_TECH_NAND18(input [17:0] in, output out); +assign out = ~(&in); +endmodule + +module f5_TECH_NAND4(input [3:0] in, output out); +assign out = ~(&in); +endmodule + +module f5_TECH_NAND2(input [1:0] in, output out); +assign out = ~(&in); +endmodule + +// test_simulation_techmap_nor_19_tech.v +module f6_TECH_NOR18(input [17:0] in, output out); +assign out = ~(|in); +endmodule + +module f6_TECH_NOR4(input [3:0] in, output out); +assign out = ~(|in); +endmodule + +module f6_TECH_NOR2(input [1:0] in, output out); +assign out = ~(|in); +endmodule + +// test_simulation_techmap_nor_2_tech.v +module f7_TECH_NOR18(input [17:0] in, output out); +assign out = ~(|in); +endmodule + +module f7_TECH_NOR4(input [3:0] in, output out); +assign out = ~(|in); +endmodule + +module f7_TECH_NOR2(input [1:0] in, output out); +assign out = ~(|in); +endmodule + +// test_simulation_techmap_nor_5_tech.v +module f8_TECH_NOR18(input [17:0] in, output out); +assign out = ~(|in); +endmodule + +module f8_TECH_NOR4(input [3:0] in, output out); +assign out = ~(|in); +endmodule + +module f8_TECH_NOR2(input [1:0] in, output out); +assign out = ~(|in); +endmodule + +// test_simulation_techmap_or_19_tech.v +module f9_TECH_OR18(input [17:0] in, output out); +assign out = |in; +endmodule + +module f9_TECH_OR4(input [3:0] in, output out); +assign out = |in; +endmodule + +// test_simulation_techmap_or_5_tech.v +module f10_TECH_OR5(input [4:0] in, output out); +assign out = |in; +endmodule + +// test_simulation_techmap_xnor_2_tech.v +module f11_TECH_XOR5(input [4:0] in, output out); +assign out = in[0] ^ in[1] ^ in[2] ^ in[3] ^ in[4]; +endmodule +module f11_TECH_XOR2(input [1:0] in, output out); +assign out = in[0] ^ in[1]; +endmodule + +// test_simulation_techmap_xnor_5_tech.v +module f12_TECH_XOR5(input [4:0] in, output out); +assign out = in[0] ^ in[1] ^ in[2] ^ in[3] ^ in[4]; +endmodule +module f12_TECH_XOR2(input [1:0] in, output out); +assign out = in[0] ^ in[1]; +endmodule + +// test_simulation_techmap_xor_19_tech.v +module f13_TECH_XOR2(input [1:0] in, output out); +assign out = in[0] ^ in[1]; +endmodule + +// test_simulation_techmap_xor_2_tech.v +module f14_TECH_XOR5(input [4:0] in, output out); +assign out = in[0] ^ in[1] ^ in[2] ^ in[3] ^ in[4]; +endmodule +module f14_TECH_XOR2(input [1:0] in, output out); +assign out = in[0] ^ in[1]; +endmodule + +// test_simulation_techmap_xor_5_tech.v +module f15_TECH_XOR5(input [4:0] in, output out); +assign out = in[0] ^ in[1] ^ in[2] ^ in[3] ^ in[4]; +endmodule +module f15_TECH_XOR2(input [1:0] in, output out); +assign out = in[0] ^ in[1]; +endmodule diff --git a/chips/yosys/tests/hana/test_simulation_vlib.v b/chips/yosys/tests/hana/test_simulation_vlib.v new file mode 100644 index 0000000000000000000000000000000000000000..49f612b805a58c896b8afe54df907f3ab042b262 --- /dev/null +++ b/chips/yosys/tests/hana/test_simulation_vlib.v @@ -0,0 +1,64 @@ +// test_simulation_mod_1_xx.v +module f1_test(in1, in2, out); +input in1; +input in2; +output out; + +wire synth_net_0; +wire synth_net_1; +BUF synth_BUF_0(.in(synth_net_1), .out(out + )); +DIV1 synth_DIV(.in1(in1), .in2(in2), .rem(synth_net_0), .out(synth_net_1 + )); +endmodule + +// test_simulation_always_31_tt.v +module f2_test(clk, cond, data); +input cond; +input clk; +output data; + +wire synth_net; +wire synth_net_0; +wire synth_net_1; +wire synth_net_2; + +wire synth_net_3; +wire synth_net_4; +wire synth_net_5; +wire synth_net_6; + +wire synth_net_7; +wire synth_net_8; +wire synth_net_9; +wire synth_net_10; + +wire synth_net_11; +wire tmp; +AND2 synth_AND(.in({synth_net_0, synth_net_1}), . + out(synth_net_2)); +AND2 synth_AND_0(.in({synth_net_3, synth_net_4}), .out( + synth_net_5)); +AND2 synth_AND_1(.in({synth_net_6, synth_net_7}), .out( + synth_net_8)); +AND2 synth_AND_2(.in({synth_net_9, synth_net_10}), .out( + synth_net_11)); +BUF synth_BUF(.in(synth_net), .out(synth_net_0)); +BUF + synth_BUF_0(.in(data), .out(synth_net_3)); +BUF synth_BUF_1(.in(synth_net_8) + , .out(tmp)); +BUF synth_BUF_2(.in(tmp), .out(synth_net_9)); +MUX2 synth_MUX(. + in({synth_net_2, synth_net_5}), .select(cond), .out(synth_net_6)); +MUX2 + synth_MUX_0(.in({synth_net_1, synth_net_4}), .select(cond), .out(synth_net_7 + )); +FF synth_FF(.d(synth_net_11), .clk(clk), .q(data)); +VCC synth_VCC(.out( + synth_net)); +VCC synth_VCC_0(.out(synth_net_1)); +VCC synth_VCC_1(.out( + synth_net_4)); +VCC synth_VCC_2(.out(synth_net_10)); +endmodule diff --git a/chips/yosys/tests/hana/test_simulation_xnor.v b/chips/yosys/tests/hana/test_simulation_xnor.v new file mode 100644 index 0000000000000000000000000000000000000000..7286d13416af8d5caa8a81d27c416e33353cc9a1 --- /dev/null +++ b/chips/yosys/tests/hana/test_simulation_xnor.v @@ -0,0 +1,20 @@ + +// test_simulation_xnor_1_test.v +module f1_test(input [1:0] in, output out); +assign out = ~(in[0] ^ in[1]); +endmodule + +// test_simulation_xnor_2_test.v +module f2_test(input [2:0] in, output out); +assign out = ~(in[0] ^ in[1] ^ in[2]); +endmodule + +// test_simulation_xnor_3_test.v +module f3_test(input [3:0] in, output out); +assign out = ~(in[0] ^ in[1] ^ in[2] ^ in[3]); +endmodule + +// test_simulation_xnor_4_test.v +module f4_test(input [3:0] in, output out); +xnor myxnor(out, in[0], in[1], in[2], in[3]); +endmodule diff --git a/chips/yosys/tests/hana/test_simulation_xor.v b/chips/yosys/tests/hana/test_simulation_xor.v new file mode 100644 index 0000000000000000000000000000000000000000..e181dd83abd96057d021ad0e32db0d1bbf585b39 --- /dev/null +++ b/chips/yosys/tests/hana/test_simulation_xor.v @@ -0,0 +1,20 @@ + +// test_simulation_xor_1_test.v +module f1_test(input [1:0] in, output out); +assign out = (in[0] ^ in[1]); +endmodule + +// test_simulation_xor_2_test.v +module f2_test(input [2:0] in, output out); +assign out = (in[0] ^ in[1] ^ in[2]); +endmodule + +// test_simulation_xor_3_test.v +module f3_test(input [3:0] in, output out); +assign out = (in[0] ^ in[1] ^ in[2] ^ in[3]); +endmodule + +// test_simulation_xor_4_test.v +module f4_test(input [3:0] in, output out); +xor myxor(out, in[0], in[1], in[2], in[3]); +endmodule diff --git a/chips/yosys/tests/liberty/.gitignore b/chips/yosys/tests/liberty/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b312f8c506b95d87b92448eeb292046e9aba742a --- /dev/null +++ b/chips/yosys/tests/liberty/.gitignore @@ -0,0 +1,2 @@ +/*.filtered +*.verilogsim diff --git a/chips/yosys/tests/liberty/XNOR2X1.lib b/chips/yosys/tests/liberty/XNOR2X1.lib new file mode 100644 index 0000000000000000000000000000000000000000..67ae8b70638c21638bb1f6a1cf9cebde908d1b3a --- /dev/null +++ b/chips/yosys/tests/liberty/XNOR2X1.lib @@ -0,0 +1,337 @@ +library (ls05_stdcells) { + capacitive_load_unit (1.0, pf); + current_unit: "1uA"; + default_operating_conditions: typical; + delay_model: table_lookup; + in_place_swap_mode: match_footprint; + input_threshold_pct_fall: 50.0; + input_threshold_pct_rise: 50.0; + leakage_power_unit: "1nW"; + nom_process: 1.0; + nom_temperature: 25.0; + nom_voltage: 5.0; + output_threshold_pct_fall: 50.0; + output_threshold_pct_rise: 50.0; + pulling_resistance_unit: "1kohm"; + slew_lower_threshold_pct_fall: 20.0; + slew_lower_threshold_pct_rise: 20.0; + slew_upper_threshold_pct_fall: 80.0; + slew_upper_threshold_pct_rise: 80.0; + time_unit: "1ns"; + voltage_unit: "1V"; + operating_conditions (typical) { + process: 1.0; + temperature: 25.0; + voltage: 5.0; + } + lu_table_template (delay_template_5x1) { + index_1 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0" + ); + variable_1: input_net_transition; + } + lu_table_template (delay_template_5x5) { + index_1 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0" + ); + index_2 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0" + ); + variable_1: total_output_net_capacitance; + variable_2: input_net_transition; + } + lu_table_template (delay_template_5x6) { + index_1 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0" + ); + index_2 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0, 1005.0" + ); + variable_1: total_output_net_capacitance; + variable_2: input_net_transition; + } + lu_table_template (delay_template_6x1) { + index_1 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0, 1005.0" + ); + variable_1: input_net_transition; + } + lu_table_template (delay_template_6x6) { + index_1 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0, 1005.0" + ); + index_2 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0, 1005.0" + ); + variable_1: total_output_net_capacitance; + variable_2: input_net_transition; + } + power_lut_template (energy_template_5x5) { + index_1 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0" + ); + index_2 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0" + ); + variable_1: total_output_net_capacitance; + variable_2: input_transition_time; + } + power_lut_template (energy_template_5x6) { + index_1 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0" + ); + index_2 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0, 1005.0" + ); + variable_1: total_output_net_capacitance; + variable_2: input_transition_time; + } + power_lut_template (energy_template_6x6) { + index_1 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0, 1005.0" + ); + index_2 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0, 1005.0" + ); + variable_1: total_output_net_capacitance; + variable_2: input_transition_time; + } + lu_table_template (hold_template_3x5) { + index_1 ( + "1000.0, 1001.0, 1002.0" + ); + index_2 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0" + ); + variable_1: related_pin_transition; + variable_2: constrained_pin_transition; + } + lu_table_template (hold_template_3x6) { + index_1 ( + "1000.0, 1001.0, 1002.0" + ); + index_2 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0, 1005.0" + ); + variable_1: related_pin_transition; + variable_2: constrained_pin_transition; + } + power_lut_template (passive_energy_template_5x1) { + index_1 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0" + ); + variable_1: input_transition_time; + } + power_lut_template (passive_energy_template_6x1) { + index_1 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0, 1005.0" + ); + variable_1: input_transition_time; + } + lu_table_template (recovery_template_3x6) { + index_1 ( + "1000.0, 1001.0, 1002.0" + ); + index_2 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0, 1005.0" + ); + variable_1: related_pin_transition; + variable_2: constrained_pin_transition; + } + lu_table_template (recovery_template_6x6) { + index_1 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0, 1005.0" + ); + index_2 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0, 1005.0" + ); + variable_1: related_pin_transition; + variable_2: constrained_pin_transition; + } + lu_table_template (removal_template_3x6) { + index_1 ( + "1000.0, 1001.0, 1002.0" + ); + index_2 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0, 1005.0" + ); + variable_1: related_pin_transition; + variable_2: constrained_pin_transition; + } + lu_table_template (setup_template_3x5) { + index_1 ( + "1000.0, 1001.0, 1002.0" + ); + index_2 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0" + ); + variable_1: related_pin_transition; + variable_2: constrained_pin_transition; + } + lu_table_template (setup_template_3x6) { + index_1 ( + "1000.0, 1001.0, 1002.0" + ); + index_2 ( + "1000.0, 1001.0, 1002.0, 1003.0, 1004.0, 1005.0" + ); + variable_1: related_pin_transition; + variable_2: constrained_pin_transition; + } + cell (XNOR2X1) { + area: 206080.0; + cell_leakage_power: 0.1173; + pin (B) { + capacitance: 0.007869572376285055; + direction: input; + fall_capacitance: 0.00787170816777918; + rise_capacitance: 0.007867436584790931; + } + pin (A) { + capacitance: 0.006181892203766934; + direction: input; + fall_capacitance: 0.006286246429833927; + rise_capacitance: 0.006077537977699941; + } + pin (Y) { + direction: output; + function: "!(B&!A|!B&A)"; + timing () { + related_pin: "B"; + timing_sense: non_unate; + cell_rise (delay_template_6x6) { + index_1 ( + "0.100000, 0.500000, 1.200000, 3.000000, 4.000000, 5.000000" + ); + index_2 ( + "0.060000, 0.240000, 0.480000, 0.900000, 1.200000, 1.800000" + ); + values ( + "0.216615, 0.255249, 0.335937, 0.462500, 0.520313, 0.565625", \ + "0.777736, 0.782028, 0.837500, 1.065625, 1.179688, 1.273438", \ + "1.527774, 1.518945, 1.546875, 1.720781, 1.847266, 1.981250", \ + "2.840291, 2.822515, 2.825000, 2.928125, 3.018750, 3.126562", \ + "3.780926, 3.758589, 3.751563, 3.818750, 3.890625, 3.982812", \ + "5.659064, 5.632141, 5.609375, 5.634375, 5.681250, 5.743750" + ); + } + cell_fall (delay_template_6x6) { + index_1 ( + "0.100000, 0.500000, 1.200000, 3.000000, 4.000000, 5.000000" + ); + index_2 ( + "0.060000, 0.240000, 0.480000, 0.900000, 1.200000, 1.800000" + ); + values ( + "0.141297, 0.176563, 0.201562, 0.210938, 0.210938, 0.204688", \ + "0.483116, 0.506250, 0.566094, 0.681250, 0.709375, 0.725000", \ + "0.935771, 0.954688, 1.003125, 1.171875, 1.251563, 1.303125", \ + "1.729021, 1.750000, 1.787500, 1.925000, 2.017188, 2.118750", \ + "2.303892, 2.307813, 2.350000, 2.476562, 2.557813, 2.650000", \ + "3.431826, 3.451562, 3.482812, 3.590625, 3.660938, 3.739063" + ); + } + rise_transition (delay_template_6x6) { + index_1 ( + "0.100000, 0.500000, 1.200000, 3.000000, 4.000000, 5.000000" + ); + index_2 ( + "0.060000, 0.240000, 0.480000, 0.900000, 1.200000, 1.800000" + ); + values ( + "0.301313, 0.323519, 0.432031, 0.843750, 1.059375, 1.275000", \ + "1.118750, 1.120547, 1.139063, 1.348906, 1.528125, 1.746875", \ + "2.212500, 2.209375, 2.210469, 2.298437, 2.406250, 2.534375", \ + "4.121875, 4.121875, 4.121875, 4.126562, 4.164063, 4.234375", \ + "5.487500, 5.487500, 5.487500, 5.489062, 5.495312, 5.528125", \ + "8.218750, 8.218750, 8.218750, 8.218750, 8.218750, 8.219531" + ); + } + fall_transition (delay_template_6x6) { + index_1 ( + "0.100000, 0.500000, 1.200000, 3.000000, 4.000000, 5.000000" + ); + index_2 ( + "0.060000, 0.240000, 0.480000, 0.900000, 1.200000, 1.800000" + ); + values ( + "0.177720, 0.238125, 0.437500, 0.945313, 1.215625, 1.478125", \ + "0.646864, 0.647852, 0.729688, 1.185938, 1.476563, 1.762500", \ + "1.278125, 1.276953, 1.290625, 1.568750, 1.804687, 2.075000", \ + "2.381250, 2.381250, 2.381094, 2.478125, 2.623437, 2.807812", \ + "3.170313, 3.168750, 3.171875, 3.201562, 3.298438, 3.440625", \ + "4.746875, 4.746875, 4.746875, 4.748281, 4.768750, 4.834375" + ); + } + } + timing () { + related_pin: "A"; + timing_sense: non_unate; + cell_rise (delay_template_6x6) { + index_1 ( + "0.100000, 0.500000, 1.200000, 3.000000, 4.000000, 5.000000" + ); + index_2 ( + "0.060000, 0.240000, 0.480000, 0.900000, 1.200000, 1.800000" + ); + values ( + "0.198661, 0.238874, 0.325000, 0.464063, 0.525000, 0.578125", \ + "0.751696, 0.739750, 0.796875, 1.043750, 1.162500, 1.262500", \ + "1.500349, 1.465688, 1.475000, 1.656836, 1.798594, 1.940625", \ + "2.813049, 2.758763, 2.725000, 2.800000, 2.895312, 3.010937", \ + "3.752184, 3.693634, 3.639063, 3.659375, 3.725000, 3.818750", \ + "5.630379, 5.564431, 5.484375, 5.431250, 5.453125, 5.504687" + ); + } + cell_fall (delay_template_6x6) { + index_1 ( + "0.100000, 0.500000, 1.200000, 3.000000, 4.000000, 5.000000" + ); + index_2 ( + "0.060000, 0.240000, 0.480000, 0.900000, 1.200000, 1.800000" + ); + values ( + "0.119260, 0.143750, 0.154687, 0.148438, 0.143750, 0.131250", \ + "0.455345, 0.435938, 0.485937, 0.550000, 0.560938, 0.564063", \ + "0.908764, 0.868750, 0.867188, 1.003125, 1.046875, 1.070313", \ + "1.699465, 1.653125, 1.606250, 1.662656, 1.746875, 1.831250", \ + "2.272986, 2.210938, 2.153125, 2.148437, 2.210469, 2.295117", \ + "3.404215, 3.351562, 3.270312, 3.175000, 3.195313, 3.240625" + ); + } + rise_transition (delay_template_6x6) { + index_1 ( + "0.100000, 0.500000, 1.200000, 3.000000, 4.000000, 5.000000" + ); + index_2 ( + "0.060000, 0.240000, 0.480000, 0.900000, 1.200000, 1.800000" + ); + values ( + "0.301159, 0.338560, 0.480469, 0.989063, 1.300000, 1.620313", \ + "1.120312, 1.118594, 1.159375, 1.468594, 1.687500, 1.934375", \ + "2.210938, 2.212500, 2.212695, 2.381250, 2.545312, 2.726562", \ + "4.121875, 4.121875, 4.121875, 4.146875, 4.232813, 4.357812", \ + "5.487500, 5.487500, 5.487500, 5.487500, 5.520312, 5.600000", \ + "8.218750, 8.218750, 8.218750, 8.218750, 8.218750, 8.228125" + ); + } + fall_transition (delay_template_6x6) { + index_1 ( + "0.100000, 0.500000, 1.200000, 3.000000, 4.000000, 5.000000" + ); + index_2 ( + "0.060000, 0.240000, 0.480000, 0.900000, 1.200000, 1.800000" + ); + values ( + "0.176166, 0.285586, 0.559375, 1.195313, 1.535938, 1.873438", \ + "0.646209, 0.662500, 0.823438, 1.507813, 1.900000, 2.271875", \ + "1.278125, 1.276250, 1.337500, 1.825000, 2.195469, 2.595313", \ + "2.381250, 2.381250, 2.384961, 2.650000, 2.907812, 3.201562", \ + "3.168750, 3.168750, 3.172031, 3.325000, 3.531250, 3.779687", \ + "4.748437, 4.746875, 4.745312, 4.779687, 4.896875, 5.076562" + ); + } + } + } + } +} diff --git a/chips/yosys/tests/liberty/XNOR2X1.lib.filtered.ok b/chips/yosys/tests/liberty/XNOR2X1.lib.filtered.ok new file mode 100644 index 0000000000000000000000000000000000000000..5ca81b2d74f8f4321ad69b15d0ce88a22a73544e --- /dev/null +++ b/chips/yosys/tests/liberty/XNOR2X1.lib.filtered.ok @@ -0,0 +1,15 @@ +library(ls05_stdcells) { + cell(XNOR2X1) { + area : 206080.0 ; + pin(B) { + direction : input ; + } + pin(A) { + direction : input ; + } + pin(Y) { + direction : output ; + function : "!(B&!A|!B&A)" ; + } + } +} diff --git a/chips/yosys/tests/liberty/XNOR2X1.lib.verilogsim.ok b/chips/yosys/tests/liberty/XNOR2X1.lib.verilogsim.ok new file mode 100644 index 0000000000000000000000000000000000000000..6c9ec26dd222d182406276c2621760aad09a3a64 --- /dev/null +++ b/chips/yosys/tests/liberty/XNOR2X1.lib.verilogsim.ok @@ -0,0 +1,6 @@ +module XNOR2X1 (B, A, Y); + input B; + input A; + output Y; + assign Y = (~((B&(~A))|((~B)&A))); // "!(B&!A|!B&A)" +endmodule diff --git a/chips/yosys/tests/liberty/busdef.lib b/chips/yosys/tests/liberty/busdef.lib new file mode 100644 index 0000000000000000000000000000000000000000..10c45cd996a476b3e1e3b8f0db360b559ba2cb45 --- /dev/null +++ b/chips/yosys/tests/liberty/busdef.lib @@ -0,0 +1,81 @@ +/********************************************/ +/* */ +/* Supergate cell library for Bench marking */ +/* */ +/* Symbiotic EDA GmbH / Moseley Instruments */ +/* Niels A. Moseley */ +/* */ +/* Process: none */ +/* */ +/* Date : 02-11-2018 */ +/* Version: 1.0 */ +/* */ +/********************************************/ + +library(supergate) { + technology (cmos); + revision : 1.0; + + time_unit : "1ps"; + pulling_resistance_unit : "1kohm"; + voltage_unit : "1V"; + current_unit : "1uA"; + + capacitive_load_unit(1,ff); + + default_inout_pin_cap : 7.0; + default_input_pin_cap : 7.0; + default_output_pin_cap : 0.0; + default_fanout_load : 1.0; + + default_wire_load_capacitance : 0.1; + default_wire_load_resistance : 1.0e-3; + default_wire_load_area : 0.0; + + nom_process : 1.0; + nom_temperature : 25.0; + nom_voltage : 1.2; + + delay_model : generic_cmos; + + type( IO_bus_3_to_0 ) { + base_type : array ; + data_type : bit ; + bit_width : 4; + bit_from : 3 ; + bit_to : 0 ; + downto : true ; + } + + cell (SRAM) { + area : 1 ; + memory() { + type : ram; + address_width : 4; + word_width : 4; + } + pin(CE1) { + direction : input; + capacitance : 0.021; + max_transition : 1.024; + switch_pin : true; + } + bus(I1) { + bus_type : IO_bus_3_to_0 ; + direction : input; + pin (I1[3:0]) { + timing() { + related_pin : "CE1" ; + timing_type : setup_rising ; + rise_constraint (scalar) { + values("0.0507786"); + } + fall_constraint (scalar) { + values("0.0507786"); + } + } + } + } + } + +} /* end */ diff --git a/chips/yosys/tests/liberty/busdef.lib.filtered.ok b/chips/yosys/tests/liberty/busdef.lib.filtered.ok new file mode 100644 index 0000000000000000000000000000000000000000..55f5b08a3bf4564c89c7286771b8369597690fa4 --- /dev/null +++ b/chips/yosys/tests/liberty/busdef.lib.filtered.ok @@ -0,0 +1,8 @@ +library(supergate) { + cell(SRAM) { + area : 1 ; + pin(CE1) { + direction : input ; + } + } +} diff --git a/chips/yosys/tests/liberty/busdef.lib.verilogsim.ok b/chips/yosys/tests/liberty/busdef.lib.verilogsim.ok new file mode 100644 index 0000000000000000000000000000000000000000..5d7f47f371237ec1533daa76a3b069878e00c458 --- /dev/null +++ b/chips/yosys/tests/liberty/busdef.lib.verilogsim.ok @@ -0,0 +1,3 @@ +module SRAM (CE1); + input CE1; +endmodule diff --git a/chips/yosys/tests/liberty/dff.lib b/chips/yosys/tests/liberty/dff.lib new file mode 100644 index 0000000000000000000000000000000000000000..0f725fd9d0707816738bd848bd85b43e34592f6f --- /dev/null +++ b/chips/yosys/tests/liberty/dff.lib @@ -0,0 +1,22 @@ +// Test library for different DFF function expressions + +library(dff) { + cell (dff) { + area : 1; + ff("IQ", "IQN") { + next_state : "(D)"; + clocked_on : (CLK); + } + pin(D) { + direction : input; + } + pin(CLK) { + direction : input; + } + pin(Q) { + direction: output; + function : IQ; + } + } + +} /* end */ diff --git a/chips/yosys/tests/liberty/dff.lib.filtered.ok b/chips/yosys/tests/liberty/dff.lib.filtered.ok new file mode 100644 index 0000000000000000000000000000000000000000..2c2804ca11fba790628d5a9326f7089c71c45090 --- /dev/null +++ b/chips/yosys/tests/liberty/dff.lib.filtered.ok @@ -0,0 +1,19 @@ +library(dff) { + cell(dff) { + area : 1 ; + ff("IQ", "IQN") { + next_state : "(D)" ; + clocked_on : ( CLK ) ; + } + pin(D) { + direction : input ; + } + pin(CLK) { + direction : input ; + } + pin(Q) { + direction : output ; + function : IQ ; + } + } +} diff --git a/chips/yosys/tests/liberty/dff.lib.verilogsim.ok b/chips/yosys/tests/liberty/dff.lib.verilogsim.ok new file mode 100644 index 0000000000000000000000000000000000000000..5f991541f8d4d706dbe01c4c315532ab00ff4e07 --- /dev/null +++ b/chips/yosys/tests/liberty/dff.lib.verilogsim.ok @@ -0,0 +1,13 @@ +module dff (D, CLK, Q); + reg IQ, IQN; + input D; + input CLK; + output Q; + assign Q = IQ; // IQ + always @(posedge CLK) begin + IQ <= D; + end + always @(posedge CLK) begin + IQN <= ~(D); + end +endmodule diff --git a/chips/yosys/tests/liberty/dff.log.ok b/chips/yosys/tests/liberty/dff.log.ok new file mode 100644 index 0000000000000000000000000000000000000000..509d3464c1bb4c76ef1e8916c1077de7c8692336 --- /dev/null +++ b/chips/yosys/tests/liberty/dff.log.ok @@ -0,0 +1,47 @@ + +-- Running command `dfflibmap -info -liberty dff.lib' -- + +1. Executing DFFLIBMAP pass (mapping DFF/DLATCH cells to sequential cells from liberty file). + cell dff (noninv, pins=3, area=1.00) is a direct match for cell type $_DFF_P_. + final dff/dlatch cell mappings: + unmapped dff/dlatch cell: $_DFF_N_ + \dff _DFF_P_ (.CLK( C), .D( D), .Q( Q)); + unmapped dff/dlatch cell: $_DFF_NN0_ + unmapped dff/dlatch cell: $_DFF_NN1_ + unmapped dff/dlatch cell: $_DFF_NP0_ + unmapped dff/dlatch cell: $_DFF_NP1_ + unmapped dff/dlatch cell: $_DFF_PN0_ + unmapped dff/dlatch cell: $_DFF_PN1_ + unmapped dff/dlatch cell: $_DFF_PP0_ + unmapped dff/dlatch cell: $_DFF_PP1_ + unmapped dff/dlatch cell: $_DFFE_NN_ + unmapped dff/dlatch cell: $_DFFE_NP_ + unmapped dff/dlatch cell: $_DFFE_PN_ + unmapped dff/dlatch cell: $_DFFE_PP_ + unmapped dff/dlatch cell: $_DFFSR_NNN_ + unmapped dff/dlatch cell: $_DFFSR_NNP_ + unmapped dff/dlatch cell: $_DFFSR_NPN_ + unmapped dff/dlatch cell: $_DFFSR_NPP_ + unmapped dff/dlatch cell: $_DFFSR_PNN_ + unmapped dff/dlatch cell: $_DFFSR_PNP_ + unmapped dff/dlatch cell: $_DFFSR_PPN_ + unmapped dff/dlatch cell: $_DFFSR_PPP_ + unmapped dff/dlatch cell: $_DLATCH_N_ + unmapped dff/dlatch cell: $_DLATCH_P_ + unmapped dff/dlatch cell: $_DLATCH_NN0_ + unmapped dff/dlatch cell: $_DLATCH_NN1_ + unmapped dff/dlatch cell: $_DLATCH_NP0_ + unmapped dff/dlatch cell: $_DLATCH_NP1_ + unmapped dff/dlatch cell: $_DLATCH_PN0_ + unmapped dff/dlatch cell: $_DLATCH_PN1_ + unmapped dff/dlatch cell: $_DLATCH_PP0_ + unmapped dff/dlatch cell: $_DLATCH_PP1_ + unmapped dff/dlatch cell: $_DLATCHSR_NNN_ + unmapped dff/dlatch cell: $_DLATCHSR_NNP_ + unmapped dff/dlatch cell: $_DLATCHSR_NPN_ + unmapped dff/dlatch cell: $_DLATCHSR_NPP_ + unmapped dff/dlatch cell: $_DLATCHSR_PNN_ + unmapped dff/dlatch cell: $_DLATCHSR_PNP_ + unmapped dff/dlatch cell: $_DLATCHSR_PPN_ + unmapped dff/dlatch cell: $_DLATCHSR_PPP_ +dfflegalize command line: dfflegalize -cell $_DFF_P_ 01 t:$_DFF* t:$_SDFF* t:$_DLATCH* diff --git a/chips/yosys/tests/liberty/foundry_data/.gitignore b/chips/yosys/tests/liberty/foundry_data/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3b97f2a3e74b97f758c3999a3788145e7e1a82ab --- /dev/null +++ b/chips/yosys/tests/liberty/foundry_data/.gitignore @@ -0,0 +1,2 @@ +*.lib +*.lib.filtered diff --git a/chips/yosys/tests/liberty/foundry_data/RM_IHPSG13_1P_64x64_c2_bm_bist_typ_1p20V_25C.lib.filtered.gz b/chips/yosys/tests/liberty/foundry_data/RM_IHPSG13_1P_64x64_c2_bm_bist_typ_1p20V_25C.lib.filtered.gz new file mode 100644 index 0000000000000000000000000000000000000000..a524e360866f24659c9fc30ed55775ff9a56eba1 --- /dev/null +++ b/chips/yosys/tests/liberty/foundry_data/RM_IHPSG13_1P_64x64_c2_bm_bist_typ_1p20V_25C.lib.filtered.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4833f00f39eb452143b984115c9ffa042a5a8e28a42a3980794e3993839ad0e2 +size 5519 diff --git a/chips/yosys/tests/liberty/foundry_data/rules.txt b/chips/yosys/tests/liberty/foundry_data/rules.txt new file mode 100644 index 0000000000000000000000000000000000000000..1e739f552b9289cad749136dac78300edd060050 --- /dev/null +++ b/chips/yosys/tests/liberty/foundry_data/rules.txt @@ -0,0 +1,16 @@ +-wire_load +-wire_load_selection +-default_wire_load +-default_wire_load_area +-default_wire_load_capacitance +-default_wire_load_mode +-default_wire_load_resistance +-default_cell_leakage_power +-default_wire_load_selection +-default_leakage_power_density +-lu_table_template +-power_lut_template +-leakage_power +-cell_leakage_power +-leakage_power +-internal_power diff --git a/chips/yosys/tests/liberty/foundry_data/sg13g2_stdcell_typ_1p20V_25C.lib.filtered.gz b/chips/yosys/tests/liberty/foundry_data/sg13g2_stdcell_typ_1p20V_25C.lib.filtered.gz new file mode 100644 index 0000000000000000000000000000000000000000..4caca64213b748b3affd05010452c56bf996c9c1 --- /dev/null +++ b/chips/yosys/tests/liberty/foundry_data/sg13g2_stdcell_typ_1p20V_25C.lib.filtered.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:261364f5b9ce7d42c4482f73def2eb263d0cbd7f1a3c0345a566bed6fcd2aefd +size 170073 diff --git a/chips/yosys/tests/liberty/generate_mk.py b/chips/yosys/tests/liberty/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..45a26caa914f9e10ecf2153512b538bd58c024e5 --- /dev/null +++ b/chips/yosys/tests/liberty/generate_mk.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 + +import glob +import os +import sys +sys.path.append("..") + +import gen_tests_makefile + +def lib_tests(): + for lib in sorted(glob.glob("*.lib")): + base = os.path.splitext(lib)[0] + + gen_tests_makefile.generate_cmd_test(lib, [ + f'$(YOSYS) -p "read_verilog small.v; synth -top small; dfflibmap -info -liberty {lib}" -ql {base}.log', + + f'$(YOSYS_FILTERLIB) - {lib} > {lib}.filtered', + f'$(YOSYS_FILTERLIB) -verilogsim {lib} > {lib}.verilogsim', + + f'diff {lib}.filtered {lib}.filtered.ok', + f'diff {lib}.verilogsim {lib}.verilogsim.ok', + + f'if [ -e {base}.log.ok ]; then ' + f'$(YOSYS) -p "dfflibmap -info -liberty {lib}" -TqqQl {base}.log; ' + f'diff {base}.log {base}.log.ok; ' + f'fi', + ]) + + +def ys_tests(): + for ys in sorted(glob.glob("*.ys")): + gen_tests_makefile.generate_ys_test(ys) + +def main(): + def callback(): + lib_tests() + ys_tests() + + gen_tests_makefile.generate_custom(callback) + + +if __name__ == "__main__": + main() diff --git a/chips/yosys/tests/liberty/idranges.lib b/chips/yosys/tests/liberty/idranges.lib new file mode 100644 index 0000000000000000000000000000000000000000..89016140368cc283f488981c37ce7656e9aeceb8 --- /dev/null +++ b/chips/yosys/tests/liberty/idranges.lib @@ -0,0 +1,5 @@ +library("foobar") { + pin("foo") { + bar : baz[0] ; + } +} diff --git a/chips/yosys/tests/liberty/idranges.lib.filtered.ok b/chips/yosys/tests/liberty/idranges.lib.filtered.ok new file mode 100644 index 0000000000000000000000000000000000000000..8a780fd6736e29d8950e506daea6caf437023428 --- /dev/null +++ b/chips/yosys/tests/liberty/idranges.lib.filtered.ok @@ -0,0 +1,2 @@ +library("foobar") { +} diff --git a/chips/yosys/tests/liberty/idranges.lib.verilogsim.ok b/chips/yosys/tests/liberty/idranges.lib.verilogsim.ok new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/chips/yosys/tests/liberty/issue3498_bad.lib b/chips/yosys/tests/liberty/issue3498_bad.lib new file mode 100644 index 0000000000000000000000000000000000000000..9f2a90295f442fbb19ec3bec1387665d2e75fff5 --- /dev/null +++ b/chips/yosys/tests/liberty/issue3498_bad.lib @@ -0,0 +1,8 @@ +library(fake) { + cell(bugbad) { + bundle(X) { + members(x1, x2); + power_down_function : !a+b ; + } + } +} diff --git a/chips/yosys/tests/liberty/issue3498_bad.lib.filtered.ok b/chips/yosys/tests/liberty/issue3498_bad.lib.filtered.ok new file mode 100644 index 0000000000000000000000000000000000000000..e121193df71faffe61bf72e3b7e6581836931c1c --- /dev/null +++ b/chips/yosys/tests/liberty/issue3498_bad.lib.filtered.ok @@ -0,0 +1,4 @@ +library(fake) { + cell(bugbad) { + } +} diff --git a/chips/yosys/tests/liberty/issue3498_bad.lib.verilogsim.ok b/chips/yosys/tests/liberty/issue3498_bad.lib.verilogsim.ok new file mode 100644 index 0000000000000000000000000000000000000000..2ce41ea6cd26eff1cf35b94bf305d5c2a9ef7585 --- /dev/null +++ b/chips/yosys/tests/liberty/issue3498_bad.lib.verilogsim.ok @@ -0,0 +1,2 @@ +module bugbad (); +endmodule diff --git a/chips/yosys/tests/liberty/libcache.ys b/chips/yosys/tests/liberty/libcache.ys new file mode 100644 index 0000000000000000000000000000000000000000..5914a50e45b212d1f3faba6efabf3989efa5430b --- /dev/null +++ b/chips/yosys/tests/liberty/libcache.ys @@ -0,0 +1,72 @@ +libcache -verbose +libcache -enable bus*f.lib + +logger -expect log "Caching is disabled by default." 1 +logger -expect log "Caching is enabled for `busdef.lib'." 1 +libcache -list +logger -check-expected + +logger -expect log "Caching data" 1 +log Caching data +read_liberty normal.lib; design -reset +logger -check-expected + +logger -expect log "Caching data" 1 +read_liberty -lib busdef.lib; design -reset +logger -check-expected + +logger -expect log "Using cached data" 1 +log Using cached data +read_liberty normal.lib; design -reset +logger -check-expected + +logger -expect log "Using cached data" 1 +read_liberty -lib busdef.lib; design -reset +logger -check-expected + +libcache -quiet +logger -expect log "Using cached data" 1 +log Using cached data +read_liberty -lib busdef.lib; design -reset +logger -check-expected +libcache -verbose + +libcache -purge busdef.lib + +logger -expect log "Caching is disabled by default." 1 +logger -expect log "Caching is enabled for `busdef.lib'." 1 +log Caching is enabled for `busdef.lib'. +libcache -list +logger -check-expected + +libcache -enable -all + +logger -expect log "Caching is enabled by default." 1 +libcache -list +logger -check-expected + +logger -expect log "Caching data" 1 +read_liberty normal.lib; design -reset +logger -check-expected + +logger -expect log "Caching data" 1 +read_liberty -lib busdef.lib; design -reset +logger -check-expected + +logger -expect log "Using cached data" 1 +read_liberty -lib busdef.lib; design -reset +logger -check-expected + +logger -expect log "Using cached data" 1 +read_liberty normal.lib; design -reset +logger -check-expected + +logger -expect log "Using cached data" 1 +dfflibmap -liberty normal.lib +logger -check-expected + +libcache -disable -all + +logger -expect log "Caching is disabled by default." 1 +libcache -list +logger -check-expected diff --git a/chips/yosys/tests/liberty/non-ascii.lib b/chips/yosys/tests/liberty/non-ascii.lib new file mode 100644 index 0000000000000000000000000000000000000000..92e9f7b77c9a16f01f35205ee615b284f237c14a --- /dev/null +++ b/chips/yosys/tests/liberty/non-ascii.lib @@ -0,0 +1,14 @@ +// The parser used to choke on the copyright symbol even in comments +// © ® ø Φ +library(dummy) { + cell(buffer) { + area : 1 ; + pin(A) { + direction : input ; + } + pin(Y) { + direction : output ; + function : "A" ; + } + } +} diff --git a/chips/yosys/tests/liberty/non-ascii.lib.filtered.ok b/chips/yosys/tests/liberty/non-ascii.lib.filtered.ok new file mode 100644 index 0000000000000000000000000000000000000000..f03f725f7f0d464b52288b05dd0206ff95d359e0 --- /dev/null +++ b/chips/yosys/tests/liberty/non-ascii.lib.filtered.ok @@ -0,0 +1,12 @@ +library(dummy) { + cell(buffer) { + area : 1 ; + pin(A) { + direction : input ; + } + pin(Y) { + direction : output ; + function : "A" ; + } + } +} diff --git a/chips/yosys/tests/liberty/non-ascii.lib.verilogsim.ok b/chips/yosys/tests/liberty/non-ascii.lib.verilogsim.ok new file mode 100644 index 0000000000000000000000000000000000000000..de5e2e5f330c155bd326f87846e14de2fccda651 --- /dev/null +++ b/chips/yosys/tests/liberty/non-ascii.lib.verilogsim.ok @@ -0,0 +1,5 @@ +module buffer (A, Y); + input A; + output Y; + assign Y = A; // "A" +endmodule diff --git a/chips/yosys/tests/liberty/normal.lib b/chips/yosys/tests/liberty/normal.lib new file mode 100644 index 0000000000000000000000000000000000000000..d8cc1d91b2c25f0444a948fe52ced0ac3425c30a --- /dev/null +++ b/chips/yosys/tests/liberty/normal.lib @@ -0,0 +1,359 @@ +/********************************************/ +/* */ +/* Supergate cell library for Bench marking */ +/* */ +/* Symbiotic EDA GmbH / Moseley Instruments */ +/* Niels A. Moseley */ +/* */ +/* Process: none */ +/* */ +/* Date : 02-11-2018 */ +/* Version: 1.0 */ +/* */ +/********************************************/ + +library(supergate) { + technology (cmos); + revision : 1.0; + + time_unit : "1ps"; + pulling_resistance_unit : "1kohm"; + voltage_unit : "1V"; + current_unit : "1uA"; + + capacitive_load_unit(1,ff); + + default_inout_pin_cap : 7.0; + default_input_pin_cap : 7.0; + default_output_pin_cap : 0.0; + default_fanout_load : 1.0; + + default_wire_load_capacitance : 0.1; + default_wire_load_resistance : 1.0e-3; + default_wire_load_area : 0.0; + + nom_process : 1.0; + nom_temperature : 25.0; + nom_voltage : 1.2; + + delay_model : generic_cmos; + + /* Inverter */ + cell (inv) { + area : 1; + pin(A) { + direction : input; + } + + pin(Y) { + direction : output; + function : "A'"; + } + } + + /* tri-state inverter */ + cell (tri_inv) { + area : 4; + pin(A) { + direction : input; + } + pin(S) { + direction : input; + } + pin(Z) { + direction : output; + function : "A'"; + three_State : "S'"; + } + } + + cell (buffer) { + area : 5; + pin(A) { + direction : input; + } + pin(Y) { + direction : output; + function : "A"; + } + } + + /* 2-input NAND gate */ + cell (nand2) { + area : 3; + pin(A) { + direction : input; + } + pin(B) { + direction : input; + } + pin(Y) { + direction: output; + function : "(A * B)'"; + } + } + + /* 2-input NOR gate */ + cell (nor2) { + area : 3; + pin(A) { + direction : input; + } + pin(B) { + direction : input; + } + pin(Y) { + direction: output; + function : "(A + B)'"; + } + } + + /* 2-input XOR */ + cell (xor2) { + area : 6; + pin(A) { + direction : input; + } + pin(B) { + direction : input; + } + pin(Y) { + direction: output; + function : "(A *B') + (A' * B)"; + } + } + + /* 2-input inverting MUX */ + cell (imux2) { + area : 5; + pin(A) { + direction : input; + } + pin(B) { + direction : input; + } + pin(S) { + direction : input; + } + pin(Y) { + direction: output; + function : "( (A * S) + (B * S') )'"; + } + } + + /* D-type flip-flop with asynchronous reset and preset */ + cell (dff) { + area : 6; + ff("IQ", "IQN") { + next_state : "D"; + clocked_on : "CLK"; + clear : "RESET"; + preset : "PRESET"; + clear_preset_var1 : L; + clear_preset_var2 : L; + } + pin(D) { + direction : input; + } + pin(CLK) { + direction : input; + } + pin(RESET) { + direction : input; + } + pin(PRESET) { + direction : input; + } + pin(Q) { + direction: output; + function : "IQ"; + timing() { + timing_type : rising_edge; + intrinsic_rise : 65; + intrinsic_fall : 65; + rise_resistance : 0; + fall_resistance : 0; + related_pin : "CLK"; + } + timing () { + timing_type : clear; + timing_sense : positive_unate; + intrinsic_fall : 75; + related_pin : "RESET"; + } + timing () { + timing_type : preset; + timing_sense : negative_unate; + intrinsic_rise : 75; + related_pin : "PRESET"; + } + } + pin(QN) { + direction: output; + function : "IQN"; + timing() { + timing_type : rising_edge; + intrinsic_rise : 65; + intrinsic_fall : 65; + rise_resistance : 0; + fall_resistance : 0; + related_pin : "CLK"; + } + timing () { + timing_type : preset; + timing_sense : negative_unate; + intrinsic_rise : 75; + related_pin : "RESET"; + } + timing () { + timing_type : clear; + timing_sense : positive_unate; + intrinsic_fall : 75; + related_pin : "PRESET"; + } + } + } + + /* Latch */ + cell(latch) { + area : 5; + latch ("IQ","IQN") { + enable : "G"; + data_in : "D"; + } + + pin(D) { + direction : input; + } + pin(G) { + direction : input; + } + + pin(Q) { + direction : output; + function : "IQ"; + internal_node : "Q"; + + timing() { + timing_type : rising_edge; + intrinsic_rise : 65; + intrinsic_fall : 65; + rise_resistance : 0; + fall_resistance : 0; + related_pin : "G"; + } + + timing() { + timing_sense : positive_unate; + intrinsic_rise : 65; + intrinsic_fall : 65; + rise_resistance : 0; + fall_resistance : 0; + related_pin : "D"; + } + } + + pin(QN) { + direction : output; + function : "IQN"; + internal_node : "QN"; + + timing() { + timing_type : rising_edge; + intrinsic_rise : 65; + intrinsic_fall : 65; + rise_resistance : 0; + fall_resistance : 0; + related_pin : "G"; + } + + timing() { + timing_sense : negative_unate; + intrinsic_rise : 65; + intrinsic_fall : 65; + rise_resistance : 0; + fall_resistance : 0; + related_pin : "D"; + } + } + } + + /* 3 input AND-OR-INVERT gate */ + cell (aoi211) { + area : 3; + pin(A) { + direction : input; + } + pin(B) { + direction : input; + } + pin(C) { + direction : input; + } + pin(Y) { + direction: output; + function : "((A * B) + C)'"; + } + } + + + /* 3 input OR-AND-INVERT gate */ + cell (oai211) { + area : 3; + pin(A) { + direction : input; + } + pin(B) { + direction : input; + } + pin(C) { + direction : input; + } + pin(Y) { + direction: output; + function : "((A + B) * C)'"; + } + } + + /* half adder */ + cell (halfadder) { + area : 5; + pin(A) { + direction : input; + } + pin(B) { + direction : input; + } + pin(C) { + direction : output; + function : "(A * B)"; + } + pin(Y) { + direction: output; + function : "(A *B') + (A' * B)"; + } + } + + /* full adder */ + cell (fulladder) { + area : 8; + pin(A) { + direction : input; + } + pin(B) { + direction : input; + } + pin(CI) { + direction : input; + } + pin(CO) { + direction : output; + function : "(((A * B)+(B * CI))+(CI * A))"; + } + pin(Y) { + direction: output; + function : "((A^B)^CI)"; + } + } + +} /* end */ diff --git a/chips/yosys/tests/liberty/normal.lib.filtered.ok b/chips/yosys/tests/liberty/normal.lib.filtered.ok new file mode 100644 index 0000000000000000000000000000000000000000..eea7df8feba3eacc3139640860774d9df63ab2a3 --- /dev/null +++ b/chips/yosys/tests/liberty/normal.lib.filtered.ok @@ -0,0 +1,211 @@ +library(supergate) { + cell(inv) { + area : 1 ; + pin(A) { + direction : input ; + } + pin(Y) { + direction : output ; + function : "A'" ; + } + } + cell(tri_inv) { + area : 4 ; + pin(A) { + direction : input ; + } + pin(S) { + direction : input ; + } + pin(Z) { + direction : output ; + function : "A'" ; + } + } + cell(buffer) { + area : 5 ; + pin(A) { + direction : input ; + } + pin(Y) { + direction : output ; + function : "A" ; + } + } + cell(nand2) { + area : 3 ; + pin(A) { + direction : input ; + } + pin(B) { + direction : input ; + } + pin(Y) { + direction : output ; + function : "(A * B)'" ; + } + } + cell(nor2) { + area : 3 ; + pin(A) { + direction : input ; + } + pin(B) { + direction : input ; + } + pin(Y) { + direction : output ; + function : "(A + B)'" ; + } + } + cell(xor2) { + area : 6 ; + pin(A) { + direction : input ; + } + pin(B) { + direction : input ; + } + pin(Y) { + direction : output ; + function : "(A *B') + (A' * B)" ; + } + } + cell(imux2) { + area : 5 ; + pin(A) { + direction : input ; + } + pin(B) { + direction : input ; + } + pin(S) { + direction : input ; + } + pin(Y) { + direction : output ; + function : "( (A * S) + (B * S') )'" ; + } + } + cell(dff) { + area : 6 ; + ff("IQ", "IQN") { + next_state : "D" ; + clocked_on : "CLK" ; + clear : "RESET" ; + preset : "PRESET" ; + clear_preset_var1 : L ; + clear_preset_var2 : L ; + } + pin(D) { + direction : input ; + } + pin(CLK) { + direction : input ; + } + pin(RESET) { + direction : input ; + } + pin(PRESET) { + direction : input ; + } + pin(Q) { + direction : output ; + function : "IQ" ; + } + pin(QN) { + direction : output ; + function : "IQN" ; + } + } + cell(latch) { + area : 5 ; + latch("IQ", "IQN") { + enable : "G" ; + data_in : "D" ; + } + pin(D) { + direction : input ; + } + pin(G) { + direction : input ; + } + pin(Q) { + direction : output ; + function : "IQ" ; + } + pin(QN) { + direction : output ; + function : "IQN" ; + } + } + cell(aoi211) { + area : 3 ; + pin(A) { + direction : input ; + } + pin(B) { + direction : input ; + } + pin(C) { + direction : input ; + } + pin(Y) { + direction : output ; + function : "((A * B) + C)'" ; + } + } + cell(oai211) { + area : 3 ; + pin(A) { + direction : input ; + } + pin(B) { + direction : input ; + } + pin(C) { + direction : input ; + } + pin(Y) { + direction : output ; + function : "((A + B) * C)'" ; + } + } + cell(halfadder) { + area : 5 ; + pin(A) { + direction : input ; + } + pin(B) { + direction : input ; + } + pin(C) { + direction : output ; + function : "(A * B)" ; + } + pin(Y) { + direction : output ; + function : "(A *B') + (A' * B)" ; + } + } + cell(fulladder) { + area : 8 ; + pin(A) { + direction : input ; + } + pin(B) { + direction : input ; + } + pin(CI) { + direction : input ; + } + pin(CO) { + direction : output ; + function : "(((A * B)+(B * CI))+(CI * A))" ; + } + pin(Y) { + direction : output ; + function : "((A^B)^CI)" ; + } + } +} diff --git a/chips/yosys/tests/liberty/normal.lib.verilogsim.ok b/chips/yosys/tests/liberty/normal.lib.verilogsim.ok new file mode 100644 index 0000000000000000000000000000000000000000..9e8beb2e1a4dfa824e7cd96af238ae5c77e6a3c9 --- /dev/null +++ b/chips/yosys/tests/liberty/normal.lib.verilogsim.ok @@ -0,0 +1,123 @@ +module inv (A, Y); + input A; + output Y; + assign Y = (~A); // "A'" +endmodule +module tri_inv (A, S, Z); + input A; + input S; + output Z; + assign Z = (~A); // "A'" +endmodule +module buffer (A, Y); + input A; + output Y; + assign Y = A; // "A" +endmodule +module nand2 (A, B, Y); + input A; + input B; + output Y; + assign Y = (~(A&B)); // "(A * B)'" +endmodule +module nor2 (A, B, Y); + input A; + input B; + output Y; + assign Y = (~(A|B)); // "(A + B)'" +endmodule +module xor2 (A, B, Y); + input A; + input B; + output Y; + assign Y = ((A&(~B))|((~A)&B)); // "(A *B') + (A' * B)" +endmodule +module imux2 (A, B, S, Y); + input A; + input B; + input S; + output Y; + assign Y = (~((A&S)|(B&(~S)))); // "( (A * S) + (B * S') )'" +endmodule +module dff (D, CLK, RESET, PRESET, Q, QN); + reg IQ, IQN; + wire IQ_clear, IQ_preset; + input D; + input CLK; + input RESET; + input PRESET; + output Q; + assign Q = IQ; // "IQ" + output QN; + assign QN = IQN; // "IQN" + always @(posedge CLK, posedge IQ_clear, posedge IQ_preset) begin + if (IQ_clear) begin + IQ <= 0; + end + else if (IQ_preset) begin + IQ <= 1; + end + else begin + IQ <= D; + end + end + always @(posedge CLK, posedge IQ_clear, posedge IQ_preset) begin + if (IQ_preset) begin + IQN <= 0; + end + else if (IQ_clear) begin + IQN <= 1; + end + else begin + IQN <= ~(D); + end + end + assign IQ_clear = RESET; + assign IQ_preset = PRESET; +endmodule +module latch (D, G, Q, QN); + reg IQ, IQN; + input D; + input G; + output Q; + assign Q = IQ; // "IQ" + output QN; + assign QN = IQN; // "IQN" + always @* begin + if (G) begin + IQ <= D; + IQN <= ~(D); + end + end +endmodule +module aoi211 (A, B, C, Y); + input A; + input B; + input C; + output Y; + assign Y = (~((A&B)|C)); // "((A * B) + C)'" +endmodule +module oai211 (A, B, C, Y); + input A; + input B; + input C; + output Y; + assign Y = (~((A|B)&C)); // "((A + B) * C)'" +endmodule +module halfadder (A, B, C, Y); + input A; + input B; + output C; + assign C = (A&B); // "(A * B)" + output Y; + assign Y = ((A&(~B))|((~A)&B)); // "(A *B') + (A' * B)" +endmodule +module fulladder (A, B, CI, CO, Y); + input A; + input B; + input CI; + output CO; + assign CO = (((A&B)|(B&CI))|(CI&A)); // "(((A * B)+(B * CI))+(CI * A))" + output Y; + assign Y = ((A^B)^CI); // "((A^B)^CI)" +endmodule diff --git a/chips/yosys/tests/liberty/normal.verilogsim.ok b/chips/yosys/tests/liberty/normal.verilogsim.ok new file mode 100644 index 0000000000000000000000000000000000000000..30f164a3115ab103e031ab3172a4b88bac8688bd --- /dev/null +++ b/chips/yosys/tests/liberty/normal.verilogsim.ok @@ -0,0 +1,117 @@ +module inv (A, Y); + input A; + output Y; + assign Y = ~A; // A' +endmodule +module tri_inv (A, S, Z); + input A; + input S; + output Z; + assign Z = ~A; // A' +endmodule +module buffer (A, Y); + input A; + output Y; + assign Y = A; // A +endmodule +module nand2 (A, B, Y); + input A; + input B; + output Y; + assign Y = ~(A&B); // (A * B)' +endmodule +module nor2 (A, B, Y); + input A; + input B; + output Y; + assign Y = ~(A|B); // (A + B)' +endmodule +module xor2 (A, B, Y); + input A; + input B; + output Y; + assign Y = (A&~B)|(~A&B); // (A *B') + (A' * B) +endmodule +module imux2 (A, B, S, Y); + input A; + input B; + input S; + output Y; + assign Y = ~(&(A&S)|(B&~S)&); // ( (A * S) + (B * S') )' +endmodule +module dff (D, CLK, RESET, PRESET, Q, QN); + reg IQ, IQN; + input D; + input CLK; + input RESET; + input PRESET; + output Q; + assign Q = IQ; // IQ + output QN; + assign QN = IQN; // IQN + always @(posedge CLK, posedge RESET, posedge PRESET) begin + if ((RESET) && (PRESET)) begin + IQ <= 0; + IQN <= 0; + end + else if (RESET) begin + IQ <= 0; + IQN <= 1; + end + else if (PRESET) begin + IQ <= 1; + IQN <= 0; + end + else begin + // D + IQ <= D; + IQN <= ~(D); + end + end +endmodule +module latch (D, G, Q, QN); + reg IQ, IQN; + input D; + input G; + output Q; + assign Q = IQ; // IQ + output QN; + assign QN = IQN; // IQN + always @* begin + if (G) begin + IQ <= D; + IQN <= ~(D); + end + end +endmodule +module aoi211 (A, B, C, Y); + input A; + input B; + input C; + output Y; + assign Y = ~((A&B)|C); // ((A * B) + C)' +endmodule +module oai211 (A, B, C, Y); + input A; + input B; + input C; + output Y; + assign Y = ~((A|B)&C); // ((A + B) * C)' +endmodule +module halfadder (A, B, C, Y); + input A; + input B; + output C; + assign C = (A&B); // (A * B) + output Y; + assign Y = (A&~B)|(~A&B); // (A *B') + (A' * B) +endmodule +module fulladder (A, B, CI, CO, Y); + input A; + input B; + input CI; + output CO; + assign CO = (((A&B)|(B&CI))|(CI&A)); // (((A * B)+(B * CI))+(CI * A)) + output Y; + assign Y = ((A^B)^CI); // ((A^B)^CI) +endmodule diff --git a/chips/yosys/tests/liberty/options_test.ys b/chips/yosys/tests/liberty/options_test.ys new file mode 100644 index 0000000000000000000000000000000000000000..54957950e4f682d8ff32a07297791b942ef43da6 --- /dev/null +++ b/chips/yosys/tests/liberty/options_test.ys @@ -0,0 +1,23 @@ +# Test memory macro gets ignored due to -ignore_buses +read_verilog -noblackbox <Y arc on nand2_1 exists +select -assert-any =sg13g2_nand2_1/i:A %co1:+$specify2[SRC] =sg13g2_nand2_1/o:Y %co1:+$specify2[DST] %i + +# D->Q arc on sdfbbp_1 doesn't +select -assert-none =sg13g2_sdfbbp_1/i:D %co1:+$specify2[SRC] =sg13g2_nand2_1/o:Q %co1:+$specify2[DST] %i diff --git a/chips/yosys/tests/liberty/processdefs.lib b/chips/yosys/tests/liberty/processdefs.lib new file mode 100644 index 0000000000000000000000000000000000000000..209ee148ceacd5b406c0aaf702a4036f74d786ff --- /dev/null +++ b/chips/yosys/tests/liberty/processdefs.lib @@ -0,0 +1,48 @@ +/********************************************/ +/* */ +/* Supergate cell library for Bench marking */ +/* */ +/* Symbiotic EDA GmbH / Moseley Instruments */ +/* Niels A. Moseley */ +/* */ +/* Process: none */ +/* */ +/* Date : 25-03-2019 */ +/* Version: 1.0 */ +/* */ +/********************************************/ + +library(processdefs) { + technology (cmos); + revision : 1.0; + + time_unit : "1ps"; + pulling_resistance_unit : "1kohm"; + voltage_unit : "1V"; + current_unit : "1uA"; + + capacitive_load_unit(1,ff); + + default_inout_pin_cap : 7.0; + default_input_pin_cap : 7.0; + default_output_pin_cap : 0.0; + default_fanout_load : 1.0; + + default_wire_load_capacitance : 0.1; + default_wire_load_resistance : 1.0e-3; + default_wire_load_area : 0.0; + + nom_process : 1.0; + nom_temperature : 25.0; + nom_voltage : 1.2; + + delay_model : generic_cmos; + + define_cell_area(bond_pads,pad_slots) + input_voltage(cmos) { + vil : 0.3 * VDD ; + vih : 0.7 * VDD ; + vimin : -0.5 ; + vimax : VDD + 0.5 ; + } +} diff --git a/chips/yosys/tests/liberty/processdefs.lib.filtered.ok b/chips/yosys/tests/liberty/processdefs.lib.filtered.ok new file mode 100644 index 0000000000000000000000000000000000000000..d50f0e17bad49794be6f1ece043f141b3cfc9aef --- /dev/null +++ b/chips/yosys/tests/liberty/processdefs.lib.filtered.ok @@ -0,0 +1,2 @@ +library(processdefs) { +} diff --git a/chips/yosys/tests/liberty/processdefs.lib.verilogsim.ok b/chips/yosys/tests/liberty/processdefs.lib.verilogsim.ok new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/chips/yosys/tests/liberty/read_liberty.ys b/chips/yosys/tests/liberty/read_liberty.ys new file mode 100644 index 0000000000000000000000000000000000000000..7cbb0a19d28ba5e73a66f019e48eb078cda5d875 --- /dev/null +++ b/chips/yosys/tests/liberty/read_liberty.ys @@ -0,0 +1,9 @@ +read_liberty retention.lib +rename retention_cell retention_cell_lib +read_verilog retention.lib.verilogsim +proc +rename retention_cell retention_cell_vlog +async2sync +equiv_make retention_cell_lib retention_cell_vlog equiv +equiv_induct equiv +equiv_status -assert equiv diff --git a/chips/yosys/tests/liberty/retention.lib b/chips/yosys/tests/liberty/retention.lib new file mode 100644 index 0000000000000000000000000000000000000000..5a38b6623882680cd790060d09c54863644caa55 --- /dev/null +++ b/chips/yosys/tests/liberty/retention.lib @@ -0,0 +1,57 @@ +library (retention) { + delay_model : table_lookup; + voltage_unit : 1V; + current_unit : 1mA; + leakage_power_unit : 1nW; + time_unit : 1ns; + capacitive_load_unit (1, pf); + pulling_resistance_unit : 1kohm; + input_threshold_pct_rise : 50; + input_threshold_pct_fall : 50; + output_threshold_pct_rise : 50; + output_threshold_pct_fall : 50; + slew_lower_threshold_pct_rise : 30; + slew_upper_threshold_pct_rise : 70; + slew_upper_threshold_pct_fall : 70; + slew_lower_threshold_pct_fall : 30; + cell ("retention_cell") { + ff (Q1,QN1) { + clocked_on : "CK"; + next_state : "(D * !SE + SI * SE)"; + clear : "(((!B2B) * !Q2) + !RD)"; + preset : "((!B2B) * Q2)"; + clear_preset_var1 : "L"; + clear_preset_var2 : "H"; + } + latch (Q2,QN2) { + enable : "B1"; + data_in : "Q1"; + } + pin (B1) { + direction : input; + } + pin (B2B) { + direction : input; + } + pin (CK) { + clock : true; + direction : input; + } + pin (D) { + direction : input; + } + pin (Q) { + direction : output; + function : "Q1"; + } + pin (RD) { + direction : input; + } + pin (SE) { + direction : input; + } + pin (SI) { + direction : input; + } + } +} diff --git a/chips/yosys/tests/liberty/retention.lib.filtered.ok b/chips/yosys/tests/liberty/retention.lib.filtered.ok new file mode 100644 index 0000000000000000000000000000000000000000..0cfc7edfc17795f89ccb59fdab2e580f7e21f3bb --- /dev/null +++ b/chips/yosys/tests/liberty/retention.lib.filtered.ok @@ -0,0 +1,42 @@ +library(retention) { + cell("retention_cell") { + ff(Q1, QN1) { + clocked_on : "CK" ; + next_state : "(D * !SE + SI * SE)" ; + clear : "(((!B2B) * !Q2) + !RD)" ; + preset : "((!B2B) * Q2)" ; + clear_preset_var1 : "L" ; + clear_preset_var2 : "H" ; + } + latch(Q2, QN2) { + enable : "B1" ; + data_in : "Q1" ; + } + pin(B1) { + direction : input ; + } + pin(B2B) { + direction : input ; + } + pin(CK) { + clock : true ; + direction : input ; + } + pin(D) { + direction : input ; + } + pin(Q) { + direction : output ; + function : "Q1" ; + } + pin(RD) { + direction : input ; + } + pin(SE) { + direction : input ; + } + pin(SI) { + direction : input ; + } + } +} diff --git a/chips/yosys/tests/liberty/retention.lib.verilogsim.ok b/chips/yosys/tests/liberty/retention.lib.verilogsim.ok new file mode 100644 index 0000000000000000000000000000000000000000..f264e58cde1e49b149d4b67409dff045bbb4ef81 --- /dev/null +++ b/chips/yosys/tests/liberty/retention.lib.verilogsim.ok @@ -0,0 +1,44 @@ +module retention_cell (B1, B2B, CK, D, Q, RD, SE, SI); + reg Q1, QN1; + wire Q1_clear, Q1_preset; + reg Q2, QN2; + input B1; + input B2B; + input CK; + input D; + output Q; + assign Q = Q1; // "Q1" + input RD; + input SE; + input SI; + always @(posedge CK, posedge Q1_clear, posedge Q1_preset) begin + if (Q1_clear) begin + Q1 <= 0; + end + else if (Q1_preset) begin + Q1 <= 1; + end + else begin + Q1 <= ((D&(~SE))|(SI&SE)); + end + end + always @(posedge CK, posedge Q1_clear, posedge Q1_preset) begin + if (Q1_clear) begin + QN1 <= 1; + end + else if (Q1_preset) begin + QN1 <= 0; + end + else begin + QN1 <= ~(((D&(~SE))|(SI&SE))); + end + end + assign Q1_clear = (((~B2B)&(~Q2))|(~RD)); + assign Q1_preset = ((~B2B)&Q2); + always @* begin + if (B1) begin + Q2 <= Q1; + QN2 <= ~(Q1); + end + end +endmodule diff --git a/chips/yosys/tests/liberty/scl_cache.ys b/chips/yosys/tests/liberty/scl_cache.ys new file mode 100644 index 0000000000000000000000000000000000000000..e7305fe2592ecd9298c880ad6f43b16253a45dd7 --- /dev/null +++ b/chips/yosys/tests/liberty/scl_cache.ys @@ -0,0 +1,23 @@ +read_verilog small.v +synth -top small +abc -liberty normal.lib + +logger -expect log "using cached merged SCL" 1 +abc -liberty normal.lib +logger -check-expected + +libcache -scl -disable + +logger -expect log "SCL caching is disabled." 1 +libcache -list +logger -check-expected + +logger -expect log "SCL cache disabled, using liberty format" 1 +abc -liberty normal.lib +logger -check-expected + +libcache -scl -enable + +logger -expect log "using cached merged SCL" 1 +abc -liberty normal.lib +logger -check-expected diff --git a/chips/yosys/tests/liberty/semicolextra.lib b/chips/yosys/tests/liberty/semicolextra.lib new file mode 100644 index 0000000000000000000000000000000000000000..49b33d918f867de7138282e13d01ffaf37099c22 --- /dev/null +++ b/chips/yosys/tests/liberty/semicolextra.lib @@ -0,0 +1,48 @@ +/* + + Test case for https://www.reddit.com/r/yosys/comments/b5texg/yosys_fails_to_parse_apparentlycorrect_liberty/ + + fall_constraint (SETUP_HOLD) formatting. + +*/ + +library(supergate) { + technology (cmos); + revision : 1.0; + + cell (DFF) { + cell_footprint : dff; + area : 50; + pin(D) { + direction : input; + capacitance : 0.002; + timing() { + related_pin : "CK"; + timing_type : setup_rising; + + fall_constraint (SETUP_HOLD) { values ("0.4000, 0.3000, 0.2000, 0.1000, 0.0000", \ + "0.4000, 0.3000, 0.2000, 0.1000, 0.000", \ + "0.5000, 0.4000, 0.3000, 0.2000, 0.0000", \ + "0.7000, 0.6000, 0.5000, 0.4000, 0.2000", \ + "1.0000, 1.0000, 0.9000, 0.8000, 0.6000"); }; + } + } + + pin(CK) { + direction : input; + clock : true; + capacitance : 0.00290; + } + + ff(IQ,IQN) { + clocked_on : "CK"; + next_state : "D"; + } + pin(Q) { + direction : output; + capacitance : 0.003; + max_capacitance : 0.3; + } + cell_leakage_power : 0.3; + } +} diff --git a/chips/yosys/tests/liberty/semicolextra.lib.filtered.ok b/chips/yosys/tests/liberty/semicolextra.lib.filtered.ok new file mode 100644 index 0000000000000000000000000000000000000000..10f9618cbc0f05492eee6b6abdc2ee46df417529 --- /dev/null +++ b/chips/yosys/tests/liberty/semicolextra.lib.filtered.ok @@ -0,0 +1,20 @@ +library(supergate) { + cell(DFF) { + cell_footprint : dff ; + area : 50 ; + pin(D) { + direction : input ; + } + pin(CK) { + direction : input ; + clock : true ; + } + ff(IQ, IQN) { + clocked_on : "CK" ; + next_state : "D" ; + } + pin(Q) { + direction : output ; + } + } +} diff --git a/chips/yosys/tests/liberty/semicolextra.lib.verilogsim.ok b/chips/yosys/tests/liberty/semicolextra.lib.verilogsim.ok new file mode 100644 index 0000000000000000000000000000000000000000..1efbf6cf0d237f13d0b5913f297a47522ebd3887 --- /dev/null +++ b/chips/yosys/tests/liberty/semicolextra.lib.verilogsim.ok @@ -0,0 +1,12 @@ +module DFF (D, CK, Q); + reg IQ, IQN; + input D; + input CK; + output Q; + always @(posedge CK) begin + IQ <= D; + end + always @(posedge CK) begin + IQN <= ~(D); + end +endmodule diff --git a/chips/yosys/tests/liberty/semicolmissing.lib b/chips/yosys/tests/liberty/semicolmissing.lib new file mode 100644 index 0000000000000000000000000000000000000000..b18f14d9aec9a9ba5dd09e406e53db45349fcb5f --- /dev/null +++ b/chips/yosys/tests/liberty/semicolmissing.lib @@ -0,0 +1,70 @@ +/********************************************/ +/* */ +/* Supergate cell library for Bench marking */ +/* */ +/* Symbiotic EDA GmbH / Moseley Instruments */ +/* Niels A. Moseley */ +/* */ +/* Process: none */ +/* */ +/* Date : 24-03-2019 */ +/* Version: 1.0 */ +/* Version: 1.1 - Removed semicolons in */ +/* full adder */ +/* */ +/********************************************/ + +/* + semi colon is missing in full-adder specification + some TSMC liberty files are formatted this way.. +*/ + +library(supergate) { + technology (cmos); + revision : 1.0; + + time_unit : "1ps"; + pulling_resistance_unit : "1kohm"; + voltage_unit : "1V"; + current_unit : "1uA"; + + capacitive_load_unit(1,ff); + + default_inout_pin_cap : 7.0; + default_input_pin_cap : 7.0; + default_output_pin_cap : 0.0; + default_fanout_load : 1.0; + + default_wire_load_capacitance : 0.1; + default_wire_load_resistance : 1.0e-3; + default_wire_load_area : 0.0; + + nom_process : 1.0; + nom_temperature : 25.0; + nom_voltage : 1.2; + + delay_model : generic_cmos; + + /* full adder */ + cell (fulladder) { + area : 8 + pin(A) { + direction : input + } + pin(B) { + direction : input + } + pin(CI) { + direction : input + } + pin(CO) { + direction : output + function : "(((A * B)+(B * CI))+(CI * A))" + } + pin(Y) { + direction: output + function : "((A^B)^CI)" + } + } + +} /* end */ diff --git a/chips/yosys/tests/liberty/semicolmissing.lib.filtered.ok b/chips/yosys/tests/liberty/semicolmissing.lib.filtered.ok new file mode 100644 index 0000000000000000000000000000000000000000..2a00cc136806102c37d30a55b693a35db56d64c4 --- /dev/null +++ b/chips/yosys/tests/liberty/semicolmissing.lib.filtered.ok @@ -0,0 +1,22 @@ +library(supergate) { + cell(fulladder) { + area : 8 ; + pin(A) { + direction : input ; + } + pin(B) { + direction : input ; + } + pin(CI) { + direction : input ; + } + pin(CO) { + direction : output ; + function : "(((A * B)+(B * CI))+(CI * A))" ; + } + pin(Y) { + direction : output ; + function : "((A^B)^CI)" ; + } + } +} diff --git a/chips/yosys/tests/liberty/semicolmissing.lib.verilogsim.ok b/chips/yosys/tests/liberty/semicolmissing.lib.verilogsim.ok new file mode 100644 index 0000000000000000000000000000000000000000..56d57209d08484646ee8d2fd9a378906734128a6 --- /dev/null +++ b/chips/yosys/tests/liberty/semicolmissing.lib.verilogsim.ok @@ -0,0 +1,9 @@ +module fulladder (A, B, CI, CO, Y); + input A; + input B; + input CI; + output CO; + assign CO = (((A&B)|(B&CI))|(CI&A)); // "(((A * B)+(B * CI))+(CI * A))" + output Y; + assign Y = ((A^B)^CI); // "((A^B)^CI)" +endmodule diff --git a/chips/yosys/tests/liberty/small.v b/chips/yosys/tests/liberty/small.v new file mode 100644 index 0000000000000000000000000000000000000000..89774881cd5dd8e82a28ac2445850f3fcdbbf33a --- /dev/null +++ b/chips/yosys/tests/liberty/small.v @@ -0,0 +1,16 @@ +/** small, meaningless design to test loading of liberty files */ + +module small +( + input clk, + output reg[7:0] count +); + +initial count = 0; + +always @ (posedge clk) +begin + count <= count + 1'b1; +end + +endmodule diff --git a/chips/yosys/tests/liberty/unquoted.lib b/chips/yosys/tests/liberty/unquoted.lib new file mode 100644 index 0000000000000000000000000000000000000000..c2bf538d24e8bb2bb667dc9d8894abfab760b5ef --- /dev/null +++ b/chips/yosys/tests/liberty/unquoted.lib @@ -0,0 +1,60 @@ +library(dff_unquoted) { + cell (dff1) { + area : 1; + ff("IQ", "IQN") { + next_state : !D; + clocked_on : (CLK); + } + pin(D) { + direction : input; + } + pin(CLK) { + direction : input; + } + pin(Q) { + direction: output; + function : IQ; + } + } + cell (dff2) { + area : 1; + ff(IQ, IQN) { + next_state : D'; + clocked_on : CLK; + } + pin(D) { + direction : input; + } + pin(CLK) { + direction : input; + } + pin(Q) { + direction: output; + function : "IQ"; + } + } + cell (dffe) { + area : 6; + ff("IQ", "IQN") { + next_state : (D&EN) | (IQ&!EN); + clocked_on : !CLK; + } + pin(D) { + direction : input; + } + pin(EN) { + direction : input; + } + pin(CLK) { + direction : input; + } + pin(Q) { + direction: output; + function : "IQ"; + } + pin(QN) { + direction: output; + function : "IQN"; + } + } +} diff --git a/chips/yosys/tests/liberty/unquoted.lib.filtered.ok b/chips/yosys/tests/liberty/unquoted.lib.filtered.ok new file mode 100644 index 0000000000000000000000000000000000000000..0ffc157b4cf70f570b5762d00ff438ad4ee3ac5c --- /dev/null +++ b/chips/yosys/tests/liberty/unquoted.lib.filtered.ok @@ -0,0 +1,60 @@ +library(dff_unquoted) { + cell(dff1) { + area : 1 ; + ff("IQ", "IQN") { + next_state : !D ; + clocked_on : ( CLK ) ; + } + pin(D) { + direction : input ; + } + pin(CLK) { + direction : input ; + } + pin(Q) { + direction : output ; + function : IQ ; + } + } + cell(dff2) { + area : 1 ; + ff(IQ, IQN) { + next_state : D ' ; + clocked_on : CLK ; + } + pin(D) { + direction : input ; + } + pin(CLK) { + direction : input ; + } + pin(Q) { + direction : output ; + function : "IQ" ; + } + } + cell(dffe) { + area : 6 ; + ff("IQ", "IQN") { + next_state : ( D & EN ) | ( IQ & ! EN ) ; + clocked_on : !CLK ; + } + pin(D) { + direction : input ; + } + pin(EN) { + direction : input ; + } + pin(CLK) { + direction : input ; + } + pin(Q) { + direction : output ; + function : "IQ" ; + } + pin(QN) { + direction : output ; + function : "IQN" ; + } + } +} diff --git a/chips/yosys/tests/liberty/unquoted.lib.verilogsim.ok b/chips/yosys/tests/liberty/unquoted.lib.verilogsim.ok new file mode 100644 index 0000000000000000000000000000000000000000..f6b022194284a6eb871e88694260a0142c63f635 --- /dev/null +++ b/chips/yosys/tests/liberty/unquoted.lib.verilogsim.ok @@ -0,0 +1,42 @@ +module dff1 (D, CLK, Q); + reg IQ, IQN; + input D; + input CLK; + output Q; + assign Q = IQ; // IQ + always @(posedge CLK) begin + IQ <= (~D); + end + always @(posedge CLK) begin + IQN <= ~((~D)); + end +endmodule +module dff2 (D, CLK, Q); + reg IQ, IQN; + input D; + input CLK; + output Q; + assign Q = IQ; // "IQ" + always @(posedge CLK) begin + IQ <= (~D); + end + always @(posedge CLK) begin + IQN <= ~((~D)); + end +endmodule +module dffe (D, EN, CLK, Q, QN); + reg IQ, IQN; + input D; + input EN; + input CLK; + output Q; + assign Q = IQ; // "IQ" + output QN; + assign QN = IQN; // "IQN" + always @(negedge CLK) begin + IQ <= ((D&EN)|(IQ&(~EN))); + end + always @(negedge CLK) begin + IQN <= ~(((D&EN)|(IQ&(~EN)))); + end +endmodule diff --git a/chips/yosys/tests/lut/check_map.ys b/chips/yosys/tests/lut/check_map.ys new file mode 100644 index 0000000000000000000000000000000000000000..46854e82e3e56fb2b3d025af3c8d561d53eadf9a --- /dev/null +++ b/chips/yosys/tests/lut/check_map.ys @@ -0,0 +1,6 @@ +simplemap +equiv_opt -assert techmap -D LUT_WIDTH=4 -map +/cmp2lut.v +design -load postopt +equiv_opt -assert techmap -D LUT_WIDTH=4 -map +/gate2lut.v +design -load postopt +select -assert-count 0 t:* t:$lut %d diff --git a/chips/yosys/tests/lut/check_map_lut6.ys b/chips/yosys/tests/lut/check_map_lut6.ys new file mode 100644 index 0000000000000000000000000000000000000000..8a32e4d106bc681ad9320bae2310dc5af47e25c8 --- /dev/null +++ b/chips/yosys/tests/lut/check_map_lut6.ys @@ -0,0 +1,7 @@ +chparam -set LUT_WIDTH 6 top +simplemap +equiv_opt -assert techmap -D LUT_WIDTH=6 -map +/cmp2lut.v +design -load postopt +equiv_opt -assert techmap -D LUT_WIDTH=6 -map +/gate2lut.v +design -load postopt +select -assert-count 0 t:* t:$lut %d diff --git a/chips/yosys/tests/lut/generate_mk.py b/chips/yosys/tests/lut/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..10ced96dc5001d46d99fbc61d437a998dd003612 --- /dev/null +++ b/chips/yosys/tests/lut/generate_mk.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile + +gen_tests_makefile.generate(["--bash"]) diff --git a/chips/yosys/tests/lut/lut.sh b/chips/yosys/tests/lut/lut.sh new file mode 100644 index 0000000000000000000000000000000000000000..255743bfa40b6d92a9cdb5a14a44485792f779c8 --- /dev/null +++ b/chips/yosys/tests/lut/lut.sh @@ -0,0 +1,26 @@ +set -e +DIR=$(cd "$(dirname "$0")" && pwd) + +run_cmp_test() +{ + cmp=$1 + log=${DIR}/map_cmp_${cmp}_eq.log + + echo "Running ${DIR}/map_cmp.v with CMP=4'd${cmp}.." + ${YOSYS} -D "CMP_VALUE=4'd${cmp}" -q -s ${DIR}/check_map.ys -l ${log} -f verilog ${DIR}/map_cmp.v +} + +cmp=0 +while [ ${cmp} -lt 16 ]; do + run_cmp_test ${cmp} + cmp=$((cmp + 1)) +done + +for x in ${DIR}/*.v; do + echo "Running $x.." + ${YOSYS} -q -s ${DIR}/check_map.ys -l ${x%.v}.log -f verilog $x +done +for x in ${DIR}/map_cmp.v; do + echo "Running $x.." + ${YOSYS} -q -s ${DIR}/check_map_lut6.ys -l ${x%.v}_lut6.log -f verilog $x +done diff --git a/chips/yosys/tests/lut/map_and.v b/chips/yosys/tests/lut/map_and.v new file mode 100644 index 0000000000000000000000000000000000000000..68ae33fd6deeac155afa349086a7ec1e3ccd141b --- /dev/null +++ b/chips/yosys/tests/lut/map_and.v @@ -0,0 +1,5 @@ +module top(...); + input a, b; + output y; + assign y = a&b; +endmodule diff --git a/chips/yosys/tests/lut/map_cmp.v b/chips/yosys/tests/lut/map_cmp.v new file mode 100644 index 0000000000000000000000000000000000000000..fa1a4a8c68024f8201ed62f81a954e66e64fa7e1 --- /dev/null +++ b/chips/yosys/tests/lut/map_cmp.v @@ -0,0 +1,71 @@ +`ifndef CMP_VALUE +`define CMP_VALUE {(LUT_WIDTH/2){2'b10}} +`endif + +module top(...); + parameter LUT_WIDTH = 4; // Multiples of 2 only + + input [LUT_WIDTH-1:0] a; + + output o1_1 = $unsigned(`CMP_VALUE) <= $unsigned(a); + output o1_2 = $unsigned(`CMP_VALUE) < $unsigned(a); + output o1_3 = $unsigned(`CMP_VALUE) >= $unsigned(a); + output o1_4 = $unsigned(`CMP_VALUE) > $unsigned(a); + output o1_5 = $unsigned(`CMP_VALUE) == $unsigned(a); + output o1_6 = $unsigned(`CMP_VALUE) != $unsigned(a); + + output o2_1 = $unsigned(a) <= $unsigned(`CMP_VALUE); + output o2_2 = $unsigned(a) < $unsigned(`CMP_VALUE); + output o2_3 = $unsigned(a) >= $unsigned(`CMP_VALUE); + output o2_4 = $unsigned(a) > $unsigned(`CMP_VALUE); + output o2_5 = $unsigned(a) == $unsigned(`CMP_VALUE); + output o2_6 = $unsigned(a) != $unsigned(`CMP_VALUE); + + // ######################## + + output o3_1 = $signed(`CMP_VALUE) <= $unsigned(a); + output o3_2 = $signed(`CMP_VALUE) < $unsigned(a); + output o3_3 = $signed(`CMP_VALUE) >= $unsigned(a); + output o3_4 = $signed(`CMP_VALUE) > $unsigned(a); + output o3_5 = $signed(`CMP_VALUE) == $unsigned(a); + output o3_6 = $signed(`CMP_VALUE) != $unsigned(a); + + output o4_1 = $unsigned(a) <= $signed(`CMP_VALUE); + output o4_2 = $unsigned(a) < $signed(`CMP_VALUE); + output o4_3 = $unsigned(a) >= $signed(`CMP_VALUE); + output o4_4 = $unsigned(a) > $signed(`CMP_VALUE); + output o4_5 = $unsigned(a) == $signed(`CMP_VALUE); + output o4_6 = $unsigned(a) != $signed(`CMP_VALUE); + + // ######################## + + output o5_1 = $unsigned(`CMP_VALUE) <= $signed(a); + output o5_2 = $unsigned(`CMP_VALUE) < $signed(a); + output o5_3 = $unsigned(`CMP_VALUE) >= $signed(a); + output o5_4 = $unsigned(`CMP_VALUE) > $signed(a); + output o5_5 = $unsigned(`CMP_VALUE) == $signed(a); + output o5_6 = $unsigned(`CMP_VALUE) != $signed(a); + + output o6_1 = $signed(a) <= $unsigned(`CMP_VALUE); + output o6_2 = $signed(a) < $unsigned(`CMP_VALUE); + output o6_3 = $signed(a) >= $unsigned(`CMP_VALUE); + output o6_4 = $signed(a) > $unsigned(`CMP_VALUE); + output o6_5 = $signed(a) == $unsigned(`CMP_VALUE); + output o6_6 = $signed(a) != $unsigned(`CMP_VALUE); + + // ######################## + + output o7_1 = $signed(`CMP_VALUE) <= $signed(a); + output o7_2 = $signed(`CMP_VALUE) < $signed(a); + output o7_3 = $signed(`CMP_VALUE) >= $signed(a); + output o7_4 = $signed(`CMP_VALUE) > $signed(a); + output o7_5 = $signed(`CMP_VALUE) == $signed(a); + output o7_6 = $signed(`CMP_VALUE) != $signed(a); + + output o8_1 = $signed(a) <= $signed(`CMP_VALUE); + output o8_2 = $signed(a) < $signed(`CMP_VALUE); + output o8_3 = $signed(a) >= $signed(`CMP_VALUE); + output o8_4 = $signed(a) > $signed(`CMP_VALUE); + output o8_5 = $signed(a) == $signed(`CMP_VALUE); + output o8_6 = $signed(a) != $signed(`CMP_VALUE); +endmodule diff --git a/chips/yosys/tests/lut/map_mux.v b/chips/yosys/tests/lut/map_mux.v new file mode 100644 index 0000000000000000000000000000000000000000..ccecf30230f94c658fb5c017dcd7ac5d7e5b3d0d --- /dev/null +++ b/chips/yosys/tests/lut/map_mux.v @@ -0,0 +1,5 @@ +module top(...); + input a, b, s; + output y; + assign y = s?a:b; +endmodule diff --git a/chips/yosys/tests/lut/map_not.v b/chips/yosys/tests/lut/map_not.v new file mode 100644 index 0000000000000000000000000000000000000000..38599741427d3ffefa54a10c3f5e9aa532f2322f --- /dev/null +++ b/chips/yosys/tests/lut/map_not.v @@ -0,0 +1,5 @@ +module top(...); + input a; + output y; + assign y = ~a; +endmodule diff --git a/chips/yosys/tests/lut/map_or.v b/chips/yosys/tests/lut/map_or.v new file mode 100644 index 0000000000000000000000000000000000000000..8b8c551885ba2871f3abf489cad106815627090e --- /dev/null +++ b/chips/yosys/tests/lut/map_or.v @@ -0,0 +1,5 @@ +module top(...); + input a, b; + output y; + assign y = a|b; +endmodule diff --git a/chips/yosys/tests/lut/map_xor.v b/chips/yosys/tests/lut/map_xor.v new file mode 100644 index 0000000000000000000000000000000000000000..708a05789a3363e98fdb271c9e160da35715cbca --- /dev/null +++ b/chips/yosys/tests/lut/map_xor.v @@ -0,0 +1,5 @@ +module top(...); + input a, b; + output y; + assign y = a^b; +endmodule diff --git a/chips/yosys/tests/memfile/.gitignore b/chips/yosys/tests/memfile/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..61b0d426432ae69e6bd10bd767f97f39a1b511aa --- /dev/null +++ b/chips/yosys/tests/memfile/.gitignore @@ -0,0 +1 @@ +temp* diff --git a/chips/yosys/tests/memfile/content1.dat b/chips/yosys/tests/memfile/content1.dat new file mode 100644 index 0000000000000000000000000000000000000000..4d1c67c26a4a1d241b99ec5a0e0d5bd1544185c6 --- /dev/null +++ b/chips/yosys/tests/memfile/content1.dat @@ -0,0 +1,64 @@ +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 +00001111000000001111111100000000 diff --git a/chips/yosys/tests/memfile/generate_mk.py b/chips/yosys/tests/memfile/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..0ed24447246819422cf02ef89d825243073bca8a --- /dev/null +++ b/chips/yosys/tests/memfile/generate_mk.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile + +def create_tests(): + setup = "mkdir -p temp && cp content1.dat temp/content2.dat" + + gen_tests_makefile.generate_cmd_test("parent_content1", [ + f"{setup}", + 'cd .. && $(YOSYS) -qp "read_verilog -defer memfile/memory.v; ' + 'chparam -set MEMFILE \\"content1.dat\\" memory"' + ]) + + gen_tests_makefile.generate_cmd_test("parent_content2_temp", [ + f"{setup}", + 'cd .. && $(YOSYS) -qp "read_verilog -defer memfile/memory.v; ' + 'chparam -set MEMFILE \\"temp/content2.dat\\" memory"' + ]) + + gen_tests_makefile.generate_cmd_test("parent_content2_full", [ + f"{setup}", + 'cd .. && $(YOSYS) -qp "read_verilog -defer memfile/memory.v; ' + 'chparam -set MEMFILE \\"memfile/temp/content2.dat\\" memory"' + ]) + + gen_tests_makefile.generate_cmd_test("same_content1", [ + f"{setup}", + '$(YOSYS) -qp "read_verilog -defer memory.v; ' + 'chparam -set MEMFILE \\"content1.dat\\" memory"' + ]) + + gen_tests_makefile.generate_cmd_test("same_content2", [ + f"{setup}", + '$(YOSYS) -qp "read_verilog -defer memory.v; ' + 'chparam -set MEMFILE \\"temp/content2.dat\\" memory"' + ]) + + gen_tests_makefile.generate_cmd_test("child_content1", [ + f"{setup}", + 'cd temp && $(YOSYS) -qp "read_verilog -defer ../memory.v; ' + 'chparam -set MEMFILE \\"content1.dat\\" memory"' + ]) + + gen_tests_makefile.generate_cmd_test("child_content2_temp", [ + f"{setup}", + 'cd temp && $(YOSYS) -qp "read_verilog -defer ../memory.v; ' + 'chparam -set MEMFILE \\"temp/content2.dat\\" memory"' + ]) + + gen_tests_makefile.generate_cmd_test("child_content2_direct", [ + f"{setup}", + 'cd temp && $(YOSYS) -qp "read_verilog -defer ../memory.v; ' + 'chparam -set MEMFILE \\"temp/content2.dat\\" memory"' + ]) + + gen_tests_makefile.generate_cmd_test("fail_empty_filename", + '! $(YOSYS) -qp "read_verilog memory.v"') + + gen_tests_makefile.generate_cmd_test("fail_missing_file", [ + '! $(YOSYS) -qp "read_verilog -defer memory.v; ' + 'chparam -set MEMFILE \\"content3.dat\\" memory"' + ]) + +gen_tests_makefile.generate_custom(create_tests) diff --git a/chips/yosys/tests/memfile/memory.v b/chips/yosys/tests/memfile/memory.v new file mode 100644 index 0000000000000000000000000000000000000000..57106eae8bb44c908e2f02f39a2680a868927479 --- /dev/null +++ b/chips/yosys/tests/memfile/memory.v @@ -0,0 +1,23 @@ +// A memory initialized with an external file + +module memory ( + input clk_i, + input we_i, + input [5:0] addr_i, + input [31:0] data_i, + output reg [31:0] data_o +); + +parameter MEMFILE = ""; + +reg [31:0] mem [0:63]; + +initial $readmemb(MEMFILE,mem); + +always @(posedge clk_i) begin + if (we_i) + mem[addr_i] <= data_i; + data_o <= mem[addr_i]; +end + +endmodule diff --git a/chips/yosys/tests/memlib/.gitignore b/chips/yosys/tests/memlib/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..bfa1a801eb44033a02148185b3632544e469c90e --- /dev/null +++ b/chips/yosys/tests/memlib/.gitignore @@ -0,0 +1,2 @@ +t_*.v +t_*.ys diff --git a/chips/yosys/tests/memlib/generate_mk.py b/chips/yosys/tests/memlib/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..230d2ebd6a0f11a5c72fb775186a0295a9200ae2 --- /dev/null +++ b/chips/yosys/tests/memlib/generate_mk.py @@ -0,0 +1,1590 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") +import gen_tests_makefile + +# TODO: + +# - priority logic +# - swizzles for weird width progressions + + +class Test: + def __init__(self, name, src, libs, defs, cells): + self.name = name + self.src = src + self.libs = libs + self.defs = defs + self.cells = cells + +TESTS = [] + +### basic sanity tests +# Asynchronous-read RAM + +ASYNC = """ +module top(clk, ra, wa, rd, wd, we); + +localparam ABITS = {abits}; +localparam DBITS = {dbits}; + +input wire clk; +input wire we; +input wire [ABITS-1:0] ra, wa; +input wire [DBITS-1:0] wd; +output wire [DBITS-1:0] rd; + +reg [DBITS-1:0] mem [0:2**ABITS-1]; + +always @(posedge clk) + if (we) + mem[wa] <= wd; + +assign rd = mem[ra]; + +endmodule +""" + +ASYNC_SMALL = ASYNC.format(abits=6, dbits=6) +ASYNC_BIG = ASYNC.format(abits=11, dbits=10) + +TESTS += [ + Test("async_big", ASYNC_BIG, ["lut", "block_tdp"], [], {"RAM_LUT": 384}), + Test("async_big_block", ASYNC_BIG, ["block_tdp"], [], {"RAM_BLOCK_TDP": 0}), + Test("async_small", ASYNC_SMALL, ["lut", "block_tdp"], [], {"RAM_LUT": 8}), + Test("async_small_block", ASYNC_SMALL, ["block_tdp"], [], {"RAM_BLOCK_TDP": 0}), +] + +# Synchronous SDP read first +SYNC = """ +module top(clk, ra, wa, rd, wd, we); + +localparam ABITS = {abits}; +localparam DBITS = {dbits}; + +input wire clk; +input wire we; +input wire [ABITS-1:0] ra, wa; +input wire [DBITS-1:0] wd; +output reg [DBITS-1:0] rd; + +{attr} +reg [DBITS-1:0] mem [0:2**ABITS-1]; + +always @(posedge clk) + if (we) + mem[wa] <= wd; + +always @(posedge clk) + rd <= mem[ra]; + +endmodule +""" + +SYNC_SMALL = SYNC.format(abits=6, dbits=6, attr="") +SYNC_SMALL_BLOCK = SYNC.format(abits=6, dbits=6, attr='(* ram_style="block" *)') +SYNC_BIG = SYNC.format(abits=11, dbits=10, attr="") +SYNC_MID = SYNC.format(abits=6, dbits=16, attr="") + +TESTS += [ + Test("sync_big", SYNC_BIG, ["lut", "block_tdp"], [], {"RAM_BLOCK_TDP": 20}), + Test("sync_big_sdp", SYNC_BIG, ["lut", "block_sdp"], [], {"RAM_BLOCK_SDP": 20}), + Test("sync_big_lut", SYNC_BIG, ["lut"], [], {"RAM_LUT": 384}), + Test("sync_small", SYNC_SMALL, ["lut", "block_tdp"], [], {"RAM_LUT": 8}), + Test("sync_small_block", SYNC_SMALL, ["block_tdp"], [], {"RAM_BLOCK_TDP": 1}), + Test("sync_small_block_attr", SYNC_SMALL_BLOCK, ["lut", "block_tdp"], [], {"RAM_BLOCK_TDP": 1}), +] + +### initialization values testing +LUT_INIT = """ +module top(clk, ra, wa, rd, wd, we); + +localparam ABITS = {abits}; +localparam DBITS = {dbits}; + +input wire clk; +input wire we; +input wire [ABITS-1:0] ra, wa; +input wire [DBITS-1:0] wd; +output wire [DBITS-1:0] rd; + +reg [DBITS-1:0] mem [0:2**ABITS-1]; + +integer i; +initial + for (i = 0; i < 2**ABITS-1; i = i + 1) + mem[i] = {ival}; + +always @(posedge clk) + if (we) + mem[wa] <= wd; + +assign rd = mem[ra]; + +endmodule +""" + +INIT_LUT_ZEROS = LUT_INIT.format(abits=4, dbits=4, ival=0); +INIT_LUT_VAL = LUT_INIT.format(abits=4, dbits=4, ival=5); +INIT_LUT_VAL2 = LUT_INIT.format(abits=6, dbits=6, ival="6'h12"); +INIT_LUT_X = LUT_INIT.format(abits=4, dbits=4, ival="4'hx") + +TESTS += [ + Test("init_lut_zeros_zero", INIT_LUT_ZEROS, ["lut"], ["INIT_ZERO"], {"RAM_LUT":1}), + Test("init_lut_zeros_any", INIT_LUT_ZEROS, ["lut"], ["INIT_ANY"], {"RAM_LUT":1}), + Test("init_lut_val_zero", INIT_LUT_VAL, ["lut"], ["INIT_ZERO"], {"RAM_LUT":0}), #CHECK: no emulation? + Test("init_lut_val_any", INIT_LUT_VAL, ["lut"], ["INIT_ANY"], {"RAM_LUT":1}), + Test("init_lut_val_no_undef", INIT_LUT_VAL, ["lut"], ["INIT_NO_UNDEF"], {"RAM_LUT":1}), + Test("init_lut_val2_any", INIT_LUT_VAL2, ["lut"], ["INIT_ANY"], {"RAM_LUT":8}), + Test("init_lut_val2_no_undef", INIT_LUT_VAL2, ["lut"], ["INIT_NO_UNDEF"], {"RAM_LUT":8}), + Test("init_lut_x_none", INIT_LUT_X, ["lut"], ["INIT_NONE"], {"RAM_LUT":1}), + Test("init_lut_x_zero", INIT_LUT_X, ["lut"], ["INIT_ZERO"], {"RAM_LUT":1}), + Test("init_lut_x_any", INIT_LUT_X, ["lut"], ["INIT_ANY"], {"RAM_LUT":1}), + Test("init_lut_x_no_undef", INIT_LUT_X, ["lut"], ["INIT_NO_UNDEF"], {"RAM_LUT":1}), +] + +### width testing 9-bit-per-byte +RAM_9b1B = """ +module top(clk, ra, wa, rd, wd, we); + +localparam ABITS = {abits}; +localparam DBITS = {dbits}; + +input wire clk; +input wire we; +input wire [ABITS-1:0] ra, wa; +input wire [DBITS-1:0] wd; +output reg [DBITS-1:0] rd; + +reg [DBITS-1:0] mem [0:2**ABITS-1]; + +always @(posedge clk) + if (we) + mem[wa] <= wd; + +always @(posedge clk) + rd <= mem[ra]; + +endmodule +""" + +RAM_18b2B = RAM_9b1B.format(abits=3, dbits=18); +RAM_9b1B = RAM_9b1B.format(abits=4, dbits=9); +RAM_4b1B = RAM_9b1B.format(abits=5, dbits=4); +RAM_2b1B = RAM_9b1B.format(abits=6, dbits=2); +RAM_1b1B = RAM_9b1B.format(abits=7, dbits=1); + +TESTS += [ + Test("ram_18b2B", RAM_18b2B, ["9b1B"], [], {"RAM_9b1B":1}), + Test("ram_9b1B", RAM_9b1B, ["9b1B"], [], {"RAM_9b1B":1}), + Test("ram_4b1B", RAM_4b1B, ["9b1B"], [], {"RAM_9b1B":1}), + Test("ram_2b1B", RAM_2b1B, ["9b1B"], [], {"RAM_9b1B":1}), + Test("ram_1b1B", RAM_1b1B, ["9b1B"], [], {"RAM_9b1B":1}), +] + +### initializing 9-bits-per-byte +RAM_9b1B_init = """ +module top(clk, ra, wa, rd, wd, we); + +localparam ABITS = {abits}; +localparam DBITS = {dbits}; + +input wire clk; +input wire we; +input wire [ABITS-1:0] ra, wa; +input wire [DBITS-1:0] wd; +output reg [DBITS-1:0] rd; + +reg [DBITS-1:0] mem [0:2**ABITS-1]; + +integer i; +initial + for (i = 0; i < 2**ABITS-1; i = i + 1) + mem[i] = {ival}; + +always @(posedge clk) + if (we) + mem[wa] <= wd; + +always @(posedge clk) + rd <= mem[ra]; + +endmodule +""" + +INIT_9b1B_ZEROS = RAM_9b1B_init.format(abits=4, dbits=9, ival=0); +INIT_9b1B_VAL = RAM_9b1B_init.format(abits=4, dbits=9, ival=275); +INIT_13b2B_VAL = RAM_9b1B_init.format(abits=3, dbits=13, ival="13'h01f3") +INIT_18b2B_VAL = RAM_9b1B_init.format(abits=4, dbits=18, ival="18'h1f39a"); +INIT_4b1B_X = RAM_9b1B_init.format(abits=5, dbits=4, ival="4'hx") + +TESTS += [ + Test("init_9b1B_zeros_zero", INIT_9b1B_ZEROS, ["9b1B"], ["INIT_ZERO"], {"RAM_9b1B":1}), + Test("init_9b1B_zeros_any", INIT_9b1B_ZEROS, ["9b1B"], ["INIT_ANY"], {"RAM_9b1B":1}), + Test("init_9b1B_val_zero", INIT_9b1B_VAL, ["9b1B"], ["INIT_ZERO"], {"RAM_9b1B":0}), #CHECK: no emulation? + Test("init_9b1B_val_any", INIT_9b1B_VAL, ["9b1B"], ["INIT_ANY"], {"RAM_9b1B":1}), + Test("init_9b1B_val_no_undef", INIT_9b1B_VAL, ["9b1B"], ["INIT_NO_UNDEF"], {"RAM_9b1B":1}), + Test("init_13b2B_val_any", INIT_13b2B_VAL, ["9b1B"], ["INIT_ANY"], {"RAM_9b1B":1}), + Test("init_18b2B_val_any", INIT_18b2B_VAL, ["9b1B"], ["INIT_ANY"], {"RAM_9b1B":2}), + Test("init_18b2B_val_no_undef", INIT_18b2B_VAL, ["9b1B"], ["INIT_NO_UNDEF"], {"RAM_9b1B":2}), + Test("init_4b1B_x_none", INIT_4b1B_X, ["9b1B"], ["INIT_NONE"], {"RAM_9b1B":1}), + Test("init_4b1B_x_zero", INIT_4b1B_X, ["9b1B"], ["INIT_ZERO"], {"RAM_9b1B":1}), + Test("init_4b1B_x_any", INIT_4b1B_X, ["9b1B"], ["INIT_ANY"], {"RAM_9b1B":1}), + Test("init_4b1B_x_no_undef", INIT_4b1B_X, ["9b1B"], ["INIT_NO_UNDEF"], {"RAM_9b1B":1}), +] + +### Clock polarity combinations +# I'm not entirely convinced auto-test is correctly testing clock edging +# but they do at least all gen/synth +SYNCCLOCK = """ +module top(clk, ra, wa, rd, wd, we); + +localparam ABITS = {abits}; +localparam DBITS = 8; + +input wire clk; +input wire we; +input wire [ABITS-1:0] ra, wa; +input wire [DBITS-1:0] wd; +output reg [DBITS-1:0] rd; + +reg [DBITS-1:0] mem [0:2**ABITS-1]; + +always @(posedge clk) + if (we) + mem[wa] <= wd; + +always @(posedge clk) + rd <= mem[ra]; + +endmodule +""" +for (abits, cnt, wclk, rclk, shared) in [ + (4, 1, "ANY","ANY", False), + (4, 1, "ANY","NEG", False), + (4, 1, "ANY","POS", False), + (4, 1, "NEG","ANY", False), + (4, 1, "NEG","POS", False), + (4, 1, "NEG","NEG", False), + (4, 1, "POS","ANY", False), + (4, 1, "POS","NEG", False), + (4, 1, "POS","POS", False), + (4, 1, "ANY","ANY", True), + (4, 0, "NEG","POS", True), # FF mapping + (4, 1, "NEG","NEG", True), + (4, 0, "POS","NEG", True), # FF mapping + (4, 1, "POS","POS", True), + # cannot combine "ANY" with "POS|NEG" when using shared clock +]: + name = f"clock_a{abits}_w{wclk}r{rclk}s{shared}" + defs = ["WCLK_" + wclk, "RCLK_" + rclk] + if (shared): + defs.append("SHARED_CLK") + TESTS.append(Test( + name, SYNCCLOCK.format(abits=abits), + ["clock_sdp"], defs, {"RAM_CLOCK_SDP": cnt} + )) + +### mixed width testing +# Wide write port +MIXED_WRITE = """ +module top(clk, ra, wa, rd, wd, we); + +localparam WABITS = {wabits}; +localparam WDBITS = {wdbits}; + +localparam RABITS = {rabits}; +localparam RDBITS = {rdbits}; + +input wire clk; +input wire we; +input wire [WABITS-1:0] wa; +input wire [WDBITS-1:0] wd; +input wire [RABITS-1:0] ra; +output reg [RDBITS-1:0] rd; + +localparam DEPTH = (2**WABITS); + +localparam OFFSET = RABITS-WABITS; + +(* syn_ramstyle = "block_ram" *) +reg [WDBITS-1:0] mem [0:DEPTH-1]; + +always @(posedge clk) + if (we) + mem[wa] <= wd; + +if (OFFSET > 0) begin + reg [WDBITS-1:0] mem_read; + reg [OFFSET-1:0] subaddr_r; + always @(posedge clk) begin + mem_read <= mem[ra[RABITS-1:OFFSET]]; + subaddr_r <= ra[OFFSET-1:0]; + end + + always @(mem_read, subaddr_r) + rd <= mem_read[subaddr_r*RDBITS+:RDBITS]; +end +else +begin + always @(posedge clk) + case (OFFSET) + 0: rd <= mem[ra]; + -1: rd <= {{ mem[ra], mem[ra+1] }}; + endcase +end +endmodule +""" + +UNMIXED = MIXED_WRITE.format(wabits=4, wdbits=9, rabits=4, rdbits=9) +MIXED_9_18 = MIXED_WRITE.format(wabits=5, wdbits=9, rabits=4, rdbits=18) +MIXED_18_9 = MIXED_WRITE.format(wabits=3, wdbits=18, rabits=4, rdbits=9) +MIXED_36_9 = MIXED_WRITE.format(wabits=3, wdbits=36, rabits=5, rdbits=9) +MIXED_4_2 = MIXED_WRITE.format(wabits=5, wdbits=4, rabits=6, rdbits=2); + +TESTS += [ + Test("unmixed", UNMIXED, ["9b1B"], [], {"RAM_9b1B":1}), + Test("mixed_9_18", MIXED_9_18, ["9b1B"], [], {"RAM_9b1B":4}), #CHECK: only using half the memory + Test("mixed_18_9", MIXED_18_9, ["9b1B"], [], {"RAM_9b1B":1}), + Test("mixed_36_9", MIXED_36_9, ["9b1B"], [], {"RAM_9b1B":2}), + Test("mixed_4_2", MIXED_4_2, ["9b1B"], [], {"RAM_9b1B":1}), +] + +### basic TDP test + +TDP = """ +module top(clka, clkb, addra, addrb, rda, rdb, wda, wdb, wea, web); + +localparam ABITS = 6; +localparam DBITS = 6; + +input wire clka, clkb; +input wire wea, web; +input wire [ABITS-1:0] addra, addrb; +input wire [DBITS-1:0] wda, wdb; +output reg [DBITS-1:0] rda, rdb; + +reg [DBITS-1:0] mem [0:2**ABITS-1]; + +always @(posedge clka) + if (wea) + mem[addra] <= wda; + else + rda <= mem[addra]; + +always @(posedge clkb) + if (web) + mem[addrb] <= wdb; + else + rdb <= mem[addrb]; + +endmodule +""" + +TESTS += [ + Test("tdp", TDP, ["block_tdp", "block_sdp"], [], {"RAM_BLOCK_TDP": 1}), +] + +# shared clock +# Synchronous SDP with clock domain crossing +SYNC_2CLK = """ +module top(rclk, wclk, ra, wa, rd, wd, we); + +localparam ABITS = 6; +localparam DBITS = 16; + +input wire rclk, wclk; +input wire we; +input wire [ABITS-1:0] ra, wa; +input wire [DBITS-1:0] wd; +output reg [DBITS-1:0] rd; + +reg [DBITS-1:0] mem [0:2**ABITS-1]; + +always @(posedge wclk) + if (we) + mem[wa] <= wd; + +always @(posedge rclk) + rd <= mem[ra]; + +endmodule +""" + +TESTS += [ + Test("sync_2clk", SYNC_2CLK, ["block_sdp"], [], {"RAM_BLOCK_SDP": 1}), + Test("sync_shared", SYNC_MID, ["block_sdp_1clk"], [], {"RAM_BLOCK_SDP_1CLK": 1}), + Test("sync_2clk_shared", SYNC_2CLK, ["block_sdp_1clk"], [], {"RAM_BLOCK_SDP_1CLK": 0}), +] + +# inter-port transparency +# Synchronous SDP with write-first behaviour +SYNC_TRANS = """ +module top(clk, ra, wa, rd, wd, we); + +localparam ABITS = 6; +localparam DBITS = 16; + +input wire clk; +input wire we; +input wire [ABITS-1:0] ra, wa; +input wire [DBITS-1:0] wd; +output reg [DBITS-1:0] rd; + +reg [DBITS-1:0] mem [0:2**ABITS-1]; + +always @(negedge clk) + if (we) + mem[wa] <= wd; + +always @(negedge clk) begin + rd <= mem[ra]; + if (we && ra == wa) + rd <= wd; +end + +endmodule +""" + +TESTS += [ + Test("sync_trans_old_old", SYNC_MID, ["block_sdp_1clk"], ["TRANS_OLD"], {"RAM_BLOCK_SDP_1CLK": (1, {"OPTION_TRANS": 0})}), + Test("sync_trans_old_new", SYNC_MID, ["block_sdp_1clk"], ["TRANS_NEW"], {"RAM_BLOCK_SDP_1CLK": 1}), + Test("sync_trans_old_none", SYNC_MID, ["block_sdp_1clk"], [], {"RAM_BLOCK_SDP_1CLK": 1}), + Test("sync_trans_new_old", SYNC_TRANS, ["block_sdp_1clk"], ["TRANS_OLD"], {"RAM_BLOCK_SDP_1CLK": 1}), + Test("sync_trans_new_new", SYNC_TRANS, ["block_sdp_1clk"], ["TRANS_NEW"], {"RAM_BLOCK_SDP_1CLK": (1, {"OPTION_TRANS": 1})}), + Test("sync_trans_new_none", SYNC_TRANS, ["block_sdp_1clk"], [], {"RAM_BLOCK_SDP_1CLK": 1}), +] + +# rdwr checks +# Synchronous single-port RAM with mutually exclusive read/write +SP_NO_CHANGE = """ +module top(clk, addr, rd, wd, we); + +input wire clk; +input wire we; +input wire [3:0] addr; +input wire [15:0] wd; +output reg [15:0] rd; + +reg [15:0] mem [0:15]; + +always @(negedge clk) begin + if (we) + mem[addr] <= wd; + else + rd <= mem[addr]; +end + +endmodule +""" + +SP_NO_CHANGE_BE = """ +module top(clk, addr, rd, wd, we); + +input wire clk; +input wire [1:0] we; +input wire [3:0] addr; +input wire [15:0] wd; +output reg [15:0] rd; + +reg [15:0] mem [0:15]; + +always @(negedge clk) begin + if (we) begin + if (we[0]) + mem[addr][7:0] <= wd[7:0]; + if (we[1]) + mem[addr][15:8] <= wd[15:8]; + end else + rd <= mem[addr]; +end + +endmodule +""" + +# Synchronous single-port RAM with write-first behaviour +SP_NEW = """ +module top(clk, addr, rd, wd, we); + +input wire clk; +input wire we; +input wire [3:0] addr; +input wire [15:0] wd; +output reg [15:0] rd; + +reg [15:0] mem [0:15]; + +always @(negedge clk) begin + if (we) begin + mem[addr] <= wd; + rd <= wd; + end else + rd <= mem[addr]; +end + +endmodule +""" + +SP_NEW_BE = """ +module top(clk, addr, rd, wd, we); + +input wire clk; +input wire [1:0] we; +input wire [3:0] addr; +input wire [15:0] wd; +output reg [15:0] rd; + +reg [15:0] mem [0:15]; + +always @(negedge clk) begin + rd <= mem[addr]; + if (we[0]) begin + mem[addr][7:0] <= wd[7:0]; + rd[7:0] <= wd[7:0]; + end + if (we[1]) begin + mem[addr][15:8] <= wd[15:8]; + rd[15:8] <= wd[15:8]; + end +end + +endmodule +""" + +# Synchronous single-port RAM with read-first behaviour +SP_OLD = """ +module top(clk, addr, rd, wd, we); + +input wire clk; +input wire we; +input wire [3:0] addr; +input wire [15:0] wd; +output reg [15:0] rd; + +reg [15:0] mem [0:15]; + +always @(negedge clk) begin + if (we) + mem[addr] <= wd; + rd <= mem[addr]; +end + +endmodule +""" + +SP_OLD_BE = """ +module top(clk, addr, rd, wd, we); + +input wire clk; +input wire [1:0] we; +input wire [3:0] addr; +input wire [15:0] wd; +output reg [15:0] rd; + +reg [15:0] mem [0:15]; + +always @(negedge clk) begin + if (we[0]) + mem[addr][7:0] <= wd[7:0]; + if (we[1]) + mem[addr][15:8] <= wd[15:8]; + rd <= mem[addr]; +end + +endmodule +""" + +TESTS += [ + Test("sp_nc_none", SP_NO_CHANGE, ["block_sp"], [], {"RAM_BLOCK_SP": 1}), + Test("sp_new_none", SP_NEW, ["block_sp"], [], {"RAM_BLOCK_SP": 1}), + Test("sp_old_none", SP_OLD, ["block_sp"], [], {"RAM_BLOCK_SP": 0}), + Test("sp_nc_nc", SP_NO_CHANGE, ["block_sp"], ["RDWR_NO_CHANGE"], {"RAM_BLOCK_SP": 1}), + Test("sp_new_nc", SP_NEW, ["block_sp"], ["RDWR_NO_CHANGE"], {"RAM_BLOCK_SP": 1}), + Test("sp_old_nc", SP_OLD, ["block_sp"], ["RDWR_NO_CHANGE"], {"RAM_BLOCK_SP": 0}), + Test("sp_nc_new", SP_NO_CHANGE, ["block_sp"], ["RDWR_NEW"], {"RAM_BLOCK_SP": 1}), + Test("sp_new_new", SP_NEW, ["block_sp"], ["RDWR_NEW"], {"RAM_BLOCK_SP": 1}), + Test("sp_old_new", SP_OLD, ["block_sp"], ["RDWR_NEW"], {"RAM_BLOCK_SP": 0}), + Test("sp_nc_old", SP_NO_CHANGE, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_new_old", SP_NEW, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_old_old", SP_OLD, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_nc_new_only", SP_NO_CHANGE, ["block_sp"], ["RDWR_NEW_ONLY"], {"RAM_BLOCK_SP": 1}), + Test("sp_new_new_only", SP_NEW, ["block_sp"], ["RDWR_NEW_ONLY"], {"RAM_BLOCK_SP": 1}), + Test("sp_old_new_only", SP_OLD, ["block_sp"], ["RDWR_NEW_ONLY"], {"RAM_BLOCK_SP": 0}), + Test("sp_nc_new_only_be", SP_NO_CHANGE_BE, ["block_sp"], ["RDWR_NEW_ONLY"], {"RAM_BLOCK_SP": 1}), + Test("sp_new_new_only_be", SP_NEW_BE, ["block_sp"], ["RDWR_NEW_ONLY"], {"RAM_BLOCK_SP": 2}), + Test("sp_old_new_only_be", SP_OLD_BE, ["block_sp"], ["RDWR_NEW_ONLY"], {"RAM_BLOCK_SP": 0}), + Test("sp_nc_new_be", SP_NO_CHANGE_BE, ["block_sp"], ["RDWR_NEW"], {"RAM_BLOCK_SP": 1}), + Test("sp_new_new_be", SP_NEW_BE, ["block_sp"], ["RDWR_NEW"], {"RAM_BLOCK_SP": 1}), + Test("sp_old_new_be", SP_OLD_BE, ["block_sp"], ["RDWR_NEW"], {"RAM_BLOCK_SP": 0}), + Test("sp_nc_old_be", SP_NO_CHANGE_BE, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_new_old_be", SP_NEW_BE, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_old_old_be", SP_OLD_BE, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_nc_nc_be", SP_NO_CHANGE_BE, ["block_sp"], ["RDWR_NO_CHANGE"], {"RAM_BLOCK_SP": 1}), + Test("sp_new_nc_be", SP_NEW_BE, ["block_sp"], ["RDWR_NO_CHANGE"], {"RAM_BLOCK_SP": 2}), + Test("sp_old_nc_be", SP_OLD_BE, ["block_sp"], ["RDWR_NO_CHANGE"], {"RAM_BLOCK_SP": 0}), + Test("sp_nc_auto", SP_NO_CHANGE, ["block_sp"], ["RDWR_NO_CHANGE", "RDWR_OLD", "RDWR_NEW"], {"RAM_BLOCK_SP": 1}), + Test("sp_new_auto", SP_NEW, ["block_sp"], ["RDWR_NO_CHANGE", "RDWR_OLD", "RDWR_NEW"], {"RAM_BLOCK_SP": (1, {"OPTION_RDWR": "NEW"})}), + Test("sp_old_auto", SP_OLD, ["block_sp"], ["RDWR_NO_CHANGE", "RDWR_OLD", "RDWR_NEW"], {"RAM_BLOCK_SP": (1, {"OPTION_RDWR": "OLD"})}), + Test("sp_nc_auto_be", SP_NO_CHANGE_BE, ["block_sp"], ["RDWR_NO_CHANGE", "RDWR_OLD", "RDWR_NEW"], {"RAM_BLOCK_SP": 1}), + Test("sp_new_auto_be", SP_NEW_BE, ["block_sp"], ["RDWR_NO_CHANGE", "RDWR_OLD", "RDWR_NEW"], {"RAM_BLOCK_SP": (1, {"OPTION_RDWR": "NEW"})}), + Test("sp_old_auto_be", SP_OLD_BE, ["block_sp"], ["RDWR_NO_CHANGE", "RDWR_OLD", "RDWR_NEW"], {"RAM_BLOCK_SP": (1, {"OPTION_RDWR": "OLD"})}), +] + +# Synchronous read port with initial value +SP_INIT = """ +module top(clk, addr, rd, wd, we, re); + +input wire clk; +input wire we, re; +input wire [3:0] addr; +input wire [15:0] wd; +output reg [15:0] rd; + +reg [15:0] mem [0:15]; + +initial rd = {ival}; + +always @(posedge clk) begin + if (we) + mem[addr] <= wd; + if (re) + rd <= mem[addr]; +end + +endmodule +""" + +SP_INIT_X = SP_INIT.format(ival="16'hxxxx") +SP_INIT_0 = SP_INIT.format(ival="16'h0000") +SP_INIT_V = SP_INIT.format(ival="16'h55aa") + +TESTS += [ + Test("sp_init_x_x", SP_INIT_X, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_init_x_x_re", SP_INIT_X, ["block_sp"], ["RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_init_x_x_ce", SP_INIT_X, ["block_sp"], ["CLKEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_init_0_x", SP_INIT_0, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_init_0_x_re", SP_INIT_0, ["block_sp"], ["RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_init_0_0", SP_INIT_0, ["block_sp"], ["RDINIT_0", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_init_0_0_re", SP_INIT_0, ["block_sp"], ["RDINIT_0", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_init_0_any", SP_INIT_0, ["block_sp"], ["RDINIT_ANY", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_init_0_any_re", SP_INIT_0, ["block_sp"], ["RDINIT_ANY", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_init_v_x", SP_INIT_V, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_init_v_x_re", SP_INIT_V, ["block_sp"], ["RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_init_v_0", SP_INIT_V, ["block_sp"], ["RDINIT_0", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_init_v_0_re", SP_INIT_V, ["block_sp"], ["RDINIT_0", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_init_v_any", SP_INIT_V, ["block_sp"], ["RDINIT_ANY", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_init_v_any_re", SP_INIT_V, ["block_sp"], ["RDINIT_ANY", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), +] + +# Synchronous read port with asynchronous reset +SP_ARST = """ +module top(clk, addr, rd, wd, we, re, ar); + +input wire clk; +input wire we, re, ar; +input wire [3:0] addr; +input wire [15:0] wd; +output reg [15:0] rd; + +reg [15:0] mem [0:15]; + +initial rd = {ival}; + +always @(posedge clk) begin + if (we) + mem[addr] <= wd; +end +always @(posedge clk, posedge ar) begin + if (ar) + rd <= {aval}; + else if (re) + rd <= mem[addr]; +end + +endmodule +""" + +SP_ARST_X = SP_ARST.format(ival="16'hxxxx", aval="16'hxxxx") +SP_ARST_0 = SP_ARST.format(ival="16'hxxxx", aval="16'h0000") +SP_ARST_V = SP_ARST.format(ival="16'hxxxx", aval="16'h55aa") +SP_ARST_E = SP_ARST.format(ival="16'h55aa", aval="16'h55aa") +SP_ARST_N = SP_ARST.format(ival="16'h1234", aval="16'h55aa") + +TESTS += [ + Test("sp_arst_x_x", SP_ARST_X, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_x_x_re", SP_ARST_X, ["block_sp"], ["RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_0_x", SP_ARST_0, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_0_x_re", SP_ARST_0, ["block_sp"], ["RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_0_0", SP_ARST_0, ["block_sp"], ["RDINIT_ANY", "RDARST_0", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_0_0_re", SP_ARST_0, ["block_sp"], ["RDINIT_ANY", "RDARST_0", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_0_any", SP_ARST_0, ["block_sp"], ["RDINIT_ANY", "RDARST_ANY", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_0_any_re", SP_ARST_0, ["block_sp"], ["RDINIT_ANY", "RDARST_ANY", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_0_init", SP_ARST_0, ["block_sp"], ["RDINIT_ANY", "RDARST_INIT", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_0_init_re", SP_ARST_0, ["block_sp"], ["RDINIT_ANY", "RDARST_INIT", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_v_x", SP_ARST_V, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_v_x_re", SP_ARST_V, ["block_sp"], ["RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_v_0", SP_ARST_V, ["block_sp"], ["RDINIT_ANY", "RDARST_0", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_v_0_re", SP_ARST_V, ["block_sp"], ["RDINIT_ANY", "RDARST_0", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_v_any", SP_ARST_V, ["block_sp"], ["RDINIT_ANY", "RDARST_ANY", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_v_any_re", SP_ARST_V, ["block_sp"], ["RDINIT_ANY", "RDARST_ANY", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_v_init", SP_ARST_V, ["block_sp"], ["RDINIT_ANY", "RDARST_INIT", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_v_init_re", SP_ARST_V, ["block_sp"], ["RDINIT_ANY", "RDARST_INIT", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_e_x", SP_ARST_E, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_e_x_re", SP_ARST_E, ["block_sp"], ["RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_e_0", SP_ARST_E, ["block_sp"], ["RDINIT_ANY", "RDARST_0", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_e_0_re", SP_ARST_E, ["block_sp"], ["RDINIT_ANY", "RDARST_0", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_e_any", SP_ARST_E, ["block_sp"], ["RDINIT_ANY", "RDARST_ANY", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_e_any_re", SP_ARST_E, ["block_sp"], ["RDINIT_ANY", "RDARST_ANY", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_e_init", SP_ARST_E, ["block_sp"], ["RDINIT_ANY", "RDARST_INIT", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_e_init_re", SP_ARST_E, ["block_sp"], ["RDINIT_ANY", "RDARST_INIT", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_n_x", SP_ARST_N, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_n_x_re", SP_ARST_N, ["block_sp"], ["RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_n_0", SP_ARST_N, ["block_sp"], ["RDINIT_ANY", "RDARST_0", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_n_0_re", SP_ARST_N, ["block_sp"], ["RDINIT_ANY", "RDARST_0", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_n_any", SP_ARST_N, ["block_sp"], ["RDINIT_ANY", "RDARST_ANY", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_n_any_re", SP_ARST_N, ["block_sp"], ["RDINIT_ANY", "RDARST_ANY", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_n_init", SP_ARST_N, ["block_sp"], ["RDINIT_ANY", "RDARST_INIT", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_arst_n_init_re", SP_ARST_N, ["block_sp"], ["RDINIT_ANY", "RDARST_INIT", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), +] + +# Synchronous read port with synchronous reset (reset priority over enable) +SP_SRST = """ +module top(clk, addr, rd, wd, we, re, sr); + +input wire clk; +input wire we, re, sr; +input wire [3:0] addr; +input wire [15:0] wd; +output reg [15:0] rd; + +reg [15:0] mem [0:15]; + +initial rd = {ival}; + +always @(posedge clk) begin + if (we) + mem[addr] <= wd; +end +always @(posedge clk) begin + if (sr) + rd <= {sval}; + else if (re) + rd <= mem[addr]; +end + +endmodule +""" + +# Synchronous read port with synchronous reet (enable priority over reset) +SP_SRST_G = """ +module top(clk, addr, rd, wd, we, re, sr); + +input wire clk; +input wire we, re, sr; +input wire [3:0] addr; +input wire [15:0] wd; +output reg [15:0] rd; + +reg [15:0] mem [0:15]; + +initial rd = {ival}; + +always @(posedge clk) begin + if (we) + mem[addr] <= wd; +end +always @(posedge clk) begin + if (re) begin + if (sr) + rd <= {sval}; + else + rd <= mem[addr]; + end +end + +endmodule +""" + +SP_SRST_X = SP_SRST.format(ival="16'hxxxx", sval="16'hxxxx") +SP_SRST_0 = SP_SRST.format(ival="16'hxxxx", sval="16'h0000") +SP_SRST_V = SP_SRST.format(ival="16'hxxxx", sval="16'h55aa") +SP_SRST_E = SP_SRST.format(ival="16'h55aa", sval="16'h55aa") +SP_SRST_N = SP_SRST.format(ival="16'h1234", sval="16'h55aa") +SP_SRST_GV = SP_SRST_G.format(ival="16'hxxxx", sval="16'h55aa") + +TESTS += [ + Test("sp_srst_x_x", SP_SRST_X, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_x_x_re", SP_SRST_X, ["block_sp"], ["RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_0_x", SP_SRST_0, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_0_x_re", SP_SRST_0, ["block_sp"], ["RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_0_0", SP_SRST_0, ["block_sp"], ["RDINIT_ANY", "RDSRST_0", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_0_0_re", SP_SRST_0, ["block_sp"], ["RDINIT_ANY", "RDSRST_0", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_0_any", SP_SRST_0, ["block_sp"], ["RDINIT_ANY", "RDSRST_ANY", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_0_any_re", SP_SRST_0, ["block_sp"], ["RDINIT_ANY", "RDSRST_ANY", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_0_init", SP_SRST_0, ["block_sp"], ["RDINIT_ANY", "RDSRST_INIT", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_0_init_re", SP_SRST_0, ["block_sp"], ["RDINIT_ANY", "RDSRST_INIT", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_v_x", SP_SRST_V, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_v_x_re", SP_SRST_V, ["block_sp"], ["RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_v_0", SP_SRST_V, ["block_sp"], ["RDINIT_ANY", "RDSRST_0", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_v_0_re", SP_SRST_V, ["block_sp"], ["RDINIT_ANY", "RDSRST_0", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_v_any", SP_SRST_V, ["block_sp"], ["RDINIT_ANY", "RDSRST_ANY", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_v_any_re", SP_SRST_V, ["block_sp"], ["RDINIT_ANY", "RDSRST_ANY", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_v_any_re_gated", SP_SRST_V, ["block_sp"], ["RDINIT_ANY", "RDSRST_ANY_RE", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_v_any_ce", SP_SRST_V, ["block_sp"], ["RDINIT_ANY", "RDSRST_ANY", "CLKEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_v_any_ce_gated", SP_SRST_V, ["block_sp"], ["RDINIT_ANY", "RDSRST_ANY_CE", "CLKEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_v_init", SP_SRST_V, ["block_sp"], ["RDINIT_ANY", "RDSRST_INIT", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_v_init_re", SP_SRST_V, ["block_sp"], ["RDINIT_ANY", "RDSRST_INIT", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_e_x", SP_SRST_E, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_e_x_re", SP_SRST_E, ["block_sp"], ["RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_e_0", SP_SRST_E, ["block_sp"], ["RDINIT_ANY", "RDSRST_0", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_e_0_re", SP_SRST_E, ["block_sp"], ["RDINIT_ANY", "RDSRST_0", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_e_any", SP_SRST_E, ["block_sp"], ["RDINIT_ANY", "RDSRST_ANY", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_e_any_re", SP_SRST_E, ["block_sp"], ["RDINIT_ANY", "RDSRST_ANY", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_e_init", SP_SRST_E, ["block_sp"], ["RDINIT_ANY", "RDSRST_INIT", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_e_init_re", SP_SRST_E, ["block_sp"], ["RDINIT_ANY", "RDSRST_INIT", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_n_x", SP_SRST_N, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_n_x_re", SP_SRST_N, ["block_sp"], ["RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_n_0", SP_SRST_N, ["block_sp"], ["RDINIT_ANY", "RDSRST_0", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_n_0_re", SP_SRST_N, ["block_sp"], ["RDINIT_ANY", "RDSRST_0", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_n_any", SP_SRST_N, ["block_sp"], ["RDINIT_ANY", "RDSRST_ANY", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_n_any_re", SP_SRST_N, ["block_sp"], ["RDINIT_ANY", "RDSRST_ANY", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_n_init", SP_SRST_N, ["block_sp"], ["RDINIT_ANY", "RDSRST_INIT", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_n_init_re", SP_SRST_N, ["block_sp"], ["RDINIT_ANY", "RDSRST_INIT", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_gv_x", SP_SRST_GV, ["block_sp"], ["RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_gv_x_re", SP_SRST_GV, ["block_sp"], ["RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_gv_0", SP_SRST_GV, ["block_sp"], ["RDINIT_ANY", "RDSRST_0", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_gv_0_re", SP_SRST_GV, ["block_sp"], ["RDINIT_ANY", "RDSRST_0", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_gv_any", SP_SRST_GV, ["block_sp"], ["RDINIT_ANY", "RDSRST_ANY", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_gv_any_re", SP_SRST_GV, ["block_sp"], ["RDINIT_ANY", "RDSRST_ANY", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_gv_any_re_gated", SP_SRST_GV, ["block_sp"], ["RDINIT_ANY", "RDSRST_ANY_RE", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_gv_any_ce", SP_SRST_GV, ["block_sp"], ["RDINIT_ANY", "RDSRST_ANY", "CLKEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_gv_any_ce_gated", SP_SRST_GV, ["block_sp"], ["RDINIT_ANY", "RDSRST_ANY_CE", "CLKEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_gv_init", SP_SRST_GV, ["block_sp"], ["RDINIT_ANY", "RDSRST_INIT", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), + Test("sp_srst_gv_init_re", SP_SRST_GV, ["block_sp"], ["RDINIT_ANY", "RDSRST_INIT", "RDEN", "RDWR_OLD"], {"RAM_BLOCK_SP": 1}), +] + +# Byte enables, wrbe_separate +SYNC_ENABLE = """ +module top(clk, rwa, rd, wd, we); + +localparam ABITS = {abits}; +localparam DBITS = {dbits}; + +input wire clk; +input wire we; +input wire [ABITS-1:0] rwa; +input wire [DBITS-1:0] wd; +output reg [DBITS-1:0] rd; + +reg [DBITS-1:0] mem [0:2**ABITS-1]; + +always @(posedge clk) begin + if (we) + mem[rwa] <= wd; + else + rd <= mem[rwa]; +end + +endmodule +""" + +for (abits, dbits, sep, defs, cells) in [ + (4, 4, False, ["NO_BYTE"], {"RAM_WREN": 1}), + (5, 4, False, ["NO_BYTE"], {"RAM_WREN": 2}), + (6, 4, False, ["NO_BYTE"], {"RAM_WREN": 4}), + # (4, 4, True, ["NO_BYTE"], {"RAM_WREN": 1}), # should throw an error + (3, 8, False, ["NO_BYTE"], {"RAM_WREN": 2}), # needs two write ports + (4, 8, False, ["NO_BYTE"], {"RAM_WREN": 2}), + (4, 4, False, ["W4_B4"], {"RAM_WREN": 1}), + (4, 8, True, ["W4_B4"], {"RAM_WREN": 2}), + (4, 8, False, ["W8_B4"], {"RAM_WREN": 1}), + (4, 8, True, ["W8_B4"], {"RAM_WREN": 1}), + (4, 8, False, ["W8_B8"], {"RAM_WREN": 1}), + (4, 8, True, ["W8_B8"], {"RAM_WREN": 1}), + +]: + name = f"wren_a{abits}d{dbits}_{defs[0]}" + if (sep): + defs.append("WRBE_SEPARATE") + name += "_separate" + + TESTS.append(Test( + name, SYNC_ENABLE.format(abits=abits, dbits=dbits), + ["wren"], defs, cells + )) + +# Write port with byte enables +ENABLES = """ +module top(clk, we, be, rwa, wd, rd); + +localparam ABITS = {abits}; +localparam WBITS = {wbits}; +localparam WORDS = {words}; + +input wire clk; +input wire we; +input wire [WORDS-1:0] be; +input wire [ABITS-1:0] rwa; +input wire [(WBITS*WORDS)-1:0] wd; +output reg [(WBITS*WORDS)-1:0] rd; + +reg [(WBITS*WORDS)-1:0] mem [0:2**ABITS-1]; + +integer i; +always @(posedge clk) + for (i=0; i> {bw}]) + for (j = 0; j < 2**{bw}; j = j + 1) + mem[wa << {ww} | i | j] <= wd[i | j]; + +always @(posedge rclk) + if (rr) + rd <= {sval}; + else if (re) + for (i = 0; i < 2**{rw}; i = i + 1) + rd[i] <= mem[ra << {rw} | i]; + +endmodule +""" + +for (aw, rw, ww, bw, xw, sval, cnt) in [ + (6, 1, 1, 1, 1, "2'h1", 1), + (7, 1, 1, 1, 1, "2'h2", 2), + (8, 1, 1, 1, 1, "2'h3", 4), + (6, 0, 0, 0, 0, "2'h0", 1), + (6, 1, 0, 0, 0, "2'h0", 1), + (6, 2, 0, 0, 0, "2'h0", 1), + (6, 3, 0, 0, 0, "2'h0", 1), + (6, 4, 0, 0, 0, "2'h0", 1), + (6, 5, 0, 0, 0, "2'h0", 2), + (6, 0, 1, 0, 0, "2'h0", 2), + (6, 0, 1, 1, 0, "2'h0", 1), + (6, 0, 2, 0, 0, "2'h0", 4), + (6, 0, 2, 2, 0, "2'h0", 1), + (6, 0, 3, 2, 0, "2'h0", 1), + (6, 0, 4, 2, 0, "2'h0", 1), + (6, 0, 5, 2, 0, "2'h0", 2), + (7, 0, 0, 0, 0, "2'h0", 2), + (7, 1, 0, 0, 0, "2'h0", 2), + (7, 2, 0, 0, 0, "2'h0", 2), + (7, 3, 0, 0, 0, "2'h0", 2), + (7, 4, 0, 0, 0, "2'h0", 2), + (7, 5, 0, 0, 0, "2'h0", 2), + (7, 0, 1, 0, 0, "2'h0", 2), + (7, 0, 1, 1, 0, "2'h0", 2), + (7, 0, 2, 0, 0, "2'h0", 4), + (7, 0, 2, 2, 0, "2'h0", 2), + (7, 0, 3, 2, 0, "2'h0", 2), + (7, 0, 4, 2, 0, "2'h0", 2), + (7, 0, 5, 2, 0, "2'h0", 2), +]: + TESTS.append(Test( + f"wide_sdp_a{aw}r{rw}w{ww}b{bw}x{xw}", + WIDE_SDP.format(aw=aw, rw=rw, ww=ww, bw=bw, xw=xw, sval=sval), + ["wide_sdp"], [], + {"RAM_WIDE_SDP": cnt} + )) + +WIDE_SP = """ +module top(clk, a, rd, re, rr, wd, we); + +input wire clk, re, rr; +input wire [2**({ww}-{bw})-1:0] we; +input wire [{aw}-1:0] a; +input wire [2**{ww}-1:0] wd; +output reg [2**{rw}-1:0] rd; + +reg mem [0:2**{aw}-1]; + +initial mem[3] = 0; +initial mem[17] = 1; +initial mem[23] = 0; +initial mem[24] = 1; + +integer i, j; +always @(posedge clk) begin + for (i = 0; i < 2**{ww}; i = i + 2**{bw}) + if (we[i >> {bw}]) + for (j = 0; j < 2**{bw}; j = j + 1) + mem[a & ~((1 << {ww}) - 1) | i | j] <= wd[i | j]; + if (rr) + rd <= {sval}; + else if (re) + for (i = 0; i < 2**{rw}; i = i + 1) + rd[i] <= mem[a & ~((1 << {rw}) - 1) | i]; +end + +endmodule +""" + +for (aw, rw, ww, bw, sval, cnt) in [ + (6, 1, 1, 1, "2'h1", 1), + (7, 1, 1, 1, "2'h2", 2), + (8, 1, 1, 1, "2'h3", 4), + (6, 0, 0, 0, "2'h0", 1), + (6, 1, 0, 0, "2'h0", 1), + (6, 2, 0, 0, "2'h0", 1), + (6, 3, 0, 0, "2'h0", 1), + (6, 4, 0, 0, "2'h0", 1), + (6, 5, 0, 0, "2'h0", 2), + (6, 0, 1, 0, "2'h0", 2), + (6, 0, 1, 1, "2'h0", 1), + (6, 0, 2, 0, "2'h0", 4), + (6, 0, 2, 2, "2'h0", 1), + (6, 0, 3, 2, "2'h0", 1), + (6, 0, 4, 2, "2'h0", 1), + (6, 0, 5, 2, "2'h0", 2), + (7, 0, 0, 0, "2'h0", 2), + (7, 1, 0, 0, "2'h0", 2), + (7, 2, 0, 0, "2'h0", 2), + (7, 3, 0, 0, "2'h0", 2), + (7, 4, 0, 0, "2'h0", 2), + (7, 5, 0, 0, "2'h0", 2), + (7, 0, 1, 0, "2'h0", 2), + (7, 0, 1, 1, "2'h0", 2), + (7, 0, 2, 0, "2'h0", 4), + (7, 0, 2, 2, "2'h0", 2), + (7, 0, 3, 2, "2'h0", 2), + (7, 0, 4, 2, "2'h0", 2), + (7, 0, 5, 2, "2'h0", 2), +]: + TESTS.append(Test( + f"wide_sp_mix_a{aw}r{rw}w{ww}b{bw}", + WIDE_SP.format(aw=aw, rw=rw, ww=ww, bw=bw, sval=sval), + ["wide_sp"], ["WIDTH_MIX"], + {"RAM_WIDE_SP": cnt} + )) + +for (aw, rw, ww, bw, sval, cnt) in [ + (6, 1, 1, 1, "2'h1", 1), + (7, 1, 1, 1, "2'h2", 2), + (8, 1, 1, 1, "2'h3", 4), + (6, 0, 0, 0, "2'h0", 1), + (6, 1, 0, 0, "2'h0", 2), + (6, 2, 0, 0, "2'h0", 4), + (6, 3, 0, 0, "2'h0", 4), + (6, 4, 0, 0, "2'h0", 4), + (6, 5, 0, 0, "2'h0", 8), + (6, 0, 1, 0, "2'h0", 2), + (6, 0, 1, 1, "2'h0", 1), + (6, 0, 2, 0, "2'h0", 4), + (6, 0, 2, 2, "2'h0", 1), + (6, 0, 3, 2, "2'h0", 1), + (6, 0, 4, 2, "2'h0", 1), + (6, 0, 5, 2, "2'h0", 2), + (7, 0, 0, 0, "2'h0", 2), + (7, 1, 0, 0, "2'h0", 2), + (7, 2, 0, 0, "2'h0", 4), + (7, 3, 0, 0, "2'h0", 8), + (7, 4, 0, 0, "2'h0", 8), + (7, 5, 0, 0, "2'h0", 8), + (7, 0, 1, 0, "2'h0", 2), + (7, 0, 1, 1, "2'h0", 2), + (7, 0, 2, 0, "2'h0", 4), + (7, 0, 2, 2, "2'h0", 2), + (7, 0, 3, 2, "2'h0", 2), + (7, 0, 4, 2, "2'h0", 2), + (7, 0, 5, 2, "2'h0", 2), +]: + TESTS.append(Test( + f"wide_sp_tied_a{aw}r{rw}w{ww}b{bw}", + WIDE_SP.format(aw=aw, rw=rw, ww=ww, bw=bw, sval=sval), + ["wide_sp"], [], + {"RAM_WIDE_SP": cnt} + )) + +WIDE_RW = """ +module top(clk, a, rd, re, wd, we); + +input wire clk, re; +input wire [2**({ww}-{bw})-1:0] we; +input wire [{aw}-1:0] a; +input wire [2**{ww}-1:0] wd; +output reg [2**{rw}-1:0] rd; + +(* ram_block *) +reg mem [0:2**{aw}-1]; + +initial mem[3] = 0; +initial mem[17] = 1; +initial mem[23] = 0; +initial mem[24] = 1; + +integer i, j; +always @(posedge clk) begin + for (i = 0; i < 2**{ww}; i = i + 2**{bw}) + if (we[i >> {bw}]) + for (j = 0; j < 2**{bw}; j = j + 1) + mem[a & ~((1 << {ww}) - 1) | i | j] <= wd[i | j]; + if (re) + for (i = 0; i < 2**{rw}; i = i + 1) + rd[i] <= mem[a & ~((1 << {rw}) - 1) | i]; +end + +endmodule +""" + +for (aw, rw, ww, bw, cntww, cntwr) in [ + (6, 1, 1, 1, 2, 1), + (7, 1, 1, 1, 4, 2), + (8, 1, 1, 1, 8, 4), + (6, 0, 0, 0, 4, 2), + (6, 1, 0, 0, 4, 2), + (6, 2, 0, 0, 4, 2), + (6, 3, 0, 0, 8, 2), + (6, 4, 0, 0, 16, 4), + (6, 5, 0, 0, 32, 8), + (6, 0, 1, 0, 4, 2), + (6, 0, 1, 1, 2, 1), + (6, 0, 2, 0, 4, 4), + (6, 0, 2, 2, 1, 2), + (6, 0, 3, 2, 1, 4), + (6, 0, 4, 2, 2, 8), + (6, 0, 5, 2, 4, 16), + (7, 0, 0, 0, 8, 4), + (7, 1, 0, 0, 8, 4), + (7, 2, 0, 0, 8, 4), + (7, 3, 0, 0, 8, 4), + (7, 4, 0, 0, 16, 4), + (7, 5, 0, 0, 32, 8), + (7, 0, 1, 0, 8, 4), + (7, 0, 1, 1, 4, 2), + (7, 0, 2, 0, 8, 4), + (7, 0, 2, 2, 2, 2), + (7, 0, 3, 2, 2, 4), + (7, 0, 4, 2, 2, 8), + (7, 0, 5, 2, 4, 16), +]: + TESTS.append(Test( + f"wide_read_a{aw}r{rw}w{ww}b{bw}", + WIDE_RW.format(aw=aw, rw=rw, ww=ww, bw=bw), + ["wide_read"], [], + {"RAM_WIDE_READ": cntwr} + )) + TESTS.append(Test( + f"wide_write_a{aw}r{rw}w{ww}b{bw}", + WIDE_RW.format(aw=aw, rw=rw, ww=ww, bw=bw), + ["wide_write"], [], + {"RAM_WIDE_WRITE": cntww} + )) + +# Multiple read ports +# 1rw port plus 3 (or 7) r ports +QUAD_PORT = """ +module top(clk, rwa, r0a, r1a, r2a, rd, r0d, r1d, r2d, wd, we); + +localparam ABITS = {abits}; +localparam DBITS = {dbits}; + +input wire clk; +input wire we; +input wire [ABITS-1:0] rwa; +input wire [ABITS-1:0] r0a; +input wire [ABITS-1:0] r1a; +input wire [ABITS-1:0] r2a; +input wire [DBITS-1:0] wd; +output wire [DBITS-1:0] rd; +output wire [DBITS-1:0] r0d; +output wire [DBITS-1:0] r1d; +output wire [DBITS-1:0] r2d; + +reg [DBITS-1:0] mem [0:2**ABITS-1]; + +always @(posedge clk) + if (we) + mem[rwa] <= wd; + +assign rd = mem[rwa]; +assign r0d = mem[r0a]; +assign r1d = mem[r1a]; +assign r2d = mem[r2a]; + +endmodule +""" + +for (abits, dbits, cnt) in [ + (2, 2, 1), + (4, 2, 1), + (5, 2, 2), + (4, 4, 2), + (6, 2, 4), + (4, 8, 4), +]: + TESTS.append(Test( + f"quad_port_a{abits}d{dbits}", + QUAD_PORT.format(abits=abits, dbits=dbits), + ["multilut"], ["PORTS_QUAD"], + {"LUT_MULTI": cnt} + )) + +# Wide asynchronous read port +WIDE_READ = """ +module top(clk, we, rwa, wd, rd); + +localparam ABITS = {abits}; +localparam WBITS = {wbits}; +localparam RWORDS = {rwords}; + +input wire clk; +input wire we; +input wire [ABITS-1:0] rwa; +input wire [WBITS-1:0] wd; +output wire [(WBITS*RWORDS)-1:0] rd; + +reg [WBITS-1:0] mem [0:2**ABITS-1]; + +always @(posedge clk) + if (we) + mem[rwa] <= wd; + +genvar i; +generate + for (i = 0; i < RWORDS; i = i + 1) + assign rd[i*WBITS+:WBITS] = mem[rwa + i]; +endgenerate + +endmodule +""" + +for (abits, wbits, rwords, cntquad, cntoct) in [ + (4, 2, 1, 1, 1), + (4, 2, 2, 1, 1), + (4, 2, 3, 1, 1), + (4, 2, 4, 1, 1), + (4, 2, 5, 2, 1), + (4, 2, 6, 2, 1), + (4, 2, 7, 2, 1), # Write port needs to be duplicated, so only 3 extra read + (4, 2, 8, 3, 1), # ports per quad port LUT (i.e. 7 ports in 2, 8 ports in 3) + (4, 2, 9, 3, 2), + (4, 4, 1, 2, 2), + (4, 4, 4, 2, 2), + (4, 4, 6, 4, 2), + (4, 4, 9, 6, 4), + (5, 2, 1, 2, 2), + (5, 2, 4, 2, 2), + (5, 2, 9, 6, 4), +]: + TESTS.append(Test( + f"wide_quad_a{abits}w{wbits}r{rwords}", + WIDE_READ.format(abits=abits, wbits=wbits, rwords=rwords), + ["multilut"], ["PORTS_QUAD"], + {"LUT_MULTI": cntquad} + )) + TESTS.append(Test( + f"wide_oct_a{abits}w{wbits}r{rwords}", + WIDE_READ.format(abits=abits, wbits=wbits, rwords=rwords), + ["multilut"], ["PORTS_OCT"], + {"LUT_MULTI": cntoct} + )) + +# signal priorities & pattern testing +PRIORITY = """ +module top(clk, clken, wren, wben, rden, rst, addr, wdata, rdata); + +localparam ABITS = {abits}; +localparam WBITS = {wbits}; +localparam WORDS = {words}; + +localparam BITS = WBITS * WORDS; + +input wire clk, clken; +input wire wren, rden, rst; +input wire [WORDS-1:0] wben; +input wire [ABITS-1:0] addr; +input wire [BITS-1:0] wdata; +output reg [BITS-1:0] rdata; + +reg [BITS-1:0] mem [0:2**ABITS-1]; + +integer i; +always @(posedge clk) begin +{code} +end +endmodule +""" +#reset_gate in ["ungated", "rst", "rden && rst"] +#clk_en in [True, False] +#rdwr in ["nc", "old", "new", "undef", "newdef"] + +for (testname, reset_gate, rdwr, clk_en, add_logic) in [ + ("no_reset", "", "old", False, 0), + ("gclken", "rst", "old", False, 0), + ("ungated", "ungated", "old", False, 1), # muxes wren with rst + ("gclken_ce", "rst", "old", True, 3), # AND to simulate CLK_EN + ("grden", "rden && rst", "old", False, 1), # selects _clken, simulates _rden + ("grden_ce", "rden && rst", "old", True, 4), # both of the above + ("exclwr", "", "nc", False, 2), # selects new_only and simulates + ("excl_rst", "rst", "nc", False, 3), # as above, extra gate for rst + ("transwr", "", "new", False, 0), + ("trans_rst", "rst", "new", False, 0), +]: + write = "if (wren) \n\t\tmem[addr] <= wdata;" + + if rdwr == "new": + read = """if (rden) + if (wren) + rdata <= wdata; + else + rdata <= mem[addr];""" + else: + read = "if (rden) \n\t\trdata <= mem[addr];" + + if "rst" in reset_gate: + read = f"if ({reset_gate})\n\t\trdata <= 0; \n\telse {read}" + + if reset_gate == "ungated": + outer = "if (rst)\n\trdata <= 0;\nelse " + else: + outer = "" + + if clk_en: + outer = f"{outer}if (clken) " + + code = f"""{outer}begin + {write} + {"else " if rdwr == "nc" else ""}{read} +end""" + + TESTS.append(Test( + testname, PRIORITY.format(code=code, abits=4, wbits=8, words=2), + ["block_sp_full"], ["USE_SRST"], + {"RAM_BLOCK_SP": 1, "$*": add_logic} + )) + +for (testname, reset_gate, defs, rdwr, add_logic) in [ + ("wr_byte", "", ["USE_SRST_BLOCKING"], "old", 0), + ("trans_byte", "", ["USE_SRST_BLOCKING"], "new", 0), + ("wr_rst_byte", "rst", ["USE_SRST"], "old", 2), # expected mux to emulate blocking + ("rst_wr_byte", "rst", ["USE_SRST_BLOCKING"], "old", 2), # should use hardware blocking, doesn't + ("rdenrst_wr_byte", "rden && rst", ["USE_SRST"], "old", 3), +]: + wordsloop = "for (i=0; i ", file=sys.stderr) + return 2 + + srcfile = Path(sys.argv[1]) + dmpfile = Path(sys.argv[2]) + + try: + src_text = srcfile.read_text() + except Exception as e: + print(f"ERROR: Failed to read {srcfile}: {e}", file=sys.stderr) + return 2 + + try: + dmp_text = dmpfile.read_text() + except Exception as e: + print(f"ERROR: Failed to read {dmpfile}: {e}", file=sys.stderr) + return 2 + + for key, pattern_template, errmsg in CHECKS: + if "{val}" in pattern_template: + val = extract_expect_value(src_text, key) + if val is None: + continue + pattern = pattern_template.format(val=re.escape(val)) + else: + if key not in src_text: + continue + pattern = pattern_template + + if not re.search(pattern, dmp_text, re.MULTILINE): + print(errmsg, file=sys.stderr) + return 1 + + print("ok.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/chips/yosys/tests/memories/wide_all.v b/chips/yosys/tests/memories/wide_all.v new file mode 100644 index 0000000000000000000000000000000000000000..1516b26fd264785ea08c07346c224578794e6343 --- /dev/null +++ b/chips/yosys/tests/memories/wide_all.v @@ -0,0 +1,36 @@ +// expect-wr-ports 2 +// expect-rd-ports 1 +// expect-wr-wide-continuation 2'10 + +module test( + input clk, + input [3:0] we, + input [6:0] ra, + input [5:0] wa, + input [31:0] wd, + output [15:0] rd +); + +reg [7:0] mem[3:254]; + +assign rd[7:0] = mem[{ra, 1'b0}]; +assign rd[15:8] = mem[{ra, 1'b1}]; + +initial begin + mem[5] = 8'h12; + mem[6] = 8'h34; + mem[7] = 8'h56; +end + +always @(posedge clk) begin + if (we[0]) + mem[{wa, 2'b00}] <= wd[7:0]; + if (we[1]) + mem[{wa, 2'b01}] <= wd[15:8]; + if (we[2]) + mem[{wa, 2'b10}] <= wd[23:16]; + if (we[3]) + mem[{wa, 2'b11}] <= wd[31:24]; +end + +endmodule diff --git a/chips/yosys/tests/memories/wide_read_async.v b/chips/yosys/tests/memories/wide_read_async.v new file mode 100644 index 0000000000000000000000000000000000000000..dd6f25dcbd01d6b3eacd595b5c2b30c6c6b56f45 --- /dev/null +++ b/chips/yosys/tests/memories/wide_read_async.v @@ -0,0 +1,26 @@ +// expect-wr-ports 1 +// expect-rd-ports 4 +// expect-rd-wide-continuation 4'1110 + +module test( + input clk, + input we, + input [5:0] ra, + input [7:0] wa, + input [7:0] wd, + output [31:0] rd +); + +reg [7:0] mem[0:255]; + +assign rd[7:0] = mem[{ra, 2'b00}]; +assign rd[15:8] = mem[{ra, 2'b01}]; +assign rd[23:16] = mem[{ra, 2'b10}]; +assign rd[31:24] = mem[{ra, 2'b11}]; + +always @(posedge clk) begin + if (we) + mem[wa] <= wd; +end + +endmodule diff --git a/chips/yosys/tests/memories/wide_read_mixed.v b/chips/yosys/tests/memories/wide_read_mixed.v new file mode 100644 index 0000000000000000000000000000000000000000..64a32c2a29a96e1702bf591e8f37ebde8a7812d3 --- /dev/null +++ b/chips/yosys/tests/memories/wide_read_mixed.v @@ -0,0 +1,45 @@ +// expect-wr-ports 1 +// expect-rd-ports 4 +// expect-rd-wide-continuation 4'1110 +// expect-rd-srst-val 32'10000111011001010100001100100001 +// expect-rd-init-val 32'10101011110011011110111110101011 + +// In this testcase, the byte-wide read ports are merged into a single +// word-wide port despite mismatched transparency, with soft transparency +// logic inserted on half the port to preserve the semantics. + +module test( + input clk, + input re, rr, + input we, + input [5:0] ra, + input [7:0] wa, + input [7:0] wd, + output reg [31:0] rd +); + +reg [7:0] mem[0:255]; + +initial rd = 32'habcdefab; + +always @(posedge clk) begin + if (rr) begin + rd <= 32'h87654321; + end else if (re) begin + rd[7:0] <= mem[{ra, 2'b00}]; + rd[15:8] <= mem[{ra, 2'b01}]; + rd[23:16] <= mem[{ra, 2'b10}]; + rd[31:24] <= mem[{ra, 2'b11}]; + if (we && wa == {ra, 2'b00}) + rd [7:0] <= wd; + if (we && wa == {ra, 2'b01}) + rd [15:8] <= wd; + end +end + +always @(posedge clk) begin + if (we) + mem[wa] <= wd; +end + +endmodule diff --git a/chips/yosys/tests/memories/wide_read_sync.v b/chips/yosys/tests/memories/wide_read_sync.v new file mode 100644 index 0000000000000000000000000000000000000000..4471611868d4a438d5bd9bd0fbb08a1907b83c6c --- /dev/null +++ b/chips/yosys/tests/memories/wide_read_sync.v @@ -0,0 +1,31 @@ +// expect-wr-ports 1 +// expect-rd-ports 4 +// expect-rd-wide-continuation 4'1110 + +module test( + input clk, + input re, + input we, + input [5:0] ra, + input [7:0] wa, + input [7:0] wd, + output reg [31:0] rd +); + +reg [7:0] mem[0:255]; + +always @(posedge clk) begin + if (re) begin + rd[7:0] <= mem[{ra, 2'b00}]; + rd[15:8] <= mem[{ra, 2'b01}]; + rd[23:16] <= mem[{ra, 2'b10}]; + rd[31:24] <= mem[{ra, 2'b11}]; + end +end + +always @(posedge clk) begin + if (we) + mem[wa] <= wd; +end + +endmodule diff --git a/chips/yosys/tests/memories/wide_read_trans.v b/chips/yosys/tests/memories/wide_read_trans.v new file mode 100644 index 0000000000000000000000000000000000000000..f7d827f7918176cf57bf4735978e12cd8331ffaf --- /dev/null +++ b/chips/yosys/tests/memories/wide_read_trans.v @@ -0,0 +1,39 @@ +// expect-wr-ports 1 +// expect-rd-ports 4 +// expect-rd-wide-continuation 4'1110 + +module test( + input clk, + input re, + input we, + input [5:0] ra, + input [7:0] wa, + input [7:0] wd, + output reg [31:0] rd +); + +reg [7:0] mem[0:255]; + +always @(posedge clk) begin + if (re) begin + rd[7:0] <= mem[{ra, 2'b00}]; + rd[15:8] <= mem[{ra, 2'b01}]; + rd[23:16] <= mem[{ra, 2'b10}]; + rd[31:24] <= mem[{ra, 2'b11}]; + if (we && wa == {ra, 2'b00}) + rd [7:0] <= wd; + if (we && wa == {ra, 2'b01}) + rd [15:8] <= wd; + if (we && wa == {ra, 2'b10}) + rd [23:16] <= wd; + if (we && wa == {ra, 2'b11}) + rd [31:24] <= wd; + end +end + +always @(posedge clk) begin + if (we) + mem[wa] <= wd; +end + +endmodule diff --git a/chips/yosys/tests/memories/wide_thru_priority.v b/chips/yosys/tests/memories/wide_thru_priority.v new file mode 100644 index 0000000000000000000000000000000000000000..10c0d837b264d091d278a71d8bdc3b5c6b53d976 --- /dev/null +++ b/chips/yosys/tests/memories/wide_thru_priority.v @@ -0,0 +1,29 @@ +// expect-wr-ports 3 +// expect-rd-ports 1 +// expect-wr-wide-continuation 3'010 + +module test( + input clk, + input we1, we2, + input [5:0] ra, + input [4:0] wa1, + input [5:0] wa2, + input [15:0] wd1, + input [7:0] wd2, + output [7:0] rd +); + +reg [7:0] mem[0:63]; + +assign rd = mem[ra]; + +always @(posedge clk) begin + if (we1) + mem[{wa1, 1'b0}] <= wd1[7:0]; + if (we2) + mem[wa2] <= wd2; + if (we1) + mem[{wa1, 1'b1}] <= wd1[15:8]; +end + +endmodule diff --git a/chips/yosys/tests/memories/wide_write.v b/chips/yosys/tests/memories/wide_write.v new file mode 100644 index 0000000000000000000000000000000000000000..5c4cc41f93de59bc9dd4b7f2fd5cda89b4f9ddf7 --- /dev/null +++ b/chips/yosys/tests/memories/wide_write.v @@ -0,0 +1,29 @@ +// expect-wr-ports 4 +// expect-rd-ports 1 +// expect-wr-wide-continuation 4'1110 + +module test( + input clk, + input [3:0] we, + input [7:0] ra, + input [5:0] wa, + input [31:0] wd, + output [7:0] rd +); + +reg [7:0] mem[0:255]; + +assign rd = mem[ra]; + +always @(posedge clk) begin + if (we[0]) + mem[{wa, 2'b00}] <= wd[7:0]; + if (we[1]) + mem[{wa, 2'b01}] <= wd[15:8]; + if (we[2]) + mem[{wa, 2'b10}] <= wd[23:16]; + if (we[3]) + mem[{wa, 2'b11}] <= wd[31:24]; +end + +endmodule diff --git a/chips/yosys/tests/opt/bug1525.ys b/chips/yosys/tests/opt/bug1525.ys new file mode 100644 index 0000000000000000000000000000000000000000..972bc0ac7c802ba33484084b94a79185b96547d3 --- /dev/null +++ b/chips/yosys/tests/opt/bug1525.ys @@ -0,0 +1,13 @@ +read_verilog << EOF +module top(...); +input A1, A2, B, S; +output O; + +assign O = S ? (A1 & B) : (A2 & B); + +endmodule +EOF + +simplemap +opt_share +dump diff --git a/chips/yosys/tests/opt/bug1758.ys b/chips/yosys/tests/opt/bug1758.ys new file mode 100644 index 0000000000000000000000000000000000000000..85dfaceb89508af545a3af52d4f669da8ac65e34 --- /dev/null +++ b/chips/yosys/tests/opt/bug1758.ys @@ -0,0 +1,21 @@ +read_verilog -noopt <= 0); +endmodule +EOF + +equiv_opt -assert opt_expr -fine diff --git a/chips/yosys/tests/opt/bug4413.ys b/chips/yosys/tests/opt/bug4413.ys new file mode 100644 index 0000000000000000000000000000000000000000..6c415888238306bed6b26b40f861f51bf5a90f2c --- /dev/null +++ b/chips/yosys/tests/opt/bug4413.ys @@ -0,0 +1,15 @@ +read_verilog <> shift2; +endmodule + +EOT + +equiv_opt -assert peepopt diff --git a/chips/yosys/tests/opt/bug4610.ys b/chips/yosys/tests/opt/bug4610.ys new file mode 100644 index 0000000000000000000000000000000000000000..0bec5935958309bf40a354f24861467141756e24 --- /dev/null +++ b/chips/yosys/tests/opt/bug4610.ys @@ -0,0 +1,15 @@ +read_rtlil <= 0) ? ((sh > 2) ? 2'h3 : (2'd1 << sh)) : (2'd1 >> -sh); +endmodule +EOT +proc +copy top merged + +# alumacc makes the negation an $alu with an empty A port +alumacc merged +share -aggressive merged +select -assert-count 2 merged/t:$alu +opt_clean merged + +miter -equiv -flatten -make_assert top merged miter +sat -verify -prove-asserts -set-def-inputs -enable_undef miter diff --git a/chips/yosys/tests/opt/generate_mk.py b/chips/yosys/tests/opt/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..4c31c5a2b59b67bbda257e01af363dcf5d2acaa1 --- /dev/null +++ b/chips/yosys/tests/opt/generate_mk.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile + +gen_tests_makefile.generate(["--yosys-scripts", "--tcl-scripts"]) diff --git a/chips/yosys/tests/opt/memory_bmux2rom.ys b/chips/yosys/tests/opt/memory_bmux2rom.ys new file mode 100644 index 0000000000000000000000000000000000000000..c28bc2ec9080aaf607a531519a69225792d3bef3 --- /dev/null +++ b/chips/yosys/tests/opt/memory_bmux2rom.ys @@ -0,0 +1,27 @@ +read_rtlil << EOT + +module \top + wire width 4 input 0 \S + wire width 5 output 1 \Y + + cell $bmux $0 + parameter \WIDTH 5 + parameter \S_WIDTH 4 + connect \A 80'10110100011101110001110010001110101010111000110011111111111110100000110100111000 + connect \S \S + connect \Y \Y + end +end + +EOT + +hierarchy -auto-top + +design -save preopt +memory_bmux2rom +select -assert-count 1 t:$memrd_v2 +memory_map +opt_dff +design -stash postopt + +equiv_opt -assert -run prepare: dummy diff --git a/chips/yosys/tests/opt/memory_dff_trans.ys b/chips/yosys/tests/opt/memory_dff_trans.ys new file mode 100644 index 0000000000000000000000000000000000000000..102b36f2670d52ec2bb7663215a5c8141b5c79a6 --- /dev/null +++ b/chips/yosys/tests/opt/memory_dff_trans.ys @@ -0,0 +1,874 @@ +# Good case 1: single port. + +read_verilog << EOT + +module top( + input [3:0] addr, + input [3:0] wd, + input we, + input clk, + output reg [3:0] rd, +); + +reg [3:0] mem[0:15]; + +always @(posedge clk) begin + if (we) begin + mem[addr] <= wd; + rd <= wd; + end else begin + rd <= mem[addr]; + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +memory_dff +memory_collect +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_TRANSPARENCY_MASK=1'b1 r:RD_COLLISION_X_MASK=1'b0 %i %i + +design -reset + +# Good case 2: single port, exclusive. + +read_verilog << EOT + +module top( + input [3:0] addr, + input [3:0] wd, + input we, + input clk, + output reg [3:0] rd, +); + +reg [3:0] mem[0:15]; + +always @(posedge clk) begin + if (we) begin + mem[addr] <= wd; + end else begin + rd <= mem[addr]; + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +memory_dff +memory_collect +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_TRANSPARENCY_MASK=1'b0 r:RD_COLLISION_X_MASK=1'b1 %i %i + +design -reset + +# Good case 3: proper bypass muxes. + +read_verilog << EOT + +module top( + input [3:0] ra, + input [3:0] wa1, + input [3:0] wa2, + input [3:0] wd1, + input [3:0] wd2, + input we1, we2, + input re, + input clk, + output reg [3:0] rd, +); + +reg [3:0] mem[0:15]; + +always @(posedge clk) begin + if (we1) + mem[wa1] <= wd1; + if (we2) + mem[wa2] <= wd2; + if (re) begin + rd <= mem[ra]; + if (we1 && wa1 == ra) + rd <= wd1; + if (we2 && wa2 == ra) + rd <= wd2; + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +memory_dff +memory_collect +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_TRANSPARENCY_MASK=2'b11 r:RD_COLLISION_X_MASK=2'b00 %i %i + +design -reset + +# Good case 4: proper bypass mux, but only one. + +read_verilog << EOT + +module top( + input [3:0] ra, + input [3:0] wa1, + input [3:0] wa2, + input [3:0] wd1, + input [3:0] wd2, + input we1, we2, + input re, + input clk, + output reg [3:0] rd, +); + +reg [3:0] mem[0:15]; + +always @(posedge clk) begin + if (we1) + mem[wa1] <= wd1; + if (we2) + mem[wa2] <= wd2; + if (re) begin + rd <= mem[ra]; + if (we1 && wa1 == ra) + rd <= wd1; + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +memory_dff +memory_collect +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_TRANSPARENCY_MASK=2'b01 r:RD_COLLISION_X_MASK=2'b00 %i %i + +design -reset + +# Good case 5: proper bypass mux, but the other one. + +read_verilog << EOT + +module top( + input [3:0] ra, + input [3:0] wa1, + input [3:0] wa2, + input [3:0] wd1, + input [3:0] wd2, + input we1, we2, + input re, + input clk, + output reg [3:0] rd, +); + +reg [3:0] mem[0:15]; + +always @(posedge clk) begin + if (we1) + mem[wa1] <= wd1; + if (we2) + mem[wa2] <= wd2; + if (re) begin + rd <= mem[ra]; + if (we2 && wa2 == ra) + rd <= wd2; + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +memory_dff +memory_collect +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_TRANSPARENCY_MASK=2'b10 r:RD_COLLISION_X_MASK=2'b00 %i %i + +design -reset + +# Good case 6: 'x mux. + +read_verilog << EOT + +module top( + input [3:0] ra, + input [3:0] wa1, + input [3:0] wa2, + input [3:0] wd1, + input [3:0] wd2, + input we1, we2, + input re, + input clk, + output reg [3:0] rd, +); + +reg [3:0] mem[0:15]; + +always @(posedge clk) begin + if (we1) + mem[wa1] <= wd1; + if (we2) + mem[wa2] <= wd2; + if (re) begin + rd <= mem[ra]; + if (we1 && wa1 == ra) + rd <= 4'hx; + if (we2 && wa2 == ra) + rd <= wd2; + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +memory_dff +memory_collect +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_TRANSPARENCY_MASK=2'b10 r:RD_COLLISION_X_MASK=2'b01 %i %i + +design -reset + +# Good case 7: uncollidable addresses. + +read_verilog << EOT + +module top( + input [3:0] addr, + input [3:0] wd1, + input [3:0] wd2, + input we1, we2, + input re, + input clk, + output reg [3:0] rd, +); + +reg [3:0] mem[0:15]; + +wire [3:0] wa1 = addr; +wire [3:0] wa2 = addr + 1; +wire [3:0] ra = addr + 2; + +always @(posedge clk) begin + if (we1) + mem[wa1] <= wd1; + if (we2) + mem[wa2] <= wd2; + if (re) begin + rd <= mem[ra]; + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +memory_dff +memory_collect +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_TRANSPARENCY_MASK=2'b00 r:RD_COLLISION_X_MASK=2'b11 %i %i + +design -reset + +# Good case 8: uncollidable addresses, but still have soft transparency logic. + +read_verilog << EOT + +module top( + input [3:0] addr, + input [3:0] wd1, + input [3:0] wd2, + input we1, we2, + input re, + input clk, + output reg [3:0] rd, +); + +reg [3:0] mem[0:15]; + +wire [3:0] wa1 = addr; +wire [3:0] wa2 = addr + 1; +wire [3:0] ra = addr + 2; + +always @(posedge clk) begin + if (we1) + mem[wa1] <= wd1; + if (we2) + mem[wa2] <= wd2; + if (re) begin + rd <= mem[ra]; + if (we1 && wa1 == ra) + rd <= wd1; + if (we2 && wa2 == ra) + rd <= wd2; + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +memory_dff +memory_collect +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_TRANSPARENCY_MASK=2'b00 r:RD_COLLISION_X_MASK=2'b11 %i %i + +design -reset + +# Bad case 1: broken bypass signal. + +read_verilog << EOT + +module top( + input [3:0] ra, + input [3:0] wa1, + input [3:0] wa2, + input [3:0] wd1, + input [3:0] wd2, + input we1, we2, + input re, + input clk, + output reg [3:0] rd, +); + +reg [3:0] mem[0:15]; + +always @(posedge clk) begin + if (we1) + mem[wa1] <= wd1; + if (we2) + mem[wa2] <= wd2; + if (re) begin + rd <= mem[ra]; + if (we1 && wa1 == ra) + rd <= wd1; + if (we2 && wa2 == ra && we1) + rd <= wd2; + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +logger -expect log "FF found, but with a mux select that doesn't seem to correspond to transparency logic" 1 +memory_dff +logger -check-expected +memory_collect +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_CLK_ENABLE=1'b0 %i + +design -reset + +# Bad case 2: bad data signal. + +read_verilog << EOT + +module top( + input [3:0] ra, + input [3:0] wa1, + input [3:0] wa2, + input [3:0] wd1, + input [3:0] wd2, + input we1, we2, + input re, + input clk, + output reg [3:0] rd, +); + +reg [3:0] mem[0:15]; + +always @(posedge clk) begin + if (we1) + mem[wa1] <= wd1; + if (we2) + mem[wa2] <= wd2; + if (re) begin + rd <= mem[ra]; + if (we1 && wa1 == ra) + rd <= wd1; + if (we2 && wa2 == ra) + rd <= wd1; + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +logger -expect log "FF found, but with a mux data input that doesn't seem to correspond to transparency logic" 1 +memory_dff +logger -check-expected +memory_collect +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_CLK_ENABLE=1'b0 %i + +design -reset + +# Bad case 3: priority mismatch. + +read_verilog << EOT + +module top( + input [3:0] ra, + input [3:0] wa1, + input [3:0] wa2, + input [3:0] wd1, + input [3:0] wd2, + input we1, we2, + input re, + input clk, + output reg [3:0] rd, +); + +reg [3:0] mem[0:15]; + +always @(posedge clk) begin + if (we1) + mem[wa1] <= wd1; + if (we2) + mem[wa2] <= wd2; + if (re) begin + rd <= mem[ra]; + if (we2 && wa2 == ra) + rd <= wd2; + if (we1 && wa1 == ra) + rd <= wd1; + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +logger -expect log "FF found, but transparency logic priority doesn't match write priority." 1 +memory_dff +logger -check-expected +memory_collect +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_CLK_ENABLE=1'b0 %i + +design -reset + +# Good case 10: priority mismatch, but since the second value is 'x, it's still OK. + +read_verilog << EOT + +module top( + input [3:0] ra, + input [3:0] wa1, + input [3:0] wa2, + input [3:0] wd1, + input [3:0] wd2, + input we1, we2, + input re, + input clk, + output reg [3:0] rd, +); + +reg [3:0] mem[0:15]; + +always @(posedge clk) begin + if (we1) + mem[wa1] <= wd1; + if (we2) + mem[wa2] <= wd2; + if (re) begin + rd <= mem[ra]; + if (we2 && wa2 == ra) + rd <= wd2; + if (we1 && wa1 == ra) + rd <= 4'hx; + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +memory_dff +memory_collect +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_TRANSPARENCY_MASK=2'b10 r:RD_COLLISION_X_MASK=2'b01 %i %i + +design -reset + +# Good case 11: priority mismatch, but since three-way collision cannot happen, it's still OK. + +read_verilog << EOT + +module top( + input [3:0] addr, + input [1:0] mode, + input [3:0] wd1, + input [3:0] wd2, + input we1, we2, + input re, + input clk, + output reg [3:0] rd, +); + +reg [3:0] wa1, wa2, ra; + +always @* begin + case (mode) + 0: begin + wa1 = addr+1; + wa2 = addr; + ra = addr; + end + 1: begin + wa1 = addr; + wa2 = addr+1; + ra = addr; + end + 2: begin + wa1 = addr; + wa2 = addr; + ra = addr+1; + end + 3: begin + wa1 = addr; + wa2 = addr+1; + ra = addr+2; + end + endcase +end + +reg [3:0] mem[0:15]; + +always @(posedge clk) begin + if (we1) + mem[wa1] <= wd1; + if (we2) + mem[wa2] <= wd2; + if (re) begin + rd <= mem[ra]; + if (we2 && wa2 == ra) + rd <= wd2; + if (we1 && wa1 == ra) + rd <= wd1; + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +memory_dff +memory_collect +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_TRANSPARENCY_MASK=2'b11 r:RD_COLLISION_X_MASK=2'b00 %i %i + +design -reset + +# Bad case 4: half of the port is transparent. + +read_verilog << EOT + +module top( + input [3:0] ra, + input [3:0] wa1, + input [3:0] wa2, + input [3:0] wd1, + input [3:0] wd2, + input we1, we2, + input re, + input clk, + output reg [3:0] rd, +); + +reg [3:0] mem[0:15]; + +always @(posedge clk) begin + if (we1) + mem[wa1] <= wd1; + if (we2) + mem[wa2] <= wd2; + if (re) begin + rd <= mem[ra]; + if (we1 && wa1 == ra) + rd <= wd1; + if (we2 && wa2 == ra) + rd[3:2] <= wd2[3:2]; + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +logger -expect log "FF found, but soft transparency logic is inconsistent for port 1." 1 +memory_dff +logger -check-expected +memory_collect +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_CLK_ENABLE=1'b0 %i + +design -reset + +# Good case 12: like above, but the other bits aren't changed by the port anyway. + +read_verilog << EOT + +module top( + input [3:0] ra, + input [3:0] wa1, + input [3:0] wa2, + input [3:0] wd1, + input [3:0] wd2, + input we1, we2, + input re, + input clk, + output reg [3:0] rd, +); + +reg [3:0] mem[0:15]; + +always @(posedge clk) begin + if (we1) + mem[wa1] <= wd1; + if (we2) + mem[wa2][3:2] <= wd2[3:2]; + if (re) begin + rd <= mem[ra]; + if (we1 && wa1 == ra) + rd <= wd1; + if (we2 && wa2 == ra) + rd[3:2] <= wd2[3:2]; + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +memory_dff +memory_collect +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_TRANSPARENCY_MASK=2'b11 r:RD_COLLISION_X_MASK=2'b00 %i %i + +design -reset + +# Good case 13: wide read, narrow write. + +read_verilog << EOT + +module top( + input [7:0] addr, + input [7:0] wd, + input we, + input re, + input clk, + output reg [31:0] rd, +); + +reg [7:0] mem[0:255]; + +always @(posedge clk) begin + if (we) + mem[addr] <= wd; + if (re) begin + rd[7:0] <= mem[{addr[7:2], 2'b00}]; + rd[15:8] <= mem[{addr[7:2], 2'b01}]; + rd[23:16] <= mem[{addr[7:2], 2'b10}]; + rd[31:24] <= mem[{addr[7:2], 2'b11}]; + case ({we, addr[1:0]}) + 3'b100: rd[7:0] <= wd; + 3'b101: rd[15:8] <= wd; + 3'b110: rd[23:16] <= wd; + 3'b111: rd[31:24] <= wd; + endcase + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +dump +memory_dff +memory_collect +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_TRANSPARENCY_MASK=4'b1111 r:RD_COLLISION_X_MASK=4'b0000 %i %i +memory_share +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_TRANSPARENCY_MASK=4'b1111 r:RD_COLLISION_X_MASK=4'b0000 %i %i +select -assert-count 1 t:$mem_v2 r:RD_WIDE_CONTINUATION=4'b1110 %i + +design -reset + +# Good case 14: narrow read, wide write. + +read_verilog << EOT + +module top( + input [7:0] addr, + input [31:0] wd, + input we, + input re, + input clk, + output reg [7:0] rd, +); + +reg [7:0] mem[0:255]; + +always @(posedge clk) begin + if (we) begin + mem[{addr[7:2], 2'b00}] <= wd[7:0]; + mem[{addr[7:2], 2'b01}] <= wd[15:8]; + mem[{addr[7:2], 2'b10}] <= wd[23:16]; + mem[{addr[7:2], 2'b11}] <= wd[31:24]; + end + if (re) begin + rd <= mem[addr]; + case ({we, addr[1:0]}) + 3'b100: rd <= wd[7:0]; + 3'b101: rd <= wd[15:8]; + 3'b110: rd <= wd[23:16]; + 3'b111: rd <= wd[31:24]; + endcase + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +dump +memory_dff +memory_collect +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_TRANSPARENCY_MASK=4'b1111 r:RD_COLLISION_X_MASK=4'b0000 %i %i +memory_share +select -assert-count 1 t:$mem_v2 +select -assert-count 1 t:$mem_v2 r:RD_TRANSPARENCY_MASK=4'b1111 r:RD_COLLISION_X_MASK=4'b0000 %i %i +select -assert-count 1 t:$mem_v2 r:WR_WIDE_CONTINUATION=4'b1110 %i + +design -reset + +# Good case 15: wide read, wide write. + +read_verilog << EOT + +module top( + input [7:0] addr, + input [31:0] wd, + input we, + input re, + input clk, + output reg [31:0] rd, +); + +reg [7:0] mem[0:255]; + +always @(posedge clk) begin + if (we) begin + mem[{addr[7:2], 2'b00}] <= wd[7:0]; + mem[{addr[7:2], 2'b01}] <= wd[15:8]; + mem[{addr[7:2], 2'b10}] <= wd[23:16]; + mem[{addr[7:2], 2'b11}] <= wd[31:24]; + end + if (re) begin + rd[7:0] <= mem[{addr[7:2], 2'b00}]; + rd[15:8] <= mem[{addr[7:2], 2'b01}]; + rd[23:16] <= mem[{addr[7:2], 2'b10}]; + rd[31:24] <= mem[{addr[7:2], 2'b11}]; + if (we) + rd <= wd; + end +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_dff +opt_clean +dump +memory_dff +select -assert-count 4 t:$memrd_v2 +select -assert-count 1 t:$memrd_v2 r:TRANSPARENCY_MASK=4'b0001 r:COLLISION_X_MASK=4'b1110 %i %i +select -assert-count 1 t:$memrd_v2 r:TRANSPARENCY_MASK=4'b0010 r:COLLISION_X_MASK=4'b1101 %i %i +select -assert-count 1 t:$memrd_v2 r:TRANSPARENCY_MASK=4'b0100 r:COLLISION_X_MASK=4'b1011 %i %i +select -assert-count 1 t:$memrd_v2 r:TRANSPARENCY_MASK=4'b1000 r:COLLISION_X_MASK=4'b0111 %i %i +memory_share +select -assert-count 1 t:$memrd_v2 +select -assert-count 1 t:$memwr_v2 +select -assert-count 1 t:$memrd_v2 r:TRANSPARENCY_MASK=1'b1 r:COLLISION_X_MASK=1'b0 %i %i + +design -reset diff --git a/chips/yosys/tests/opt/memory_map_offset.ys b/chips/yosys/tests/opt/memory_map_offset.ys new file mode 100644 index 0000000000000000000000000000000000000000..06969922d6460795c61f5e3286e219c444ff3d75 --- /dev/null +++ b/chips/yosys/tests/opt/memory_map_offset.ys @@ -0,0 +1,100 @@ +read_verilog << EOT + +module top(...); + +input [3:0] ra; +input [3:0] wa; + +input [15:0] wd; +output [15:0] rd; +input en, clk; + +reg [15:0] mem[3:9]; + +always @(posedge clk) + if (en) + mem[wa] <= wd; + +assign rd = mem[ra]; + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_clean +memory_map + +design -stash gate + +read_verilog << EOT + +module top(...); + +input [3:0] ra; +input [3:0] wa; + +input [15:0] wd; +output reg [15:0] rd; +input en, clk; + +reg [15:0] \mem[3] ; +reg [15:0] \mem[4] ; +reg [15:0] \mem[5] ; +reg [15:0] \mem[6] ; +reg [15:0] \mem[7] ; +reg [15:0] \mem[8] ; +reg [15:0] \mem[9] ; + +always @(posedge clk) begin + if (en && wa == 3) + \mem[3] <= wd; + if (en && wa == 4) + \mem[4] <= wd; + if (en && wa == 5) + \mem[5] <= wd; + if (en && wa == 6) + \mem[6] <= wd; + if (en && wa == 7) + \mem[7] <= wd; + if (en && wa == 8) + \mem[8] <= wd; + if (en && wa == 9) + \mem[9] <= wd; +end + +always @* begin + rd = 16'bx; + if (ra == 3) + rd = \mem[3] ; + if (ra == 4) + rd = \mem[4] ; + if (ra == 5) + rd = \mem[5] ; + if (ra == 6) + rd = \mem[6] ; + if (ra == 7) + rd = \mem[7] ; + if (ra == 8) + rd = \mem[8] ; + if (ra == 9) + rd = \mem[9] ; +end + +endmodule + +EOT + +hierarchy -auto-top +proc +opt_clean + +design -stash gold + +design -copy-from gold -as gold A:top +design -copy-from gate -as gate A:top + +equiv_make gold gate equiv +equiv_induct -undef equiv +equiv_status -assert equiv diff --git a/chips/yosys/tests/opt/opt_balance_tree.ys b/chips/yosys/tests/opt/opt_balance_tree.ys new file mode 100644 index 0000000000000000000000000000000000000000..dd95576c3b63dd8ddb9cc61c95b4bbcaf52f8793 --- /dev/null +++ b/chips/yosys/tests/opt/opt_balance_tree.ys @@ -0,0 +1,1339 @@ +# Test 1 +log -header "Simple AND chain" +log -push +design -reset +read_verilog <signed + + // Combine with unsigned offset + assign result = sum_full + $signed({6'b0, unsigned_offset}); +endmodule +EOF +check -assert + +# Check equivalence after opt_balance_tree +equiv_opt -assert opt_balance_tree +design -load postopt + +# Width reduction +equiv_opt -assert wreduce +design -load postopt + +design -reset +log -pop + + + +# Test 30 +log -header "Complex signedness with conditional sign extension" +log -push +design -reset +read_verilog < 4'd10) & (a < 4'd3); + end + end +endmodule +EOT + +hierarchy -top test_case +prep +design -save gold + +opt_dff +opt_clean -purge +select -assert-count 2 t:$sdff + +# q0 folds (init 0, srst 0, D proven 0), q1 must stay (init 1, srst 0) +design -load gold +opt_dff -sat +opt_clean -purge +select -assert-count 1 t:$sdff +design -save gate + +design -load gold +design -copy-from gate -as gate test_case +equiv_make test_case gate equiv +equiv_induct equiv +equiv_status -assert + + +# async load +design -reset +read_verilog -sv < 4'd10) & (a < 4'd3); + else q0 <= ~(~q0 | ~en); + always @(posedge clk or posedge load) + if (load) q1 <= a[0]; + else q1 <= ~(~q1 | ~en); +endmodule +EOT + +hierarchy -top test_case +prep +select -assert-count 2 t:$aldff +design -save gold + +opt_dff +opt_clean -purge +select -assert-count 2 t:$aldff + +design -load gold +opt_dff -sat +opt_clean -purge +select -assert-count 1 t:$aldff +design -save gate + +design -load gold +design -copy-from gate -as gate test_case +async2sync +equiv_make test_case gate equiv +equiv_induct equiv +equiv_status -assert + + +# async reset +design -reset +read_verilog -sv < 4'd10) & (a < 4'd3); + y1 <= (b > 4'd12) & (b < 4'd5); + y2 <= (a > 4'd9) & (a < 4'd2); + y3 <= (b > 4'd11) & (b < 4'd4); + end +endmodule +EOT + +hierarchy -top test_case +prep +design -save gold + +# default budget proves everything +opt_dff -sat +opt_clean -purge +select -assert-count 0 t:$dff +design -save gate_full + +# low budget skips all +design -load gold +scratchpad -set opt_dff.sat_effort 1 +logger -expect warning "solver effort budget for module test_case is exhausted" 1 +opt_dff -sat +logger -check-expected +opt_clean -purge +select -assert-count 4 t:$dff +design -save gate_low + +# only the selected cone is folded +design -load gold +scratchpad -set opt_dff.sat_effort 0 +select o:y0 %ci* +opt_dff -sat +select -clear +opt_clean -purge +select -assert-count 3 t:$dff + +# eq +design -load gold +design -copy-from gate_full -as gate_full test_case +equiv_make test_case gate_full equiv_full +equiv_induct equiv_full +equiv_status -assert + +design -load gold +design -copy-from gate_low -as gate_low test_case +equiv_make test_case gate_low equiv_low +equiv_induct equiv_low +equiv_status -assert diff --git a/chips/yosys/tests/opt/opt_dff_sr.ys b/chips/yosys/tests/opt/opt_dff_sr.ys new file mode 100644 index 0000000000000000000000000000000000000000..1d3fd300e79a6ccea03c718e12583fe970bbc8da --- /dev/null +++ b/chips/yosys/tests/opt/opt_dff_sr.ys @@ -0,0 +1,308 @@ +### Always-active SET/CLR removal. + +read_verilog -icells < a; + output o1_2 = 4'b0000 <= a; + output o1_3 = 4'b1111 < a; + output o1_4 = 4'b1111 >= a; + output o1_5 = a < 4'b0000; + output o1_6 = a >= 4'b0000; + output o1_7 = a > 4'b1111; + output o1_8 = a <= 4'b1111; + + output o2_1 = 4'sb0000 > $signed(a); + output o2_2 = 4'sb0000 <= $signed(a); + output o2_3 = $signed(a) < 4'sb0000; + output o2_4 = $signed(a) >= 4'sb0000; + + output o3_1 = 4'b0100 > a; + output o3_2 = 4'b0100 <= a; + output o3_3 = a < 4'b0100; + output o3_4 = a >= 4'b0100; + + output o4_1 = 5'b10000 > a; + output o4_2 = 5'b10000 >= a; + output o4_3 = 5'b10000 < a; + output o4_4 = 5'b10000 <= a; + output o4_5 = a < 5'b10000; + output o4_6 = a <= 5'b10000; + output o4_7 = a > 5'b10000; + output o4_8 = a >= 5'b10000; + + output o5_1 = 5'b10100 > a; + output o5_2 = 5'b10100 >= a; + output o5_3 = 5'b10100 < a; + output o5_4 = 5'b10100 <= a; + output o5_5 = a < 5'b10100; + output o5_6 = a <= 5'b10100; + output o5_7 = a > 5'b10100; + output o5_8 = a >= 5'b10100; +endmodule diff --git a/chips/yosys/tests/opt/opt_expr_cmp.ys b/chips/yosys/tests/opt/opt_expr_cmp.ys new file mode 100644 index 0000000000000000000000000000000000000000..214ce8b11ff0e8f40daa5645b01305b174d1ea53 --- /dev/null +++ b/chips/yosys/tests/opt/opt_expr_cmp.ys @@ -0,0 +1,4 @@ +read_verilog opt_expr_cmp.v +equiv_opt -assert opt_expr -fine +design -load postopt +select -assert-count 0 t:$gt t:$ge t:$lt t:$le diff --git a/chips/yosys/tests/opt/opt_expr_combined_assign.ys b/chips/yosys/tests/opt/opt_expr_combined_assign.ys new file mode 100644 index 0000000000000000000000000000000000000000..823ca959a942958fee2ab4b7786d79b42dd1ffef --- /dev/null +++ b/chips/yosys/tests/opt/opt_expr_combined_assign.ys @@ -0,0 +1,88 @@ +read_verilog -sv <> 20; + assign shr_us = in_u >> 20; + assign shr_su = in_s >> 20; + assign shr_ss = in_s >> 20; + assign sshl_uu = in_u <<< 20; + assign sshl_us = in_u <<< 20; + assign sshl_su = in_s <<< 20; + assign sshl_ss = in_s <<< 20; + assign sshr_uu = in_u >>> 20; + assign sshr_us = in_u >>> 20; + assign sshr_su = in_s >>> 20; + assign sshr_ss = in_s >>> 20; + wire [7:0] shamt = 20; + assign shiftx_uu = in_u[shamt +: 8]; + assign shiftx_us = in_u[shamt +: 8]; + assign shiftx_su = in_s[shamt +: 8]; + assign shiftx_ss = in_s[shamt +: 8]; +endmodule +EOT + +select -assert-count 4 t:$shl +select -assert-count 4 t:$shr +select -assert-count 4 t:$sshl +select -assert-count 4 t:$sshr +select -assert-count 4 t:$shiftx + +equiv_opt opt_expr + +design -load postopt +select -assert-none t:$shl +select -assert-none t:$shr +select -assert-none t:$sshl +select -assert-none t:$sshr +select -assert-none t:$shiftx + +design -reset + +read_verilog <> 36'hfffffffff; + assign sshl = in <<< 36'hfffffffff; + assign sshr = in >>> 36'hfffffffff; + assign shiftx = in[36'hfffffffff +: 8]; + + wire signed [35:0] shamt = 36'hfffffffff; + assign shl_s = in << shamt; + assign shr_s = in >> shamt; + assign sshl_s = in <<< shamt; + assign sshr_s = in >>> shamt; + assign shiftx_s = in[shamt +: 8]; +endmodule +EOT + +select -assert-count 2 t:$shl +select -assert-count 2 t:$shr +select -assert-count 2 t:$sshl +select -assert-count 2 t:$sshr +select -assert-count 1 t:$shiftx + +equiv_opt opt_expr + +design -load postopt +select -assert-none t:$shl +select -assert-none t:$shr +select -assert-none t:$sshl +select -assert-none t:$sshr +select -assert-none t:$shiftx + +design -reset + +read_verilog <> 33'h0ffffffff; + assign sshl = in <<< 33'h0ffffffff; + assign sshr = in >>> 33'h0ffffffff; +endmodule +EOT + +select -assert-count 1 t:$shl +select -assert-count 1 t:$shr +select -assert-count 1 t:$sshl +select -assert-count 1 t:$sshr + +equiv_opt -assert opt_expr + +design -load postopt +select -assert-none t:$shl +select -assert-none t:$shr +select -assert-none t:$sshl +select -assert-none t:$sshr + +design -reset + +read_verilog <> 32'hffffffff; + assign sshl = in <<< 32'hffffffff; + assign sshr = in >>> 32'hffffffff; + assign shiftx = in[32'hffffffff +: 8]; + + wire signed [31:0] shamt = 32'hffffffff; + assign shl_s = in << shamt; + assign shr_s = in >> shamt; + assign sshl_s = in <<< shamt; + assign sshr_s = in >>> shamt; + assign shiftx_s = in[shamt +: 8]; +endmodule +EOT + +select -assert-count 2 t:$shl +select -assert-count 2 t:$shr +select -assert-count 2 t:$sshl +select -assert-count 2 t:$sshr +select -assert-count 1 t:$shiftx + +equiv_opt opt_expr + +design -load postopt +select -assert-none t:$shl +select -assert-none t:$shr +select -assert-none t:$sshl +select -assert-none t:$sshr +select -assert-none t:$shiftx diff --git a/chips/yosys/tests/opt/opt_expr_shr_int_max.ys b/chips/yosys/tests/opt/opt_expr_shr_int_max.ys new file mode 100644 index 0000000000000000000000000000000000000000..5fb3c9d37891e4a831bfff4dee576da81cd0041b --- /dev/null +++ b/chips/yosys/tests/opt/opt_expr_shr_int_max.ys @@ -0,0 +1,9 @@ +read_verilog << EOF +module uut_00034(b, y); + input signed [30:0] b; + output [11:0] y = b >> ~31'b0; // shift by INT_MAX +endmodule +EOF + +# This should succeed, even with UBSAN halt_on_error +opt_expr diff --git a/chips/yosys/tests/opt/opt_expr_sub_not.ys b/chips/yosys/tests/opt/opt_expr_sub_not.ys new file mode 100644 index 0000000000000000000000000000000000000000..459ec0f948a8380468a28ba40c433913a4fb6237 --- /dev/null +++ b/chips/yosys/tests/opt/opt_expr_sub_not.ys @@ -0,0 +1,100 @@ +# Rewrite (2^k-1)-x into ~x when x is known to be smaller than 2^k + +read_verilog -icells < B; +assign Y = A > B; +endmodule +EOT +# Exercise the general case in hash_cell_inputs - accept +opt_expr +select -assert-count 2 t:$gt +equiv_opt -assert opt_merge +design -load postopt +select -assert-count 1 t:$gt + +design -reset +read_verilog < B; +assign Y = A > C; // <- look here +endmodule +EOT +# Exercise the general case in hash_cell_inputs - reject +opt_expr +select -assert-count 2 t:$gt +opt_merge +select -assert-count 2 t:$gt diff --git a/chips/yosys/tests/opt/opt_merge_init.ys b/chips/yosys/tests/opt/opt_merge_init.ys new file mode 100644 index 0000000000000000000000000000000000000000..7ee7d3dd748883b212e9e1fb470e6f4a69cf4178 --- /dev/null +++ b/chips/yosys/tests/opt/opt_merge_init.ys @@ -0,0 +1,127 @@ +read_verilog -icells <:1.1-3.10" +module \top + attribute \src ":2.17-2.20" + wire width 32 $add$:2$1_Y + attribute \src ":2.12-2.21" + wire width 32 signed $pow$:2$2_Y + attribute \src ":1.29-1.30" + wire width 15 input 1 \a + attribute \src ":1.51-1.52" + wire width 32 output 2 \b + attribute \src ":2.17-2.20" + cell $add $add$:2$1 + parameter \A_SIGNED 0 + parameter \A_WIDTH 15 + parameter \B_SIGNED 0 + parameter \B_WIDTH 32 + parameter \Y_WIDTH 32 + connect \A \a + connect \B 2 + connect \Y $add$:2$1_Y + end + attribute \src ":2.12-2.21" + cell $pow $pow$:2$2 + parameter \A_SIGNED 0 + parameter \A_WIDTH 32 + parameter \B_SIGNED 0 + parameter \B_WIDTH 32 + parameter \Y_WIDTH 32 + connect \A 2 + connect \B $add$:2$1_Y + connect \Y $pow$:2$2_Y + end + connect \b $pow$:2$2_Y +end +EOT + +select -assert-count 1 t:$pow +select -assert-none t:$shl +opt_expr +select -assert-none t:$pow +select -assert-count 1 t:$shl + +read_verilog << EOT +module ref(input wire [14:0] a, output wire [31:0] b); +assign b = 1 << (a+2); +endmodule +EOT + +equiv_make top ref equiv +select -assert-any -module equiv t:$equiv +equiv_induct +equiv_status -assert + +# Other power of 2 value + +design -reset + +read_verilog < 4'd10; + assign y = s1 ? a*b : 8'd0; + assign z = s2 ? a*c : 8'd0; +endmodule +EOT + +hierarchy -top test_case +prep +design -save gold + +share +opt_clean -purge +select -assert-count 1 t:$mul +design -save gate_full + +# low budget skips all merges +design -load gold +scratchpad -set share.sat_effort 1 +logger -expect warning "solver effort budget for module test_case is exhausted" 1 +share +logger -check-expected +opt_clean -purge +select -assert-count 2 t:$mul +design -save gate_low + +# 0 disables the limit +design -load gold +scratchpad -set share.sat_effort 0 +share +opt_clean -purge +select -assert-count 1 t:$mul + +# eq +design -load gold +design -copy-from gate_full -as gate test_case +miter -equiv -flatten -make_outputs test_case gate miter +sat -verify -prove trigger 0 miter + +design -load gold +design -copy-from gate_low -as gate test_case +miter -equiv -flatten -make_outputs test_case gate miter +sat -verify -prove trigger 0 miter diff --git a/chips/yosys/tests/opt_share/.gitignore b/chips/yosys/tests/opt_share/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..90ea6e92a975d81076f6ec8bab6349178e053a5e --- /dev/null +++ b/chips/yosys/tests/opt_share/.gitignore @@ -0,0 +1 @@ +uut_*.* diff --git a/chips/yosys/tests/opt_share/generate_mk.py b/chips/yosys/tests/opt_share/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..dea96d6dfcbe09d6fbcbb622459b59e35c8c045d --- /dev/null +++ b/chips/yosys/tests/opt_share/generate_mk.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile + +import argparse +import sys +import random + +def random_plus_x(): + return "%s x" % random.choice(['+', '+', '+', '-', '-', '|', '&', '^']) + +def maybe_plus_x(expr): + if random.randint(0, 4) == 0: + return "(%s %s)" % (expr, random_plus_x()) + else: + return expr + +parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) +parser.add_argument('-S', '--seed', type = int, help = 'seed for PRNG') +parser.add_argument('-c', '--count', type = int, default = 100, help = 'number of test cases to generate') +args = parser.parse_args() + +seed = args.seed +if seed is None: + seed = random.randrange(sys.maxsize) +print("opt_share PRNG seed: %d" % seed) +random.seed(seed) + +gen_tests_makefile.remove_generated("uut_*.*") + +for idx in range(args.count): + with open('uut_%05d.v' % idx, 'w') as f: + with gen_tests_makefile.redirect_stdout(f): + print('module uut_%05d(a, b, c, s, y);' % (idx)) + op = random.choice([ + random.choice(['+', '-', '*', '/', '%']), + random.choice(['<', '<=', '==', '!=', '===', '!==', '>=', + '>']), + random.choice(['<<', '>>', '<<<', '>>>']), + random.choice(['|', '&', '^', '~^', '||', '&&']), + ]) + print(' input%s [%d:0] a;' % (random.choice(['', ' signed']), 8)) + print(' input%s [%d:0] b;' % (random.choice(['', ' signed']), 8)) + print(' input%s [%d:0] c;' % (random.choice(['', ' signed']), 8)) + print(' input s;') + print(' output [%d:0] y;' % 8) + ops1 = ['a', 'b'] + ops2 = ['a', 'c'] + random.shuffle(ops1) + random.shuffle(ops2) + cast1 = random.choice(['', '$signed', '$unsigned']) + cast2 = random.choice(['', '$signed', '$unsigned']) + print(' assign y = (s ? %s(%s %s %s) : %s(%s %s %s));' % + (cast1, ops1[0], op, ops1[1], + cast2, ops2[0], op, ops2[1])) + print('endmodule') + + with open('uut_%05d.ys' % idx, 'w') as f: + with gen_tests_makefile.redirect_stdout(f): + print('read_verilog uut_%05d.v' % idx) + print('proc;;') + print('copy uut_%05d gold' % idx) + print('rename uut_%05d gate' % idx) + print('tee -o uut_%05d.txt opt gate' % idx) + print('tee -o uut_%05d.txt opt_share gate' % idx) + print('tee -o uut_%05d.txt opt_clean gate' % idx) + print( + 'miter -equiv -flatten -ignore_gold_x -make_outputs -make_outcmp gold gate miter' + ) + print( + 'sat -set-def-inputs -verify -prove trigger 0 -show-inputs -show-outputs miter' + ) + +gen_tests_makefile.generate(["--yosys-scripts"]) diff --git a/chips/yosys/tests/pass-fuzzing.md b/chips/yosys/tests/pass-fuzzing.md new file mode 100644 index 0000000000000000000000000000000000000000..99bf51c08e80ee6f8f71490b1fcdeccf04a1db56 --- /dev/null +++ b/chips/yosys/tests/pass-fuzzing.md @@ -0,0 +1,106 @@ +Suppose you're making significant changes to a pass that should not change +the pass's output in any way. It might be useful to run a large number of +automatically generated tests to try to find bugs where the output has +changed. This document describes how to do that. + +Basically we're going to use [AFL++](https://github.com/AFLplusplus/AFLplusplus) with the +[Grammar-Mutator](https://github.com/AFLplusplus/Grammar-Mutator) plugin to generate +RTLIL testcases. For each testcase, we run a Yosys script that applies both the old and new +implementation of the pass to the same design and compares the results. Testcase +generation is coverage-guided, i.e. the fuzzer will try to find testcases that exercise all +code in the old and new implementation of the pass (and in the RTLIL parser). + +## Setup + +These instructions clone tools into subdirectories of your home directory. They assume +you have a Yosys checkout under `$HOME/yosys`, and that you're testing the `opt_merge` pass. +They have been tested with AFL++ revision 68b492b2c7725816068718ef9437b72b40e67519 and Grammar-Mutator revision 05d8f537f8d656f0754e7ad5dcc653c42cb4f8ff. + +Clone and build AFL++ and Grammar-Mutator: +``` +cd $HOME +git clone https://github.com/AFLplusplus/AFLplusplus.git +git -C AFLplusplus checkout stable +git clone https://github.com/AFLplusplus/Grammar-Mutator.git +git -C Grammar-Mutator checkout stable +``` + +Check that `rtlil-fuzz-grammar.json` generates RTLIL constructs relevant to your pass. +Currently it's quite simple and generates a limited set of cells and wires; you may need to +extend it to generate different kinds of cells and other RTLIL constructs (e.g. `proc`). + +Build AFL++ and Grammar-Mutator: +``` +make -C $HOME/AFLplusplus -j all +make -C $HOME/Grammar-Mutator -j GRAMMAR_FILE=$HOME/yosys/tests/tools/rtlil-fuzz-grammar.json +``` + +Create a Yosys commit that adds the old version of your pass as a new command, e.g. copy +`opt_merge.cc` into `old_opt_merge.cc` and change the name of the command to `old_opt_merge`. +[Here's](https://github.com/YosysHQ/yosys/commit/827cd8c998f3e455b14ac990a3159030ddc19b21) an example. + +You may also need to patch in [this commit](https://github.com/YosysHQ/yosys/commit/121c52f514c4ca282b4e6b3b14f71184f3849ddf) to work around a bug involving `std::reverse` on +empty vectors in the RTLIL parser when building with fuzzing instrumentation. +I think this is a clang++ bug so hopefully it will get fixed eventually and that patch will not be +necessary. + +Rebuild Yosys with the AFL++ compiler wrapper. This assumes your config builds Yosys with clang++. +``` +(cd $HOME/yosys; patch -lp1 << EOF) +diff --git a/Makefile b/Makefile +index 9c361294d..c9a98f74c 100644 +--- a/Makefile ++++ b/Makefile +@@ -238,7 +238,7 @@ + LTOFLAGS := $(GCC_LTO) + + ifeq ($(CONFIG),clang) +-CXX = clang++ ++CXX = $(HOME)/AFLplusplus/afl-c++ + CXXFLAGS += -std=$(CXXSTD) $(OPT_LEVEL) + ifeq ($(ENABLE_LTO),1) + LINKFLAGS += -fuse-ld=lld +EOF +make -C yosys clean && make -C yosys -j +``` + +You probably need to configure coredumps to work normally instead of going through some OS service: +``` +echo core | sudo tee /proc/sys/kernel/core_pattern +``` + +## Running the fuzzer + +Generate some initial testcases using Grammar-Mutator: +``` +(cd $HOME/Grammar-Mutator; rm -rf seeds trees; ./grammar_generator-rtlil 100 1000 ./seeds ./trees) +``` + +Now run AFL++. +``` +(cd $HOME/Grammar-Mutator; \ + AFL_CUSTOM_MUTATOR_LIBRARY=./libgrammarmutator-rtlil.so \ + AFL_CUSTOM_MUTATOR_ONLY=1 \ + AFL_BENCH_UNTIL_CRASH=1 \ + YOSYS_WORK_UNITS_PER_THREAD=1 \ + YOSYS_ABORT_ON_LOG_ERROR=1 \ + $HOME/AFLplusplus/afl-fuzz -t 5000 -m none -i seeds -o out -- \ + $HOME/yosys/yosys -p 'read_rtlil -legalize @@; design -save init; old_opt_merge; design -save old; design -load init; opt_merge; design_equal old' \ +) +``` +This will run the fuzzer until the first crash (including any pass output mismatches) and then stop. +Or if you're lucky, the fuzzer will run indefinitely. This uses very little parallelism; if it doesn't find any errors right away, you can increase the test throughput by running AFL++ in parallel using the instructions [here](https://aflplus.plus/docs/parallel_fuzzing). + +## Working with fuzz test failures + +Any failing testcases will be dropped in `$HOME/Grammar-Mutator/out/default/crashes`. +Run `yosys -p 'read_rtlil -legalize ... ; dump'` to get the testcase as legalized RTLIL. + +## Notes on generating semantically valid RTLIL + +`Grammar-Mutator` generates RTLIL files according to the context-free grammar in `rtlil-fuzz-grammar.json`. +However, the testcases must also be semantically valid, e.g. references to wires should only refer to +wires that actually exist. These constraints cannot reasonably be expresed in a CFG. Therefore we +have added a `-legalize` option to the `read_rtlil` command. When `-legalize` is set, when `read_rtlil` +detects a failed semantic check, instead of erroring out it emits a warning and patches the incoming RTLIL +to make it valid. diff --git a/chips/yosys/tests/peepopt/generate_mk.py b/chips/yosys/tests/peepopt/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..6a921d5a026cbd59f805c297d1c28db16de0c1e9 --- /dev/null +++ b/chips/yosys/tests/peepopt/generate_mk.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile + +gen_tests_makefile.generate(["--yosys-scripts"]) diff --git a/chips/yosys/tests/peepopt/muldiv_c.ys b/chips/yosys/tests/peepopt/muldiv_c.ys new file mode 100644 index 0000000000000000000000000000000000000000..62777caabc6aff56018aa8e1c2ac7eb948a6b93d --- /dev/null +++ b/chips/yosys/tests/peepopt/muldiv_c.ys @@ -0,0 +1,343 @@ +log -header "Test simple positive case" +log -push +design -reset +read_verilog < idx; + else + out = 0; +end +endmodule +EOT +design -save read + +logger -expect-no-warnings +proc -latches error +logger -check-expected +select -assert-none t:$dlatch t:$adlatch +check -assert + +# synth_ice40 defaults to -latches error +design -load read +logger -expect-no-warnings +synth_ice40 +logger -check-expected + +design -reset + +# latch value read later in the same process is reported +read_verilog < 2 or len(sys.argv) == 2 and sys.argv[1] != 'yosys': + print(f"Usage: {sys.argv[0]} [yosys]") + exit(64) + +if len(sys.argv) == 2: + binary = [str(__file_dir__.parents[1] / "yosys"), "-Qy"] +else: + binary = [sys.executable or shutil.which("python3") or "python3"] # sys.executable can actually be None + +tests = __file_dir__.glob("test_*.py") + +log_dir = __file_dir__ / "logs" +try: + shutil.rmtree(log_dir) +except FileNotFoundError: + pass +fail_logs = set() +for test in tests: + print(f"* {test.name} ", end="") + log_dir.mkdir(parents=True, exist_ok=True) + log = log_dir / (test.stem + ".log") + cmd = [*binary, str(test)] + log_file = open(log, "w", encoding="utf8") + log_file.write(f"$ {shlex.join(cmd)}\n") + log_file.flush() + result = subprocess.run(cmd, stdout=log_file, stderr=subprocess.STDOUT) + if result.returncode == 0: + print("OK!") + else: + print(f"FAILED: {log}") + fail_logs.add(log) + log_file.close() +for log in fail_logs: + print(f">>> {log}") + with open(log, encoding="utf8") as f: + print(f.read()) +if len(fail_logs): + exit(1) diff --git a/chips/yosys/tests/pyosys/spm.cut.v.gz b/chips/yosys/tests/pyosys/spm.cut.v.gz new file mode 100644 index 0000000000000000000000000000000000000000..ddba04ea79c248f324d5dd4a1f723e694f328eee --- /dev/null +++ b/chips/yosys/tests/pyosys/spm.cut.v.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:202684ec3f9198c0418639f579a22a94489e16a48a0ef7630bd9f613d5ac852e +size 5294 diff --git a/chips/yosys/tests/pyosys/test_data_read.py b/chips/yosys/tests/pyosys/test_data_read.py new file mode 100644 index 0000000000000000000000000000000000000000..0588c1e6413851148543c3d726300a61a810442d --- /dev/null +++ b/chips/yosys/tests/pyosys/test_data_read.py @@ -0,0 +1,45 @@ +from pyosys import libyosys as ys +from pathlib import Path + +__file_dir__ = Path(__file__).absolute().parent + +d = ys.Design() + +ys.run_pass(f"read_verilog {__file_dir__ / 'spm.cut.v.gz'}", d) +ys.run_pass("hierarchy -top spm", d) + +name_by_tv_location = [] +name_by_au_location = [] + +# test both dictionary mapping and equiv operators working fine +module = None +print(d.modules_) +for idstr, module_obj in d.modules_.items(): + if idstr != "\\spm": + continue + if idstr.str() != "\\spm": + continue + module = module_obj + break + +assert module == d.top_module(), "top module search failed" +for name in module.ports: + wire = module.wires_[name] + name_str = name.str() + if name_str.endswith(".d"): # single reg output, in au + name_by_au_location.append(name_str[1:-2]) + elif name_str.endswith(".q"): # single reg input, in tv + name_by_tv_location.append(name_str[1:-2]) + else: # port/boundary scan + frm = wire.start_offset + wire.width + to = wire.start_offset + for i in range(frm - 1, to - 1, -1): + bit_name = name_str[1:] + f"\\[{i}\\]" + if wire.port_input: + name_by_tv_location.append(bit_name) + elif wire.port_output: + name_by_au_location.append(bit_name) + +assert name_by_tv_location == ['x\\[0\\]', 'a\\[31\\]', 'a\\[30\\]', 'a\\[29\\]', 'a\\[28\\]', 'a\\[27\\]', 'a\\[26\\]', 'a\\[25\\]', 'a\\[24\\]', 'a\\[23\\]', 'a\\[22\\]', 'a\\[21\\]', 'a\\[20\\]', 'a\\[19\\]', 'a\\[18\\]', 'a\\[17\\]', 'a\\[16\\]', 'a\\[15\\]', 'a\\[14\\]', 'a\\[13\\]', 'a\\[12\\]', 'a\\[11\\]', 'a\\[10\\]', 'a\\[9\\]', 'a\\[8\\]', 'a\\[7\\]', 'a\\[6\\]', 'a\\[5\\]', 'a\\[4\\]', 'a\\[3\\]', 'a\\[2\\]', 'a\\[1\\]', 'a\\[0\\]', '_315_', '_314_', '_313_', '_312_', '_311_', '_310_', '_309_', '_308_', '_307_', '_306_', '_305_', '_304_', '_303_', '_302_', '_301_', '_300_', '_299_', '_298_', '_297_', '_296_', '_295_', '_294_', '_293_', '_292_', '_291_', '_290_', '_289_', '_288_', '_287_', '_286_', '_285_', '_284_', '_283_', '_282_', '_281_', '_280_', '_279_', '_278_', '_277_', '_276_', '_275_', '_274_', '_273_', '_272_', '_271_', '_270_', '_269_', '_268_', '_267_', '_266_', '_265_', '_264_', '_263_', '_262_', '_261_', '_260_', '_259_', '_258_', '_257_', '_256_', '_255_', '_254_', '_253_', '_252_'], "failed to extract test vector register locations" +assert name_by_au_location == ['y\\[0\\]', '_315_', '_314_', '_313_', '_312_', '_311_', '_310_', '_309_', '_308_', '_307_', '_306_', '_305_', '_304_', '_303_', '_302_', '_301_', '_300_', '_299_', '_298_', '_297_', '_296_', '_295_', '_294_', '_293_', '_292_', '_291_', '_290_', '_289_', '_288_', '_287_', '_286_', '_285_', '_284_', '_283_', '_282_', '_281_', '_280_', '_279_', '_278_', '_277_', '_276_', '_275_', '_274_', '_273_', '_272_', '_271_', '_270_', '_269_', '_268_', '_267_', '_266_', '_265_', '_264_', '_263_', '_262_', '_261_', '_260_', '_259_', '_258_', '_257_', '_256_', '_255_', '_254_', '_253_', '_252_'], "failed to extract golden output register locations" +print("ok!") diff --git a/chips/yosys/tests/pyosys/test_design_run_pass.py b/chips/yosys/tests/pyosys/test_design_run_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..7638cc0644db7b3872d959d89ca8f7ddd14781b4 --- /dev/null +++ b/chips/yosys/tests/pyosys/test_design_run_pass.py @@ -0,0 +1,20 @@ +from pathlib import Path +from pyosys import libyosys as ys + +__file_dir__ = Path(__file__).absolute().parent +add_sub = __file_dir__.parent / "arch" / "common" / "add_sub.v" + +base = ys.Design() +base.run_pass(["read_verilog", str(add_sub)]) +base.run_pass("hierarchy -top top") +base.run_pass(["proc"]) +base.run_pass("equiv_opt -assert -map +/ecp5/cells_sim.v synth_ecp5") + +postopt = ys.Design() +postopt.run_pass("design -load postopt") +postopt.run_pass(["cd", "top"]) +postopt.run_pass("select -assert-min 25 t:LUT4") +postopt.run_pass("select -assert-max 26 t:LUT4") +postopt.run_pass(["select", "-assert-count", "10", "t:PFUMX"]) +postopt.run_pass(["select", "-assert-count", "6", "t:L6MUX21"]) +postopt.run_pass("select -assert-none t:LUT4 t:PFUMX t:L6MUX21 %% t:* %D") diff --git a/chips/yosys/tests/pyosys/test_dict.py b/chips/yosys/tests/pyosys/test_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..59342391c83166600655c319568120184a582436 --- /dev/null +++ b/chips/yosys/tests/pyosys/test_dict.py @@ -0,0 +1,35 @@ +from typing import Mapping +from pyosys import libyosys as ys + +StringToStringDict = ys.StringToStringDict + +my_dict = StringToStringDict() + +assert isinstance(my_dict, Mapping) + +my_dict["foo"] = "bar" +my_dict.update([("first", "second")]) +my_dict.update({"key": "value"}) +for key, value in my_dict.items(): + print(key, value) + +new_dict = my_dict | {"tomato": "tomato"} +del new_dict["foo"] +assert set(my_dict.keys()) == {"first", "key", "foo"} +assert set(new_dict.keys()) == {"first", "key", "tomato"} + +constructor_test_1 = ys.StringToStringDict(new_dict) +constructor_test_2 = ys.StringToStringDict([("tomato", "tomato")]) +constructor_test_3 = ys.StringToStringDict({ "im running": "out of string ideas" }) + +the_great_or = constructor_test_1 | constructor_test_2 | constructor_test_3 + +assert set(the_great_or) == {"first", "key", "tomato", "im running"} +repr_test = eval(repr(the_great_or)) + +assert repr_test == the_great_or # compare dicts +assert repr_test == {'tomato': 'tomato', 'first': 'second', 'key': 'value', 'im running': 'out of string ideas', } # compare dict with mapping + +before = len(repr_test) +print(repr_test.popitem()) +assert before - 1 == len(repr_test) diff --git a/chips/yosys/tests/pyosys/test_ecp5_addsub.py b/chips/yosys/tests/pyosys/test_ecp5_addsub.py new file mode 100644 index 0000000000000000000000000000000000000000..ddc50b77545b430e700418833d5b3b8a6c294d89 --- /dev/null +++ b/chips/yosys/tests/pyosys/test_ecp5_addsub.py @@ -0,0 +1,20 @@ +from pathlib import Path +from pyosys import libyosys as ys + +__file_dir__ = Path(__file__).absolute().parent +add_sub = __file_dir__.parent / "arch" / "common" / "add_sub.v" + +base = ys.Design() +ys.run_pass(f"read_verilog {add_sub}", base) +ys.run_pass("hierarchy -top top", base) +ys.run_pass("proc", base) +ys.run_pass("equiv_opt -assert -map +/ecp5/cells_sim.v synth_ecp5", base) + +postopt = ys.Design() +ys.run_pass("design -load postopt", postopt) +ys.run_pass("cd top", postopt) +ys.run_pass("select -assert-min 25 t:LUT4", postopt) +ys.run_pass("select -assert-max 26 t:LUT4", postopt) +ys.run_pass("select -assert-count 10 t:PFUMX", postopt) +ys.run_pass("select -assert-count 6 t:L6MUX21", postopt) +ys.run_pass("select -assert-none t:LUT4 t:PFUMX t:L6MUX21 %% t:* %D", postopt) diff --git a/chips/yosys/tests/pyosys/test_idict.py b/chips/yosys/tests/pyosys/test_idict.py new file mode 100644 index 0000000000000000000000000000000000000000..64cce2fc77395aef189c27ce627d5d8b17bcc594 --- /dev/null +++ b/chips/yosys/tests/pyosys/test_idict.py @@ -0,0 +1,34 @@ +from pyosys import libyosys as ys + +d = ys.Design() +hello, world, dummy, copy, the = [d.id_add(n) for n in ("\\hello", "\\world", "\\dummy", "\\copy", "\\the")] + +my_idict = ys.IdstringIdict() +print(my_idict(hello)) +print(my_idict(world)) +print(my_idict.get(world)) +try: + print(my_idict.get(dummy)) +except IndexError as e: + print(f"{repr(e)}") +print(d.str(my_idict[0])) +print(d.str(my_idict[1])) +try: + print(my_idict[2]) +except IndexError as e: + print(f"{repr(e)}") + +for i in my_idict: + print(d.str(i)) + +current_len = len(my_idict) +assert current_len == 2, "copy" + +my_copy = my_idict.copy() +my_copy(copy) +assert len(my_idict) == current_len, "copy seemed to have mutate original idict" +assert len(my_copy) == current_len + 1, "copy not behaving as expected" + +current_copy_len = len(my_copy) +my_copy |= (the, world) # 1 new element +assert len(my_copy) == current_copy_len + 1, "or operator returned unexpected result" diff --git a/chips/yosys/tests/pyosys/test_idstring_lifetime.py b/chips/yosys/tests/pyosys/test_idstring_lifetime.py new file mode 100644 index 0000000000000000000000000000000000000000..c2c602fa383b27b302708c499a79d1e7c9b1a836 --- /dev/null +++ b/chips/yosys/tests/pyosys/test_idstring_lifetime.py @@ -0,0 +1,40 @@ + +from pyosys import libyosys as ys +from pathlib import Path + +__file_dir__ = Path(__file__).absolute().parent + +d = ys.Design() +ys.run_pass(f"read_verilog {__file_dir__ / 'spm.cut.v.gz'}", d) +ys.run_pass("hierarchy -top spm", d) + +external_idstring_holder_0 = None +external_idstring_holder_1 = None + +def get_top_module_idstring(): + global external_idstring_holder_0, external_idstring_holder_1 + d = ys.Design() + ys.run_pass(f"read_verilog {__file_dir__ / 'spm.cut.v.gz'}", d) + ys.run_pass("hierarchy -top spm", d) + external_idstring_holder_0 = d.top_module().name + for cell in d.top_module().cells_: + external_idstring_holder_1 = cell + break + # d deallocates + +get_top_module_idstring() +for holder in (external_idstring_holder_0, external_idstring_holder_1): + try: + str(holder) + assert False, "expected RuntimeError" + except RuntimeError: + pass +assert str(d.top_module().name) == "\\spm" + +before_reset = d.top_module().name +ys.run_pass("design -reset", d) +try: + str(before_reset) + assert False, "expected RuntimeError" +except RuntimeError: + pass diff --git a/chips/yosys/tests/pyosys/test_import.py b/chips/yosys/tests/pyosys/test_import.py new file mode 100644 index 0000000000000000000000000000000000000000..b6a36b0c128fdbbc6f40d8849cb38577c935277c --- /dev/null +++ b/chips/yosys/tests/pyosys/test_import.py @@ -0,0 +1,20 @@ +import os +import sys + +from pyosys import libyosys as ys + +print(ys) + +ys.log("Hello, world!\n") + +from pyosys.libyosys import log + +print(log) + +log("Goodbye, world!\n") + +import pyosys + +if os.path.basename(sys.executable) == "yosys": + # make sure it's not importing the directory + assert "built-in" in repr(pyosys) diff --git a/chips/yosys/tests/pyosys/test_indirect_inheritance.py b/chips/yosys/tests/pyosys/test_indirect_inheritance.py new file mode 100644 index 0000000000000000000000000000000000000000..e29737e3239a4ad241c758429f736ac89f260446 --- /dev/null +++ b/chips/yosys/tests/pyosys/test_indirect_inheritance.py @@ -0,0 +1,15 @@ + +from pyosys import libyosys as ys +from pathlib import Path + +__file_dir__ = Path(__file__).absolute().parent + + +d = ys.Design() +ys.run_pass(f"read_verilog {__file_dir__ / 'spm.cut.v.gz'}", d) +ys.run_pass("hierarchy -top spm", d) + +for idstr, cell in d.top_module().cells_.items(): + cell.set_bool_attribute("\\set") + print(cell.attributes) + break diff --git a/chips/yosys/tests/pyosys/test_logs.py b/chips/yosys/tests/pyosys/test_logs.py new file mode 100644 index 0000000000000000000000000000000000000000..b6bd022225be5f8fe7ef41263a7b690767f90bd3 --- /dev/null +++ b/chips/yosys/tests/pyosys/test_logs.py @@ -0,0 +1,8 @@ +from pyosys import libyosys as ys + +d = ys.Design(); ys.log_header(d, "foo\n") +ys.log("foo\n") +ys.log_warning("foo\n") +ys.log_warning_noprefix("foo\n") +ys.log_file_info("foo.ys", 1, "foo\n") +ys.log_file_warning("foo.ys", 1, "foo\n") diff --git a/chips/yosys/tests/pyosys/test_monitor.py b/chips/yosys/tests/pyosys/test_monitor.py new file mode 100644 index 0000000000000000000000000000000000000000..f9e435faa4664c35d4226513bda4e26835808e8f --- /dev/null +++ b/chips/yosys/tests/pyosys/test_monitor.py @@ -0,0 +1,22 @@ +from pyosys import libyosys as ys +from pathlib import Path + +__file_dir__ = Path(__file__).absolute().parent + +d = ys.Design() + +class Monitor(ys.Monitor): + def __init__(self): + super().__init__() + self.mods = [] + + def notify_module_add(self, mod): + self.mods.append(mod.name.str()) + +m = Monitor() +d.monitors = [m] + +ys.run_pass(f"read_verilog {__file_dir__ / 'spm.cut.v.gz'}", d) +ys.run_pass("hierarchy -top spm", d) + +assert m.mods == ["\\spm"] diff --git a/chips/yosys/tests/pyosys/test_names.py b/chips/yosys/tests/pyosys/test_names.py new file mode 100644 index 0000000000000000000000000000000000000000..625bd1a7788468e6e64b41f3bed433203325a8cf --- /dev/null +++ b/chips/yosys/tests/pyosys/test_names.py @@ -0,0 +1,35 @@ +from pyosys import libyosys as ys + +d = ys.Design() +m = d.addModule("\\top") +w = m.addWire("\\data", 4) +c = m.addCell("\\u_child", "\\child") +c.setPort("\\custom", ys.SigSpec(w)) + +assert m.wire("\\data").name == "\\data" +assert m.wire("\\missing") is None +assert d.id_find("\\missing") is None +assert str(m.uniquify("\\data")) != "\\data" + +assert "\\data" in m.wires_ +assert {w.name: 1}["\\data"] == 1 +assert c.getPort("\\custom") == ys.SigSpec(w) + +c.type = "\\other_child" +assert c.type == "\\other_child" +c.name = d.id_add("\\u_renamed") +assert c.name == "\\u_renamed" + +w.attributes["\\note"] = ys.Const("hello") +assert w.get_string_attribute("\\note") == "hello" +del w.attributes["\\note"] +assert not w.has_attribute("\\note") + +other = ys.Design() +assert other.addModule("\\other").addWire(w.name).name == "\\data" + +try: + m.addWire("no_prefix") + assert False, "expected ValueError" +except ValueError: + pass diff --git a/chips/yosys/tests/pyosys/test_pass.py b/chips/yosys/tests/pyosys/test_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..d8174d4fc68d3996ffe2a034cef24d3ec4416c16 --- /dev/null +++ b/chips/yosys/tests/pyosys/test_pass.py @@ -0,0 +1,34 @@ +from pyosys import libyosys as ys + +import json +from pathlib import Path + +__file_dir__ = Path(__file__).absolute().parent + +class CellStatsPass(ys.Pass): + def __init__(self): + super().__init__( + "cell_stats", + "dumps cell statistics in JSON format" + ) + + def execute(self, args, design): + ys.log_header(design, "Dumping cell stats\n") + ys.log_push() + cell_stats = {} + for module in design.all_selected_whole_modules(): + for cell in module.selected_cells(): + if cell.type.str() in cell_stats: + cell_stats[cell.type.str()] += 1 + else: + cell_stats[cell.type.str()] = 1 + ys.log(json.dumps(cell_stats)) + ys.log_pop() + +p = CellStatsPass() # registration + +design = ys.Design() +ys.run_pass(f"read_verilog {__file_dir__.parent / 'simple' / 'fiedler-cooley.v'}", design) +ys.run_pass("prep", design) +ys.run_pass("opt -full", design) +ys.run_pass("cell_stats", design) diff --git a/chips/yosys/tests/pyosys/test_set.py b/chips/yosys/tests/pyosys/test_set.py new file mode 100644 index 0000000000000000000000000000000000000000..5698cffbef380562b67855ccc857e5586e74d778 --- /dev/null +++ b/chips/yosys/tests/pyosys/test_set.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +from pyosys.libyosys import StringSet, StringPool + +for cls in [StringSet, StringPool]: + print(f"Testing {cls.__name__}...") + A = cls() + A.add("a") + + B = cls() + B = A | {"b"} + + assert A < B + assert A <= B + + A.add("b") + + assert A == B + assert A <= B + assert not A < B + + A.add("c") + + assert A > B + + A &= B + assert A == B + + Ø = A - B + assert len(Ø) == 0 + + C = cls({"A", "B", "C"}) + D = cls() + C |= {"A", "B", "C"} + D |= {"C", "D", "E"} + c_symdiff_d = (C ^ D) + assert c_symdiff_d == {"A", "B", "D", "E"} # compare against iterable + + repr_test = eval(repr(c_symdiff_d)) + assert c_symdiff_d == repr_test # compare against self + + +print("Done.") diff --git a/chips/yosys/tests/pyosys/test_sigspec_it.py b/chips/yosys/tests/pyosys/test_sigspec_it.py new file mode 100644 index 0000000000000000000000000000000000000000..c875b19284f7eafca39ccda5f775143649214e29 --- /dev/null +++ b/chips/yosys/tests/pyosys/test_sigspec_it.py @@ -0,0 +1,27 @@ +from pyosys import libyosys as ys +from pathlib import Path + +__file_dir__ = Path(__file__).absolute().parent + +def _dump_sigbit(bit): + if bit.is_wire(): + if bit.wire.width == 1: + return bit.wire.name.str() + else: + return f"{bit.wire.name} [{bit.offset}]" + else: + if bit.data == ys.State.S1: + return 1 + elif bit.data == ys.State.S0: + return 0 + else: + assert "unknown constants not supported" + +d = ys.Design() + +ys.run_pass(f"read_verilog {__file_dir__ / 'spm.cut.v.gz'}", d) +ys.run_pass(f"hierarchy -top spm", d) +module = d.module(r"\spm") +for conn_from, conn_to in module.connections_: + for bit_from, bit_to in zip(conn_from, conn_to): + print(f"assign {_dump_sigbit(bit_from)} = {_dump_sigbit(bit_to)};") diff --git a/chips/yosys/tests/realmath/.gitignore b/chips/yosys/tests/realmath/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..9418562059c18c85ee2e380c7a6387f82a73798a --- /dev/null +++ b/chips/yosys/tests/realmath/.gitignore @@ -0,0 +1 @@ +uut_* diff --git a/chips/yosys/tests/realmath/generate_mk.py b/chips/yosys/tests/realmath/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..bee55816e58653cddc463c3c083cca14fe680319 --- /dev/null +++ b/chips/yosys/tests/realmath/generate_mk.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") +import gen_tests_makefile +import argparse +import sys +import random + + +def random_expression(depth = 3, maxparam = 0): + def recursion(): + return random_expression(depth = depth-1, maxparam = maxparam) + if depth == 0: + if maxparam != 0 and random.randint(0, 1) != 0: + return 'p%02d' % random.randint(0, maxparam-1) + return random.choice([ '%e', '%f', '%g' ]) % random.uniform(-2, +2) + if random.randint(0, 4) == 0: + return recursion() + random.choice([ ' < ', ' <= ', ' == ', ' != ', ' >= ', ' > ' ]) + recursion() + ' ? ' + recursion() + ' : ' + recursion() + op_prefix = [ '+(', '-(' ] + op_infix = [ ' + ', ' - ', ' * ', ' / ' ] + op_func1 = [ '$ln', '$log10', '$exp', '$sqrt', '$floor', '$ceil', '$sin', '$cos', '$tan', '$asin', '$acos', '$atan', '$sinh', '$cosh', '$tanh', '$asinh', '$acosh', '$atanh' ] + op_func2 = [ '$pow', '$atan2', '$hypot' ] + op = random.choice(op_prefix + op_infix + op_func1 + op_func2) + if op in op_prefix: + return op + recursion() + ')' + if op in op_infix: + return '(' + recursion() + op + recursion() + ')' + if op in op_func1: + return op + '(' + recursion() + ')' + if op in op_func2: + return op + '(' + recursion() + ', ' + recursion() + ')' + raise + +parser = argparse.ArgumentParser(formatter_class = argparse.ArgumentDefaultsHelpFormatter) +parser.add_argument('-S', '--seed', type = int, help = 'seed for PRNG') +parser.add_argument('-c', '--count', type = int, default = 100, help = 'number of test cases to generate') +args = parser.parse_args() + +seed = args.seed +if seed is None: + seed = random.randrange(sys.maxsize) +print("realmath PRNG seed: %d" % seed) +random.seed(seed) + +for idx in range(args.count): + with open('uut_%05d.v' % idx, 'w') as f: + with gen_tests_makefile.redirect_stdout(f): + print('module uut_%05d(output [63:0] %s);\n' % (idx, ', '.join(['y%02d' % i for i in range(100)]))) + for i in range(30): + if idx < 10: + print('localparam p%02d = %s;' % (i, random_expression())) + else: + print('localparam%s p%02d = %s;' % (random.choice(['', ' real', ' integer']), i, random_expression())) + for i in range(30, 60): + if idx < 10: + print('localparam p%02d = %s;' % (i, random_expression(maxparam = 30))) + else: + print('localparam%s p%02d = %s;' % (random.choice(['', ' real', ' integer']), i, random_expression(maxparam = 30))) + for i in range(100): + print('assign y%02d = 65536 * (%s);' % (i, random_expression(maxparam = 60))) + print('endmodule') + with open('uut_%05d.ys' % idx, 'w') as f: + with gen_tests_makefile.redirect_stdout(f): + print('read_verilog uut_%05d.v' % idx) + print('rename uut_%05d uut_%05d_syn' % (idx, idx)) + print('write_verilog uut_%05d_syn.v' % idx) + with open('uut_%05d_tb.v' % idx, 'w') as f: + with gen_tests_makefile.redirect_stdout(f): + print('module uut_%05d_tb;\n' % idx) + print('wire [63:0] %s;' % (', '.join(['r%02d' % i for i in range(100)]))) + print('wire [63:0] %s;' % (', '.join(['s%02d' % i for i in range(100)]))) + print('uut_%05d ref(%s);' % (idx, ', '.join(['r%02d' % i for i in range(100)]))) + print('uut_%05d_syn syn(%s);' % (idx, ', '.join(['s%02d' % i for i in range(100)]))) + print('task compare_ref_syn;') + print(' input [7:0] i;') + print(' input [63:0] r, s;') + print(' reg [64*8-1:0] buffer;') + print(' integer j;') + print(' begin') + print(' if (-1 <= $signed(r-s) && $signed(r-s) <= +1) begin') + print(' // $display("%d: %b %b", i, r, s);') + print(' end else if (r === s) begin ') + print(' // $display("%d: %b %b", i, r, s);') + print(' end else begin ') + print(' for (j = 0; j < 64; j = j+1)') + print(' buffer[j*8 +: 8] = r[j] !== s[j] ? "^" : " ";') + print(' $display("\\n%3d: %b %b", i, r, s);') + print(' $display(" %s %s", buffer, buffer);') + print(' end') + print(' end') + print('endtask') + print('initial begin #1;') + for i in range(100): + print(' compare_ref_syn(%2d, r%02d, s%02d);' % (i, i, i)) + print('end') + print('endmodule') + + +def create_tests(): + for idx in range(args.count): + cmd = [ + f"$(YOSYS) -qq uut_{idx:05d}.ys", + f"iverilog -o uut_{idx:05d}_tb uut_{idx:05d}_tb.v uut_{idx:05d}.v uut_{idx:05d}_syn.v", + f"./uut_{idx:05d}_tb" +# f"./uut_{idx:05d}_tb | tee uut_{idx:05d}.err;", +# f"if test -s uut_{idx:05d}.err; then", +# " echo \"Note: Make sure that iverilog is an up-to-date git checkout of Icarus Verilog.\";", +# " exit 1;", +# "fi;", +# f"rm -f uut_{idx:05d}.err" + ] + gen_tests_makefile.generate_cmd_test(f"uut_{idx:05d}", cmd) + +gen_tests_makefile.generate_custom(create_tests) diff --git a/chips/yosys/tests/rpc/design.v b/chips/yosys/tests/rpc/design.v new file mode 100644 index 0000000000000000000000000000000000000000..80f1dac1a2653fec55eb9cb7c89599fc9abda1b0 --- /dev/null +++ b/chips/yosys/tests/rpc/design.v @@ -0,0 +1,8 @@ +module top(input [3:0] i, output [3:0] o); + python_inv #( + .width(4) + ) inv ( + .i(i), + .o(o), + ); +endmodule diff --git a/chips/yosys/tests/rpc/exec.ys b/chips/yosys/tests/rpc/exec.ys new file mode 100644 index 0000000000000000000000000000000000000000..b46009fb9b603879855d9ea70578aa6a3ff3a4ac --- /dev/null +++ b/chips/yosys/tests/rpc/exec.ys @@ -0,0 +1,5 @@ +connect_rpc -exec python3 frontend.py stdio +read_verilog design.v +hierarchy -top top +flatten +select -assert-count 1 t:$neg diff --git a/chips/yosys/tests/rpc/frontend.py b/chips/yosys/tests/rpc/frontend.py new file mode 100644 index 0000000000000000000000000000000000000000..6619fb153bdd9322fe43fd0e394a83555dbb30fc --- /dev/null +++ b/chips/yosys/tests/rpc/frontend.py @@ -0,0 +1,132 @@ +def modules(): + return ["python_inv"] + +def derive(module, parameters): + assert module == r"python_inv" + if parameters.keys() != {r"\width"}: + raise ValueError("Invalid parameters") + return "rtlil", r""" +module \impl + wire width {width:d} input 1 \i + wire width {width:d} output 2 \o + cell $neg $0 + parameter \A_SIGNED 1'0 + parameter \A_WIDTH 32'{width:b} + parameter \Y_WIDTH 32'{width:b} + connect \A \i + connect \Y \o + end +end +module \python_inv + wire width {width:d} input 1 \i + wire width {width:d} output 2 \o + cell \impl $0 + connect \i \i + connect \o \o + end +end +""".format(width=parameters[r"\width"]) + +# ---------------------------------------------------------------------------- + +import json +import argparse +import sys, socket, os, subprocess +try: + import msvcrt, win32pipe, win32file +except ImportError: + msvcrt = win32pipe = win32file = None + +def map_parameter(parameter): + if parameter["type"] == "unsigned": + return int(parameter["value"], 2) + if parameter["type"] == "signed": + width = len(parameter["value"]) + value = int(parameter["value"], 2) + if value & (1 << (width - 1)): + value = -((1 << width) - value) + return value + if parameter["type"] == "string": + return parameter["value"] + if parameter["type"] == "real": + return float(parameter["value"]) + +def call(input_json): + input = json.loads(input_json) + if input["method"] == "modules": + return json.dumps({"modules": modules()}) + if input["method"] == "derive": + try: + frontend, source = derive(input["module"], + {name: map_parameter(value) for name, value in input["parameters"].items()}) + return json.dumps({"frontend": frontend, "source": source}) + except ValueError as e: + return json.dumps({"error": str(e)}) + +def main(): + parser = argparse.ArgumentParser() + modes = parser.add_subparsers(dest="mode") + mode_stdio = modes.add_parser("stdio") + if os.name == "posix": + mode_path = modes.add_parser("unix-socket") + if os.name == "nt": + mode_path = modes.add_parser("named-pipe") + mode_path.add_argument("path") + args = parser.parse_args() + + if args.mode == "stdio": + while True: + input = sys.stdin.readline() + if not input: break + sys.stdout.write(call(input) + "\n") + sys.stdout.flush() + + if args.mode == "unix-socket": + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.settimeout(30) + sock.bind(args.path) + try: + sock.listen(1) + ys_proc = subprocess.Popen([os.environ.get("YOSYS", "../../yosys"), "-ql", "unix.log", "-p", "connect_rpc -path {}; read_verilog design.v; hierarchy -top top; flatten; select -assert-count 1 t:$neg".format(args.path)]) + conn, addr = sock.accept() + file = conn.makefile("rw") + while True: + input = file.readline() + if not input: break + file.write(call(input) + "\n") + file.flush() + ys_proc.wait(timeout=10) + if ys_proc.returncode: + raise subprocess.CalledProcessError(ys_proc.returncode, ys_proc.args) + finally: + ys_proc.kill() + sock.close() + os.unlink(args.path) + + if args.mode == "named-pipe": + pipe = win32pipe.CreateNamedPipe(args.path, win32pipe.PIPE_ACCESS_DUPLEX, + win32pipe.PIPE_TYPE_BYTE|win32pipe.PIPE_READMODE_BYTE|win32pipe.PIPE_WAIT, + 1, 4096, 4096, 0, None) + win32pipe.ConnectNamedPipe(pipe, None) + try: + while True: + input = b"" + while not input.endswith(b"\n"): + result, data = win32file.ReadFile(pipe, 4096) + assert result == 0 + input += data + assert not b"\n" in input or input.endswith(b"\n") + output = (call(input.decode("utf-8")) + "\n").encode("utf-8") + length = len(output) + while length > 0: + result, done = win32file.WriteFile(pipe, output) + assert result == 0 + length -= done + except win32file.error as e: + if e.args[0] == 109: # ERROR_BROKEN_PIPE + pass + else: + raise + +if __name__ == "__main__": + main() diff --git a/chips/yosys/tests/rpc/generate_mk.py b/chips/yosys/tests/rpc/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..aca802ebeba3a7eb79887b2512f1bc05cbf04780 --- /dev/null +++ b/chips/yosys/tests/rpc/generate_mk.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile +import glob + +def create_tests(): + yss = sorted(glob.glob("*.ys")) + for ys in yss: + gen_tests_makefile.generate_ys_test(ys) + + cmd = [ "python3 frontend.py unix-socket frontend.sock" ] + gen_tests_makefile.generate_cmd_test("frontend.py", cmd) + +gen_tests_makefile.generate_custom(create_tests) diff --git a/chips/yosys/tests/rtlil/.gitignore b/chips/yosys/tests/rtlil/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..36445e53cb40bd998daedb70dc1f3eeb23eca98e --- /dev/null +++ b/chips/yosys/tests/rtlil/.gitignore @@ -0,0 +1 @@ +/temp diff --git a/chips/yosys/tests/rtlil/bug1206.ys b/chips/yosys/tests/rtlil/bug1206.ys new file mode 100644 index 0000000000000000000000000000000000000000..0084bb0f4b10879db8fba669b23f0d8f565553eb --- /dev/null +++ b/chips/yosys/tests/rtlil/bug1206.ys @@ -0,0 +1,6 @@ +logger -expect error "Wire width .* out of range" 1 +read_rtlil < temp/suffix-twines-write-nogen.il +diff suffix-twines.il temp/suffix-twines-write-nogen.il + +${YOSYS} -p "read_rtlil suffix-twines.il; design -push; design -pop; write_rtlil temp/suffix-twines-push.il" +tail -n +2 temp/suffix-twines-push.il > temp/suffix-twines-push-nogen.il +diff suffix-twines.il temp/suffix-twines-push-nogen.il + +${YOSYS} -p "read_rtlil suffix-chain.il; design -push; design -pop; write_rtlil temp/suffix-chain-push.il" +tail -n +2 temp/suffix-chain-push.il > temp/suffix-chain-push-nogen.il +diff suffix-chain.il temp/suffix-chain-push-nogen.il + +${YOSYS} -p "read_rtlil suffix-chain.il; opt_clean; write_rtlil -readable temp/suffix-chain-gc-resolved.il" +grep 'wire' temp/suffix-chain-gc-resolved.il | sort > temp/suffix-chain-gc-resolved.names +cat > temp/suffix-chain-expected.names < temp/tmp + mv temp/tmp "$file" +} + +# write_rtlil and dump are equivalent +${YOSYS} -p "read_verilog -sv everything.v; copy alu zzz; proc zzz; dump -o temp/roundtrip-text.dump.il; write_rtlil temp/roundtrip-text.write.il" +remove_empty_lines temp/roundtrip-text.dump.il +remove_empty_lines temp/roundtrip-text.write.il +# Trim first line ("Generated by Yosys ...") +tail -n +2 temp/roundtrip-text.write.il > temp/roundtrip-text.write-nogen.il +diff temp/roundtrip-text.dump.il temp/roundtrip-text.write-nogen.il + +# Loading and writing it out again doesn't change the RTLIL +${YOSYS} -p "read_rtlil temp/roundtrip-text.dump.il; write_rtlil temp/roundtrip-text.reload.il" +remove_empty_lines temp/roundtrip-text.reload.il +tail -n +2 temp/roundtrip-text.reload.il > temp/roundtrip-text.reload-nogen.il +diff temp/roundtrip-text.dump.il temp/roundtrip-text.reload-nogen.il diff --git a/chips/yosys/tests/rtlil/suffix-chain.il b/chips/yosys/tests/rtlil/suffix-chain.il new file mode 100644 index 0000000000000000000000000000000000000000..ad72f47cdf0baf37d94ed4dc8a039862708ec9e8 --- /dev/null +++ b/chips/yosys/tests/rtlil/suffix-chain.il @@ -0,0 +1,15 @@ +autoidx 1 +metadata + twines + root 1054 "home" + suffix 1055 1054 ".repo" + suffix 1056 1055 ".chain" + suffix 1057 1056 ".in" + suffix 1058 1056 ".out" + end +end +module \chain + wire input 1 $pub@1057 # \home.repo.chain.in + wire output 2 $pub@1058 # \home.repo.chain.out + connect $pub@1058 $pub@1057 # \home.repo.chain.out \home.repo.chain.in +end diff --git a/chips/yosys/tests/rtlil/suffix-twines.il b/chips/yosys/tests/rtlil/suffix-twines.il new file mode 100644 index 0000000000000000000000000000000000000000..460f9490f8a9d400a2bc83ad44153d0fa0756a51 --- /dev/null +++ b/chips/yosys/tests/rtlil/suffix-twines.il @@ -0,0 +1,14 @@ +autoidx 1 +metadata + twines + root 1054 "everything" + suffix 1055 1054 ".a" + suffix 1056 1054 ".b" + root 1057 "tiny" + end +end +module $pub@1057 # \tiny + wire input 1 $pub@1055 # \everything.a + wire output 2 $pub@1056 # \everything.b + connect $pub@1056 $pub@1055 # \everything.b \everything.a +end diff --git a/chips/yosys/tests/rtlil/twines-forward-compat.sh b/chips/yosys/tests/rtlil/twines-forward-compat.sh new file mode 100644 index 0000000000000000000000000000000000000000..fb88c5cc01548f5866cf45b2c467aba56624f405 --- /dev/null +++ b/chips/yosys/tests/rtlil/twines-forward-compat.sh @@ -0,0 +1,42 @@ +set -euo pipefail + +mkdir -p temp + +# If a different version of Yosys with different constids.inc wrote a file, +# the integers have to get remapped when read into this version +cat > temp/moved-static.il < temp/stale-dynamic.il <&1 | grep 'Unknown getter' diff --git a/chips/yosys/tests/select/boxes.v b/chips/yosys/tests/select/boxes.v new file mode 100644 index 0000000000000000000000000000000000000000..696b265230a92c29b7ebd2d01cb1fea6bce6ef18 --- /dev/null +++ b/chips/yosys/tests/select/boxes.v @@ -0,0 +1,16 @@ +module top(input a, b, output o); +assign o = a & b; +endmodule + +(* blackbox *) +module bb(input a, b, output o); +assign o = a | b; +specify + (a => o) = 1; +endspecify +endmodule + +(* whitebox *) +module wb(input a, b, output o); +assign o = a ^ b; +endmodule diff --git a/chips/yosys/tests/select/boxes_equals_name.ys b/chips/yosys/tests/select/boxes_equals_name.ys new file mode 100644 index 0000000000000000000000000000000000000000..fea62a59637a943fcd9ed67b894c6069b6eed2e6 --- /dev/null +++ b/chips/yosys/tests/select/boxes_equals_name.ys @@ -0,0 +1,7 @@ +read_verilog -specify boxes.v +clean + +select -set top top +select -assert-count 4 @top +select -set boxes =?b +select -assert-count 9 @boxes diff --git a/chips/yosys/tests/select/boxes_equals_operators.ys b/chips/yosys/tests/select/boxes_equals_operators.ys new file mode 100644 index 0000000000000000000000000000000000000000..e2dcac9bf397c5f69f38e5c9cfaee09af330d8f0 --- /dev/null +++ b/chips/yosys/tests/select/boxes_equals_operators.ys @@ -0,0 +1,38 @@ +read_verilog -specify boxes.v +clean + +# wb = 4w1c, bb = 3w1c, top = 3w1c +select =wb +select -assert-count 5 % +select -add =bb +select -assert-count 9 % +select -del =wb +select -assert-count 4 % + +# unions +select -assert-count 8 =bb * %u +select -assert-count 8 * =bb %u +select -assert-count 13 top =* %u +select -assert-count 8 =bb top %u +select -assert-count 8 top =bb %u + +# intersections +select -assert-count 3 =w:* =bb %i +select -assert-count 4 =* * %i +select -assert-count 4 * =* %i + +# inverses +select -assert-count 8 =wb %n +select -assert-none top %n +select -assert-none * %n +select -assert-none =* %n +select -assert-count 9 =top %n + +# differences +select -assert-count 9 =* top %d +select -assert-count 0 top =* %d +select -assert-count 9 =* * %d +select -assert-count 0 * =* %d + +# random +select -assert-any =?b %R diff --git a/chips/yosys/tests/select/boxes_equals_pattern.ys b/chips/yosys/tests/select/boxes_equals_pattern.ys new file mode 100644 index 0000000000000000000000000000000000000000..d84091cc4cdb8860d88e090f8bdf1a5df02f4efa --- /dev/null +++ b/chips/yosys/tests/select/boxes_equals_pattern.ys @@ -0,0 +1,7 @@ +read_verilog -specify boxes.v +clean + +select -assert-none ?b +select -assert-count 4 =bb +select -assert-count 5 =wb +select -assert-count 9 =?b diff --git a/chips/yosys/tests/select/boxes_equals_wildcard.ys b/chips/yosys/tests/select/boxes_equals_wildcard.ys new file mode 100644 index 0000000000000000000000000000000000000000..0ff387a0aec8bfd3493b4ec4dc6faf8d9077ea80 --- /dev/null +++ b/chips/yosys/tests/select/boxes_equals_wildcard.ys @@ -0,0 +1,6 @@ +read_verilog -specify boxes.v +clean + +select -assert-count 3 =c:* +select -assert-count 10 =w:* +select -assert-count 13 =* diff --git a/chips/yosys/tests/select/boxes_import.ys b/chips/yosys/tests/select/boxes_import.ys new file mode 100644 index 0000000000000000000000000000000000000000..d5b414e054a121ee8b7f778d36884b80f593c5da --- /dev/null +++ b/chips/yosys/tests/select/boxes_import.ys @@ -0,0 +1,29 @@ +read_verilog -specify boxes.v +design -save read + +logger -expect-no-warnings + +delete =bb %n +select -assert-mod-count 1 =* +design -stash just_bb + +design -import just_bb +select -assert-mod-count 0 * +select -assert-mod-count 1 =* +design -reset + +design -import just_bb -as new +select -assert-mod-count 0 * +select -assert-mod-count 1 =* +design -reset + +design -import read -as new_top top +design -import read -as new_bb =bb +select -assert-mod-count 1 * +select -assert-mod-count 2 =* + +logger -check-expected + +logger -expect warning "Selection .wb. did not match any module\." 1 +logger -expect error "No top module found in source design\." 1 +design -import read -as new_wb wb diff --git a/chips/yosys/tests/select/boxes_no_equals.ys b/chips/yosys/tests/select/boxes_no_equals.ys new file mode 100644 index 0000000000000000000000000000000000000000..d9da7387c3268fcc9506cc0bba3f469a9b9a61e8 --- /dev/null +++ b/chips/yosys/tests/select/boxes_no_equals.ys @@ -0,0 +1,7 @@ +read_verilog -specify boxes.v +clean + +select -assert-count 1 c:* +select -assert-none t:* t:$and %d +select -assert-count 3 w:* +select -assert-count 4 * diff --git a/chips/yosys/tests/select/boxes_no_equals_clean.ys b/chips/yosys/tests/select/boxes_no_equals_clean.ys new file mode 100644 index 0000000000000000000000000000000000000000..856be8d1b79919ca28f371f1b3b407fe84989212 --- /dev/null +++ b/chips/yosys/tests/select/boxes_no_equals_clean.ys @@ -0,0 +1,18 @@ +read_verilog -specify boxes.v + +logger -expect warning "did not match any module" 2 +clean wb +opt_clean wb +logger -check-expected + +select -clear +logger -expect warning "did not match any module" 2 +clean wb +opt_clean wb +logger -check-expected + +select -none +logger -expect warning "did not match any module" 2 +clean wb +opt_clean wb +logger -check-expected diff --git a/chips/yosys/tests/select/boxes_setattr.ys b/chips/yosys/tests/select/boxes_setattr.ys new file mode 100644 index 0000000000000000000000000000000000000000..6a7383d58f121d0b1290b1d1952915bc1cdbb29c --- /dev/null +++ b/chips/yosys/tests/select/boxes_setattr.ys @@ -0,0 +1,39 @@ +read_verilog -specify boxes.v + +design -save read +select -assert-none =a:test_attr +select -assert-none =A:test_attr + +# setattr =* affects all modules +setattr -set test_attr 1 =* +select -assert-mod-count 3 =a:test_attr +select -assert-none =A:test_attr + +design -load read +setattr -mod -set test_attr 1 =* +select -assert-none =a:test_attr +select -assert-mod-count 3 =A:test_attr + +# setattr * doesn't affect boxed modules +design -load read +setattr -mod -set test_attr 1 * +select -assert-mod-count 1 =A:test_attr + +# setattr can set and unset whitebox attr +design -load read +setattr -mod -unset whitebox =wb +select -assert-mod-count 2 * +setattr -mod -set whitebox 1 wb +select -assert-mod-count 1 * + +# wbflip works on all non-bb in selection +design -load read +select -assert-mod-count 1 =A:whitebox +wbflip +select -assert-mod-count 2 =A:whitebox +wbflip +select -assert-mod-count 2 =A:whitebox +wbflip =wb +select -assert-mod-count 1 =A:whitebox +wbflip =bb +select -assert-mod-count 1 =A:whitebox diff --git a/chips/yosys/tests/select/boxes_stack.ys b/chips/yosys/tests/select/boxes_stack.ys new file mode 100644 index 0000000000000000000000000000000000000000..8c2eb7526ebfdd1fec0279063617fc7a6697d371 --- /dev/null +++ b/chips/yosys/tests/select/boxes_stack.ys @@ -0,0 +1,29 @@ +read_verilog -specify boxes.v +clean + +# default selection == select * +select -assert-count 4 * +select -assert-count 4 % + +# -none replaces default selection +select -none +select -assert-none % +select -assert-count 13 =* + +# select replaces current selection +select =* +select -assert-count 13 % + +# -module changes module +select -module wb +select -assert-none % +select -assert-count 5 =* + +# -none maintains module +select -none +select -assert-count 5 =* + +# -clear clears current selection and module +select -clear +select -assert-count 4 % +select -assert-count 13 =* diff --git a/chips/yosys/tests/select/generate_mk.py b/chips/yosys/tests/select/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..6a921d5a026cbd59f805c297d1c28db16de0c1e9 --- /dev/null +++ b/chips/yosys/tests/select/generate_mk.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile + +gen_tests_makefile.generate(["--yosys-scripts"]) diff --git a/chips/yosys/tests/select/internal_selects.ys b/chips/yosys/tests/select/internal_selects.ys new file mode 100644 index 0000000000000000000000000000000000000000..67b7cf63fb2a7b593f64b508b772f548154cce4b --- /dev/null +++ b/chips/yosys/tests/select/internal_selects.ys @@ -0,0 +1,165 @@ +read_verilog boxes.v + +## base case, no warnings ## +logger -expect-no-warnings + +select =* +select -assert-count 13 % +select -assert-mod-count 3 % +test_select # SELECT_ALL && SB_ALL +select -assert-count 13 % +select -assert-mod-count 3 % + +select =* +select -assert-mod-count 3 % +test_select -whole_only # SELECT_WHOLE_ONLY +select -assert-mod-count 3 % + +select =* +select -assert-count 13 % +test_select -unboxed_only -include_wb # SB_EXCL_BB_ONLY +select -assert-count 10 % + +select =* +select -assert-count 13 % +test_select -unboxed_only # SB_UNBOXED_ONLY +select -assert-count 5 % + +logger -check-expected + +## don't add to selection ## +select * +select -assert-count 5 % +select -assert-mod-count 1 % +test_select # SELECT_ALL && SB_ALL +select -assert-count 5 % +select -assert-mod-count 1 % + +select =wb/a %n +select -assert-mod-count 3 % +test_select -whole_only # SELECT_WHOLE_ONLY +select -assert-mod-count 2 % + +select =w:* +select -assert-mod-count 3 % +test_select -whole_only # SELECT_WHOLE_ONLY +select -assert-mod-count 1 % + +select =w:* +select -assert-mod-count 3 % +test_select -whole_only -unboxed_only # SELECT_WHOLE_ONLY && SB_UNBOXED_ONLY +select -assert-none % + +select =w:* %n +select -assert-mod-count 2 % +test_select -whole_only # SELECT_WHOLE_ONLY +select -assert-none % + +select =?b +select -assert-count 8 % +test_select -unboxed_only -include_wb # SB_EXCL_BB_ONLY +select -assert-count 5 % + +select =?b +select -assert-count 8 % +test_select -unboxed_only # SB_UNBOXED_ONLY +select -assert-none % + +select =wb %n +select -assert-count 8 % +test_select -unboxed_only -include_wb # SB_EXCL_BB_ONLY +select -assert-count 5 % + +select =top/a %n +select -assert-count 12 % +select -assert-mod-count 3 % +test_select -whole_only -unboxed_only -include_wb # SELECT_WHOLE_ONLY && SB_EXCL_BB_ONLY +select -assert-count 5 % +select -assert-mod-count 1 % + +## warnings work ## +logger -expect warning "Ignoring blackbox module bb." 1 +select =* +test_select -unboxed_only -include_wb -warn_boxes # SB_EXCL_BB_WARN +logger -check-expected + +logger -expect warning "Ignoring boxed module .b." 2 +select =* +test_select -unboxed_only -warn_boxes # SB_UNBOXED_WARN +logger -check-expected + +logger -expect warning "Ignoring partially selected module [wb|top]." 2 +select =w:* +test_select -whole_warn # SELECT_WHOLE_WARN +logger -check-expected + +logger -expect warning "Ignoring partially selected module [wb|top]." 2 +logger -expect warning "Ignoring blackbox module bb." 1 +select =w:* +test_select -whole_warn -unboxed_only -include_wb -warn_boxes # SELECT_WHOLE_WARN && SB_EXCL_BB_WARN +logger -check-expected + +logger -expect warning "Ignoring partially selected module [wb|top]." 2 +logger -expect warning "Ignoring boxed module bb." 1 +select =w:* +test_select -whole_warn -unboxed_only -warn_boxes # SELECT_WHOLE_WARN && SB_UNBOXED_WARN +logger -check-expected + +## partials warn before boxes ## +logger -expect warning "Ignoring partially selected module wb." 1 +select =wb/a +test_select -whole_warn -unboxed_only -warn_boxes # SELECT_WHOLE_WARN && SB_UNBOXED_WARN +logger -check-expected + +## boxes won't warn if they've been removed because of partial selection ## +logger -expect-no-warnings +select =wb/a +test_select -whole_only -unboxed_only -warn_boxes # SELECT_WHOLE_ONLY && SB_UNBOXED_WARN +logger -check-expected + +## boxes still warn if they're not partially selected +logger -expect warning "Ignoring boxed module wb." 1 +select =bb %n +test_select -whole_only -unboxed_only -warn_boxes # SELECT_WHOLE_ONLY && SB_UNBOXED_WARN +logger -check-expected + +## don't warn if it's not selected ## +logger -expect-no-warnings +select =bb %n +test_select -unboxed_only -include_wb -warn_boxes # SB_EXCL_BB_WARN +logger -check-expected + +logger -expect-no-warnings +select * +test_select -unboxed_only -warn_boxes # SB_UNBOXED_WARN +logger -check-expected + +logger -expect warning "Ignoring boxed module bb." 1 +select =wb %n +test_select -unboxed_only -warn_boxes # SB_UNBOXED_WARN +logger -check-expected + +## don't error if it's not selected ## +logger -expect-no-warnings + +select =bb %n +test_select -unboxed_only -include_wb -err_boxes # SB_EXCL_BB_ERR + +select =bb %n +test_select -unboxed_only -include_wb -cmderr_boxes # SB_EXCL_BB_CMDERR + +select * +test_select -unboxed_only -err_boxes # SB_UNBOXED_ERR + +select * +test_select -unboxed_only -cmderr_boxes # SB_UNBOXED_CMDERR + +select * +test_select -whole_err # SELECT_WHOLE_ERR + +select * +test_select -whole_cmderr # SELECT_WHOLE_CMDERR + +logger -check-expected + +## diff --git a/chips/yosys/tests/select/list_mod.ys b/chips/yosys/tests/select/list_mod.ys new file mode 100644 index 0000000000000000000000000000000000000000..c8a3ac8b5eb6236fa0bbb3c007b14346fa2c2a12 --- /dev/null +++ b/chips/yosys/tests/select/list_mod.ys @@ -0,0 +1,13 @@ +read_verilog <=', '>' ]), + random.choice(['<<', '>>', '<<<', '>>>']), + random.choice(['|', '&', '^', '~^', '||', '&&']), + ]) + print(' input%s [%d:0] a;' % (random.choice(['', ' signed']), random.randint(0, 8))) + print(' input%s [%d:0] b;' % (random.choice(['', ' signed']), random.randint(0, 8))) + print(' input%s [%d:0] c;' % (random.choice(['', ' signed']), random.randint(0, 8))) + print(' input%s [%d:0] d;' % (random.choice(['', ' signed']), random.randint(0, 8))) + print(' input%s [%d:0] x;' % (random.choice(['', ' signed']), random.randint(0, 8))) + print(' input s;') + print(' output [%d:0] y;' % random.randint(0, 8)) + print(' assign y = (s ? %s(%s %s %s) : %s(%s %s %s))%s;' % + (random.choice(['', '$signed', '$unsigned']), maybe_plus_x('a'), op, maybe_plus_x('b'), + random.choice(['', '$signed', '$unsigned']), maybe_plus_x('c'), op, maybe_plus_x('d'), + random_plus_x() if random.randint(0, 4) == 0 else '')) + print('endmodule') + else: + print('module uut_%05d(a, b, x, s, y);' % (idx)) + op = random.choice(['~', '-', '!']) + print(' input%s [%d:0] a;' % (random.choice(['', ' signed']), random.randint(0, 8))) + print(' input%s [%d:0] b;' % (random.choice(['', ' signed']), random.randint(0, 8))) + print(' input%s [%d:0] x;' % (random.choice(['', ' signed']), random.randint(0, 8))) + print(' input s;') + print(' output [%d:0] y;' % random.randint(0, 8)) + print(' assign y = (s ? %s(%s%s) : %s(%s%s))%s;' % + (random.choice(['', '$signed', '$unsigned']), op, maybe_plus_x('a'), + random.choice(['', '$signed', '$unsigned']), op, maybe_plus_x('b'), + random_plus_x() if random.randint(0, 4) == 0 else '')) + print('endmodule') + with open('uut_%05d.ys' % idx, 'w') as f: + with gen_tests_makefile.redirect_stdout(f): + print('read_verilog uut_%05d.v' % idx) + print('proc -noopt;;') + print('copy uut_%05d gold' % idx) + print('rename uut_%05d gate' % idx) + print('tee -o uut_%05d.txt wreduce' % idx) + print('tee -a uut_%05d.txt share -aggressive gate' % idx) + print('miter -equiv -flatten -ignore_gold_x -make_outputs -make_outcmp gold gate miter') + print('sat -set-def-inputs -verify -prove trigger 0 -show-inputs -show-outputs miter') + print('! grep -q \'^Removing [246] cells\' uut_%05d.txt' % idx) + +gen_tests_makefile.generate(["--yosys-scripts"]) diff --git a/chips/yosys/tests/sim/.gitignore b/chips/yosys/tests/sim/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..769b314cdba28a9daee70f659b10fcdc49fb44c4 --- /dev/null +++ b/chips/yosys/tests/sim/.gitignore @@ -0,0 +1,3 @@ ++*_synth.v ++*_testbench +*.fst diff --git a/chips/yosys/tests/sim/adff.v b/chips/yosys/tests/sim/adff.v new file mode 100644 index 0000000000000000000000000000000000000000..8c8fb0acf5a0994ad0055b51c1fc01d98299061f --- /dev/null +++ b/chips/yosys/tests/sim/adff.v @@ -0,0 +1,7 @@ +module adff( input d, clk, rst, output reg q ); + always @( posedge clk, posedge rst ) + if (rst) + q <= 0; + else + q <= d; +endmodule diff --git a/chips/yosys/tests/sim/adffe.v b/chips/yosys/tests/sim/adffe.v new file mode 100644 index 0000000000000000000000000000000000000000..55c7d8d4e141c0756c9b9b22dd2296ad06889ef6 --- /dev/null +++ b/chips/yosys/tests/sim/adffe.v @@ -0,0 +1,8 @@ +module adffe( input d, clk, rst, en, output reg q ); + always @( posedge clk, posedge rst ) + if (rst) + q <= 0; + else + if (en) + q <= d; +endmodule diff --git a/chips/yosys/tests/sim/adlatch.v b/chips/yosys/tests/sim/adlatch.v new file mode 100644 index 0000000000000000000000000000000000000000..5e8f48e49188db0145561f5c7f0901f82631701c --- /dev/null +++ b/chips/yosys/tests/sim/adlatch.v @@ -0,0 +1,8 @@ +module adlatch( input d, rst, en, output reg q ); + always @* begin + if (rst) + q = 0; + else if (en) + q = d; + end +endmodule diff --git a/chips/yosys/tests/sim/aldff.v b/chips/yosys/tests/sim/aldff.v new file mode 100644 index 0000000000000000000000000000000000000000..eeb0f06739d138fa343dcaa6bd2dab1db9da3d3c --- /dev/null +++ b/chips/yosys/tests/sim/aldff.v @@ -0,0 +1,7 @@ +module aldff( input [0:3] d, input [0:3] ad, input clk, aload, output reg [0:3] q ); + always @( posedge clk, posedge aload) + if (aload) + q <= ad; + else + q <= d; +endmodule diff --git a/chips/yosys/tests/sim/aldffe.v b/chips/yosys/tests/sim/aldffe.v new file mode 100644 index 0000000000000000000000000000000000000000..79c65afc49af49a226643d204dff137f8f503d84 --- /dev/null +++ b/chips/yosys/tests/sim/aldffe.v @@ -0,0 +1,8 @@ +module aldffe( input [0:3] d, input [0:3] ad, input clk, aload, en, output reg [0:3] q ); + always @( posedge clk, posedge aload) + if (aload) + q <= ad; + else + if (en) + q <= d; +endmodule diff --git a/chips/yosys/tests/sim/assume_x_first_step.ys b/chips/yosys/tests/sim/assume_x_first_step.ys new file mode 100644 index 0000000000000000000000000000000000000000..20c759950ef18c21b1854f48e3d95f661b7b1ffa --- /dev/null +++ b/chips/yosys/tests/sim/assume_x_first_step.ys @@ -0,0 +1,2 @@ +read_verilog simple_assign.v +sim -r simple_assign.vcd -scope simple_assign diff --git a/chips/yosys/tests/sim/dff.v b/chips/yosys/tests/sim/dff.v new file mode 100644 index 0000000000000000000000000000000000000000..ce792b59a0c4461d51202a836069c0bc206abb11 --- /dev/null +++ b/chips/yosys/tests/sim/dff.v @@ -0,0 +1,4 @@ +module dff( input d, clk, output reg q ); + always @( posedge clk ) + q <= d; +endmodule diff --git a/chips/yosys/tests/sim/dffe.v b/chips/yosys/tests/sim/dffe.v new file mode 100644 index 0000000000000000000000000000000000000000..853fcf66abcb70e7cd90af7fbd4ea006d485b6c5 --- /dev/null +++ b/chips/yosys/tests/sim/dffe.v @@ -0,0 +1,5 @@ +module dffe( input clk, en, d, output reg q ); + always @( posedge clk ) + if ( en ) + q <= d; +endmodule diff --git a/chips/yosys/tests/sim/dffsr.v b/chips/yosys/tests/sim/dffsr.v new file mode 100644 index 0000000000000000000000000000000000000000..2158708f171e6011ac184b9139d3362471936c82 --- /dev/null +++ b/chips/yosys/tests/sim/dffsr.v @@ -0,0 +1,9 @@ +module dffsr( input clk, d, clr, set, output reg q ); + always @( posedge clk, posedge set, posedge clr) + if ( clr ) + q <= 0; + else if (set) + q <= 1; + else + q <= d; +endmodule diff --git a/chips/yosys/tests/sim/dlatch.v b/chips/yosys/tests/sim/dlatch.v new file mode 100644 index 0000000000000000000000000000000000000000..315b4321677c8e1ceb74213e19536d5f5f645a08 --- /dev/null +++ b/chips/yosys/tests/sim/dlatch.v @@ -0,0 +1,6 @@ +module dlatch( input d, en, output reg q ); + always @* begin + if ( en ) + q = d; + end +endmodule diff --git a/chips/yosys/tests/sim/dlatchsr.v b/chips/yosys/tests/sim/dlatchsr.v new file mode 100644 index 0000000000000000000000000000000000000000..1d13ac2add7be99f793236625b84ddc38f2d3725 --- /dev/null +++ b/chips/yosys/tests/sim/dlatchsr.v @@ -0,0 +1,11 @@ +module dlatchsr( input d, set, clr, en, output reg q ); + always @* begin + if ( clr ) + q = 0; + else if (set) + q = 1; + else + if (en) + q = d; + end +endmodule diff --git a/chips/yosys/tests/sim/generate_mk.py b/chips/yosys/tests/sim/generate_mk.py new file mode 100644 index 0000000000000000000000000000000000000000..47b22971a5facc30c2e399e90aef8d84859ed882 --- /dev/null +++ b/chips/yosys/tests/sim/generate_mk.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 + +import sys +sys.path.append("..") + +import gen_tests_makefile + +import subprocess +from pathlib import Path + +print("Generate FST for sim models") + +for name in Path("tb").rglob("tb*.v"): + test_name = name.stem + print(f"Test {test_name}") + + verilog_name = f"{test_name[3:]}.v" + + out_file = Path("tb") / f"{test_name}.out" + + subprocess.run( + ["iverilog", "-o", str(out_file), str(name), verilog_name], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=True + ) + + subprocess.run( + [str(out_file), "-fst"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=True + ) + +gen_tests_makefile.generate(["--yosys-scripts", "--bash", "--yosys-args", "-w 'Yosys has only limited support for tri-state logic at the moment.'" ]) diff --git a/chips/yosys/tests/sim/sdff.v b/chips/yosys/tests/sim/sdff.v new file mode 100644 index 0000000000000000000000000000000000000000..6b25516e18b90734150383c13ec267602edba902 --- /dev/null +++ b/chips/yosys/tests/sim/sdff.v @@ -0,0 +1,7 @@ +module sdff( input d, clk, rst, output reg q ); + always @( posedge clk) + if (rst) + q <= 0; + else + q <= d; +endmodule diff --git a/chips/yosys/tests/sim/sdffce.v b/chips/yosys/tests/sim/sdffce.v new file mode 100644 index 0000000000000000000000000000000000000000..7d27d574180f9838d0202aaf598898590a98e889 --- /dev/null +++ b/chips/yosys/tests/sim/sdffce.v @@ -0,0 +1,8 @@ +module sdffce( input d, clk, rst, en, output reg q ); + always @( posedge clk) + if(en) + if (rst) + q <= 0; + else + q <= d; +endmodule diff --git a/chips/yosys/tests/sim/sdffe.v b/chips/yosys/tests/sim/sdffe.v new file mode 100644 index 0000000000000000000000000000000000000000..0a96693e16a8c2de3d4e5de72ebd97898830015f --- /dev/null +++ b/chips/yosys/tests/sim/sdffe.v @@ -0,0 +1,8 @@ +module sdffe( input d, clk, rst, en, output reg q ); + always @( posedge clk) + if (rst) + q <= 0; + else + if (en) + q <= d; +endmodule diff --git a/chips/yosys/tests/sim/sim_adff.ys b/chips/yosys/tests/sim/sim_adff.ys new file mode 100644 index 0000000000000000000000000000000000000000..6efd804a95b2a641797bef670f899aeed49c2941 --- /dev/null +++ b/chips/yosys/tests/sim/sim_adff.ys @@ -0,0 +1,6 @@ +read_verilog adff.v +proc +opt_dff +stat +select -assert-count 1 t:$adff +sim -clock clk -r tb_adff.fst -scope tb_adff.uut -sim-cmp adff diff --git a/chips/yosys/tests/sim/sim_adffe.ys b/chips/yosys/tests/sim/sim_adffe.ys new file mode 100644 index 0000000000000000000000000000000000000000..47a51ebce69e92b976039e3f0b21ee677ee57359 --- /dev/null +++ b/chips/yosys/tests/sim/sim_adffe.ys @@ -0,0 +1,6 @@ +read_verilog adffe.v +proc +opt_dff +stat +select -assert-count 1 t:$adffe +sim -clock clk -r tb_adffe.fst -scope tb_adffe.uut -sim-cmp adffe diff --git a/chips/yosys/tests/sim/sim_adlatch.ys b/chips/yosys/tests/sim/sim_adlatch.ys new file mode 100644 index 0000000000000000000000000000000000000000..eece7dc0d586f1be2410b8a2c5f1d8d1032d37f7 --- /dev/null +++ b/chips/yosys/tests/sim/sim_adlatch.ys @@ -0,0 +1,10 @@ +read_verilog -icells <>=) +`TEST(sshl, <<<=) +`TEST(sshr, >>>=) diff --git a/chips/yosys/tests/simple/attrib01_module.v b/chips/yosys/tests/simple/attrib01_module.v new file mode 100644 index 0000000000000000000000000000000000000000..38bda4c0d78bafd29284d59bca772a784913fd3c --- /dev/null +++ b/chips/yosys/tests/simple/attrib01_module.v @@ -0,0 +1,20 @@ +module attrib01_bar(clk, rst, inp, out); + input wire clk; + input wire rst; + input wire inp; + output reg out; + + always @(posedge clk) + if (rst) out <= 1'd0; + else out <= ~inp; + +endmodule + +module attrib01_foo(clk, rst, inp, out); + input wire clk; + input wire rst; + input wire inp; + output wire out; + + attrib01_bar bar_instance (clk, rst, inp, out); +endmodule diff --git a/chips/yosys/tests/simple/attrib02_port_decl.v b/chips/yosys/tests/simple/attrib02_port_decl.v new file mode 100644 index 0000000000000000000000000000000000000000..0c6b1545fe7875f0c7476253822e407dc6837915 --- /dev/null +++ b/chips/yosys/tests/simple/attrib02_port_decl.v @@ -0,0 +1,24 @@ +module attrib02_bar(clk, rst, inp, out); + (* this_is_clock = 1 *) + input wire clk; + (* this_is_reset = 1 *) + input wire rst; + input wire inp; + (* an_output_register = 1*) + output reg out; + + always @(posedge clk) + if (rst) out <= 1'd0; + else out <= ~inp; + +endmodule + +module attrib02_foo(clk, rst, inp, out); + (* this_is_the_master_clock *) + input wire clk; + input wire rst; + input wire inp; + output wire out; + + attrib02_bar bar_instance (clk, rst, inp, out); +endmodule diff --git a/chips/yosys/tests/simple/attrib03_parameter.v b/chips/yosys/tests/simple/attrib03_parameter.v new file mode 100644 index 0000000000000000000000000000000000000000..4a84b25dff27ade9626471695864b5794d3e379c --- /dev/null +++ b/chips/yosys/tests/simple/attrib03_parameter.v @@ -0,0 +1,27 @@ +module attrib03_bar(clk, rst, inp, out); + + (* bus_width *) + parameter WIDTH = 2; + + (* an_attribute_on_localparam = 55 *) + localparam INCREMENT = 5; + + input wire clk; + input wire rst; + input wire [WIDTH-1:0] inp; + output reg [WIDTH-1:0] out; + + always @(posedge clk) + if (rst) out <= 0; + else out <= inp + INCREMENT; + +endmodule + +module attrib03_foo(clk, rst, inp, out); + input wire clk; + input wire rst; + input wire [7:0] inp; + output wire [7:0] out; + + attrib03_bar # (.WIDTH(8)) bar_instance (clk, rst, inp, out); +endmodule diff --git a/chips/yosys/tests/simple/attrib04_net_var.v b/chips/yosys/tests/simple/attrib04_net_var.v new file mode 100644 index 0000000000000000000000000000000000000000..76118d56dfab51dd23c25af95106baf872825161 --- /dev/null +++ b/chips/yosys/tests/simple/attrib04_net_var.v @@ -0,0 +1,31 @@ +module attrib04_bar(clk, rst, inp, out); + input wire clk; + input wire rst; + input wire inp; + output reg out; + + (* this_is_a_prescaler *) + reg [7:0] counter; + + (* temp_wire *) + wire out_val; + + always @(posedge clk) + counter <= counter + 1; + + assign out_val = inp ^ counter[4]; + + always @(posedge clk) + if (rst) out <= 1'd0; + else out <= out_val; + +endmodule + +module attrib04_foo(clk, rst, inp, out); + input wire clk; + input wire rst; + input wire inp; + output wire out; + + attrib04_bar bar_instance (clk, rst, inp, out); +endmodule diff --git a/chips/yosys/tests/simple/attrib05_port_conn.v.DISABLED b/chips/yosys/tests/simple/attrib05_port_conn.v.DISABLED new file mode 100644 index 0000000000000000000000000000000000000000..3e256e912b4d0d4cd172245a47dc25cd05a02d64 --- /dev/null +++ b/chips/yosys/tests/simple/attrib05_port_conn.v.DISABLED @@ -0,0 +1,20 @@ +module attrib05_bar(clk, rst, inp, out); + input wire clk; + input wire rst; + input wire inp; + output reg out; + + always @(posedge clk) + if (rst) out <= 1'd0; + else out <= ~inp; + +endmodule + +module attrib05_foo(clk, rst, inp, out); + input wire clk; + input wire rst; + input wire inp; + output wire out; + + attrib05_bar bar_instance ( (* clock_connected *) clk, rst, (* this_is_the_input *) inp, out); +endmodule diff --git a/chips/yosys/tests/simple/attrib06_operator_suffix.v b/chips/yosys/tests/simple/attrib06_operator_suffix.v new file mode 100644 index 0000000000000000000000000000000000000000..8331172b6a4f302e162b5e16019422a687b61be8 --- /dev/null +++ b/chips/yosys/tests/simple/attrib06_operator_suffix.v @@ -0,0 +1,22 @@ +module attrib06_bar(clk, rst, inp_a, inp_b, out); + input wire clk; + input wire rst; + input wire [7:0] inp_a; + input wire [7:0] inp_b; + output reg [7:0] out; + + always @(posedge clk) + if (rst) out <= 0; + else out <= inp_a + (* ripple_adder *) inp_b; + +endmodule + +module attrib06_foo(clk, rst, inp_a, inp_b, out); + input wire clk; + input wire rst; + input wire [7:0] inp_a; + input wire [7:0] inp_b; + output wire [7:0] out; + + attrib06_bar bar_instance (clk, rst, inp_a, inp_b, out); +endmodule diff --git a/chips/yosys/tests/simple/attrib07_func_call.v.DISABLED b/chips/yosys/tests/simple/attrib07_func_call.v.DISABLED new file mode 100644 index 0000000000000000000000000000000000000000..5b76aefc198283255db9486b5056f9709827805b --- /dev/null +++ b/chips/yosys/tests/simple/attrib07_func_call.v.DISABLED @@ -0,0 +1,20 @@ +function [7:0] attrib07_do_add; + input [7:0] inp_a; + input [7:0] inp_b; + + do_add = inp_a + inp_b; + +endfunction + +module attri07_foo(clk, rst, inp_a, inp_b, out); + input wire clk; + input wire rst; + input wire [7:0] inp_a; + input wire [7:0] inp_b; + output wire [7:0] out; + + always @(posedge clk) + if (rst) out <= 0; + else out <= attrib07_do_add (* combinational_adder *) (inp_a, inp_b); + +endmodule diff --git a/chips/yosys/tests/simple/attrib08_mod_inst.v b/chips/yosys/tests/simple/attrib08_mod_inst.v new file mode 100644 index 0000000000000000000000000000000000000000..582f3876d05c6b00854f1a32cbf5c5ad05881f8a --- /dev/null +++ b/chips/yosys/tests/simple/attrib08_mod_inst.v @@ -0,0 +1,21 @@ +module attrib08_bar(clk, rst, inp, out); + input wire clk; + input wire rst; + input wire inp; + output reg out; + + always @(posedge clk) + if (rst) out <= 1'd0; + else out <= ~inp; + +endmodule + +module attrib08_foo(clk, rst, inp, out); + input wire clk; + input wire rst; + input wire inp; + output wire out; + + (* my_module_instance = 99 *) + attrib08_bar bar_instance (clk, rst, inp, out); +endmodule diff --git a/chips/yosys/tests/simple/attrib09_case.v b/chips/yosys/tests/simple/attrib09_case.v new file mode 100644 index 0000000000000000000000000000000000000000..d569749ca08a98fc7240e6d078667cfe0eab1cf4 --- /dev/null +++ b/chips/yosys/tests/simple/attrib09_case.v @@ -0,0 +1,25 @@ +module attrib09_bar(clk, rst, inp, out); + input wire clk; + input wire rst; + input wire [1:0] inp; + output reg [1:0] out; + + always @(inp) + (* full_case, parallel_case *) + case(inp) + 2'd0: out <= 2'd3; + 2'd1: out <= 2'd2; + 2'd2: out <= 2'd1; + 2'd3: out <= 2'd0; + endcase + +endmodule + +module attrib09_foo(clk, rst, inp, out); + input wire clk; + input wire rst; + input wire [1:0] inp; + output wire [1:0] out; + + attrib09_bar bar_instance (clk, rst, inp, out); +endmodule diff --git a/chips/yosys/tests/simple/carryadd.v b/chips/yosys/tests/simple/carryadd.v new file mode 100644 index 0000000000000000000000000000000000000000..4f777f790d6ab5e8fb4065a33a11c6f631b76245 --- /dev/null +++ b/chips/yosys/tests/simple/carryadd.v @@ -0,0 +1,24 @@ +module carryadd(a, b, y); + +parameter WIDTH = 8; + +input [WIDTH-1:0] a, b; +output [WIDTH-1:0] y; + +genvar i; +generate + for (i = 0; i < WIDTH; i = i+1) begin:STAGE + wire IN1 = a[i], IN2 = b[i]; + wire C, Y; + if (i == 0) + assign C = IN1 & IN2, Y = IN1 ^ IN2; + else + assign C = (IN1 & IN2) | ((IN1 | IN2) & STAGE[i-1].C), + Y = IN1 ^ IN2 ^ STAGE[i-1].C; + assign y[i] = Y; + end +endgenerate + +// assert property (y == a + b); + +endmodule diff --git a/chips/yosys/tests/simple/case_expr_const.v b/chips/yosys/tests/simple/case_expr_const.v new file mode 100644 index 0000000000000000000000000000000000000000..d9169c084c422b4af6375020a4241e9dec3ceeaa --- /dev/null +++ b/chips/yosys/tests/simple/case_expr_const.v @@ -0,0 +1,49 @@ +// Note: case_expr_{,non_}const.v should be modified in tandem to ensure both +// the constant and non-constant case evaluation logic is covered +module case_expr_const_top( + // expected to output all 1s + output reg a, b, c, d, e, f, g, h +); + initial begin + case (2'b0) + 1'b0: a = 1; + default: a = 0; + endcase + case (2'sb11) + 2'sb01: b = 0; + 1'sb1: b = 1; + endcase + case (2'sb11) + 1'sb0: c = 0; + 1'sb1: c = 1; + endcase + case (2'sb11) + 1'b0: d = 0; + 1'sb1: d = 0; + default: d = 1; + endcase + case (2'b11) + 1'sb0: e = 0; + 1'sb1: e = 0; + default: e = 1; + endcase + case (1'sb1) + 1'sb0: f = 0; + 2'sb11: f = 1; + default: f = 0; + endcase + case (1'sb1) + 1'sb0: g = 0; + 3'b0: g = 0; + 2'sb11: g = 0; + default: g = 1; + endcase + case (1'sb1) + 1'sb0: h = 0; + 1'b1: h = 1; + 3'b0: h = 0; + 2'sb11: h = 0; + default: h = 0; + endcase + end +endmodule diff --git a/chips/yosys/tests/simple/case_expr_extend.sv b/chips/yosys/tests/simple/case_expr_extend.sv new file mode 100644 index 0000000000000000000000000000000000000000..d4ca2aa9b93cfec1b053ddbbf8148b6ac4aca22d --- /dev/null +++ b/chips/yosys/tests/simple/case_expr_extend.sv @@ -0,0 +1,11 @@ +module top( + output logic [5:0] out +); +initial begin + out = '0; + case (1'b1 << 1) + 2'b10: out = '1; + default: out = '0; + endcase +end +endmodule diff --git a/chips/yosys/tests/simple/case_expr_non_const.v b/chips/yosys/tests/simple/case_expr_non_const.v new file mode 100644 index 0000000000000000000000000000000000000000..6dfc2e54eff5736e8912f0264bd5a3fd657268df --- /dev/null +++ b/chips/yosys/tests/simple/case_expr_non_const.v @@ -0,0 +1,59 @@ +// Note: case_expr_{,non_}const.v should be modified in tandem to ensure both +// the constant and non-constant case evaluation logic is covered +module case_expr_non_const_top( + // expected to output all 1s + output reg a, b, c, d, e, f, g, h +); + reg x_1b0 = 1'b0; + reg x_1b1 = 1'b1; + reg signed x_1sb0 = 1'sb0; + reg signed x_1sb1 = 1'sb1; + reg [1:0] x_2b0 = 2'b0; + reg [1:0] x_2b11 = 2'b11; + reg signed [1:0] x_2sb01 = 2'sb01; + reg signed [1:0] x_2sb11 = 2'sb11; + reg [2:0] x_3b0 = 3'b0; + + initial begin + case (x_2b0) + x_1b0: a = 1; + default: a = 0; + endcase + case (x_2sb11) + x_2sb01: b = 0; + x_1sb1: b = 1; + endcase + case (x_2sb11) + x_1sb0: c = 0; + x_1sb1: c = 1; + endcase + case (x_2sb11) + x_1b0: d = 0; + x_1sb1: d = 0; + default: d = 1; + endcase + case (x_2b11) + x_1sb0: e = 0; + x_1sb1: e = 0; + default: e = 1; + endcase + case (x_1sb1) + x_1sb0: f = 0; + x_2sb11: f = 1; + default: f = 0; + endcase + case (x_1sb1) + x_1sb0: g = 0; + x_3b0: g = 0; + x_2sb11: g = 0; + default: g = 1; + endcase + case (x_1sb1) + x_1sb0: h = 0; + x_1b1: h = 1; + x_3b0: h = 0; + x_2sb11: h = 0; + default: h = 0; + endcase + end +endmodule diff --git a/chips/yosys/tests/simple/case_expr_query.sv b/chips/yosys/tests/simple/case_expr_query.sv new file mode 100644 index 0000000000000000000000000000000000000000..844dfb713bbe5e109aa84240324b40678ae6c722 --- /dev/null +++ b/chips/yosys/tests/simple/case_expr_query.sv @@ -0,0 +1,32 @@ +module top( + output logic [5:0] out +); +initial begin + out = '0; + case ($bits (out)) 6: + case ($size (out)) 6: + case ($high (out)) 5: + case ($low (out)) 0: + case ($left (out)) 5: + case ($right(out)) 0: + case (6) $bits (out): + case (6) $size (out): + case (5) $high (out): + case (0) $low (out): + case (5) $left (out): + case (0) $right(out): + out = '1; + endcase + endcase + endcase + endcase + endcase + endcase + endcase + endcase + endcase + endcase + endcase + endcase +end +endmodule diff --git a/chips/yosys/tests/simple/case_large.v b/chips/yosys/tests/simple/case_large.v new file mode 100644 index 0000000000000000000000000000000000000000..ec8ed6038685a2db585de803477247fba12f060a --- /dev/null +++ b/chips/yosys/tests/simple/case_large.v @@ -0,0 +1,273 @@ +module case_lage_top ( + input wire [127:0] x, + output reg [31:0] y +); + localparam A = 32'hDEAD_BEEF; + localparam B = 32'h0BAD_0B01; + localparam C = 32'hC001_D00D; + localparam D = 32'h1234_5678; + + always @* + case (x) + + {C,A,D,B}: y = 142; + {C,A,D,A}: y = 141; + {D,D,A,A}: y = 241; + {A,C,C,D}: y = 44; + {A,A,A,C}: y = 3; + {A,B,A,C}: y = 19; + {A,D,C,C}: y = 59; + {A,A,C,C}: y = 11; + {D,C,B,B}: y = 230; + {A,A,D,D}: y = 16; + {A,C,A,A}: y = 33; + {A,D,D,D}: y = 64; + {D,B,C,B}: y = 218; + {A,C,B,D}: y = 40; + {C,A,B,B}: y = 134; + {A,C,C,C}: y = 43; + {D,A,D,D}: y = 208; + {A,B,C,A}: y = 25; + {B,A,B,B}: y = 70; + {A,C,B,B}: y = 38; + {C,C,C,B}: y = 170; + {C,D,A,C}: y = 179; + {B,C,D,B}: y = 110; + {A,D,A,C}: y = 51; + {C,C,B,B}: y = 166; + {D,D,D,B}: y = 254; + {C,A,D,C}: y = 143; + {C,D,D,B}: y = 190; + {C,B,A,A}: y = 145; + {C,B,A,C}: y = 147; + {B,C,C,B}: y = 106; + {C,D,C,A}: y = 185; + {C,D,B,D}: y = 184; + {D,D,D,D}: y = 256; + {D,C,C,C}: y = 235; + {D,C,D,B}: y = 238; + {A,B,D,C}: y = 31; + {A,C,A,D}: y = 36; + {C,B,C,B}: y = 154; + {A,B,A,A}: y = 17; + {C,B,B,A}: y = 149; + {B,B,D,C}: y = 95; + {B,D,C,B}: y = 122; + {D,B,A,A}: y = 209; + {B,A,B,A}: y = 69; + {B,A,D,A}: y = 77; + {A,B,B,B}: y = 22; + {C,C,C,C}: y = 171; + {C,A,C,B}: y = 138; + {B,A,D,D}: y = 80; + {C,D,D,C}: y = 191; + {B,A,A,C}: y = 67; + {D,C,D,C}: y = 239; + {C,D,D,D}: y = 192; + {C,D,B,B}: y = 182; + {B,B,A,C}: y = 83; + {D,A,A,D}: y = 196; + {A,C,C,B}: y = 42; + {B,C,A,A}: y = 97; + {A,D,B,A}: y = 53; + {D,D,B,C}: y = 247; + {A,A,C,A}: y = 9; + {D,A,C,B}: y = 202; + {A,C,B,C}: y = 39; + {B,C,B,A}: y = 101; + {B,B,B,C}: y = 87; + {C,B,A,B}: y = 146; + {B,D,A,D}: y = 116; + {A,B,D,D}: y = 32; + {B,A,B,C}: y = 71; + {C,A,A,A}: y = 129; + {B,A,D,C}: y = 79; + {B,A,C,B}: y = 74; + {B,B,D,B}: y = 94; + {B,B,C,C}: y = 91; + {D,C,C,A}: y = 233; + {C,A,B,A}: y = 133; + {D,A,B,A}: y = 197; + {D,B,B,D}: y = 216; + {C,C,A,C}: y = 163; + {D,D,B,A}: y = 245; + {B,A,D,B}: y = 78; + {A,B,C,D}: y = 28; + {C,C,C,D}: y = 172; + {D,C,A,D}: y = 228; + {A,C,D,A}: y = 45; + {B,D,C,C}: y = 123; + {C,B,A,D}: y = 148; + {B,D,B,B}: y = 118; + {A,D,A,B}: y = 50; + {C,B,B,C}: y = 151; + {A,A,A,A}: y = 1; + {A,A,B,B}: y = 6; + {B,B,B,B}: y = 86; + {A,D,A,A}: y = 49; + {A,A,A,B}: y = 2; + {B,D,D,A}: y = 125; + {C,C,D,B}: y = 174; + {D,A,D,B}: y = 206; + {D,D,B,D}: y = 248; + {A,A,A,D}: y = 4; + {B,A,A,B}: y = 66; + {B,C,C,A}: y = 105; + {B,C,C,C}: y = 107; + {D,D,D,C}: y = 255; + {B,C,D,D}: y = 112; + {A,D,B,C}: y = 55; + {C,C,C,A}: y = 169; + {C,D,B,C}: y = 183; + {A,A,B,D}: y = 8; + {D,C,B,A}: y = 229; + {C,B,D,A}: y = 157; + {A,D,D,C}: y = 63; + {D,A,D,A}: y = 205; + {A,A,B,C}: y = 7; + {A,C,A,B}: y = 34; + {C,B,D,C}: y = 159; + {C,C,D,D}: y = 176; + {D,D,D,A}: y = 253; + {A,B,B,D}: y = 24; + {B,B,C,A}: y = 89; + {B,D,C,A}: y = 121; + {A,B,C,C}: y = 27; + {A,A,D,C}: y = 15; + {A,B,B,A}: y = 21; + {A,D,A,D}: y = 52; + {D,D,C,C}: y = 251; + {C,D,A,B}: y = 178; + {A,A,D,B}: y = 14; + {D,B,D,B}: y = 222; + {A,C,C,A}: y = 41; + {D,D,A,C}: y = 243; + {A,C,D,B}: y = 46; + {B,B,B,D}: y = 88; + {D,B,B,B}: y = 214; + {C,C,B,D}: y = 168; + {A,D,D,A}: y = 61; + {D,A,C,C}: y = 203; + {D,C,A,C}: y = 227; + {C,D,C,D}: y = 188; + {D,B,D,D}: y = 224; + {A,C,D,C}: y = 47; + {B,A,B,D}: y = 72; + {A,B,B,C}: y = 23; + {C,C,D,A}: y = 173; + {D,B,C,C}: y = 219; + {D,B,C,A}: y = 217; + {A,D,C,D}: y = 60; + {B,B,D,A}: y = 93; + {A,D,C,A}: y = 57; + {C,C,A,A}: y = 161; + {C,B,B,D}: y = 152; + {B,B,B,A}: y = 85; + {B,D,A,A}: y = 113; + {D,C,D,A}: y = 237; + {B,C,B,C}: y = 103; + {A,B,C,B}: y = 26; + {C,D,A,D}: y = 180; + {A,D,B,D}: y = 56; + {D,C,A,B}: y = 226; + {D,B,B,C}: y = 215; + {D,A,B,C}: y = 199; + {B,D,A,C}: y = 115; + {C,B,C,D}: y = 156; + {B,D,D,B}: y = 126; + {D,D,C,B}: y = 250; + {D,C,C,D}: y = 236; + {B,C,B,D}: y = 104; + {C,B,C,A}: y = 153; + {C,B,B,B}: y = 150; + {C,D,C,B}: y = 186; + {C,D,C,C}: y = 187; + {A,D,B,B}: y = 54; + {D,C,C,B}: y = 234; + {C,B,D,D}: y = 160; + {A,B,A,D}: y = 20; + {C,C,B,A}: y = 165; + {C,D,D,A}: y = 189; + {C,C,D,C}: y = 175; + {D,B,D,C}: y = 223; + {B,C,A,B}: y = 98; + {C,C,A,B}: y = 162; + {B,C,D,A}: y = 109; + {D,A,B,D}: y = 200; + {B,D,C,D}: y = 124; + {D,D,C,A}: y = 249; + {B,A,C,C}: y = 75; + {A,A,C,B}: y = 10; + {C,A,B,D}: y = 136; + {B,B,C,D}: y = 92; + {D,D,C,D}: y = 252; + {B,C,A,D}: y = 100; + {C,A,C,C}: y = 139; + {C,A,C,D}: y = 140; + {D,C,A,A}: y = 225; + {A,D,C,B}: y = 58; + {D,B,C,D}: y = 220; + {D,C,B,D}: y = 232; + {B,A,C,D}: y = 76; + {B,B,D,D}: y = 96; + {D,D,B,B}: y = 246; + {C,D,A,A}: y = 177; + {D,D,A,B}: y = 242; + {A,A,D,A}: y = 13; + {B,B,A,D}: y = 84; + {B,C,D,C}: y = 111; + {D,A,A,B}: y = 194; + {C,A,B,C}: y = 135; + {D,A,A,C}: y = 195; + {B,B,A,B}: y = 82; + {D,C,D,D}: y = 240; + {B,C,C,D}: y = 108; + {D,B,A,C}: y = 211; + {A,C,D,D}: y = 48; + {D,A,A,A}: y = 193; + {C,A,A,B}: y = 130; + {D,B,A,D}: y = 212; + {D,A,B,B}: y = 198; + {A,C,B,A}: y = 37; + {B,D,B,D}: y = 120; + {C,C,B,C}: y = 167; + {D,B,A,B}: y = 210; + {A,B,A,B}: y = 18; + {B,C,B,B}: y = 102; + {B,B,A,A}: y = 81; + {D,D,A,D}: y = 244; + {A,B,D,B}: y = 30; + {A,C,A,C}: y = 35; + {A,A,C,D}: y = 12; + {B,D,B,C}: y = 119; + {B,C,A,C}: y = 99; + {D,A,C,A}: y = 201; + {B,A,A,D}: y = 68; + {C,A,A,D}: y = 132; + {B,A,C,A}: y = 73; + {C,C,A,D}: y = 164; + {B,D,B,A}: y = 117; + {A,D,D,B}: y = 62; + {B,D,D,C}: y = 127; + {A,B,D,A}: y = 29; + {C,D,B,A}: y = 181; + {B,B,C,B}: y = 90; + {B,D,A,B}: y = 114; + {B,D,D,D}: y = 128; + {C,A,C,A}: y = 137; + {A,A,B,A}: y = 5; + {C,A,D,D}: y = 144; + {D,C,B,C}: y = 231; + {D,A,C,D}: y = 204; + {C,A,A,C}: y = 131; + {C,B,D,B}: y = 158; + {B,A,A,A}: y = 65; + {D,A,D,C}: y = 207; + {D,B,B,A}: y = 213; + {D,B,D,A}: y = 221; + {C,B,C,C}: y = 155; + + default: y = 0; + + endcase +endmodule diff --git a/chips/yosys/tests/simple/const_branch_finish.v b/chips/yosys/tests/simple/const_branch_finish.v new file mode 100644 index 0000000000000000000000000000000000000000..7e365eeb411e9c37a4a736db2fadb33531f7a35e --- /dev/null +++ b/chips/yosys/tests/simple/const_branch_finish.v @@ -0,0 +1,36 @@ +`define CONSTANT_CHECK \ + if (WIDTH === 'bx) begin \ + $display("FAIL"); \ + $finish; \ + end + +module case_branch_finish_top; + parameter WIDTH = 32; + integer j; + initial begin + `CONSTANT_CHECK + if (WIDTH == 32) begin : procedural_conditional_block + `CONSTANT_CHECK + end + case (WIDTH) + 32: `CONSTANT_CHECK + default: ; + endcase + for (j = 0; j < 2; j = j + 1) begin : procedural_loop_block + `CONSTANT_CHECK + end + end + generate + if (WIDTH == 32) begin : conditional_block + initial `CONSTANT_CHECK + end + case (WIDTH) + 32: initial `CONSTANT_CHECK + default: ; + endcase + genvar i; + for (i = 0; i < 2; i = i + 1) begin : loop_block + initial `CONSTANT_CHECK + end + endgenerate +endmodule diff --git a/chips/yosys/tests/simple/const_fold_func.v b/chips/yosys/tests/simple/const_fold_func.v new file mode 100644 index 0000000000000000000000000000000000000000..b3f476ce3fc94ab5d6b7f998cf0ee4ac3654331c --- /dev/null +++ b/chips/yosys/tests/simple/const_fold_func.v @@ -0,0 +1,61 @@ +module const_fold_func_top( + input wire [3:0] inp, + output wire [3:0] out1, out2, out3, out4, out5, + output reg [3:0] out6 +); + function automatic [3:0] flip; + input [3:0] inp; + flip = ~inp; + endfunction + + function automatic [3:0] help; + input [3:0] inp; + help = flip(inp); + endfunction + + // while loops are const-eval-only + function automatic [3:0] loop; + input [3:0] inp; + reg [3:0] val; + begin + val = inp; + loop = 1; + while (val != inp) begin + loop = loop * 2; + val = val + 1; + end + end + endfunction + + // not const-eval-only, despite calling a const-eval-only function + function automatic [3:0] help_mul; + input [3:0] inp; + help_mul = inp * loop(2); + endfunction + + // can be elaborated so long as exp is a constant + function automatic [3:0] pow_flip_a; + input [3:0] base, exp; + begin + pow_flip_a = 1; + if (exp > 0) + pow_flip_a = base * pow_flip_a(flip(base), exp - 1); + end + endfunction + + function automatic [3:0] pow_flip_b; + input [3:0] base, exp; + begin + out6[exp] = base & 1; + pow_flip_b = 1; + if (exp > 0) + pow_flip_b = base * pow_flip_b(flip(base), exp - 1); + end + endfunction + + assign out1 = flip(flip(inp)); + assign out2 = help(flip(inp)); + assign out3 = help_mul(inp); + assign out4 = pow_flip_a(flip(inp), 3); + assign out5 = pow_flip_b(2, 2); +endmodule diff --git a/chips/yosys/tests/simple/const_func_shadow.v b/chips/yosys/tests/simple/const_func_shadow.v new file mode 100644 index 0000000000000000000000000000000000000000..fb4f148f6e23245835b7738672bd402d46b7bde1 --- /dev/null +++ b/chips/yosys/tests/simple/const_func_shadow.v @@ -0,0 +1,33 @@ +module const_func_shadow_top(w, x, y, z); + function [11:0] func; + input reg [2:0] x; + input reg [2:0] y; + begin + x = x * (y + 1); + begin : foo + reg [2:0] y; + y = x + 1; + begin : bar + reg [2:0] x; + x = y + 1; + begin : blah + reg [2:0] y; + y = x + 1; + func[2:0] = y; + end + func[5:3] = x; + end + func[8:6] = y; + end + func[11:9] = x; + end + endfunction + output wire [func(2, 3) - 1:0] w; + output wire [func(1, 3) - 1:0] x; + output wire [func(3, 1) - 1:0] y; + output wire [func(5, 2) - 1:0] z; + assign w = 1'sb1; + assign x = 1'sb1; + assign y = 1'sb1; + assign z = 1'sb1; +endmodule diff --git a/chips/yosys/tests/simple/constmuldivmod.v b/chips/yosys/tests/simple/constmuldivmod.v new file mode 100644 index 0000000000000000000000000000000000000000..5dd8f9295afe07d80ede06d906a9b2b9390dc5bf --- /dev/null +++ b/chips/yosys/tests/simple/constmuldivmod.v @@ -0,0 +1,67 @@ +module constmuldivmod(input [7:0] A, input [5:0] mode, output reg [7:0] Y); + always @* begin + case (mode) + 0: Y = A / 8'd0; + 1: Y = A % 8'd0; + 2: Y = A * 8'd0; + + 3: Y = A / 8'd1; + 4: Y = A % 8'd1; + 5: Y = A * 8'd1; + + 6: Y = A / 8'd2; + 7: Y = A % 8'd2; + 8: Y = A * 8'd2; + + 9: Y = A / 8'd4; + 10: Y = A % 8'd4; + 11: Y = A * 8'd4; + + 12: Y = A / 8'd8; + 13: Y = A % 8'd8; + 14: Y = A * 8'd8; + + 15: Y = $signed(A) / $signed(8'd0); + 16: Y = $signed(A) % $signed(8'd0); + 17: Y = $signed(A) * $signed(8'd0); + + 18: Y = $signed(A) / $signed(8'd1); + 19: Y = $signed(A) % $signed(8'd1); + 20: Y = $signed(A) * $signed(8'd1); + + 21: Y = $signed(A) / $signed(8'd2); + 22: Y = $signed(A) % $signed(8'd2); + 23: Y = $signed(A) * $signed(8'd2); + + 24: Y = $signed(A) / $signed(8'd4); + 25: Y = $signed(A) % $signed(8'd4); + 26: Y = $signed(A) * $signed(8'd4); + + 27: Y = $signed(A) / $signed(8'd8); + 28: Y = $signed(A) % $signed(8'd8); + 29: Y = $signed(A) * $signed(8'd8); + + 30: Y = $signed(A) / $signed(-8'd0); + 31: Y = $signed(A) % $signed(-8'd0); + 32: Y = $signed(A) * $signed(-8'd0); + + 33: Y = $signed(A) / $signed(-8'd1); + 34: Y = $signed(A) % $signed(-8'd1); + 35: Y = $signed(A) * $signed(-8'd1); + + 36: Y = $signed(A) / $signed(-8'd2); + 37: Y = $signed(A) % $signed(-8'd2); + 38: Y = $signed(A) * $signed(-8'd2); + + 39: Y = $signed(A) / $signed(-8'd4); + 40: Y = $signed(A) % $signed(-8'd4); + 41: Y = $signed(A) * $signed(-8'd4); + + 42: Y = $signed(A) / $signed(-8'd8); + 43: Y = $signed(A) % $signed(-8'd8); + 44: Y = $signed(A) * $signed(-8'd8); + + default: Y = 8'd16 * A; + endcase + end +endmodule diff --git a/chips/yosys/tests/simple/constpower.v b/chips/yosys/tests/simple/constpower.v new file mode 100644 index 0000000000000000000000000000000000000000..451866a63c3eee81a397fbdeedae6c69e20abe56 --- /dev/null +++ b/chips/yosys/tests/simple/constpower.v @@ -0,0 +1,15 @@ +module constpower(ys, yu); + +output [8*8*8-1:0] ys, yu; + +genvar i, j; + +generate + for (i = 0; i < 8; i = i+1) + for (j = 0; j < 8; j = j+1) begin:V + assign ys[i*8 + j*64 + 7 : i*8 + j*64] = $signed(i-4) ** $signed(j-4); + assign yu[i*8 + j*64 + 7 : i*8 + j*64] = $unsigned(i) ** $unsigned(j); + end +endgenerate + +endmodule diff --git a/chips/yosys/tests/simple/defvalue.sv b/chips/yosys/tests/simple/defvalue.sv new file mode 100644 index 0000000000000000000000000000000000000000..77d7ba26be55fdf3a82c048e4f43147c677ffe11 --- /dev/null +++ b/chips/yosys/tests/simple/defvalue.sv @@ -0,0 +1,22 @@ +module defvalue_top(input clock, input [3:0] delta, output [3:0] cnt1, cnt2); + cnt #(1) foo (.clock, .cnt(cnt1), .delta); + cnt #(2) bar (.clock, .cnt(cnt2)); +endmodule + +module cnt #( + parameter integer initval = 0 +) ( + input clock, + output logic [3:0] cnt = initval, +`ifdef __ICARUS__ + input [3:0] delta +`else + input [3:0] delta = 10 +`endif +); +`ifdef __ICARUS__ + assign (weak0, weak1) delta = 10; +`endif + always @(posedge clock) + cnt <= cnt + delta; +endmodule diff --git a/chips/yosys/tests/simple/dff_different_styles.v b/chips/yosys/tests/simple/dff_different_styles.v new file mode 100644 index 0000000000000000000000000000000000000000..528513b9fd1c6b4441cd9481216bf028b7f65ca9 --- /dev/null +++ b/chips/yosys/tests/simple/dff_different_styles.v @@ -0,0 +1,103 @@ + +module dff(clk, d, q); +input clk, d; +output reg q; +always @(posedge clk) + q <= d; +endmodule + +module dffa(clk, arst, d, q); +input clk, arst, d; +output reg q; +always @(posedge clk or posedge arst) begin + if (arst) + q <= 1; + else + q <= d; +end +endmodule + +module dffa1(clk, arst, d, q); +input clk, arst, d; +output reg q; +always @(posedge clk or negedge arst) begin + if (~arst) + q <= 0; + else + q <= d; +end +endmodule + +module dffa2(clk, arst, d, q); +input clk, arst, d; +output reg q; +always @(posedge clk or negedge arst) begin + if (!arst) + q <= 0; + else + q <= d; +end +endmodule + +module dffa3(clk, arst, d, q); +input clk, arst, d; +output reg q; +always @(posedge clk or negedge arst) begin + if (~(!arst)) + q <= d; + else + q <= 1; +end +endmodule + +module dffa4(clk, arst1, arst2, arst3, d, q); +input clk, arst1, arst2, arst3, d; +output reg q; +always @(posedge clk, posedge arst1, posedge arst2, negedge arst3) begin + if (arst1) + q <= 0; + else if (arst2) + q <= 0; + else if (!arst3) + q <= 0; + else + q <= d; +end +endmodule + +// SR-Flip-Flops are on the edge of well defined Verilog constructs in terms of +// simulation-implementation mismatches. The following testcases try to cover the +// part that is defined and avoid the undefined cases. + +module dffsr1(clk, arst, d, q); +input clk, arst, d; +output reg q; +always @(posedge clk, posedge arst) begin + if (arst) + q <= d^d; // constant expression -- but the frontend optimizer does not know that.. + else + q <= d; +end +endmodule + +module dffsr2(clk, preset, clear, d, q); +input clk, preset, clear, d; +output q; +(* gentb_clock *) +wire clk, preset, clear, d; +dffsr2_sub uut (clk, preset && !clear, !preset && clear, d, q); +endmodule + +(* gentb_skip *) +module dffsr2_sub(clk, preset, clear, d, q); +input clk, preset, clear, d; +output reg q; +always @(posedge clk, posedge preset, posedge clear) begin + if (preset) + q <= 1; + else if (clear) + q <= 0; + else + q <= d; +end +endmodule