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

Bitwise operation on 64 bit is giving wrong value when optimization (instCombine) is ON

Open vigbalu opened this issue 3 years ago • 1 comments

Testcase:

#include <iostream>
class A {
public:
       int a = 0;
      A () { }
        A* getthis ();
        void chkthis ();
};
 typedef unsigned long pint_t;
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, 0x1);
}
 void A::chkthis ()
{
        std::cout << this << std::endl;
        unsigned long x = ~(0x1);
        std::cout <<  std::hex  << ((unsigned long)this & x) << std::endl;
        return ;
}
 int main ()
{
        A a;
        A* p = a.getthis();
       p->chkthis();         return 0;
}

LLVM : LSB is not reversed. https://clang.godbolt.org/z/csnE5xn3x

GCC: LSB is reversed. https://clang.godbolt.org/z/8MYn9x4zv

vigbalu avatar Mar 06 '23 09:03 vigbalu

Your code invokes undefined behavior. Adding -fsanitize=undefined yields:

/app/example.cpp:29:11: runtime error: member call on misaligned address 0x7ffd335f00fd for type 'A', which requires 4 byte alignment
0x7ffd335f00fd: note: pointer points here
 00 00 00 00 00 00 00  d0 d0 69 97 bb 55 00 00  83 d0 33 c7 48 7f 00 00  08 00 00 00 00 00 00 00  f8
             ^ 
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /app/example.cpp:29:11 in 
0x7ffd335f00fd
7ffd335f00fd

asl avatar Mar 06 '23 10:03 asl