I am struggling to find the best way to write some good code with arithmetic operations (sum, multiplications) in SystemVerilog. It is crucial that this code need to be synthesized for an ASIC, so no use of real numbers or classes.
My code eventually works, but it feels like I am re-inventing the wheel each time.
Here it follows an example of the syntax I use, with fixed point signals, with integers aligned on bit at index [0].
logic [4:-5] a, b; //5 bits for integers, 5 bits for fractionals
logic [9:-10] res; //full result
logic [9:-5] res_trunc; //result truncated with the same precisions as a,b
always_comb res = a*b;
always_comb res_trunc = res>>5;
Please notice how the last operation, in case of signed negative numbers (>>> operator needed) will have issues.
What I am looking for, would be some kind of standard way of expressing fractional numbers (with a typedef maybe?), with possible "automatic alignment" of integers, exploiting the fact that synthesis engine will simplify and get rid of what is not necessary.
Hereafter, I will write some pseudocode that is similar to what I would like to achieve.
//parametric typedef? not synthesizable if done exploting classes...
typedef signed logic [15,-16] fp_num_t(PRECISION);
fp_num_t(2) a; //e.g. 10.01 = 2.250, assigned in u_my_mod module
fp_num_t(3) b; //e.g. 01.001 = 1.125, assigned in u_my_mod module
my_mod u_my_mod (
.....
.o1 (a),
.o2 (b)
);
fp_num_t(1) c; //result, 10.1 = 2.5
always_comb c = a*b;
I hope I managed to explain what my target would be. I don't know if anything similar to this might be possible, or if some of you found a better way to handle this kind of operations without expliciting all the bits each time (awful code readability, error prone).
logic [4:-5] a, b;declares two 10-bit vars, not 5 bit. You need[4:0]for 5 bits. As for the rest, look into packed structs and text macros.2**4+2**3+2**2+2**1+2**0+2**-1+2**-2+2**-3+2**-4+2**-5). It is an implementation of the Q notation, where for simplicity I used only unsigned instead of signed numbers. Please check also this answer from @dave_59.