Reimplementing the bulk of std.meta iteratively

Stefan Koch uplink.coder at gmail.com
Tue Sep 29 12:54:53 UTC 2020


On Tuesday, 29 September 2020 at 12:38:42 UTC, Stefan Koch wrote:
> [continuing]

So we had this:

> int mul(
>   int x,
>   int y
> ) {
>   int result = 0;
>   for(int i = 0; i < x; i++)
>   {
>     result += y;
>   }
>   return result;
> }


And the code generated was

	imull	%esi, %edi // y *= x
	xorl	%eax, %eax // result = 0
	testl	%esi, %esi // if (y)
	cmovgl	%edi, %eax // if (x > 0) result = x;
         retq               // return result;

On first glance these instructions seem superfluous
But we have to understand that the compiler had no way of knowing 
that we actually wanted to generate a mere multilply.

For example there is the loop entrance check.
Why is it there?

We can proof it's necessity quite easily.
- let's assume we did not have it.
In that case we are allowd to enter loop body even if (x == 0)
so we would execute result += y; once.
Which would cause mul(0, 32) to result in 32. And that would be a 
violation of the semantics.

So there's no way to get rid of the check.
And this code will always perform worse than an intrinsic 'mul' 
which the compiler knows about.


More information about the Digitalmars-d mailing list