llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

Bitwise operation on 64 bit is wrong output when Optimization is ON

Open vigbalu opened this issue 3 years ago • 1 comments

This is similar to https://github.com/llvm/llvm-project/issues/61205

Testcase:

#include <iostream>
 typedef unsigned long pint_t;
template<typename P, typename M> inline M
uSysMaskGet(P* ptr, M mask) {
  return (pint_t)ptr & (pint_t)mask;
}
 class A {
public:
         int a = 0;
                enum maskFlags {
    hasAssFlag = 0x1,
    hasOutFlag = 0x2
  };
        A () { }
        A* getthis ();
        void chkthis ();
                bool          hasOut()          const {
                                 return thisMsk() & hasOutFlag;}
                int           thisMsk()         const {return uSysMaskGet(this, 0x3);}
};
 template<typename P, typename M> inline P*
add (P* ptr, M mask) {
  return (P*)((pint_t)ptr | (pint_t)mask);
}
 A* A::getthis ()
{
        return add (this, 0x2);
}
 void A::chkthis ()
{
        int x = (0x3);
                std::cout <<  hasOut() << std::endl;
        return ;
}
 int main ()
{
        A a;
        A* p = a.getthis();
        p->chkthis();
         return 0;
}

LLVM (output is 0): https://clang.godbolt.org/z/9Yaeovcz6

GCC (output is 1): https://clang.godbolt.org/z/ocq6Ydvad

vigbalu avatar Mar 06 '23 09:03 vigbalu

Similar to #61205, this is UB:

/app/example.cpp:39:12: runtime error: member call on misaligned address 0x7ffc37dc482e for type 'A', which requires 4 byte alignment
0x7ffc37dc482e: note: pointer points here
 00 00 00 00 00 00  d0 fb 2d ee 5e 55 00 00  83 b0 d8 a8 34 7f 00 00  08 00 00 00 00 00 00 00  28 49
             ^ 
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /app/example.cpp:39:12 in 
0

asl avatar Mar 06 '23 10:03 asl