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 22c1a56
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 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
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 22c1a56

Please sign in to comment.