Bug 24250 – Recognize immediate indexing of array literal to prevent GC allocation

Status
NEW
Severity
enhancement
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2023-11-19T16:23:02Z
Last change time
2024-12-13T19:31:52Z
Assigned to
No Owner
Creator
johanengelen
Moved to GitHub: dmd#20361 →

Comments

Comment #0 by johanengelen — 2023-11-19T16:23:02Z
Testcase: ``` enum int[3] masks = [1, 2, 3]; int foo(int a) @nogc { return masks[a]; } int foo2(int a) @nogc { int[3] m = [1, 2, 3]; return m[a]; } int foo3(int a) @nogc { return (cast(int[3])[1, 2, 3])[a]; } int foo4(int a) @nogc { return [1, 2, 3][a]; // <-- Error } ``` Compilation error: `Error: array literal in `@nogc` function `example.foo4` may cause a GC allocation` I think this is correct, because the spec says that an array literal is a dynamic array (https://dlang.org/spec/expression.html#array_literals). However, it would be nice if the pattern in foo4 is recognized and turned into foo3 (immediate indexing of array, thus the array does not have to be dynamic), and no GC allocation is used in foo4. This does lead to more stack usage in foo4, so there should be an array size limit for this pattern. But note that foo (with enum) suffers from the same problem, without clear visibility. (in foo2 and foo3 the potentially large stack usage is more obvious to the programmer)
Comment #1 by robert.schadek — 2024-12-13T19:31:52Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dmd/issues/20361 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB