Skip to content

Commit

Permalink
POC: automatically move scope array literals to the stack
Browse files Browse the repository at this point in the history
  • Loading branch information
Dennis Korpel authored and dkorpel committed Sep 27, 2024
1 parent 1d0b93b commit a179c54
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
20 changes: 20 additions & 0 deletions compiler/src/dmd/semantic3.d
Original file line number Diff line number Diff line change
Expand Up @@ -1310,6 +1310,26 @@ private extern(C++) final class Semantic3Visitor : Visitor

finishScopeParamInference(funcdecl, f);

{
// Promote array literals like `auto x = [y];` to stack if possible
import dmd.foreachvar;
void dgVar(VarDeclaration v)
{
if (v.maybeScope && v._init)
if (auto ei = v._init.isExpInitializer())
if (auto ce = ei.exp.isConstructExp())
if (auto ale = ce.e2.isArrayLiteralExp())
ale.onstack = true;
}

void dgExp(Expression e)
{
foreachVar(e, &dgVar);
}

foreachExpAndVar(funcdecl.fbody, &dgExp, &dgVar);
}

// reset deco to apply inference result to mangled name
if (f != funcdecl.type)
f.deco = null;
Expand Down
5 changes: 3 additions & 2 deletions compiler/test/fail_compilation/test21477.d
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
/* REQUIRED_ARGS: -betterC
TEST_OUTPUT:
---
fail_compilation/test21477.d(103): Error: expression `[1]` uses the GC and cannot be used with switch `-betterC`
fail_compilation/test21477.d(14): Error: expression `[1]` uses the GC and cannot be used with switch `-betterC`
---
*/

// https://issues.dlang.org/show_bug.cgi?id=21477

#line 100
int[] global;

int test()
{
int[] foo = [1];
global = foo;
return 0;
}
13 changes: 13 additions & 0 deletions compiler/test/runnable/betterc.d
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ extern (C) void main()
testRuntimeLowerings();
test18457();
test20737();
testScopeInferenceArrayLiteral();
}

/*******************************************/
Expand Down Expand Up @@ -221,3 +222,15 @@ void test22427()
char[] p;
auto a = cast(int[])p;
}

/*******************************************/
// Test that local variable can be inferred scope, moving
// array literal from GC to stack, allowing usage in betterC

int testScopeInferenceArrayLiteral()
{
auto x = [10, 20, 30] ~ [40];
x[0] = 50;
assert(x[0] + x[1] == 70);
return x[0];
}

0 comments on commit a179c54

Please sign in to comment.