# Re: Trick with SBB instruction

From: alextangent (spamtrap_at_crayne.org)
Date: 01/13/05

• Next message: Rene: "Re: Beginner q: plugging into an IRQ handler"

```Date: Thu, 13 Jan 2005 19:40:31 +0000 (UTC)

```

Terje Mathisen wrote:
> spamtrap@crayne.org wrote:
>
> > I have seen some (uncommented) Intel assembler code that
> > frequently uses the following pair of lines:
> >
> > sbb eax,eax
> > sbb eax,0FFFFFFFFh
> >
> > and I was wondering what this is intended to achieve.
> >
> > Some Googling on 'sbb' indicates that the first is a
> > well-known trick for setting eax to 0 if the carry flag
> > is not set and to 0FFFFFFFFh otherwise.
>
> Right, SBB is used to replicating the carry flag across the entire
> register. As a side-effect, it will also maintain the incoming carry
flag.
>
> This means that the second SBB will either subtract -1 from zero,
i.e.
> adding 1 to generate 1, or subtract (-1 + 1) = 0 from -1.
>
> I.e. the idiom seems to turn a carry flag into either +1 or -1, which

> would be perfect for a signum function.
>

generating these optimised code sequences. Can't remember the author
either; it was the late 80s iirc. The technique is;

1. Write a standard function that performs the basic function in
unoptimised code (for example a signum using if/then/else).

2. Generate code sequences from the instruction set in question. For
instance, generate for eax all two-instruction sequences, followed by
three-instruction sequences.

3. For several hundred (possibly thousands to catch a range of boundary
conditions) of test case input values, run against each generated code
fragment and compare against the standard function's output.

Obviously most of the generated functions are going to fail as the code
sequences will, in the main, be nonsense; but most will do so quite
quickly. Those that pass are then hand checked for accuracy. The
summary of the paper suggested that in several hours, succesful code
sequences can be generated and tested for simple functions like signum;
and that some functions may have several equally elegant solutions.

I'll dig out the reference for this if anyone is interested.

```--
Regards
Alex McDonald
```

• Next message: Rene: "Re: Beginner q: plugging into an IRQ handler"