- To: ohav chochmah <philomath868@xxxxxxxxx>
- Subject: Re: optimizing out string functions when the string contains a NUL
- From: Ian Lance Taylor <iant@xxxxxxxxxx>
- Date: Wed, 20 Jun 2012 10:42:10 -0700
- Cc: gcc-help@xxxxxxxxxxx
- Comment: DKIM? See http://www.dkim.org
- Comment: DomainKeys? See http://antispam.yahoo.com/domainkeys
- In-reply-to: <CABOpGfufXox5NtjFk-D2WvGUUAmteTZG0PM1Kh5Fnpvc=r6eRQ@mail.gmail.com> (ohav chochmah's message of "Wed, 20 Jun 2012 18:02:27 +0200")
- User-agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux)
ohav chochmah <philomath868@xxxxxxxxx> writes:
> On 6/20/12, Ian Lance Taylor <iant@xxxxxxxxxx> wrote:
>> ohav chochmah <philomath868@xxxxxxxxx> writes:
>>
>>> #define HIDDEN "\0this string starts with a NUL"
>>> ...
>>> AFAICT, the puts and printf are both no-ops, as the C-string stops
>>> before it starts. yet when doing 'gcc -S tst.c -O2 -march=native' or
>>> even 'gcc -S tst.c -O3 -march=native', GCC generates the following:
>>> ...
>>> in short, the printf was removed but not the puts. which left me
>>> wondering why?
>>
>> You are describing an optimization in which GCC looks in constant string
>> literals passed to puts and truncates them at \0. Nobody has
>> implemented that optimization. It sounds like it would affect very very
>> very few programs, so I'm not sure why anybody would bother to implement
>
> right, but then why is the printf omitted entirely?
Because, unlike the uncommon case of using puts with a string literal
containing '\0', it's very common to use printf in a way that can be
optimized. In particular, if STRING ends with \n, then printf(STRING)
can be optimized to puts(STRING), which is more efficient. That kind of
code occurs frequently, so the optimization is worth doing, and it has
been implemented.
>> it. If anything I think it would be more useful to have a warning. But
>
> a warning is issued for printf (tst.c:8:5: warning: embedded ‘\0’ in
> format [-Wformat-contains-nul]), but not for puts.
This warning is essentially a side-effect. Since the printf
optimization requires analyzing the string, it's easy to add this check.
It's not a separate and additional warning, as it would be for puts.
Ian
[Linux C Programming]
[Linux Kernel]
[eCos]
[Fedora Development]
[Fedora Announce]
[Autoconf]
[The DWARVES Debugging Tools]
[Yosemite Campsites]
[Yosemite News]
[Linux GCC]