.Net assembly adds superfluous AND when setting bool to TRUE?
The following code written in C# in VS2010 for .Net 4.0:
bool b = false;
has the following disassembly:
XOR EDX,EDX
MOV DWORD PTR[EBP-3Ch],EDX
which makes perfect sense.
However, the following code:
bool b = true;
has the following disassembly:
MOV EAX,1
AND EAX,0FFh
MOV DWORD PTR[EBP-3Ch],EAX
What is the purpose of the AND
operation? Why not just MOV EAX,1
?
Line | EAX
-----------
1 | 0x01
2 | 0x01 & 0xFF = 0x01
3 | 0xFF
I suspect the and 0xff
is truncation to 8-bit bool. I don't know nearly enough about the internals to be sure, but I suspect bool b = true
is becoming something like bool b = int(1)
which is then becoming bool b = bool(int(1))
and it's that coercion to bool causes the and 0xff
. I see similar things in x86 epilogs of C++ functions returning bool (eg ending in test; setal
) rather than just returning an arbitrary nonzero value.
This is the kind of code that a peephole optimizer would fix...
This code
bool a = true;
bool c = false;
generates this IL assembly:
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.0
IL_0004: stloc.1
You can see in the intermediate language, the code is essentially the same. How the jitter is translating that, or why it would not do effectively parallel code for the two is very bizarre.
(I put this as an answer instead of a comment just so I could format the discussion to be readable.)
The AND opcode will also cause some of the status FLAGS to be set (OF, CF, SF, ZF, and PF) according to the Intel manual (http://www.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html). Without the context of the rest of the instructions in the function its pretty hard to guess what the purpose is.
链接地址: http://www.djcxy.com/p/11498.html