https://gcc.gnu.org/bugzilla/show_bug.cgi?id=112758
Bug ID: 112758 Summary: Inconsistent Bitwise AND Operation Result between int and long long int on Different Optimization Levels in GCC Trunk Product: gcc Version: 14.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c Assignee: unassigned at gcc dot gnu.org Reporter: guminb at ajou dot ac.kr Target Milestone: --- Dear GCC Development Team, I would like to report an inconsistency observed in the GCC RISC-V 64 version 14.0.0 when compiling code involving bitwise AND operations between an `int` and a `long long int` variable under different optimization levels. The issue appears when both operands are negative, with results varying significantly between non-optimized and optimized compilations. The proof of concept (PoC) code provided below demonstrates this issue. The code performs a bitwise AND operation between a 32-bit integer with its high bit set (`globalVar`) and a 64-bit long long integer (`localVar`), both containing negative values. The expected result of the operation seems to differ based on the optimization level used during compilation. PoC Code: ```c #include <stdio.h> int globalVar = 0x80000000; // 32-bit int with high bit set int main () { long long int localVar = 0xffFF00ffffffffff; // 64-bit long long int printf("localVar: 0x%llx\\n", localVar); printf("globalVar: 0x%llx\\n", (long long int)globalVar); printf("Result: 0x%llx\\n", ((localVar) & ((long long int) (globalVar)))); return 0; } ``` Observed Results: - With **`O0`** optimization, the result of the bitwise AND operation is as expected (**`0xffff00ff80000000`**). - With **`O1`**, **`O2`**, **`O3`**, **`Os`**, **`Oz`** optimizations, the result changes to **`0x80000000`**. Assembly Output: The assembly output for -O0 and -O1 can be viewed at the following Compiler Explorer link: https://godbolt.org/z/fb33vWT7o - The **`O0`** output shows the expected behavior with explicit casting and AND operation. - The **`O1`** output, however, omits the casting and AND operation, leading to an unexpected result. I suspect this might be related to how the compiler handles casting or the bitwise operation under different optimization levels. This inconsistency could potentially lead to unintended behavior in applications that rely on such operations, especially when negative values are involved. I appreciate your attention to this matter and look forward to any insights or potential solutions you might provide. Best regards, [Gyumin Baek]