https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86265

--- Comment #6 from Martin Sebor <msebor at gcc dot gnu.org> ---
The strlen range optimization doesn't take advantage of undefined behavior --
like all other optimizations, it simply assumes code is free of it.

I have two goals for the warnings I work on: a) most important is to find bugs
in user code, and b) less important is to drive improvements to help GCC better
analyze source code and emit more efficient object code.

By relying on valid calls to strcpy() writing only into the destination array
and not beyond, and reading only from the source array and not beyond, GCC can
safely assume that other members of the same struct or other elements of the
same array of structs than the one written to are unchanged by the strcpy()
call.  For instance, in the following, the tests can safely be eliminated:

  struct A {
    char a[4];
    int i;
  };

  void f (struct A *a)
  {
    int i = a[0].i + a[1].i;

    __builtin_strcpy (a[0].a, a[1].a);

    if (i != a[0].i + a[1].i)
      __builtin_abort ();
  }

There is no reason not to take advantage of this except to cater to
exceptionally poorly written (and I'd say exceedingly rare) code, and thus
penalize the overwhelming majority of code that doesn't violate the basic rules
of the language.

Reply via email to