Skip to content

Commit

Permalink
Merge pull request #3593 from 9rnsr/fix3032
Browse files Browse the repository at this point in the history
Issue 3032 - No stack allocation for "scope c = new class Object {};"
  • Loading branch information
WalterBright committed May 27, 2014
2 parents 884be67 + abc7033 commit 9d48c47
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 21 deletions.
48 changes: 27 additions & 21 deletions src/declaration.c
Expand Up @@ -1517,27 +1517,6 @@ void VarDeclaration::semantic(Scope *sc)
sc->stc &= ~(STC_TYPECTOR | STCpure | STCnothrow | STCnogc | STCref | STCdisable);

ExpInitializer *ei = init->isExpInitializer();
if (ei && isScope())
{
if (ei->exp->op == TOKnew)
{
// See if initializer is a NewExp that can be allocated on the stack
NewExp *ne = (NewExp *)ei->exp;
if (!(ne->newargs && ne->newargs->dim) && type->toBasetype()->ty == Tclass)
{
ne->onstack = 1;
onstack = 1;
if (type->isBaseOf(ne->newtype->semantic(loc, sc), NULL))
onstack = 2;
}
}
else if (ei->exp->op == TOKfunction)
{
// or a delegate that doesn't escape a reference to the function
FuncDeclaration *f = ((FuncExp *)ei->exp)->fd;
f->tookAddressOf--;
}
}

// If inside function, there is no semantic3() call
if (sc->func)
Expand Down Expand Up @@ -1581,6 +1560,33 @@ void VarDeclaration::semantic(Scope *sc)
ei->exp = ei->exp->semantic(sc);
canassign--;
ei->exp->optimize(WANTvalue);

if (isScope())
{
Expression *ex = ei->exp;
while (ex->op == TOKcomma)
ex = ((CommaExp *)ex)->e2;
assert(ex->op == TOKblit || ex->op == TOKconstruct);
ex = ((AssignExp *)ex)->e2;
if (ex->op == TOKnew)
{
// See if initializer is a NewExp that can be allocated on the stack
NewExp *ne = (NewExp *)ex;
if (!(ne->newargs && ne->newargs->dim) && type->toBasetype()->ty == Tclass)
{
ne->onstack = 1;
onstack = 1;
if (type->isBaseOf(ne->newtype->semantic(loc, sc), NULL))
onstack = 2;
}
}
else if (ex->op == TOKfunction)
{
// or a delegate that doesn't escape a reference to the function
FuncDeclaration *f = ((FuncExp *)ex)->fd;
f->tookAddressOf--;
}
}
}
else
{
Expand Down
15 changes: 15 additions & 0 deletions test/runnable/nogc.d
Expand Up @@ -8,6 +8,20 @@ extern(C) int printf(const char*, ...);
return 3;
}

/***********************/
// 3032

void test3032() @nogc
{
scope o1 = new Object(); // on stack
scope o2 = new class Object {}; // on stack

int n = 1;
scope fp = (){ n = 10; }; // no closure
fp();
assert(n == 10);
}

/***********************/
// 12642

Expand All @@ -34,6 +48,7 @@ void test12642() @nogc
int main()
{
test1();
test3032();
test12642();

printf("Success\n");
Expand Down

0 comments on commit 9d48c47

Please sign in to comment.