Where does the SRA shift amount come from?
For register shifts, the amount comes from the low log2(XLEN) bits of rs2.
Shift rs1 right arithmetically by the low log2(XLEN) bits of rs2, result in rd
SRA uses opcode 0110011 (0x33), funct3 101, funct7 0100000. The rs1 and rs2 fields select the two source registers, and rd selects the destination register.
SRA shifts rs1 right arithmetically by the amount in the low log2(XLEN) bits of rs2 (rs2[4:0] on RV32, rs2[5:0] on RV64), filling upper bits with the original sign bit. Result in rd. funct7=0100000, funct3=101, bit30=1. bit30=1 distinguishes it from SRL. Used for signed division by powers of two and sign-preserving right shifts.
SRA performs a arithmetic right shift, fills high bits with the original sign bit, and writes rd. The shift amount comes from the low log2(XLEN) bits of rs2.
Understand this scenario with real code like «sra x5, x6, x7 # x5 = x6 >> (x7[4:0]) (arithmetic, sign fill)».
Understand this scenario with real code like «sra x5, x6, x7 # x5 = x6 >> (x7[4:0]) (arithmetic, sign fill)».
For register shifts, the amount comes from the low log2(XLEN) bits of rs2.
Logical right shift fills high bits with zeros. Arithmetic right shift copies the original sign bit, which is usually used to preserve signedness.