Bug 81533 - g++ pops up a constructor for objects that could be initialized at load-time
Summary: g++ pops up a constructor for objects that could be initialized at load-time
Status: NEW
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 8.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: missed-optimization
Depends on:
Blocks:
 
Reported: 2017-07-24 13:41 UTC by Georg-Johann Lay
Modified: 2021-08-02 04:23 UTC (History)
2 users (show)

See Also:
Host:
Target: x86_64,avr
Build:
Known to work:
Known to fail:
Last reconfirmed: 2021-08-01 00:00:00


Attachments
foo.cpp: C++ test case (170 bytes, text/plain)
2017-07-24 13:41 UTC, Georg-Johann Lay
Details

Note You need to log in before you can comment on or make changes to this bug.
Description Georg-Johann Lay 2017-07-24 13:41:35 UTC
Created attachment 41817 [details]
foo.cpp: C++ test case

When compiling the following module with g++ from v8 trunk

$ g++ foo.cpp -S -O2 -save-temps

then it pops a constructor to initialize s:

struct S { int id; const char *labl; };

const S* get_S_B()
{
  static const S s =
    { 456,
      (__extension__({
          static char ccc[] = "TextB";
          &ccc[0];
	})) };
  return &s;
}


The generated assembly reads (x86_64):

_Z7get_S_Bv:
.LFB0:
	.cfi_startproc
	movzbl	_ZGVZ7get_S_BvE1s(%rip), %eax
	testb	%al, %al
	je	.L13
	movl	$_ZZ7get_S_BvE1s, %eax
	ret
	.p2align 4,,10
	.p2align 3
.L13:
	subq	$8, %rsp
	.cfi_def_cfa_offset 16
	movl	$_ZGVZ7get_S_BvE1s, %edi
	call	__cxa_guard_acquire
	testl	%eax, %eax
	jne	.L14
	movl	$_ZZ7get_S_BvE1s, %eax
	addq	$8, %rsp
	.cfi_remember_state
	.cfi_def_cfa_offset 8
	ret


The code could be just as smart as with the following test case

struct S { int id; const char *labl; };

const S* get_S_A()
{
  static const S s = { 123, "TextA" };
  return &s;
}

which generates:

_Z7get_S_Av:
	movl	$_ZZ7get_S_AvE1s, %eax
	ret

	.section	.rodata.str1.1,"aMS",@progbits,1
.LC0:
	.string	"TextA"

	.section	.rodata
_ZZ7get_S_AvE1s:
	.long	123
	.zero	4
	.quad	.LC0
	.ident	"GCC: (GNU) 8.0.0 20170724 (experimental)"


The first version with the "TextB" assignment to ccc is useful when ccc needs a variable attribute.
Comment 1 Richard Biener 2017-07-25 07:48:58 UTC
I think there's a separate PR with the suggestion to try constexpr evaluation of all constructors for optimization.
Comment 2 Georg-Johann Lay 2017-07-25 12:25:31 UTC
(In reply to Richard Biener from comment #1)
> I think there's a separate PR with the suggestion to try constexpr
> evaluation of all constructors for optimization.

Addresses are not constexpr because they are not known at compile-time.