How to keep unreachable code?
Posted
by Gabriel
on Stack Overflow
See other posts from Stack Overflow
or by Gabriel
Published on 2010-04-01T20:20:37Z
Indexed on
2010/04/01
20:23 UTC
Read the original article
Hit count: 507
I'd like to write a function that would have some optional code to execute or not depending on user settings. The function is cpu-intensive and having ifs in it would be slow since the branch predictor is not that good.
My idea is making a copy in memory of the function and replace NOPs with jumps when I don't want to execute some code. My working example goes like this:
int Test()
{
int x = 2;
for (int i=0 ; i<10 ; i++)
{
x *= 2;
__asm {NOP}; // to skip it replace this
__asm {NOP}; // by JMP 2 (after the goto)
x *= 2; // Op to skip or not
x *= 2;
}
return x;
}
In my test's main, I copy this function into a newly allocated executable memory and replace the NOPs by a JMP 2 so that the following x *= 2 is not executed.
The problem is that I would have to change the JMP operand every time I change the code to be skipped.
An alternative that would fix this problem would be:
__asm {NOP}; // to skip it replace this
__asm {NOP}; // by JMP 2 (after the goto)
goto dont_do_it;
x *= 2; // Op to skip or not
dont_do_it:
x *= 2;
This way, as a goto uses 2 bytes of binary, I would be able to replace the NOPs by a fixed JMP of alway 2 in order to skip the goto. Unfortunately, in full optimization mode, the goto and the x*=2 are removed because they are unreachable at compilation time.
Hence the need to keep that dead code.
© Stack Overflow or respective owner