https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81433
Bug ID: 81433 Summary: missing strlen optimization for strncpy Product: gcc Version: 8.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: tree-optimization Assignee: unassigned at gcc dot gnu.org Reporter: msebor at gcc dot gnu.org Target Milestone: --- GCC can track the length of some strings created dynamically by calling strcpy (among other functions) but it's missing the same optimization for the related strncpy function. The test case below shows two equivalent functions, where the first is optimized while the second is not. The tree-sssa-strlen pass has no support for strncpy. Since strncpy is often used as a replacement for strcpy, adding such support where possible (i.e., in cases where the length of the source string is known to be less than the specified size) is a potentially significant optimization opportunity. $ cat a.c && gcc -O2 -S -Wall -Wextra -fdump-tree-optimized=/dev/stdout a.c void f (void) { char a[7]; __builtin_strcpy (a, "123"); if (__builtin_strlen (a) != 3) __builtin_abort (); } void g (void) { char a[7]; __builtin_strncpy (a, "123", sizeof a); if (__builtin_strlen (a) != 3) __builtin_abort (); } ;; Function f (f, funcdef_no=0, decl_uid=1814, cgraph_uid=0, symbol_order=0) f () { <bb 2> [100.00%] [count: INV]: return; } ;; Function g (g, funcdef_no=1, decl_uid=1818, cgraph_uid=1, symbol_order=1) g () { char a[7]; long unsigned int _1; <bb 2> [100.00%] [count: INV]: __builtin_strncpy (&a, "123", 7); _1 = __builtin_strlen (&a); if (_1 != 3) goto <bb 3>; [0.04%] [count: 0] else goto <bb 4>; [99.96%] [count: INV] <bb 3> [0.04%] [count: 0]: __builtin_abort (); <bb 4> [99.96%] [count: INV]: a ={v} {CLOBBER}; return; }