From: "☂Josh Chia (謝任中)" <joshchia@gmail.com>
To: gcc-help <gcc-help@gcc.gnu.org>
Subject: Generated assembly code for returning std::optional<uint32_t>
Date: Thu, 28 Oct 2021 15:10:41 +0800 [thread overview]
Message-ID: <CALxtSbTM7OT1K-_Z5h36q0Co=LAm-FZpezmZH=DB1hnmb+DT+g@mail.gmail.com> (raw)
Under -O3 -std=c++17, the assembly code generated by gcc 11.2 for some
std::optional C++ code seems less optimal than I expect; it is writing the
content of optional<uint64_t> return values to both the stack and to the
RAX register. What am I missing? I was under the impression that return
values are put in RAX if they can fit. Why does gcc have to write the
return value to both the stack and RAX instead of just one of them? Can the
writing to the stack be avoided?
foo() & bar() return optional<uint32_t> and demonstrate this problem. baz()
returns int32_t and does not have the problem. bun(), which calls foo() and
bar(), accesses the optional<uint32_t> return value through RAX and not
through the stack, so it is evident that the stack value is redundant.
https://godbolt.org/z/Ef14n8EcM
C++ code:
#include <cstdint>
#include <optional>
using namespace std;
optional<uint32_t> foo() {
return 111;
}
optional<uint32_t> bar() {
return nullopt;
}
uint32_t baz() {
return 111;
}
bool bun(bool x) {
auto f = x ? foo : bar;
return f().has_value();
}
Generated assembly code:
foo():
mov DWORD PTR [rsp-8], 111
mov BYTE PTR [rsp-4], 1
mov rax, QWORD PTR [rsp-8]
ret
bar():
mov BYTE PTR [rsp-4], 0
mov rax, QWORD PTR [rsp-8]
ret
baz():
mov eax, 111
ret
bun(bool):
sub rsp, 24
mov edx, OFFSET FLAT:bar()
test dil, dil
mov eax, OFFSET FLAT:foo()
cmove rax, rdx
call rax
add rsp, 24
shr rax, 32
ret
next reply other threads:[~2021-10-28 7:10 UTC|newest]
Thread overview: 3+ messages / expand[flat|nested] mbox.gz Atom feed top
2021-10-28 7:10 ☂Josh Chia (謝任中) [this message]
2021-10-28 9:55 ` Jonathan Wakely
2021-10-28 10:54 ` ☂Josh Chia (謝任中)
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to='CALxtSbTM7OT1K-_Z5h36q0Co=LAm-FZpezmZH=DB1hnmb+DT+g@mail.gmail.com' \
--to=joshchia@gmail.com \
--cc=gcc-help@gcc.gnu.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).