Natarich J
Natarich J

Reputation: 427

How to represent the product of multiplication instructions in RISCV?

In RISCV, we have mul t1, s1, s2 and mulh t2, s1, s2 instructions, which store the lower 32-bits of the product and upper 32-bits of the product respectively. If I need to use the product, should I do add t0, t2, t1?

Thank you!

Upvotes: 4

Views: 14806

Answers (2)

Sun.
Sun.

Reputation: 113

You can't.

Just as an example using 4 bits instead of 32 bits. The highest possible multiplication with signed integers is 0111 (7) * 0111 (7) resulting in 110001 (49). So no matter how you twist it, you can not display the result in just 4 bits. Commonly its said that you need double the bits after a multiplication. That is also why there are also two multiply operations in Risc-V.

So to conclude. You must use two 32 bit registers. Except if you are certain that the result will not overflow the 32 bits. Then you can just use the mul operation without using mulh at all.

Upvotes: 3

Leon404
Leon404

Reputation: 9

If both the high and low bits of the same product are required, then the recommended code sequence is: MULH[[S]U] rdh, rs1, rs2; MUL rdl, rs1, rs2 (source register speci ers must be in same order and rdh cannot be the same as rs1 or rs2). Microarchitectures can then fuse these into a single multiply operation instead of performing two separate multiplies. MULW is only valid for RV64, and multiplies the lower 32 bits of the source registers, placing the sign-extension of the lower 32 bits of the result into the destination register. MUL can be used to obtain the upper 32 bits of the 64-bit product, but signed arguments must be proper 32-bit signed values, whereas unsigned arguments must have their upper 32 bits clear.

Page 35/36 of RiscV Istruction Set Manual at this link: https://riscv.org/wp-content/uploads/2017/05/riscv-spec-v2.2.pdf

Upvotes: -1

Related Questions