Signed multiplication overflow detection in Verilog

前端 未结 3 418
既然无缘
既然无缘 2020-12-19 11:54

Beginner here. I\'m trying to code a simple 16-bit microprocessor in Verilog and implement it on a Spartan 6. The ALU implements all signed operations (no unsigned operation

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-19 12:28

    Looking at detecting Overflow and underflow in addition, Analysing a simple 4 bit example, sign extended to 5 bits.

    Addition all +ve

      3 : [0]0011
    + 3 : [0]0011
    = 6 : [0]0110
    

    With negative numbers

      -3 : [1]1101 
    + -3 : [1]1101
    = -6 : [1]1010
    

    Now causing an overflow : Result should be +8 but can not represent that in 4 bits.

      +7 : [0]0111
      +1 : [0]0001 
      +8 : [0]1000
    

    Now cause underflow : Result should be -9 but can not represent that in 4 bits.

      -8 : [1]1000
    + -1 : [1]1111
      -9 : [1]0111 
    

    Therefore overflow and underflow are easy to detect if we sign extend the inputs by 1 bit

    localparam WIDTH = 4;
    localparam MSB   = WIDTH-1;
    logic [WIDTH-1:0] a;
    logic [WIDTH-1:0] b;
    logic [WIDTH-1:0] result;
    logic extra;
    logic overflow;
    logic underflow;
    
    
    always @* begin
      {extra, result} = {a[MSB], a} + {b[MSB], b} ;
      overflow  = ({extra, result[MSB]} == 2’b01 );
      underflow = ({extra, result[MSB]} == 2’b10 );
    end
    

    Regarding multiplication I do not understand why you can not have a 32 bit register. even if you reduce the final output to 16.

    When performing the bit reduction you would need to check that the value is under the max and above the minimum negative number that you can support with the reduced width.

    NB: In addition the result grows 1 bit bigger than largest input. The overflow/underflow occurs when truncating back to original width.

    With multiplication the result is the width of both added together, 16bits * 16bits results in a 32 bit answer. Pretty sure you do not need 33 bits. If you do not keep the full width then it is pretty hard to tell if the result will overflow when truncated. It is quite common to design these things with a wide combinatorial result and only output so many bits through a flip-flop for the final output from the ALU.

    I think that keeping a 32 bit output and comparing it to the max/min of a signed 16 bit number, will synthesise smaller than only using 16 bit multiplier and extra logic to detect the overflow condition.

提交回复
热议问题