By ref and by pointer kills performance.

Richard (Rikki) Andrew Cattermole richard at cattermole.co.nz
Tue Feb 13 19:20:21 UTC 2024


On 14/02/2024 2:30 AM, Johan wrote:
> On Tuesday, 13 February 2024 at 03:31:31 UTC, Richard (Rikki) Andrew 
> Cattermole wrote:
>> dmd having bad codegen here isn't a surprise, that is to be expected.
>>
>> Now for ldc:
>>
>> ```d
>> void fillBP(immutable(uint*) value, uint* dest) {
>>      dest[0] = *value;
>>      dest[1] = *value;
>>      dest[2] = *value;
>>      dest[3] = *value;
>> }
>> ```
>>
>> I expected that to not do the extra loads, but it did.
> 
> I hope someone can find the link to some DConf talk (me or Andrei) or 
> forum post where I talk about why LDC assumes that `immutable(uint*)` 
> points to _mutable_ (nota bene) data. The reason is the mutable thread 
> synchronization field in immutable class variable storage (`__monitor`), 
> combined with casting an immutable class to an array of immutable bytes.
> 
> Side-effects in-between immutable(uint*) lookup could run into a 
> synchronization event on the immutable data (i.e. mutating it).
> In the case of `fillBP` there are no side-effects possible between the 
> reads, so it appears that indeed the optimization could be done. But a 
> different thread might write to the data. I don't know how that 
> data-race is then defined...
> For the general case, side-effects are possible (e.g. a function call) 
> so it is not possible to simply assume that `immutable` reference 
> arguments never alias to other reference arguments; this complicates 
> implementing the desired optimization.
> I'm not saying it is impossible, it's just extra effort (and proof is 
> needed).
> 
> -Johan

If you don't like the problem, change the problem.

After thinking about it, I can agree for D classes immutable can't be 
known if it truely applies or not. A lock could still be taken in const 
code.

So the problem is:

For a type that is not a D class (COM, extern(C++) are not included in 
that definition), mark as immutable to LLVM IR so optimizations can be 
used wrt. immutable.

After all, to call an immutable this, method it must also be marked as 
const or immutable. The this pointer won't be allowed to be mutated 
unless someone did something bad (again, not the compiler's fault that 
the user went against it).

I don't think much thought needs to go into this.


More information about the Digitalmars-d mailing list