Open matklad opened 1 year ago
Correction:
The above LLVM is for debug build mode. If I actually enable release safe, I see that LLVM is capable optimizing this particular memcpy. Howevere:
The compiler term for this seems to be Dead Store Elimination.
Seems like a reasonable optimization to introduce, given that this pattern is useful.
Consider the following code:
Currently (
0.11.0-dev.4004+a57608217
) it produces the following LLVM IR:This
memcpy
is a no-op, as it assignsx
to itself and could be optimized out. I want to argue that it should be optimized out, specifically:ReleaseSafe
we still emit a safety check that the field is initializedContext:
Why special-case this weird code? Turns out, this is a useful pattern we use quite a bit in TigerBeetle, with the most representative example being Replica.init. The overall situation there is that the
S
we want to initialize has quite a few fields, with some dedendencies between them. So we can't initS
in one-go, using.{}
syntax, we need to do a piece-wise initialization. However, we also want the compiler to hold our hand here, and to make sure that we indeed did initialize all fields. So what we do in the end isWe can imagine having some dedicated language feature for saying "I have already initialized this field", like
but the current pattern seems basically fine, modulo this missing optimization.
Note: this is another offshoot of https://ziggit.dev/t/how-to-avoid-implicit-memcpys/1197.