Skip to content

signed integer division: unspecified rounding mode for the quotient; and overflow #1774

Closed

Description

@dneto0

Consider x/y where x and y are signed integers.
What is the result when the ratio x/y is not an integer.

I think it's common to say it's implementation-defined.
This is the case:

  • all the way up through C++11.
  • SPIR-V (and Vulkan does not further qualify)

Signed integer overflow can occur for:
INT_MIN / -1
where INT_MIN is the largest-magnitude negative number. This occurs because signed integers use twos-complement.

Activity

  1. added
    wgsl
    on May 27, 2021
  2. added this to the MVP milestone on May 27, 2021
  3. self-assigned this
    on May 27, 2021
  4. kvark commented on May 28, 2021

    @kvark
    Contributor

    What about MSL and HLSL. Isn't it defined there?

  5. dneto0 commented on Jun 1, 2021

    @dneto0
    ContributorAuthor

    MSL 3.1 "Scalar and vector operators" doesn't say what happens for arguments of opposite signs. Since MSL is based on C++14, I think it gets (from cppreference)

    The quotient is truncated towards zero (fractional part is discarded).

    HLSL doc (https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-operators ):

    • Doesn't say specifically what happens for integer division of opposite signs
    • Gives only examples with positive sign

    For modulus it says:

    The modulus operator returns the remainder of a division. This produces different results when using integers and floating-point numbers. Integer remainders that are fractional will be truncated.

    And then:

    The % operator is defined only in cases where either both sides are positive or both sides are negative

  6. dneto0 commented on Jun 1, 2021

    @dneto0
    ContributorAuthor

    Something concrete to look at:

    x y float x/y quotient truncated to zero trunc(x/y) quotient round down int(x/y) x-y*trunc(x/y) x-y*int(x/y)
    15 4 3.75 3 3 3 3
    15 -4 -3.75 -3 -4 3 -1
    -15 4 -3.75 -3 -4 -3 1
    -15 -4 3.75 3 3 -3 -3
  7. kdashg commented on Jun 1, 2021

    @kdashg
    Contributor
    WGSL meeting minutes 2021-06-01
    • DN: MSL inherits C++’s behavior for opposite-signed division: implementation defined. HLSL is undefined for opposite-signed modulus.
    • AB: Spir-v says for div is undefined behavior
    • JG: Surely we don’t want to forbid opp-signed div, yeah?
    • AB: Yeah, but just call out what the behaviors might be. Could try to bound the result to one of two answers, but don’t know if it’s worth it.
    • DM: Do we have a proposal for this?
    • DN: 1) Ban int division; or 2) allow different results; or 3) Polyfill? Tempted by leaving it undefined like HLSL.
    • JG: I would like 2. Other prior art is doing fine.
    • DM: I think our portability reqs are higher.
    • RM: It would be nice to know if we can require strict behavior efficiently.
    • DM: David: Can you write the proposed polyfill?
    • DN: Offline, maybe.
    • JB:: What are the costs of the polyfills.
    • DN: Expect quotient and remainder are produced at the same time; tie the decision to include but polyfill both / and % together.
    • JG: Want portability, but concern about cost.
  8. dneto0 commented on Jun 3, 2021

    @dneto0
    ContributorAuthor

    Polyfilling signed integer division

    Unsigned division

    For integers x, y, with 0 <= x and 0 < y, there are unique integers
    q (the quotient) and r (the remainder) such that:

    x = q * y + r, where
    0 <= r < y
    

    The quotient is taken to be "the" integer division of x by y.

    Signed division

    If either x or y is negative, and b is non-zero, there are two natural choices
    for q:

    q_rtz is real-valued x/y but rounded toward zero (truncation)
    q_rtn is real-valued x/y but rounded negative infinity.
    

    The trend in C-family languages is to use truncation, i.e. q_rtz.

    Computing q_rtz in in terms of unsigned integer division is done as follows:

    q_rtz = abs(x) / abs(y) * sign(x) * sign(y)      [algorithm 1]
    

    where sign(w) is 1 when x < 0 and -1 when w > 0.

    Then define the signed remainder from:

    x = q_rtz * y + r
    

    that is:

    r = x - q_rtz * y
    

    Algorithm 1 in pseudo-code

    // Ignoring y = 0 case.
    fn sdiv(x: i32, y: i32) -> i32 {
      let q_abs = u32(x) / u32(y);
      return select(i32(q_abs), -i32(q_abs), (x<0) == (y<0));
    }
    

    Table of examples

    x y float x/y abs(x) abs(y) int(abs(x)/abs(y)) sign(x) sign(y) sign(x) * sign(y) int(abs(x)/abs(y)) * sign(x) * sign(y)
    15 4 3.75 15 4 3 1 1 1 3
    15 -4 -3.75 15 4 3 1 -1 -1 -3
    -15 4 -3.75 15 4 3 -1 1 -1 -3
    -15 -4 3.75 15 4 3 -1 -1 1 3

    edit: Fix the select condition in the code sample.

  9. dneto0 commented on Jun 3, 2021

    @dneto0
    ContributorAuthor

    I think @alan-baker had a more concise way to compute the corresponding modulus:

       r_signed = (abs(x) mod abs(y))  * sign(x)
    
    x y float x/y trunc(x/y) x - trunc(x/y)*y mod(abs(x),abs(y)) sign(x) mod(abs(x),abs(y))*sign(x)
    15 4 3.75 3 3 3 1 3
    15 -4 -3.75 -3 3 3 1 3
    -15 4 -3.75 -3 -3 3 -1 -3
    -15 -4 3.75 3 -3 3 -1 -3
    17 4 4.25 4 1 1 1 1
    17 -4 -4.25 -4 1 1 1 1
    -17 4 -4.25 -4 -1 1 -1 -1
    -17 -4 4.25 4 -1 1 -1 -1

    I think that's

    // ignoring y=0 and extreme x = INT_MIN, y = -1.
    fn smod(x: i32, y:i32) -> i32 {
        let r_abs = u32(x) % u32(y);
        return select( i32(r_abs), -i32(r_abs), x > 0 );
    }
    
  10. kvark commented on Jun 3, 2021

    @kvark
    Contributor

    Looks quite doable, thank you for investigating this!

  11. kdashg commented on Jun 8, 2021

    @kdashg
    Contributor
    WGSL meeting minutes 2021-06-08
    • (Polyfill of signed integer division turned out not too bad. signed integer division: unspecified rounding mode for the quotient; and overflow #1774 (comment))
    • DN: Polyfill more straightforward than I expected. It’s more instructions now, but people probably don’t care?
    • MM: Probably best to be portable first. Maybe less portable a la fastmath later
    • KN: Devs probably won’t love that they get 3 instructions for one “instruction”. So maybe we can allow operator% only for unsigned, since that’s “perfect”, but mod(int,int) that’s portable.
    • DM: Do people care wrt how expensive division is?
    • MM: Ints uncommon in shaders, too. And division on ints are doubly uncommon. Perhaps even so uncommon that it’s fine for it to be 3 instructions.
    • JG: Ints will be more common in compute shaders, though.
    • Consensus:
      • Require portability even if it emits extra instructions
      • Allow operator syntax for % and / with ints
  12. dneto0 commented on Jun 10, 2021

    @dneto0
    ContributorAuthor

    Decision from 2021-06-08

    • Define / and % for signed integers.
    • When the quotient is non-integral, it's rounded toward zero. And % is defined to satisfy the a = q * b + r equation.
    • Functionality for both is as in the polyfills above.

    We didn't talk about division by zero or the INT_MIN / -1 case.

    • that's MSL says these result in undefined value (section 3.1)
    • I couldn't find the HLSL rule. (here)
    • SPIR-V OpSDiv for these cases result in undefined behaviour. It's the same as LLVM sdiv.
      • Vulkan overrides part of that to say division by zero produces an unspecified result (and does not cause interruption or termination). (here).
  13. added 3 commits that reference this issue on Jun 10, 2021
    fe42cc4
    99f1465
    edd6207
  14. dneto0 commented on Jun 10, 2021

    @dneto0
    ContributorAuthor

    Whoops. The pseudocode for the sdiv and smod algorithms should use abs(u32(.)) instead of u32(.) constructors directly.

  15. dneto0 commented on Jun 10, 2021

    @dneto0
    ContributorAuthor

    And abs is slightly more expensive than u32 construction, but probably still much cheaper than the division.

  16. dneto0 commented on Jun 10, 2021

    @dneto0
    ContributorAuthor

    So, restating:

    // Ignoring y = 0 case.
    fn sdiv(x: i32, y: i32) -> i32 {
      let q_abs = u32(abs(x)) / u32(abs(y));
      return select(i32(q_abs), -i32(q_abs), (x<0) == (y<0));
    }
    fn smod(x: i32, y:i32) -> i32 {
        let r_abs = u32(abs(x)) % u32(abs(y));
        return select( i32(r_abs), -i32(r_abs), x > 0 );
    }
    
  17. dneto0 commented on Jun 10, 2021

    @dneto0
    ContributorAuthor

    What happens for INT_MIN / -1.
    INT_MIN in i32 is 0x10000000.
    Taking the rule abs(x) = -x when x <0, then abs(INT_MIN), with two's complement is:

      0x1000 0000   = x
      0x7fff 0000 = ~x
      0x1000 0000  = (~x) + 1
    

    So u32(abs(INTMIN)) = 0x10000000
    Divided by u32(abs(-1)) = 1 yields:

    q_abs = 0x1000 0000

    And (INT_MIN < 0) == (-1 <0) is true, so the result of the polyfill for sdiv is:

         i32(q_abs) = i32(q_abs) = 0x1000 0000    = INT_MIN.
    

    So the polyfill result INT_MIN = sdiv(INT_MIN, -1).

    We have a choice:

    1. Say that INT_MIN / -1 is a dynamic error (or whatever)
    2. INT_MIN / -1 = INT_MIN by rule. (And enforce all implementations to use the polyfill, essentially).
  18. dneto0 commented on Jun 10, 2021

    @dneto0
    ContributorAuthor

    I've updated #1830 to take option 2 for the overflow case: define the result by rule.

  19. added a commit that references this issue on Jan 18, 2022
    2a4b5b0
  20. added a commit that references this issue on Jan 25, 2022
    3ba7623
  21. added a commit that references this issue on Jan 25, 2022
    277148f
  22. added a commit that references this issue on Sep 6, 2022
    5c43591
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

wgsl

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions