Reputation: 493
I have the following inline method and call it several times in other methods. Will the vc and gcc compilers with O2 optimization be able to notice the value is fixed in the calling methods and evaluated it only once? -- Indeed indexAndFlag
is not changed inside those methods. -- Or, maybe for thread-safety, it will be evaluated per each call?
unsigned int indexAndFlag;
...
inline Index* index() const
{
return (Index*)(indexAndFlag & ~1);
}
The code is only for protected mode x86 32/64bit architecture, so I hope, I can assume sizeof(unsigned int) == sizeof(Index*)
. If not, please correct me.
Upvotes: 0
Views: 61
Reputation: 254711
If, as it seems to be, indexAndFlag
is a non-const non-static global, then no. The compiler has no way to determine whether or not another translation unit might modify it, and so the program must access its value wherever it's used.
If it were const
, and initialised with a constant expression, then the compiler must treat it as a constant value, and your expression should also be treated as a constant value.
I hope, I can assume
sizeof(unsigned int) == sizeof(Index*)
I wouldn't: many popular 64-bit architectures have a 32-bit int
. Use uintptr_t
to be sure.
Upvotes: 3
Reputation: 129524
To start from the bottom: sizeof(unsigned int) != sizeof(Index *)
in 64-bit, that's for sure. And if you are making that assumption, I would definitely suggest that you use a static_assert(sizeof(unsigned int) == sizeof(Index *))
somewhere in the code.
Next, what the compiler does or doesn't do with regards to global variables and optimization is definitely a case of "up to the compiler". The compiler may well decide to re-load the value each time, or it may decide that "Ah, I know this doesn't change". It really depends on how well it "understands" that indexAndFlag
is not changing.
I personally would use something like:
Index* temp = index();
...
use temp
...
Then it's guaranteed that no extra operations are made to "calculate" the index.
Upvotes: 2