FPGA-RISC-V-CPU / hardware / src / riscv_core / imm_gen.v
imm_gen.v
Raw
module imm_gen(
    input [31:0] inst,
    input [2:0] ImmSel,
    output [31:0] imm
);
    reg [31:0] out;
    always @(*) begin
        case (ImmSel)
            3'b000:  out = {{21{inst[31]}},inst[30:20]};                           // I-type
            3'b001:  out = {{21{inst[31]}},inst[30:25],inst[11:7]};                // S-type
            3'b010:  out = {{20{inst[31]}},inst[7],inst[30:25],inst[11:8],1'b0};   // SB-type
            3'b011:  out = {inst[31:12], 12'b0};                                   // U-type
            3'b100:  out = {{11{inst[31]}},inst[19:12],inst[20],inst[30:21],1'b0}; // UJ-type
            default: out = 32'd0;
        endcase
    end
    assign imm = out;
endmodule

module immediate_gen (
    input [31:0] inst,
    output [31:0] imm
); 

    wire [4:0] opcode = inst[6:2];

    reg [2:0] ImmSel;
    always @(*) begin
        case (opcode)
            `OPC_STORE_5:  ImmSel = 3'b001;
            `OPC_AUIPC_5:  ImmSel = 3'b011;
            `OPC_LUI_5:    ImmSel = 3'b011;
            `OPC_JAL_5:    ImmSel = 3'b100;
            `OPC_BRANCH_5: ImmSel = 3'b010;
            default:       ImmSel = 3'b000;
        endcase
    end
    reg [31:0] out;
    always @(*) begin
        case (ImmSel)
            3'b000:  out = {{21{inst[31]}},inst[30:20]};                           // I-type
            3'b001:  out = {{21{inst[31]}},inst[30:25],inst[11:7]};                // S-type
            3'b010:  out = {{20{inst[31]}},inst[7],inst[30:25],inst[11:8],1'b0};   // SB-type
            3'b011:  out = {inst[31:12], 12'b0};                                   // U-type
            3'b100:  out = {{12{inst[31]}},inst[19:12],inst[20],inst[30:21],1'b0}; // UJ-type
            default: out = 32'd0;
        endcase
    end
    assign imm = out;

endmodule