[swift-users] What are the various causes of "shift amount is greater than or equal to type size in bits"

Joel Gerber joel at grrbrr.ca
Sat Feb 13 13:11:28 CST 2016


I have code that is giving the "shift amount is greater than or equal to type size in bits” error when built in release mode but doesn’t in debug mode. I’m trying to understand all of the various causes of this error in order to better understand what’s happening.

Here’s a dumbed down version of the code that illustrates the issue:

/// Skeleton for actual UInt128 structure.
struct UInt128 {
  let value: (upperBits: UInt64, lowerBits: UInt64) = (0, 0)
}
/// Shifts `lhs`' bits left by `rhs` bits and returns the result.
public func <<(lhs: UInt128, rhs: UInt128) -> UInt128 {
    if rhs.value.upperBits > 0 || rhs.value.lowerBits > 128 {
        return UInt128(0)
    }
    switch rhs {
    case 0: return lhs // Do nothing shift.
    case 1...63:
        let upperBits = (lhs.value.upperBits << rhs.value.lowerBits) + (lhs.value.lowerBits >> (64 - rhs.value.lowerBits))
        let lowerBits = lhs.value.lowerBits << rhs.value.lowerBits
        return UInt128(upperBits: upperBits, lowerBits: lowerBits)
    case 64:
        // Shift 64 means move lower bits to upper bits.
        return UInt128(upperBits: lhs.value.lowerBits, lowerBits: 0)
    case 65...127:
        // This causes a "shift amount is greater than or equal to type size in bits" error
        // on release build but not debug build.
        let upperBits = lhs.value.lowerBits << (rhs.value.lowerBits - 64)
        return UInt128(upperBits: upperBits, lowerBits: 0)
    default: return UInt128(0)
    }
}

I’ve walked through the Swift code, and while I see some things that might be flagging this error, I’m having a hard time understanding what the underlying causes are.

Joel Gerber
joel at grrbrr.ca


More information about the swift-users mailing list