Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

POC: automatically move scope array literals to the stack #16897

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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];
}
Loading