Elegant D
Dom Disc
dominikus at scherkl.de
Sun Dec 7 16:11:29 UTC 2025
On Tuesday, 2 December 2025 at 14:21:05 UTC, Dom Disc wrote:
> On Tuesday, 2 December 2025 at 05:08:39 UTC, Walter Bright
> wrote:
>> It's a nice idea, but is very fragile. The exact registers
>> that are used are very sensitive to every detail, and hard to
>> predict.
> Not in this case.
Ok, you're right :-(
The result is always in the same place, but with different
calling conventions the parameters are in different registers,
that conflict with the output of the mul instruction.
I've come up with this (much less elegant):
```d
ulong mulx(ref ulong a, const ulong b, const ulong c) @safe pure
@nogc nothrow
{
/// the first of three parameters will most likely end up in
RDX, but we need this
asm @trusted pure @nogc nothrow
{
mov R8, RDX; // save address of a, because we have to
store the low bits of the result there
mov R9, c; // could be in RAX or RDI - move it to be
sure RAX is free
mov RAX, b; // could be in RCX or RSI
mul RAX, [R8]; // b*a
add RAX, R9; // +c
adc RDX, 0; // if the addition produces a carry,
increase the high bits (cannot overflow)
mov [R8], RAX;
mov RAX, RDX;
}
}
```
This at least works correct for DMD, LDC and GCD on Linux and
Windows (x86_64) - other systems I cannot test :-/
More information about the Digitalmars-d
mailing list