cpopw

Count set bits in word

This instruction is defined by:

Encoding

svg

Synopsis

Counts the number of 1’s (i.e., set bits) in the least-significant word of the source register.

Software Hint
This operations is known as population count, popcount, sideways sum,
bit summation, or Hamming weight.

The GCC builtin function `__builtin_popcount (unsigned int x)` is
implemented by cpop on RV32 and by cpopw on RV64. The GCC builtin
function `__builtin_popcountl (unsigned long x)` for LP64 is
implemented by cpop on RV64.

Access

M HS U VS VU

Always

Always

Always

Always

Always

Decode Variables

Bits<5> xs1 = $encoding[19:15];
Bits<5> xd = $encoding[11:7];

Execution

  • Pruned, XLEN == 64

  • Original

if (implemented?(ExtensionName::B) && (misa.B == 1'b0)) {
  raise(ExceptionCode::IllegalInstruction, mode(), $encoding);
}
XReg bitcount = 0;
XReg xs1_val = X[xs1];
for (U32 i = 0; i < 32; i++) {
  if (xs1_val[i] == 1'b1) {
    bitcount = bitcount + 1;
  }
}
X[xd] = bitcount;
if (implemented?(ExtensionName::B) && (misa.B == 1'b0)) {
  raise(ExceptionCode::IllegalInstruction, mode(), $encoding);
}
XReg bitcount = 0;
XReg xs1_val = X[xs1];
for (U32 i = 0; i < 32; i++) {
  if (xs1_val[i] == 1'b1) {
    bitcount = bitcount + 1;
  }
}
X[xd] = bitcount;

Exceptions

This instruction may result in the following synchronous exceptions:

  • IllegalInstruction