Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does optimisation kill this function?

We recently had a lecture in university about programming specials in several languages.

The lecturer wrote down the following function:

inline u64 Swap_64(u64 x) {     u64 tmp;     (*(u32*)&tmp)       = Swap_32(*(((u32*)&x)+1));     (*(((u32*)&tmp)+1)) = Swap_32(*(u32*) &x);      return tmp; } 

While I totally understand that this is also really bad style in terms of readability, his main point was that this part of code worked fine in production code until they enabled a high optimization level. Then, the code would just do nothing.

He said that all the assignments to the variable tmp would be optimized out by the compiler. But why would this happen?

I understand that there are circumstances where variables need to be declared volatile so that the compiler doesn't touch them even if he thinks that they are never read or written but I wouldn't know why this would happen here.

like image 353
guitarflow Avatar asked Jan 04 '14 15:01

guitarflow


1 Answers

In C++, pointer arguments are assumed not to alias (except char*) if they point to fundamentally different types ("strict aliasing" rules). This allows some optimizations.

Here, u64 tmp is never modified as u64.
A content of u32* is modified but may be unrelated to 'u64 tmp' so may be seen as nop for u64 tmp.

like image 85
Jarod42 Avatar answered Sep 17 '22 02:09

Jarod42