Thread overview
[Issue 2682] New: const struct initialized with struct literal recreates value on stack when used
Feb 22, 2009
d-bugmail
Feb 22, 2009
d-bugmail
Mar 03, 2009
d-bugmail
Mar 29, 2009
d-bugmail
February 22, 2009
http://d.puremagic.com/issues/show_bug.cgi?id=2682

           Summary: const struct initialized with struct literal recreates
                    value on stack when used
           Product: D
           Version: 1.039
          Platform: PC
        OS/Version: Linux
            Status: NEW
          Keywords: wrong-code
          Severity: normal
          Priority: P2
         Component: DMD
        AssignedTo: bugzilla@digitalmars.com
        ReportedBy: kamm-removethis@incasoftware.de


As the following code shows the const S s isn't really initialized with a constant that's put into the data segment, but works more like "alias S(5) s;".

---
struct S { int i; }

const S s = S(5);
const S u = { 5 };

void foo(int num) {
  printf("%p %p\n", &s, &u);
  if (num > 0)
    foo(num-1);
}

void main() {
  foo(2);
}
---

output:
0xbfc1774c 0x80601a0
0xbfc17738 0x80601a0
0xbfc17724 0x80601a0


-- 

February 22, 2009
http://d.puremagic.com/issues/show_bug.cgi?id=2682


smjg@iname.com changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |smjg@iname.com




------- Comment #1 from smjg@iname.com  2009-02-22 09:08 -------
This reminds me of bug 2414 ... related?


-- 

March 03, 2009
http://d.puremagic.com/issues/show_bug.cgi?id=2682





------- Comment #2 from tomas@famolsen.dk  2009-03-02 21:46 -------
I fixed this in LDC by disabling the Initializer -> Expression optimization for StructInitializerS:

--- a/dmd/optimize.c    Tue Mar 03 02:51:21 2009 +0100
+++ b/dmd/optimize.c    Tue Mar 03 04:38:49 2009 +0100
@@ -46,7 +46,7 @@
     if (e1->op == TOKvar)
     {  VarExp *ve = (VarExp *)e1;
        VarDeclaration *v = ve->var->isVarDeclaration();
-       if (v && v->isConst() && v->init)
+       if (v && v->isConst() && v->init && !v->init->isStructInitializer())
        {   Expression *ei = v->init->toExpression();
            if (ei && ei->type)
                e1 = ei;


-- 

March 29, 2009
http://d.puremagic.com/issues/show_bug.cgi?id=2682





------- Comment #3 from kamm-removethis@incasoftware.de  2009-03-29 04:50 -------
Removing that optimization lead to constant folding issues. Instead we have now demoted struct literals to rvalues in LDC. It does not create any regressions in our testsuite - please let us know if you expect this to be trouble.


--