Skip to content

Fix signed/unsigned comparison and arithmetic semantics in C codegen#1002

Draft
Copilot wants to merge 2 commits intomainfrom
copilot/fix-signed-unsigned-comparison
Draft

Fix signed/unsigned comparison and arithmetic semantics in C codegen#1002
Copilot wants to merge 2 commits intomainfrom
copilot/fix-signed-unsigned-comparison

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Mar 31, 2026

C's implicit unsigned-promotion rule causes wrong results when mixing signed/unsigned integers — e.g. (int32_t)-1 < (uint32_t)1 evaluates to false because -1 becomes UINT_MAX. Loopy's generated code was subject to this, diverging from Python semantics.

Changes

loopy/target/c/codegen/expression.pyExpressionToCExpressionMapper

  • map_comparison: When operands are integers of opposite signedness, cast both to the narrowest common signed type (via np.result_type; falls back to int64 for int64/uint64).
  • map_product (new override): When the inferred result is a signed integer and any factor is unsigned, cast those factors to the result type. Fixes subtraction's a + (-1)*b form.
  • map_sum (new override): Same treatment for addends — prevents an unsigned term from silently converting signed co-addends to unsigned arithmetic.
  • _is_mixed_sign_integer_pair / _common_signed_dtype (new helpers): Detect mixed-signedness and derive the appropriate signed cast target.

Before / after for int32 sv = -1, uint32 uv = 1:

// Before — wrong
result = ((sv < uv) ? 1 : 0);          // sv promotes to uint32 → UINT_MAX > uv
diff   = sv + -1 * uv;                 // unsigned wrap-around

// After — correct
result = (((int64_t)(sv) < (int64_t)(uv)) ? 1 : 0);
diff   = sv + -1 * (int64_t)(uv);

test/test_c_execution.py

  • test_mixed_sign_comparison: All six comparison operators (<, <=, >, >=, ==, !=) across int8/uint8, int16/uint16, int32/uint32, int64/uint64 pairs, three representative value combinations each.
  • test_mixed_sign_subtraction: Both subtraction directions (sv - uv, uv - sv) for the same dtype pairs.

Copilot AI changed the title [WIP] Fix and test signed/unsigned comparison semantics Fix signed/unsigned comparison and arithmetic semantics in C codegen Mar 31, 2026
Copilot AI requested a review from inducer March 31, 2026 18:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fix and test signed/unsigned comparison semantics

2 participants