I want to write a simple code (or algorithm) to set/clear overflow flag. For setting OF, I know that I can use signed values. But how can I clear that?
Provided:
CF-FlagSay register is al. (setc only with byte registers r/8)
; clear OF-Flag, preserve CF
setc al
sar al, 1
Note: this is good because it has no partial flag updates, which may cause stalls. (sar xx, 1 writes all flags, not leaving any unmodified, unlike inc/dec) c.f. Intel Optimization Guide, 3.5.2.6: Partial Flag Register Stalls, but note that modern Intel CPUs don't have partial-flag stalls or flag-merging at all: instructions that read FLAGS just read either or both of CF or the SPAZO group as 2 separate inputs. (That's why cmovbe is still 2 uops on Broadwell and later: it needs CF and ZF. https://uops.info/)
Source:Intel Documentation SAR p.1234
Say register is al. (works with r/8, r/16, r/32, r/64)
; set OF-Flag, preserve CF
mov al, 0x7F
inc al
; clear OF-Flag, preserve CF
mov al, 0x0
inc al
Source:Intel Documentation INC p.551
Different apporach, if you can assume:
adx enabled processor (You check cpu flags with grep adx /proc/cpuinfo)Say register is eax. (need r64/r32)
; clear OF-Flag, preserve CF
mov eax, 0x0
adox eax, eax
; set OF-Flag, preserve CF
mov eax, 0xFFFFFFFF
adox eax, eax
Note: Don't try to replace mov with xor (or similar) since that will clear CF
Source:Intel Documentation ADOX p.150