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

local __result variable declared const for non-virtual methods #20967

Open
ibuclaw opened this issue Mar 8, 2025 · 0 comments
Open

local __result variable declared const for non-virtual methods #20967

ibuclaw opened this issue Mar 8, 2025 · 0 comments
Labels
Compiler:Backend glue code, optimizer, code generation Compiler:GDC Gnu D Compiler

Comments

@ibuclaw
Copy link
Member

ibuclaw commented Mar 8, 2025

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

Change set: http://www.dsource.org/projects/dmd/changeset/259

Current location in code:

dmd/compiler/src/dmd/funcsem.d

Lines 2420 to 2421 in 4661fec

if (!fd.isVirtual())
fd.vresult.storage_class |= STC.const_;

In the linked changeset, the second setting of const looks odd, as it's against the local variable, not the out parameter.

Consider for example:

struct B
{
    ulong n;
    invariant{}
    string str()
    {
        if (n == 0)
            return "0";
        return "1";
    }
}

The above has multiple returns, which ends up as:

string str()
{
	this.__invariant();
	if (this.n == 0LU)
	{
		__result = "0";
		goto __returnLabel;
	}
	__result = "1";
	goto __returnLabel;
	__returnLabel:
	this.__invariant();
	return __result;
}

The __result variable is initialized at more than one location, so it doesn't conform to const (despite the guarantee it is only set once).

As such, you can't do any valid const optimizations on the decl, such as promoting it to rodata, otherwise you end up with wrong result, or segfault at runtime when calling b.str().

This you don't get with const local variables in D user code, as there can only be one initializer.

The suggested fix then, is to remove these two lines in buildResultVar.

@ibuclaw ibuclaw added Compiler:Backend glue code, optimizer, code generation Compiler:GDC Gnu D Compiler labels Mar 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Compiler:Backend glue code, optimizer, code generation Compiler:GDC Gnu D Compiler
Projects
None yet
Development

No branches or pull requests

1 participant