Debian Codegraph @

gcc/tree-ssa-strlen.cc

raw
1 /* String length optimization
2 Copyright (C) 2011-2025 Free Software Foundation, Inc.
3 Contributed by Jakub Jelinek <[email protected]>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "rtl.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "alloc-pool.h"
29 #include "tree-pass.h"
30 #include "ssa.h"
31 #include "cgraph.h"
32 #include "gimple-pretty-print.h"
33 #include "gimple-ssa-warn-access.h"
34 #include "gimple-ssa-warn-restrict.h"
35 #include "fold-const.h"
36 #include "stor-layout.h"
37 #include "gimple-iterator.h"
38 #include "gimple-fold.h"
39 #include "tree-eh.h"
40 #include "gimplify.h"
41 #include "gimplify-me.h"
42 #include "expr.h"
43 #include "tree-cfg.h"
44 #include "tree-dfa.h"
45 #include "domwalk.h"
46 #include "tree-ssa-alias.h"
47 #include "tree-ssa-propagate.h"
48 #include "tree-ssa-strlen.h"
49 #include "tree-hash-traits.h"
50 #include "builtins.h"
51 #include "pointer-query.h"
52 #include "target.h"
53 #include "diagnostic-core.h"
54 #include "diagnostic.h"
55 #include "intl.h"
56 #include "attribs.h"
57 #include "calls.h"
58 #include "cfgloop.h"
59 #include "tree-ssa-loop.h"
60 #include "tree-scalar-evolution.h"
61 #include "vr-values.h"
62 #include "gimple-range.h"
63 #include "tree-ssa.h"
64
65 /* A vector indexed by SSA_NAME_VERSION. 0 means unknown, positive value
66 is an index into strinfo vector, negative value stands for
67 string length of a string literal (~strlen). */
68 static vec<int> ssa_ver_to_stridx;
69
70 /* Number of currently active string indexes plus one. */
71 static int max_stridx;
72
73 /* Set to true to optimize, false when just checking. */
74 static bool strlen_optimize;
75
76 /* String information record. */
77 struct strinfo
78 {
79 /* Number of leading characters that are known to be nonzero. This is
80 also the length of the string if FULL_STRING_P.
81
82 The values in a list of related string pointers must be consistent;
83 that is, if strinfo B comes X bytes after strinfo A, it must be
84 the case that A->nonzero_chars == X + B->nonzero_chars. */
85 tree nonzero_chars;
86 /* Any of the corresponding pointers for querying alias oracle. */
87 tree ptr;
88 /* STMT is used for two things:
89
90 - To record the statement that should be used for delayed length
91 computations. We maintain the invariant that all related strinfos
92 have delayed lengths or none do.
93
94 - To record the malloc or calloc call that produced this result
95 to optimize away malloc/memset sequences. STMT is reset after
96 a calloc-allocated object has been stored a non-zero value into. */
97 gimple *stmt;
98 /* Set to the dynamic allocation statement for the object (alloca,
99 calloc, malloc, or VLA). Unlike STMT, once set for a strinfo
100 object, ALLOC doesn't change. */
101 gimple *alloc;
102 /* Pointer to '\0' if known, if NULL, it can be computed as
103 ptr + length. */
104 tree endptr;
105 /* Reference count. Any changes to strinfo entry possibly shared
106 with dominating basic blocks need unshare_strinfo first, except
107 for dont_invalidate which affects only the immediately next
108 maybe_invalidate. */
109 int refcount;
110 /* Copy of index. get_strinfo (si->idx) should return si; */
111 int idx;
112 /* These 3 fields are for chaining related string pointers together.
113 E.g. for
114 bl = strlen (b); dl = strlen (d); strcpy (a, b); c = a + bl;
115 strcpy (c, d); e = c + dl;
116 strinfo(a) -> strinfo(c) -> strinfo(e)
117 All have ->first field equal to strinfo(a)->idx and are doubly
118 chained through prev/next fields. The later strinfos are required
119 to point into the same string with zero or more bytes after
120 the previous pointer and all bytes in between the two pointers
121 must be non-zero. Functions like strcpy or memcpy are supposed
122 to adjust all previous strinfo lengths, but not following strinfo
123 lengths (those are uncertain, usually invalidated during
124 maybe_invalidate, except when the alias oracle knows better).
125 Functions like strcat on the other side adjust the whole
126 related strinfo chain.
127 They are updated lazily, so to use the chain the same first fields
128 and si->prev->next == si->idx needs to be verified. */
129 int first;
130 int next;
131 int prev;
132 /* A flag whether the string is known to be written in the current
133 function. */
134 bool writable;
135 /* A flag for the next maybe_invalidate that this strinfo shouldn't
136 be invalidated. Always cleared by maybe_invalidate. */
137 bool dont_invalidate;
138 /* True if the string is known to be nul-terminated after NONZERO_CHARS
139 characters. False is useful when detecting strings that are built
140 up via successive memcpys. */
141 bool full_string_p;
142 };
143
144 /* Pool for allocating strinfo_struct entries. */
145 static object_allocator<strinfo> strinfo_pool ("strinfo pool");
146
147 /* Vector mapping positive string indexes to strinfo, for the
148 current basic block. The first pointer in the vector is special,
149 it is either NULL, meaning the vector isn't shared, or it is
150 a basic block pointer to the owner basic_block if shared.
151 If some other bb wants to modify the vector, the vector needs
152 to be unshared first, and only the owner bb is supposed to free it. */
153 static vec<strinfo *, va_heap, vl_embed> *stridx_to_strinfo;
154
155 /* One OFFSET->IDX mapping. */
156 struct stridxlist
157 {
158 struct stridxlist *next;
159 HOST_WIDE_INT offset;
160 int idx;
161 };
162
163 /* Hash table entry, mapping a DECL to a chain of OFFSET->IDX mappings. */
164 struct decl_stridxlist_map
165 {
166 struct tree_map_base base;
167 struct stridxlist list;
168 };
169
170 /* Hash table for mapping decls to a chained list of offset -> idx
171 mappings. */
172 typedef hash_map<tree_decl_hash, stridxlist> decl_to_stridxlist_htab_t;
173 static decl_to_stridxlist_htab_t *decl_to_stridxlist_htab;
174
175 /* Hash table mapping strlen (or strnlen with constant bound and return
176 smaller than bound) calls to stridx instances describing
177 the calls' arguments. Non-null only when warn_stringop_truncation
178 is non-zero. */
179 typedef std::pair<int, location_t> stridx_strlenloc;
180 static hash_map<tree, stridx_strlenloc> *strlen_to_stridx;
181
182 /* Obstack for struct stridxlist and struct decl_stridxlist_map. */
183 static struct obstack stridx_obstack;
184
185 /* Last memcpy statement if it could be adjusted if the trailing
186 '\0' written is immediately overwritten, or
187 *x = '\0' store that could be removed if it is immediately overwritten. */
188 struct laststmt_struct
189 {
190 gimple *stmt;
191 tree len;
192 int stridx;
193 } laststmt;
194
195 static int get_stridx_plus_constant (strinfo *, unsigned HOST_WIDE_INT, tree);
196 static bool get_range_strlen_dynamic (tree, gimple *, c_strlen_data *,
197 bitmap, pointer_query *, unsigned *);
198
199 /* Sets MINMAX to either the constant value or the range VAL is in
200 and returns either the constant value or VAL on success or null
201 when the range couldn't be determined. Uses RVALS or CFUN for
202 range info, whichever is nonnull. */
203
204 tree
205 get_range (tree val, gimple *stmt, wide_int minmax[2],
206 range_query *rvals /* = NULL */)
207 {
208 if (!rvals)
209 {
210 if (!cfun)
211 /* When called from front ends for global initializers CFUN
212 may be null. */
213 return NULL_TREE;
214
215 rvals = get_range_query (cfun);
216 }
217
218 value_range vr (TREE_TYPE (val));
219 if (!rvals->range_of_expr (vr, val, stmt))
220 return NULL_TREE;
221
222 tree vrmin, vrmax;
223 value_range_kind rng = get_legacy_range (vr, vrmin, vrmax);
224 if (rng == VR_RANGE)
225 {
226 /* Only handle straight ranges. */
227 minmax[0] = wi::to_wide (vrmin);
228 minmax[1] = wi::to_wide (vrmax);
229 return val;
230 }
231
232 return NULL_TREE;
233 }
234
235 class strlen_pass : public dom_walker
236 {
237 public:
238 strlen_pass (function *fun, cdi_direction direction)
239 : dom_walker (direction),
240 ptr_qry (get_range_query (fun)),
241 m_cleanup_cfg (false)
242 {
243 }
244
245 ~strlen_pass ();
246
247 edge before_dom_children (basic_block) final override;
248 void after_dom_children (basic_block) final override;
249
250 bool check_and_optimize_stmt (bool *cleanup_eh);
251 bool check_and_optimize_call (bool *zero_write);
252 bool handle_assign (tree lhs, bool *zero_write);
253 bool handle_store (bool *zero_write);
254 void handle_pointer_plus ();
255 void handle_builtin_strlen ();
256 void handle_builtin_strchr ();
257 void handle_builtin_strcpy (built_in_function);
258 void handle_integral_assign (bool *cleanup_eh);
259 void handle_builtin_stxncpy_strncat (bool append_p);
260 void handle_builtin_memcpy (built_in_function bcode);
261 void handle_builtin_strcat (built_in_function bcode);
262 void handle_builtin_strncat (built_in_function);
263 bool handle_builtin_memset (bool *zero_write);
264 bool handle_builtin_memcmp ();
265 bool handle_builtin_string_cmp ();
266 void handle_alloc_call (built_in_function);
267 void maybe_warn_overflow (gimple *stmt, bool call_lhs, tree len,
268 strinfo *si = NULL, bool plus_one = false,
269 bool rawmem = false);
270 void maybe_warn_overflow (gimple *stmt, bool call_lhs,
271 unsigned HOST_WIDE_INT len,
272 strinfo *si = NULL,
273 bool plus_one = false, bool rawmem = false);
274 void adjust_last_stmt (strinfo *si, gimple *stmt, bool is_strcat);
275 tree strxcmp_eqz_result (gimple *stmt, tree arg1, int idx1,
276 tree arg2, int idx2,
277 unsigned HOST_WIDE_INT bound,
278 unsigned HOST_WIDE_INT len[2],
279 unsigned HOST_WIDE_INT *psize);
280 bool count_nonzero_bytes (tree expr_or_type,
281 gimple *stmt,
282 unsigned lenrange[3], bool *nulterm,
283 bool *allnul, bool *allnonnul);
284 bool count_nonzero_bytes (tree exp, tree vuse,
285 gimple *stmt,
286 unsigned HOST_WIDE_INT offset,
287 unsigned HOST_WIDE_INT nbytes,
288 unsigned lenrange[3], bool *nulterm,
289 bool *allnul, bool *allnonnul,
290 ssa_name_limit_t &snlim);
291 bool count_nonzero_bytes_addr (tree exp, tree vuse,
292 gimple *stmt,
293 unsigned HOST_WIDE_INT offset,
294 unsigned HOST_WIDE_INT nbytes,
295 unsigned lenrange[3], bool *nulterm,
296 bool *allnul, bool *allnonnul,
297 ssa_name_limit_t &snlim);
298 bool get_len_or_size (gimple *stmt, tree arg, int idx,
299 unsigned HOST_WIDE_INT lenrng[2],
300 unsigned HOST_WIDE_INT *size, bool *nulterm);
301
302 /* A pointer_query object to store information about pointers and
303 their targets in. */
304 pointer_query ptr_qry;
305
306 gimple_stmt_iterator m_gsi;
307
308 /* Flag that will trigger TODO_cleanup_cfg to be returned in strlen
309 execute function. */
310 bool m_cleanup_cfg;
311 };
312
313 /* Return:
314
315 * +1 if SI is known to start with more than OFF nonzero characters.
316
317 * 0 if SI is known to start with exactly OFF nonzero characters.
318
319 * -1 if SI either does not start with OFF nonzero characters
320 or the relationship between the number of leading nonzero
321 characters in SI and OFF is unknown. */
322
323 static int
324 compare_nonzero_chars (strinfo *si, unsigned HOST_WIDE_INT off)
325 {
326 if (si->nonzero_chars
327 && TREE_CODE (si->nonzero_chars) == INTEGER_CST)
328 return compare_tree_int (si->nonzero_chars, off);
329 else
330 return -1;
331 }
332
333 /* Same as above but suitable also for strings with non-constant lengths.
334 Uses RVALS to determine length range. */
335
336 static int
337 compare_nonzero_chars (strinfo *si, gimple *stmt,
338 unsigned HOST_WIDE_INT off,
339 range_query *rvals)
340 {
341 if (!si->nonzero_chars)
342 return -1;
343
344 if (TREE_CODE (si->nonzero_chars) == INTEGER_CST)
345 return compare_tree_int (si->nonzero_chars, off);
346
347 if (!rvals || TREE_CODE (si->nonzero_chars) != SSA_NAME)
348 return -1;
349
350 int_range_max vr;
351 if (!rvals->range_of_expr (vr, si->nonzero_chars, stmt)
352 || vr.varying_p ()
353 || vr.undefined_p ())
354 return -1;
355
356 /* If the offset is less than the minimum length or if the bounds
357 of the length range are equal return the result of the comparison
358 same as in the constant case. Otherwise return a conservative
359 result. */
360 signop sign = TYPE_SIGN (vr.type ());
361 unsigned prec = TYPE_PRECISION (vr.type ());
362 int cmpmin = wi::cmp (vr.lower_bound (), wi::uhwi (off, prec), sign);
363 if (cmpmin > 0 || vr.singleton_p ())
364 return cmpmin;
365
366 return -1;
367 }
368
369 /* Return true if SI is known to be a zero-length string. */
370
371 static inline bool
372 zero_length_string_p (strinfo *si)
373 {
374 return si->full_string_p && integer_zerop (si->nonzero_chars);
375 }
376
377 /* Return strinfo vector entry IDX. */
378
379 static inline strinfo *
380 get_strinfo (int idx)
381 {
382 if (vec_safe_length (stridx_to_strinfo) <= (unsigned int) idx)
383 return NULL;
384 return (*stridx_to_strinfo)[idx];
385 }
386
387 /* Get the next strinfo in the chain after SI, or null if none. */
388
389 static inline strinfo *
390 get_next_strinfo (strinfo *si)
391 {
392 if (si->next == 0)
393 return NULL;
394 strinfo *nextsi = get_strinfo (si->next);
395 if (nextsi == NULL || nextsi->first != si->first || nextsi->prev != si->idx)
396 return NULL;
397 return nextsi;
398 }
399
400 /* Helper function for get_stridx. Return the strinfo index of the address
401 of EXP, which is available in PTR if nonnull. If OFFSET_OUT, it is
402 OK to return the index for some X <= &EXP and store &EXP - X in
403 *OFFSET_OUT. When RVALS is nonnull uses it to determine range
404 information. */
405
406 static int
407 get_addr_stridx (tree exp, gimple *stmt,
408 tree ptr, unsigned HOST_WIDE_INT *offset_out,
409 range_query *rvals = NULL)
410 {
411 HOST_WIDE_INT off;
412 struct stridxlist *list, *last = NULL;
413 tree base;
414
415 if (!decl_to_stridxlist_htab)
416 return 0;
417
418 poly_int64 poff;
419 base = get_addr_base_and_unit_offset (exp, &poff);
420 if (base == NULL || !DECL_P (base) || !poff.is_constant (&off))
421 return 0;
422
423 list = decl_to_stridxlist_htab->get (base);
424 if (list == NULL)
425 return 0;
426
427 do
428 {
429 if (list->offset == off)
430 {
431 if (offset_out)
432 *offset_out = 0;
433 return list->idx;
434 }
435 if (list->offset > off)
436 return 0;
437 last = list;
438 list = list->next;
439 }
440 while (list);
441
442 if ((offset_out || ptr) && last && last->idx > 0)
443 {
444 unsigned HOST_WIDE_INT rel_off
445 = (unsigned HOST_WIDE_INT) off - last->offset;
446 strinfo *si = get_strinfo (last->idx);
447 if (si && compare_nonzero_chars (si, stmt, rel_off, rvals) >= 0)
448 {
449 if (offset_out)
450 {
451 *offset_out = rel_off;
452 return last->idx;
453 }
454 else
455 return get_stridx_plus_constant (si, rel_off, ptr);
456 }
457 }
458 return 0;
459 }
460
461 /* Returns string index for EXP. When EXP is an SSA_NAME that refers
462 to a known strinfo with an offset and OFFRNG is non-null, sets
463 both elements of the OFFRNG array to the range of the offset and
464 returns the index of the known strinfo. In this case the result
465 must not be used in for functions that modify the string.
466 When nonnull, uses RVALS to determine range information. */
467
468 static int
469 get_stridx (tree exp, gimple *stmt,
470 wide_int offrng[2] = NULL, range_query *rvals = NULL)
471 {
472 if (offrng)
473 offrng[0] = offrng[1] = wi::zero (TYPE_PRECISION (ptrdiff_type_node));
474
475 if (TREE_CODE (exp) == SSA_NAME)
476 {
477 if (ssa_ver_to_stridx[SSA_NAME_VERSION (exp)])
478 return ssa_ver_to_stridx[SSA_NAME_VERSION (exp)];
479
480 tree e = exp;
481 int last_idx = 0;
482 HOST_WIDE_INT offset = 0;
483 /* Follow a chain of at most 5 assignments. */
484 for (int i = 0; i < 5; i++)
485 {
486 gimple *def_stmt = SSA_NAME_DEF_STMT (e);
487 if (!is_gimple_assign (def_stmt))
488 return last_idx;
489
490 tree_code rhs_code = gimple_assign_rhs_code (def_stmt);
491 tree ptr, off;
492
493 if (rhs_code == ADDR_EXPR)
494 {
495 /* Handle indices/offsets into VLAs which are implemented
496 as pointers to arrays. */
497 ptr = gimple_assign_rhs1 (def_stmt);
498 ptr = TREE_OPERAND (ptr, 0);
499
500 /* Handle also VLAs of types larger than char. */
501 if (tree eltsize = TYPE_SIZE_UNIT (TREE_TYPE (ptr)))
502 {
503 if (TREE_CODE (ptr) == ARRAY_REF)
504 {
505 off = TREE_OPERAND (ptr, 1);
506 ptr = TREE_OPERAND (ptr, 0);
507 if (!integer_onep (eltsize))
508 {
509 /* Scale the array index by the size of the element
510 type in the rare case that it's greater than
511 the typical 1 for char, making sure both operands
512 have the same type. */
513 eltsize = fold_convert (ssizetype, eltsize);
514 off = fold_convert (ssizetype, off);
515 off = fold_build2 (MULT_EXPR, ssizetype, off, eltsize);
516 }
517 }
518 else
519 off = integer_zero_node;
520 }
521 else
522 return 0;
523
524 if (TREE_CODE (ptr) != MEM_REF)
525 return 0;
526
527 /* Add the MEM_REF byte offset. */
528 tree mem_off = TREE_OPERAND (ptr, 1);
529 off = fold_build2 (PLUS_EXPR, TREE_TYPE (off), off, mem_off);
530 ptr = TREE_OPERAND (ptr, 0);
531 }
532 else if (rhs_code == POINTER_PLUS_EXPR)
533 {
534 ptr = gimple_assign_rhs1 (def_stmt);
535 off = gimple_assign_rhs2 (def_stmt);
536 }
537 else
538 return 0;
539
540 if (TREE_CODE (ptr) != SSA_NAME)
541 return 0;
542
543 if (!tree_fits_shwi_p (off))
544 {
545 if (int idx = ssa_ver_to_stridx[SSA_NAME_VERSION (ptr)])
546 if (offrng)
547 {
548 /* Only when requested by setting OFFRNG to non-null,
549 return the index corresponding to the SSA_NAME.
550 Do this irrespective of the whether the offset
551 is known. */
552 if (get_range (off, def_stmt, offrng, rvals))
553 {
554 /* When the offset range is known, increment it
555 it by the constant offset computed in prior
556 iterations and store it in the OFFRNG array. */
557 offrng[0] += offset;
558 offrng[1] += offset;
559 }
560 else
561 {
562 /* When the offset range cannot be determined
563 store [0, SIZE_MAX] and let the caller decide
564 if the offset matters. */
565 offrng[1] = wi::to_wide (TYPE_MAX_VALUE (sizetype));
566 offrng[0] = wi::zero (offrng[1].get_precision ());
567 }
568 return idx;
569 }
570 return 0;
571 }
572
573 HOST_WIDE_INT this_off = tree_to_shwi (off);
574 if (offrng)
575 {
576 offrng[0] += wi::shwi (this_off, offrng->get_precision ());
577 offrng[1] += offrng[0];
578 }
579
580 if (this_off < 0)
581 return last_idx;
582
583 offset = (unsigned HOST_WIDE_INT) offset + this_off;
584 if (offset < 0)
585 return last_idx;
586
587 if (int idx = ssa_ver_to_stridx[SSA_NAME_VERSION (ptr)])
588 {
589 strinfo *si = get_strinfo (idx);
590 if (si)
591 {
592 if (compare_nonzero_chars (si, offset) >= 0)
593 return get_stridx_plus_constant (si, offset, exp);
594
595 if (offrng)
596 last_idx = idx;
597 }
598 }
599 e = ptr;
600 }
601
602 return last_idx;
603 }
604
605 if (TREE_CODE (exp) == ADDR_EXPR)
606 {
607 int idx = get_addr_stridx (TREE_OPERAND (exp, 0), stmt, exp, NULL);
608 if (idx != 0)
609 return idx;
610 }
611
612 const char *p = c_getstr (exp);
613 if (p)
614 return ~(int) strlen (p);
615
616 return 0;
617 }
618
619 /* Return true if strinfo vector is shared with the immediate dominator. */
620
621 static inline bool
622 strinfo_shared (void)
623 {
624 return vec_safe_length (stridx_to_strinfo)
625 && (*stridx_to_strinfo)[0] != NULL;
626 }
627
628 /* Unshare strinfo vector that is shared with the immediate dominator. */
629
630 static void
631 unshare_strinfo_vec (void)
632 {
633 strinfo *si;
634 unsigned int i = 0;
635
636 gcc_assert (strinfo_shared ());
637 stridx_to_strinfo = vec_safe_copy (stridx_to_strinfo);
638 for (i = 1; vec_safe_iterate (stridx_to_strinfo, i, &si); ++i)
639 if (si != NULL)
640 si->refcount++;
641 (*stridx_to_strinfo)[0] = NULL;
642 }
643
644 /* Attempt to create a string index for exp, ADDR_EXPR's operand.
645 Return a pointer to the location where the string index can
646 be stored (if 0) or is stored, or NULL if this can't be tracked. */
647
648 static int *
649 addr_stridxptr (tree exp)
650 {
651 HOST_WIDE_INT off;
652
653 poly_int64 poff;
654 tree base = get_addr_base_and_unit_offset (exp, &poff);
655 if (base == NULL_TREE || !DECL_P (base) || !poff.is_constant (&off))
656 return NULL;
657
658 if (!decl_to_stridxlist_htab)
659 {
660 decl_to_stridxlist_htab
661 = new hash_map<tree_decl_hash, stridxlist> (64);
662 gcc_obstack_init (&stridx_obstack);
663 }
664
665 bool existed;
666 stridxlist *list = &decl_to_stridxlist_htab->get_or_insert (base, &existed);
667 if (existed)
668 {
669 int i;
670 stridxlist *before = NULL;
671 for (i = 0; i < 32; i++)
672 {
673 if (list->offset == off)
674 return &list->idx;
675 if (list->offset > off && before == NULL)
676 before = list;
677 if (list->next == NULL)
678 break;
679 list = list->next;
680 }
681 if (i == 32)
682 return NULL;
683 if (before)
684 {
685 list = before;
686 before = XOBNEW (&stridx_obstack, struct stridxlist);
687 *before = *list;
688 list->next = before;
689 list->offset = off;
690 list->idx = 0;
691 return &list->idx;
692 }
693 list->next = XOBNEW (&stridx_obstack, struct stridxlist);
694 list = list->next;
695 }
696
697 list->next = NULL;
698 list->offset = off;
699 list->idx = 0;
700 return &list->idx;
701 }
702
703 /* Create a new string index, or return 0 if reached limit. */
704
705 static int
706 new_stridx (tree exp)
707 {
708 int idx;
709 if (max_stridx >= param_max_tracked_strlens)
710 return 0;
711 if (TREE_CODE (exp) == SSA_NAME)
712 {
713 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (exp))
714 return 0;
715 idx = max_stridx++;
716 ssa_ver_to_stridx[SSA_NAME_VERSION (exp)] = idx;
717 return idx;
718 }
719 if (TREE_CODE (exp) == ADDR_EXPR)
720 {
721 int *pidx = addr_stridxptr (TREE_OPERAND (exp, 0));
722 if (pidx != NULL)
723 {
724 gcc_assert (*pidx == 0);
725 *pidx = max_stridx++;
726 return *pidx;
727 }
728 }
729 return 0;
730 }
731
732 /* Like new_stridx, but for ADDR_EXPR's operand instead. */
733
734 static int
735 new_addr_stridx (tree exp)
736 {
737 int *pidx;
738 if (max_stridx >= param_max_tracked_strlens)
739 return 0;
740 pidx = addr_stridxptr (exp);
741 if (pidx != NULL)
742 {
743 gcc_assert (*pidx == 0);
744 *pidx = max_stridx++;
745 return *pidx;
746 }
747 return 0;
748 }
749
750 /* Create a new strinfo. */
751
752 static strinfo *
753 new_strinfo (tree ptr, int idx, tree nonzero_chars, bool full_string_p)
754 {
755 strinfo *si = strinfo_pool.allocate ();
756 si->nonzero_chars = nonzero_chars;
757 STRIP_USELESS_TYPE_CONVERSION (ptr);
758 si->ptr = ptr;
759 si->stmt = NULL;
760 si->alloc = NULL;
761 si->endptr = NULL_TREE;
762 si->refcount = 1;
763 si->idx = idx;
764 si->first = 0;
765 si->prev = 0;
766 si->next = 0;
767 si->writable = false;
768 si->dont_invalidate = false;
769 si->full_string_p = full_string_p;
770 return si;
771 }
772
773 /* Decrease strinfo refcount and free it if not referenced anymore. */
774
775 static inline void
776 free_strinfo (strinfo *si)
777 {
778 if (si && --si->refcount == 0)
779 strinfo_pool.remove (si);
780 }
781
782 /* Set strinfo in the vector entry IDX to SI. */
783
784 static inline void
785 set_strinfo (int idx, strinfo *si)
786 {
787 if (vec_safe_length (stridx_to_strinfo) && (*stridx_to_strinfo)[0])
788 unshare_strinfo_vec ();
789 if (vec_safe_length (stridx_to_strinfo) <= (unsigned int) idx)
790 vec_safe_grow_cleared (stridx_to_strinfo, idx + 1, true);
791 (*stridx_to_strinfo)[idx] = si;
792 }
793
794 /* Return the first strinfo in the related strinfo chain
795 if all strinfos in between belong to the chain, otherwise NULL. */
796
797 static strinfo *
798 verify_related_strinfos (strinfo *origsi)
799 {
800 strinfo *si = origsi, *psi;
801
802 if (origsi->first == 0)
803 return NULL;
804 for (; si->prev; si = psi)
805 {
806 if (si->first != origsi->first)
807 return NULL;
808 psi = get_strinfo (si->prev);
809 if (psi == NULL)
810 return NULL;
811 if (psi->next != si->idx)
812 return NULL;
813 }
814 if (si->idx != si->first)
815 return NULL;
816 return si;
817 }
818
819 /* Set SI's endptr to ENDPTR and compute its length based on SI->ptr.
820 Use LOC for folding. */
821
822 static void
823 set_endptr_and_length (location_t loc, strinfo *si, tree endptr)
824 {
825 si->endptr = endptr;
826 si->stmt = NULL;
827 tree start_as_size = fold_convert_loc (loc, size_type_node, si->ptr);
828 tree end_as_size = fold_convert_loc (loc, size_type_node, endptr);
829 si->nonzero_chars = fold_build2_loc (loc, MINUS_EXPR, size_type_node,
830 end_as_size, start_as_size);
831 si->full_string_p = true;
832 }
833
834 /* Return the string length, or NULL if it can't be computed.
835 The length may but need not be constant. Instead, it might be
836 the result of a strlen() call. */
837
838 static tree
839 get_string_length (strinfo *si)
840 {
841 /* If the length has already been computed return it if it's exact
842 (i.e., the string is nul-terminated at NONZERO_CHARS), or return
843 null if it isn't. */
844 if (si->nonzero_chars)
845 return si->full_string_p ? si->nonzero_chars : NULL;
846
847 /* If the string is the result of one of the built-in calls below
848 attempt to compute the length from the call statement. */
849 if (si->stmt)
850 {
851 gimple *stmt = si->stmt, *lenstmt = NULL, *g;
852 tree callee, lhs, fn, tem;
853 location_t loc;
854 gimple_stmt_iterator gsi;
855
856 gcc_assert (is_gimple_call (stmt));
857 callee = gimple_call_fndecl (stmt);
858 gcc_assert (callee && fndecl_built_in_p (callee, BUILT_IN_NORMAL));
859 lhs = gimple_call_lhs (stmt);
860 /* unshare_strinfo is intentionally not called here. The (delayed)
861 transformation of strcpy or strcat into stpcpy is done at the place
862 of the former strcpy/strcat call and so can affect all the strinfos
863 with the same stmt. If they were unshared before and transformation
864 has been already done, the handling of BUILT_IN_STPCPY{,_CHK} should
865 just compute the right length. */
866 switch (DECL_FUNCTION_CODE (callee))
867 {
868 case BUILT_IN_STRCAT:
869 case BUILT_IN_STRCAT_CHK:
870 gsi = gsi_for_stmt (stmt);
871 fn = builtin_decl_implicit (BUILT_IN_STRLEN);
872 gcc_assert (lhs == NULL_TREE);
873 tem = unshare_expr (gimple_call_arg (stmt, 0));
874 lenstmt = gimple_build_call (fn, 1, tem);
875 lhs = make_ssa_name (TREE_TYPE (TREE_TYPE (fn)), lenstmt);
876 gimple_call_set_lhs (lenstmt, lhs);
877 gimple_set_vuse (lenstmt, gimple_vuse (stmt));
878 gsi_insert_before (&gsi, lenstmt, GSI_SAME_STMT);
879 tem = gimple_call_arg (stmt, 0);
880 if (!ptrofftype_p (TREE_TYPE (lhs)))
881 {
882 lhs = convert_to_ptrofftype (lhs);
883 lhs = force_gimple_operand_gsi (&gsi, lhs, true, NULL_TREE,
884 true, GSI_SAME_STMT);
885 }
886 g = gimple_build_assign
887 (make_ssa_name (TREE_TYPE (gimple_call_arg (stmt, 0))),
888 POINTER_PLUS_EXPR,tem, lhs);
889 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
890 gimple_call_set_arg (stmt, 0, gimple_assign_lhs (g));
891 lhs = NULL_TREE;
892 /* FALLTHRU */
893 case BUILT_IN_STRCPY:
894 case BUILT_IN_STRCPY_CHK:
895 gcc_assert (builtin_decl_implicit_p (BUILT_IN_STPCPY));
896 if (gimple_call_num_args (stmt) == 2)
897 fn = builtin_decl_implicit (BUILT_IN_STPCPY);
898 else
899 fn = builtin_decl_explicit (BUILT_IN_STPCPY_CHK);
900 gcc_assert (lhs == NULL_TREE);
901 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
902 {
903 fprintf (dump_file, "Optimizing: ");
904 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
905 }
906 gimple_call_set_fndecl (stmt, fn);
907 lhs = make_ssa_name (TREE_TYPE (TREE_TYPE (fn)), stmt);
908 gimple_call_set_lhs (stmt, lhs);
909 if (DECL_FUNCTION_CODE (callee) == BUILT_IN_STRCAT_CHK)
910 {
911 tree objsz = gimple_call_lhs (lenstmt);
912 gimple *g
913 = gimple_build_assign (make_ssa_name (TREE_TYPE (objsz)),
914 MINUS_EXPR, gimple_call_arg (stmt, 2),
915 objsz);
916 gimple_set_location (g, gimple_location (stmt));
917 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
918 gimple_call_set_arg (stmt, 2, gimple_assign_lhs (g));
919 }
920 update_stmt (stmt);
921 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
922 {
923 fprintf (dump_file, "into: ");
924 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
925 }
926 /* FALLTHRU */
927 case BUILT_IN_STPCPY:
928 case BUILT_IN_STPCPY_CHK:
929 gcc_assert (lhs != NULL_TREE);
930 loc = gimple_location (stmt);
931 set_endptr_and_length (loc, si, lhs);
932 for (strinfo *chainsi = verify_related_strinfos (si);
933 chainsi != NULL;
934 chainsi = get_next_strinfo (chainsi))
935 if (chainsi->nonzero_chars == NULL)
936 set_endptr_and_length (loc, chainsi, lhs);
937 break;
938 case BUILT_IN_ALLOCA:
939 case BUILT_IN_ALLOCA_WITH_ALIGN:
940 case BUILT_IN_MALLOC:
941 break;
942 /* BUILT_IN_CALLOC always has si->nonzero_chars set. */
943 default:
944 gcc_unreachable ();
945 break;
946 }
947 }
948
949 return si->nonzero_chars;
950 }
951
952 /* Dump strlen data to FP for statement STMT. When non-null, RVALS
953 points to the valuation engine used to calculate ranges, and is
954 used to dump strlen range for non-constant results. */
955
956 DEBUG_FUNCTION void
957 dump_strlen_info (FILE *fp, gimple *stmt, range_query *rvals)
958 {
959 if (stmt)
960 {
961 fprintf (fp, "\nDumping strlen pass data after ");
962 print_gimple_expr (fp, stmt, TDF_LINENO);
963 fputc ('\n', fp);
964 }
965 else
966 fprintf (fp, "\nDumping strlen pass data\n");
967
968 fprintf (fp, "max_stridx = %i\n", max_stridx);
969 fprintf (fp, "ssa_ver_to_stridx has %u elements\n",
970 ssa_ver_to_stridx.length ());
971 fprintf (fp, "stridx_to_strinfo");
972 if (stridx_to_strinfo)
973 {
974 fprintf (fp, " has %u elements\n", stridx_to_strinfo->length ());
975 for (unsigned i = 0; i != stridx_to_strinfo->length (); ++i)
976 {
977 if (strinfo *si = (*stridx_to_strinfo)[i])
978 {
979 if (!si->idx)
980 continue;
981 fprintf (fp, " idx = %i", si->idx);
982 if (si->ptr)
983 {
984 fprintf (fp, ", ptr = ");
985 print_generic_expr (fp, si->ptr);
986 }
987
988 if (si->nonzero_chars)
989 {
990 fprintf (fp, ", nonzero_chars = ");
991 print_generic_expr (fp, si->nonzero_chars);
992 if (TREE_CODE (si->nonzero_chars) == SSA_NAME)
993 {
994 int_range_max vr;
995 if (rvals)
996 rvals->range_of_expr (vr, si->nonzero_chars,
997 si->stmt);
998 else
999 get_range_query (cfun)->range_of_expr (vr,
1000 si->nonzero_chars);
1001 vr.dump (fp);
1002 }
1003 }
1004
1005 fprintf (fp, ", refcount = %i", si->refcount);
1006 if (si->stmt)
1007 {
1008 fprintf (fp, ", stmt = ");
1009 print_gimple_expr (fp, si->stmt, 0);
1010 }
1011 if (si->alloc)
1012 {
1013 fprintf (fp, ", alloc = ");
1014 print_gimple_expr (fp, si->alloc, 0);
1015 }
1016 if (si->writable)
1017 fprintf (fp, ", writable");
1018 if (si->dont_invalidate)
1019 fprintf (fp, ", dont_invalidate");
1020 if (si->full_string_p)
1021 fprintf (fp, ", full_string_p");
1022 if (strinfo *next = get_next_strinfo (si))
1023 {
1024 fprintf (fp, ", {");
1025 do
1026 fprintf (fp, "%i%s", next->idx, next->first ? ", " : "");
1027 while ((next = get_next_strinfo (next)));
1028 fprintf (fp, "}");
1029 }
1030 fputs ("\n", fp);
1031 }
1032 }
1033 }
1034 else
1035 fprintf (fp, " = null\n");
1036
1037 fprintf (fp, "decl_to_stridxlist_htab");
1038 if (decl_to_stridxlist_htab)
1039 {
1040 fputs ("\n", fp);
1041 typedef decl_to_stridxlist_htab_t::iterator iter_t;
1042 for (iter_t it = decl_to_stridxlist_htab->begin ();
1043 it != decl_to_stridxlist_htab->end (); ++it)
1044 {
1045 tree decl = (*it).first;
1046 stridxlist *list = &(*it).second;
1047 fprintf (fp, " decl = ");
1048 print_generic_expr (fp, decl);
1049 if (list)
1050 {
1051 fprintf (fp, ", offsets = {");
1052 for (; list; list = list->next)
1053 fprintf (fp, "%lli%s", (long long) list->offset,
1054 list->next ? ", " : "");
1055 fputs ("}", fp);
1056 }
1057 fputs ("\n", fp);
1058 }
1059 }
1060 else
1061 fprintf (fp, " = null\n");
1062
1063 if (laststmt.stmt)
1064 {
1065 fprintf (fp, "laststmt = ");
1066 print_gimple_expr (fp, laststmt.stmt, 0);
1067 fprintf (fp, ", len = ");
1068 print_generic_expr (fp, laststmt.len);
1069 fprintf (fp, ", stridx = %i\n", laststmt.stridx);
1070 }
1071 }
1072
1073 /* Helper of get_range_strlen_dynamic(). See below. */
1074
1075 static bool
1076 get_range_strlen_phi (tree src, gphi *phi,
1077 c_strlen_data *pdata, bitmap visited,
1078 pointer_query *ptr_qry, unsigned *pssa_def_max)
1079 {
1080 if (!bitmap_set_bit (visited, SSA_NAME_VERSION (src)))
1081 return true;
1082
1083 if (*pssa_def_max == 0)
1084 return false;
1085
1086 --*pssa_def_max;
1087
1088 /* Iterate over the PHI arguments and determine the minimum and maximum
1089 length/size of each and incorporate them into the overall result. */
1090 for (unsigned i = 0; i != gimple_phi_num_args (phi); ++i)
1091 {
1092 tree arg = gimple_phi_arg_def (phi, i);
1093 if (arg == gimple_phi_result (phi))
1094 continue;
1095
1096 c_strlen_data argdata = { };
1097 if (!get_range_strlen_dynamic (arg, phi, &argdata, visited, ptr_qry,
1098 pssa_def_max))
1099 {
1100 pdata->maxlen = build_all_ones_cst (size_type_node);
1101 continue;
1102 }
1103
1104 /* Set the DECL of an unterminated array this argument refers to
1105 if one hasn't been found yet. */
1106 if (!pdata->decl && argdata.decl)
1107 pdata->decl = argdata.decl;
1108
1109 if (!argdata.minlen
1110 || (integer_zerop (argdata.minlen)
1111 && (!argdata.maxbound
1112 || integer_all_onesp (argdata.maxbound))
1113 && integer_all_onesp (argdata.maxlen)))
1114 {
1115 /* Set the upper bound of the length to unbounded. */
1116 pdata->maxlen = build_all_ones_cst (size_type_node);
1117 continue;
1118 }
1119
1120 /* Adjust the minimum and maximum length determined so far and
1121 the upper bound on the array size. */
1122 if (TREE_CODE (argdata.minlen) == INTEGER_CST
1123 && (!pdata->minlen
1124 || tree_int_cst_lt (argdata.minlen, pdata->minlen)))
1125 pdata->minlen = argdata.minlen;
1126
1127 if (TREE_CODE (argdata.maxlen) == INTEGER_CST
1128 && (!pdata->maxlen
1129 || (argdata.maxlen
1130 && tree_int_cst_lt (pdata->maxlen, argdata.maxlen))))
1131 pdata->maxlen = argdata.maxlen;
1132
1133 if (!pdata->maxbound
1134 || TREE_CODE (pdata->maxbound) != INTEGER_CST
1135 || (argdata.maxbound
1136 && tree_int_cst_lt (pdata->maxbound, argdata.maxbound)
1137 && !integer_all_onesp (argdata.maxbound)))
1138 pdata->maxbound = argdata.maxbound;
1139 }
1140
1141 return true;
1142 }
1143
1144 /* Return the maximum possible length of the string PTR that's less
1145 than MAXLEN given the size of the object of subobject it points
1146 to at the given STMT. MAXLEN is the maximum length of the string
1147 determined so far. Return null when no such maximum can be
1148 determined. */
1149
1150 static tree
1151 get_maxbound (tree ptr, gimple *stmt, offset_int maxlen,
1152 pointer_query *ptr_qry)
1153 {
1154 access_ref aref;
1155 if (!ptr_qry->get_ref (ptr, stmt, &aref))
1156 return NULL_TREE;
1157
1158 offset_int sizrem = aref.size_remaining ();
1159 if (sizrem <= 0)
1160 return NULL_TREE;
1161
1162 if (sizrem < maxlen)
1163 maxlen = sizrem - 1;
1164
1165 /* Try to determine the maximum from the subobject at the offset.
1166 This handles MEM [&some-struct, member-offset] that's often
1167 the result of folding COMPONENT_REF [some-struct, member]. */
1168 tree reftype = TREE_TYPE (aref.ref);
1169 if (!RECORD_OR_UNION_TYPE_P (reftype)
1170 || aref.offrng[0] != aref.offrng[1]
1171 || !wi::fits_shwi_p (aref.offrng[0]))
1172 return wide_int_to_tree (size_type_node, maxlen);
1173
1174 HOST_WIDE_INT off = aref.offrng[0].to_shwi ();
1175 tree fld = field_at_offset (reftype, NULL_TREE, off);
1176 if (!fld || !DECL_SIZE_UNIT (fld))
1177 return wide_int_to_tree (size_type_node, maxlen);
1178
1179 offset_int size = wi::to_offset (DECL_SIZE_UNIT (fld));
1180 if (maxlen < size)
1181 return wide_int_to_tree (size_type_node, maxlen);
1182
1183 return wide_int_to_tree (size_type_node, size - 1);
1184 }
1185
1186 /* Attempt to determine the length of the string SRC. On success, store
1187 the length in *PDATA and return true. Otherwise, return false.
1188 VISITED is a bitmap of visited PHI nodes. RVALS points to the valuation
1189 engine used to calculate ranges. PSSA_DEF_MAX to an SSA_NAME
1190 assignment limit used to prevent runaway recursion. */
1191
1192 static bool
1193 get_range_strlen_dynamic (tree src, gimple *stmt,
1194 c_strlen_data *pdata, bitmap visited,
1195 pointer_query *ptr_qry, unsigned *pssa_def_max)
1196 {
1197 int idx = get_stridx (src, stmt);
1198 if (!idx)
1199 {
1200 if (TREE_CODE (src) == SSA_NAME)
1201 {
1202 gimple *def_stmt = SSA_NAME_DEF_STMT (src);
1203 if (gphi *phi = dyn_cast<gphi *>(def_stmt))
1204 return get_range_strlen_phi (src, phi, pdata, visited, ptr_qry,
1205 pssa_def_max);
1206 }
1207
1208 /* Return success regardless of the result and handle *PDATA
1209 in the caller. */
1210 get_range_strlen (src, pdata, 1);
1211 return true;
1212 }
1213
1214 if (idx < 0)
1215 {
1216 /* SRC is a string of constant length. */
1217 pdata->minlen = build_int_cst (size_type_node, ~idx);
1218 pdata->maxlen = pdata->minlen;
1219 pdata->maxbound = pdata->maxlen;
1220 return true;
1221 }
1222
1223 if (strinfo *si = get_strinfo (idx))
1224 {
1225 pdata->minlen = get_string_length (si);
1226 if (!pdata->minlen && si->nonzero_chars)
1227 {
1228 if (TREE_CODE (si->nonzero_chars) == INTEGER_CST)
1229 pdata->minlen = si->nonzero_chars;
1230 else if (TREE_CODE (si->nonzero_chars) == SSA_NAME)
1231 {
1232 int_range_max vr;
1233 ptr_qry->rvals->range_of_expr (vr, si->nonzero_chars, si->stmt);
1234 if (vr.undefined_p () || vr.varying_p ())
1235 pdata->minlen = build_zero_cst (size_type_node);
1236 else
1237 {
1238 tree type = vr.type ();
1239 pdata->minlen = wide_int_to_tree (type, vr.lower_bound ());
1240 }
1241 }
1242 else
1243 pdata->minlen = build_zero_cst (size_type_node);
1244
1245 tree base = si->ptr;
1246 if (TREE_CODE (base) == ADDR_EXPR)
1247 base = TREE_OPERAND (base, 0);
1248
1249 HOST_WIDE_INT off;
1250 poly_int64 poff;
1251 base = get_addr_base_and_unit_offset (base, &poff);
1252 if (base
1253 && DECL_P (base)
1254 && TREE_CODE (TREE_TYPE (base)) == ARRAY_TYPE
1255 && TYPE_SIZE_UNIT (TREE_TYPE (base))
1256 && poff.is_constant (&off))
1257 {
1258 tree basetype = TREE_TYPE (base);
1259 tree size = TYPE_SIZE_UNIT (basetype);
1260 if (TREE_CODE (size) == INTEGER_CST)
1261 {
1262 ++off; /* Increment for the terminating nul. */
1263 tree toffset = build_int_cst (size_type_node, off);
1264 pdata->maxlen = fold_build2 (MINUS_EXPR, size_type_node,
1265 size, toffset);
1266 if (tree_int_cst_lt (pdata->maxlen, pdata->minlen))
1267 /* This can happen when triggering UB, when base is an
1268 array which is known to be filled with at least size
1269 non-zero bytes. E.g. for
1270 char a[2]; memcpy (a, "12", sizeof a);
1271 We don't want to create an invalid range [2, 1]
1272 where 2 comes from the number of non-zero bytes and
1273 1 from longest valid zero-terminated string that can
1274 be stored in such an array, so pick just one of
1275 those, pdata->minlen. See PR110603. */
1276 pdata->maxlen = build_all_ones_cst (size_type_node);
1277 else
1278 pdata->maxbound = pdata->maxlen;
1279 }
1280 else
1281 pdata->maxlen = build_all_ones_cst (size_type_node);
1282 }
1283 else
1284 pdata->maxlen = build_all_ones_cst (size_type_node);
1285 }
1286 else if (pdata->minlen && TREE_CODE (pdata->minlen) == SSA_NAME)
1287 {
1288 int_range_max vr;
1289 ptr_qry->rvals->range_of_expr (vr, si->nonzero_chars, stmt);
1290 if (vr.varying_p () || vr.undefined_p ())
1291 {
1292 pdata->minlen = build_zero_cst (size_type_node);
1293 pdata->maxlen = build_all_ones_cst (size_type_node);
1294 }
1295 else
1296 {
1297 tree type = vr.type ();
1298 pdata->minlen = wide_int_to_tree (type, vr.lower_bound ());
1299 pdata->maxlen = wide_int_to_tree (type, vr.upper_bound ());
1300 offset_int max = offset_int::from (vr.upper_bound (0), SIGNED);
1301 if (tree maxbound = get_maxbound (si->ptr, stmt, max, ptr_qry))
1302 pdata->maxbound = maxbound;
1303 else
1304 pdata->maxbound = pdata->maxlen;
1305 }
1306 }
1307 else if (pdata->minlen && TREE_CODE (pdata->minlen) == INTEGER_CST)
1308 {
1309 pdata->maxlen = pdata->minlen;
1310 pdata->maxbound = pdata->minlen;
1311 }
1312 else
1313 {
1314 /* For PDATA->MINLEN that's a non-constant expression such
1315 as PLUS_EXPR whose value range is unknown, set the bounds
1316 to zero and SIZE_MAX. */
1317 pdata->minlen = build_zero_cst (size_type_node);
1318 pdata->maxlen = build_all_ones_cst (size_type_node);
1319 }
1320
1321 return true;
1322 }
1323
1324 return false;
1325 }
1326
1327 /* Analogous to get_range_strlen but for dynamically created strings,
1328 i.e., those created by calls to strcpy as opposed to just string
1329 constants.
1330 Try to obtain the range of the lengths of the string(s) referenced
1331 by SRC, or the size of the largest array SRC refers to if the range
1332 of lengths cannot be determined, and store all in *PDATA. RVALS
1333 points to the valuation engine used to calculate ranges. */
1334
1335 void
1336 get_range_strlen_dynamic (tree src, gimple *stmt, c_strlen_data *pdata,
1337 pointer_query &ptr_qry)
1338 {
1339 auto_bitmap visited;
1340 tree maxbound = pdata->maxbound;
1341
1342 unsigned limit = param_ssa_name_def_chain_limit;
1343 if (!get_range_strlen_dynamic (src, stmt, pdata, visited, &ptr_qry, &limit))
1344 {
1345 /* On failure extend the length range to an impossible maximum
1346 (a valid MAXLEN must be less than PTRDIFF_MAX - 1). Other
1347 members can stay unchanged regardless. */
1348 pdata->minlen = ssize_int (0);
1349 pdata->maxlen = build_all_ones_cst (size_type_node);
1350 }
1351 else if (!pdata->minlen)
1352 pdata->minlen = ssize_int (0);
1353
1354 /* If it's unchanged from it initial non-null value, set the conservative
1355 MAXBOUND to SIZE_MAX. Otherwise leave it null (if it is null). */
1356 if (maxbound && pdata->maxbound == maxbound)
1357 pdata->maxbound = build_all_ones_cst (size_type_node);
1358 }
1359
1360 /* Invalidate string length information for strings whose length might
1361 change due to stores in STMT, except those marked DONT_INVALIDATE.
1362 For string-modifying statements, ZERO_WRITE is set when the statement
1363 wrote only zeros.
1364 Returns true if any STRIDX_TO_STRINFO entries were considered
1365 for invalidation. */
1366
1367 static bool
1368 maybe_invalidate (gimple *stmt, bool zero_write = false)
1369 {
1370 if (dump_file && (dump_flags & TDF_DETAILS))
1371 {
1372 fprintf (dump_file, "%s called for ", __func__);
1373 print_gimple_stmt (dump_file, stmt, TDF_LINENO);
1374 }
1375
1376 strinfo *si;
1377 bool nonempty = false;
1378
1379 for (unsigned i = 1; vec_safe_iterate (stridx_to_strinfo, i, &si); ++i)
1380 {
1381 if (si == NULL || !POINTER_TYPE_P (TREE_TYPE (si->ptr)))
1382 continue;
1383
1384 nonempty = true;
1385
1386 /* Unconditionally reset DONT_INVALIDATE. */
1387 bool dont_invalidate = si->dont_invalidate;
1388 si->dont_invalidate = false;
1389
1390 if (dont_invalidate)
1391 continue;
1392
1393 ao_ref r;
1394 tree size = si->nonzero_chars;
1395 ao_ref_init_from_ptr_and_size (&r, si->ptr, size);
1396 /* Include the terminating nul in the size of the string
1397 to consider when determining possible clobber. But do not
1398 add it to 'size' since we don't know whether it would
1399 actually fit the allocated area. */
1400 if (known_size_p (r.size))
1401 {
1402 if (known_le (r.size, HOST_WIDE_INT_MAX - BITS_PER_UNIT))
1403 r.max_size += BITS_PER_UNIT;
1404 else
1405 r.max_size = -1;
1406 }
1407 if (stmt_may_clobber_ref_p_1 (stmt, &r))
1408 {
1409 if (dump_file && (dump_flags & TDF_DETAILS))
1410 {
1411 fputs (" statement may clobber object ", dump_file);
1412 print_generic_expr (dump_file, si->ptr);
1413 if (size && tree_fits_uhwi_p (size))
1414 fprintf (dump_file, " " HOST_WIDE_INT_PRINT_UNSIGNED
1415 " bytes in size", tree_to_uhwi (size));
1416 fputc ('\n', dump_file);
1417 }
1418
1419 set_strinfo (i, NULL);
1420 free_strinfo (si);
1421 continue;
1422 }
1423
1424 if (size
1425 && !zero_write
1426 && si->stmt
1427 && is_gimple_call (si->stmt)
1428 && (DECL_FUNCTION_CODE (gimple_call_fndecl (si->stmt))
1429 == BUILT_IN_CALLOC))
1430 {
1431 /* If the clobber test above considered the length of
1432 the string (including the nul), then for (potentially)
1433 non-zero writes that might modify storage allocated by
1434 calloc consider the whole object and if it might be
1435 clobbered by the statement reset the statement. */
1436 ao_ref_init_from_ptr_and_size (&r, si->ptr, NULL_TREE);
1437 if (stmt_may_clobber_ref_p_1 (stmt, &r))
1438 si->stmt = NULL;
1439 }
1440 }
1441
1442 if (dump_file && (dump_flags & TDF_DETAILS))
1443 fprintf (dump_file, "%s returns %i\n", __func__, nonempty);
1444
1445 return nonempty;
1446 }
1447
1448 /* Unshare strinfo record SI, if it has refcount > 1 or
1449 if stridx_to_strinfo vector is shared with some other
1450 bbs. */
1451
1452 static strinfo *
1453 unshare_strinfo (strinfo *si)
1454 {
1455 strinfo *nsi;
1456
1457 if (si->refcount == 1 && !strinfo_shared ())
1458 return si;
1459
1460 nsi = new_strinfo (si->ptr, si->idx, si->nonzero_chars, si->full_string_p);
1461 nsi->stmt = si->stmt;
1462 nsi->alloc = si->alloc;
1463 nsi->endptr = si->endptr;
1464 nsi->first = si->first;
1465 nsi->prev = si->prev;
1466 nsi->next = si->next;
1467 nsi->writable = si->writable;
1468 set_strinfo (si->idx, nsi);
1469 free_strinfo (si);
1470 return nsi;
1471 }
1472
1473 /* Attempt to create a new strinfo for BASESI + OFF, or find existing
1474 strinfo if there is any. Return it's idx, or 0 if no strinfo has
1475 been created. */
1476
1477 static int
1478 get_stridx_plus_constant (strinfo *basesi, unsigned HOST_WIDE_INT off,
1479 tree ptr)
1480 {
1481 if (TREE_CODE (ptr) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ptr))
1482 return 0;
1483
1484 if (compare_nonzero_chars (basesi, off) < 0
1485 || !tree_fits_uhwi_p (basesi->nonzero_chars))
1486 return 0;
1487
1488 unsigned HOST_WIDE_INT nonzero_chars
1489 = tree_to_uhwi (basesi->nonzero_chars) - off;
1490 strinfo *si = basesi, *chainsi;
1491 if (si->first || si->prev || si->next)
1492 si = verify_related_strinfos (basesi);
1493 if (si == NULL
1494 || si->nonzero_chars == NULL_TREE
1495 || TREE_CODE (si->nonzero_chars) != INTEGER_CST)
1496 return 0;
1497
1498 if (TREE_CODE (ptr) == SSA_NAME
1499 && ssa_ver_to_stridx.length () <= SSA_NAME_VERSION (ptr))
1500 ssa_ver_to_stridx.safe_grow_cleared (num_ssa_names, true);
1501
1502 gcc_checking_assert (compare_tree_int (si->nonzero_chars, off) != -1);
1503 for (chainsi = si; chainsi->next; chainsi = si)
1504 {
1505 si = get_next_strinfo (chainsi);
1506 if (si == NULL
1507 || si->nonzero_chars == NULL_TREE
1508 || TREE_CODE (si->nonzero_chars) != INTEGER_CST)
1509 break;
1510 int r = compare_tree_int (si->nonzero_chars, nonzero_chars);
1511 if (r != 1)
1512 {
1513 if (r == 0)
1514 {
1515 if (TREE_CODE (ptr) == SSA_NAME)
1516 ssa_ver_to_stridx[SSA_NAME_VERSION (ptr)] = si->idx;
1517 else
1518 {
1519 int *pidx = addr_stridxptr (TREE_OPERAND (ptr, 0));
1520 if (pidx != NULL && *pidx == 0)
1521 *pidx = si->idx;
1522 }
1523 return si->idx;
1524 }
1525 break;
1526 }
1527 }
1528
1529 int idx = new_stridx (ptr);
1530 if (idx == 0)
1531 return 0;
1532 si = new_strinfo (ptr, idx, build_int_cst (size_type_node, nonzero_chars),
1533 basesi->full_string_p);
1534 set_strinfo (idx, si);
1535 if (strinfo *nextsi = get_strinfo (chainsi->next))
1536 {
1537 nextsi = unshare_strinfo (nextsi);
1538 si->next = nextsi->idx;
1539 nextsi->prev = idx;
1540 }
1541 chainsi = unshare_strinfo (chainsi);
1542 if (chainsi->first == 0)
1543 chainsi->first = chainsi->idx;
1544 chainsi->next = idx;
1545 if (chainsi->endptr == NULL_TREE && zero_length_string_p (si))
1546 chainsi->endptr = ptr;
1547 si->endptr = chainsi->endptr;
1548 si->prev = chainsi->idx;
1549 si->first = chainsi->first;
1550 si->writable = chainsi->writable;
1551 return si->idx;
1552 }
1553
1554 /* Note that PTR, a pointer SSA_NAME initialized in the current stmt, points
1555 to a zero-length string and if possible chain it to a related strinfo
1556 chain whose part is or might be CHAINSI. */
1557
1558 static strinfo *
1559 zero_length_string (tree ptr, strinfo *chainsi)
1560 {
1561 strinfo *si;
1562 int idx;
1563 if (ssa_ver_to_stridx.length () <= SSA_NAME_VERSION (ptr))
1564 ssa_ver_to_stridx.safe_grow_cleared (num_ssa_names, true);
1565 gcc_checking_assert (TREE_CODE (ptr) == SSA_NAME
1566 && ssa_ver_to_stridx[SSA_NAME_VERSION (ptr)] == 0);
1567
1568 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ptr))
1569 return NULL;
1570 if (chainsi != NULL)
1571 {
1572 si = verify_related_strinfos (chainsi);
1573 if (si)
1574 {
1575 do
1576 {
1577 /* We shouldn't mix delayed and non-delayed lengths. */
1578 gcc_assert (si->full_string_p);
1579 if (si->endptr == NULL_TREE)
1580 {
1581 si = unshare_strinfo (si);
1582 si->endptr = ptr;
1583 }
1584 chainsi = si;
1585 si = get_next_strinfo (si);
1586 }
1587 while (si != NULL);
1588 if (zero_length_string_p (chainsi))
1589 {
1590 if (chainsi->next)
1591 {
1592 chainsi = unshare_strinfo (chainsi);
1593 chainsi->next = 0;
1594 }
1595 ssa_ver_to_stridx[SSA_NAME_VERSION (ptr)] = chainsi->idx;
1596 return chainsi;
1597 }
1598 }
1599 else
1600 {
1601 /* We shouldn't mix delayed and non-delayed lengths. */
1602 gcc_assert (chainsi->full_string_p);
1603 if (chainsi->first || chainsi->prev || chainsi->next)
1604 {
1605 chainsi = unshare_strinfo (chainsi);
1606 chainsi->first = 0;
1607 chainsi->prev = 0;
1608 chainsi->next = 0;
1609 }
1610 }
1611 }
1612 idx = new_stridx (ptr);
1613 if (idx == 0)
1614 return NULL;
1615 si = new_strinfo (ptr, idx, build_int_cst (size_type_node, 0), true);
1616 set_strinfo (idx, si);
1617 si->endptr = ptr;
1618 if (chainsi != NULL)
1619 {
1620 chainsi = unshare_strinfo (chainsi);
1621 if (chainsi->first == 0)
1622 chainsi->first = chainsi->idx;
1623 chainsi->next = idx;
1624 if (chainsi->endptr == NULL_TREE)
1625 chainsi->endptr = ptr;
1626 si->prev = chainsi->idx;
1627 si->first = chainsi->first;
1628 si->writable = chainsi->writable;
1629 }
1630 return si;
1631 }
1632
1633 /* For strinfo ORIGSI whose length has been just updated, adjust other
1634 related strinfos so that they match the new ORIGSI. This involves:
1635
1636 - adding ADJ to the nonzero_chars fields
1637 - copying full_string_p from the new ORIGSI. */
1638
1639 static void
1640 adjust_related_strinfos (location_t loc, strinfo *origsi, tree adj)
1641 {
1642 strinfo *si = verify_related_strinfos (origsi);
1643
1644 if (si == NULL)
1645 return;
1646
1647 while (1)
1648 {
1649 strinfo *nsi;
1650
1651 if (si != origsi)
1652 {
1653 tree tem;
1654
1655 si = unshare_strinfo (si);
1656 /* We shouldn't see delayed lengths here; the caller must
1657 have calculated the old length in order to calculate
1658 the adjustment. */
1659 gcc_assert (si->nonzero_chars);
1660 tem = fold_convert_loc (loc, TREE_TYPE (si->nonzero_chars), adj);
1661 si->nonzero_chars = fold_build2_loc (loc, PLUS_EXPR,
1662 TREE_TYPE (si->nonzero_chars),
1663 si->nonzero_chars, tem);
1664 si->full_string_p = origsi->full_string_p;
1665
1666 si->endptr = NULL_TREE;
1667 si->dont_invalidate = true;
1668 }
1669 nsi = get_next_strinfo (si);
1670 if (nsi == NULL)
1671 return;
1672 si = nsi;
1673 }
1674 }
1675
1676 /* Find if there are other SSA_NAME pointers equal to PTR
1677 for which we don't track their string lengths yet. If so, use
1678 IDX for them. */
1679
1680 static void
1681 find_equal_ptrs (tree ptr, int idx)
1682 {
1683 if (TREE_CODE (ptr) != SSA_NAME)
1684 return;
1685 while (1)
1686 {
1687 gimple *stmt = SSA_NAME_DEF_STMT (ptr);
1688 if (!is_gimple_assign (stmt))
1689 return;
1690 ptr = gimple_assign_rhs1 (stmt);
1691 switch (gimple_assign_rhs_code (stmt))
1692 {
1693 case SSA_NAME:
1694 break;
1695 CASE_CONVERT:
1696 if (!POINTER_TYPE_P (TREE_TYPE (ptr)))
1697 return;
1698 if (TREE_CODE (ptr) == SSA_NAME)
1699 break;
1700 if (TREE_CODE (ptr) != ADDR_EXPR)
1701 return;
1702 /* FALLTHRU */
1703 case ADDR_EXPR:
1704 {
1705 int *pidx = addr_stridxptr (TREE_OPERAND (ptr, 0));
1706 if (pidx != NULL && *pidx == 0)
1707 *pidx = idx;
1708 return;
1709 }
1710 default:
1711 return;
1712 }
1713
1714 /* We might find an endptr created in this pass. Grow the
1715 vector in that case. */
1716 if (ssa_ver_to_stridx.length () <= SSA_NAME_VERSION (ptr))
1717 ssa_ver_to_stridx.safe_grow_cleared (num_ssa_names, true);
1718
1719 if (ssa_ver_to_stridx[SSA_NAME_VERSION (ptr)] != 0)
1720 return;
1721 ssa_ver_to_stridx[SSA_NAME_VERSION (ptr)] = idx;
1722 }
1723 }
1724
1725 /* Return true if STMT is a call to a builtin function with the right
1726 arguments and attributes that should be considered for optimization
1727 by this pass. */
1728
1729 static bool
1730 valid_builtin_call (gimple *stmt)
1731 {
1732 if (!gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
1733 return false;
1734
1735 tree callee = gimple_call_fndecl (stmt);
1736 switch (DECL_FUNCTION_CODE (callee))
1737 {
1738 case BUILT_IN_MEMCMP:
1739 case BUILT_IN_MEMCMP_EQ:
1740 case BUILT_IN_STRCMP:
1741 case BUILT_IN_STRNCMP:
1742 case BUILT_IN_STRCHR:
1743 case BUILT_IN_STRLEN:
1744 case BUILT_IN_STRNLEN:
1745 /* The above functions should be pure. Punt if they aren't. */
1746 if (gimple_vdef (stmt) || gimple_vuse (stmt) == NULL_TREE)
1747 return false;
1748 break;
1749
1750 case BUILT_IN_ALLOCA:
1751 case BUILT_IN_ALLOCA_WITH_ALIGN:
1752 case BUILT_IN_CALLOC:
1753 case BUILT_IN_MALLOC:
1754 case BUILT_IN_MEMCPY:
1755 case BUILT_IN_MEMCPY_CHK:
1756 case BUILT_IN_MEMPCPY:
1757 case BUILT_IN_MEMPCPY_CHK:
1758 case BUILT_IN_MEMSET:
1759 case BUILT_IN_STPCPY:
1760 case BUILT_IN_STPCPY_CHK:
1761 case BUILT_IN_STPNCPY:
1762 case BUILT_IN_STPNCPY_CHK:
1763 case BUILT_IN_STRCAT:
1764 case BUILT_IN_STRCAT_CHK:
1765 case BUILT_IN_STRCPY:
1766 case BUILT_IN_STRCPY_CHK:
1767 case BUILT_IN_STRNCAT:
1768 case BUILT_IN_STRNCAT_CHK:
1769 case BUILT_IN_STRNCPY:
1770 case BUILT_IN_STRNCPY_CHK:
1771 /* The above functions should be neither const nor pure. Punt if they
1772 aren't. */
1773 if (gimple_vdef (stmt) == NULL_TREE || gimple_vuse (stmt) == NULL_TREE)
1774 return false;
1775 break;
1776
1777 default:
1778 break;
1779 }
1780
1781 return true;
1782 }
1783
1784 /* If the last .MEM setter statement before STMT is
1785 memcpy (x, y, strlen (y) + 1), the only .MEM use of it is STMT
1786 and STMT is known to overwrite x[strlen (x)], adjust the last memcpy to
1787 just memcpy (x, y, strlen (y)). SI must be the zero length
1788 strinfo. */
1789
1790 void
1791 strlen_pass::adjust_last_stmt (strinfo *si, gimple *stmt, bool is_strcat)
1792 {
1793 tree vuse, callee, len;
1794 struct laststmt_struct last = laststmt;
1795 strinfo *lastsi, *firstsi;
1796 unsigned len_arg_no = 2;
1797
1798 laststmt.stmt = NULL;
1799 laststmt.len = NULL_TREE;
1800 laststmt.stridx = 0;
1801
1802 if (last.stmt == NULL)
1803 return;
1804
1805 vuse = gimple_vuse (stmt);
1806 if (vuse == NULL_TREE
1807 || SSA_NAME_DEF_STMT (vuse) != last.stmt
1808 || !has_single_use (vuse))
1809 return;
1810
1811 gcc_assert (last.stridx > 0);
1812 lastsi = get_strinfo (last.stridx);
1813 if (lastsi == NULL)
1814 return;
1815
1816 if (lastsi != si)
1817 {
1818 if (lastsi->first == 0 || lastsi->first != si->first)
1819 return;
1820
1821 firstsi = verify_related_strinfos (si);
1822 if (firstsi == NULL)
1823 return;
1824 while (firstsi != lastsi)
1825 {
1826 firstsi = get_next_strinfo (firstsi);
1827 if (firstsi == NULL)
1828 return;
1829 }
1830 }
1831
1832 if (!is_strcat && !zero_length_string_p (si))
1833 return;
1834
1835 if (is_gimple_assign (last.stmt))
1836 {
1837 gimple_stmt_iterator gsi;
1838
1839 if (!integer_zerop (gimple_assign_rhs1 (last.stmt)))
1840 return;
1841 if (stmt_could_throw_p (cfun, last.stmt))
1842 return;
1843 gsi = gsi_for_stmt (last.stmt);
1844 unlink_stmt_vdef (last.stmt);
1845 release_defs (last.stmt);
1846 gsi_remove (&gsi, true);
1847 return;
1848 }
1849
1850 if (!valid_builtin_call (last.stmt))
1851 return;
1852
1853 callee = gimple_call_fndecl (last.stmt);
1854 switch (DECL_FUNCTION_CODE (callee))
1855 {
1856 case BUILT_IN_MEMCPY:
1857 case BUILT_IN_MEMCPY_CHK:
1858 break;
1859 default:
1860 return;
1861 }
1862
1863 len = gimple_call_arg (last.stmt, len_arg_no);
1864 if (tree_fits_uhwi_p (len))
1865 {
1866 if (!tree_fits_uhwi_p (last.len)
1867 || integer_zerop (len)
1868 || tree_to_uhwi (len) != tree_to_uhwi (last.len) + 1)
1869 return;
1870 /* Don't adjust the length if it is divisible by 4, it is more efficient
1871 to store the extra '\0' in that case. */
1872 if ((tree_to_uhwi (len) & 3) == 0)
1873 return;
1874
1875 /* Don't fold away an out of bounds access, as this defeats proper
1876 warnings. */
1877 tree dst = gimple_call_arg (last.stmt, 0);
1878
1879 access_ref aref;
1880 tree size = compute_objsize (dst, stmt, 1, &aref, &ptr_qry);
1881 if (size && tree_int_cst_lt (size, len))
1882 return;
1883 }
1884 else if (TREE_CODE (len) == SSA_NAME)
1885 {
1886 gimple *def_stmt = SSA_NAME_DEF_STMT (len);
1887 if (!is_gimple_assign (def_stmt)
1888 || gimple_assign_rhs_code (def_stmt) != PLUS_EXPR
1889 || gimple_assign_rhs1 (def_stmt) != last.len
1890 || !integer_onep (gimple_assign_rhs2 (def_stmt)))
1891 return;
1892 }
1893 else
1894 return;
1895
1896 gimple_call_set_arg (last.stmt, len_arg_no, last.len);
1897 update_stmt (last.stmt);
1898 }
1899
1900 /* For an LHS that is an SSA_NAME that is the result of a strlen()
1901 call, or when BOUND is non-null, of a strnlen() call, set LHS
1902 range info to [0, min (MAX, BOUND)] when the range includes more
1903 than one value and return LHS. Otherwise, when the range
1904 [MIN, MAX] is such that MIN == MAX, return the tree representation
1905 of (MIN). The latter allows callers to fold suitable strnlen() calls
1906 to constants. */
1907
1908 tree
1909 set_strlen_range (tree lhs, wide_int min, wide_int max,
1910 tree bound /* = NULL_TREE */)
1911 {
1912 if (TREE_CODE (lhs) != SSA_NAME
1913 || !INTEGRAL_TYPE_P (TREE_TYPE (lhs)))
1914 return NULL_TREE;
1915
1916 if (bound)
1917 {
1918 /* For strnlen, adjust MIN and MAX as necessary. If the bound
1919 is less than the size of the array set MAX to it. It it's
1920 greater than MAX and MAX is non-zero bump MAX down to account
1921 for the necessary terminating nul. Otherwise leave it alone. */
1922 if (TREE_CODE (bound) == INTEGER_CST)
1923 {
1924 wide_int wibnd = wi::to_wide (bound);
1925 int cmp = wi::cmpu (wibnd, max);
1926 if (cmp < 0)
1927 max = wibnd;
1928 else if (cmp && wi::ne_p (max, min))
1929 --max;
1930 }
1931 else if (TREE_CODE (bound) == SSA_NAME)
1932 {
1933 int_range_max r;
1934 get_range_query (cfun)->range_of_expr (r, bound);
1935 if (!r.undefined_p ())
1936 {
1937 /* For a bound in a known range, adjust the range determined
1938 above as necessary. For a bound in some anti-range or
1939 in an unknown range, use the range determined by callers. */
1940 if (wi::ltu_p (r.lower_bound (), min))
1941 min = r.lower_bound ();
1942 if (wi::ltu_p (r.upper_bound (), max))
1943 max = r.upper_bound ();
1944 }
1945 }
1946 }
1947
1948 if (min == max)
1949 return wide_int_to_tree (size_type_node, min);
1950
1951 int_range_max vr (TREE_TYPE (lhs), min, max);
1952 set_range_info (lhs, vr);
1953 return lhs;
1954 }
1955
1956 /* For an LHS that is an SSA_NAME and for strlen() or strnlen() argument
1957 SRC, set LHS range info to [0, min (N, BOUND)] if SRC refers to
1958 a character array A[N] with unknown length bounded by N, and for
1959 strnlen(), by min (N, BOUND). */
1960
1961 static tree
1962 maybe_set_strlen_range (tree lhs, tree src, tree bound)
1963 {
1964 if (TREE_CODE (lhs) != SSA_NAME
1965 || !INTEGRAL_TYPE_P (TREE_TYPE (lhs)))
1966 return NULL_TREE;
1967
1968 if (TREE_CODE (src) == SSA_NAME)
1969 {
1970 gimple *def = SSA_NAME_DEF_STMT (src);
1971 if (is_gimple_assign (def)
1972 && gimple_assign_rhs_code (def) == ADDR_EXPR)
1973 src = gimple_assign_rhs1 (def);
1974 }
1975
1976 /* The longest string is PTRDIFF_MAX - 1 bytes including the final
1977 NUL so that the difference between a pointer to just past it and
1978 one to its beginning is positive. */
1979 wide_int max = wi::to_wide (TYPE_MAX_VALUE (ptrdiff_type_node)) - 2;
1980
1981 if (TREE_CODE (src) == ADDR_EXPR)
1982 {
1983 /* The last array member of a struct can be bigger than its size
1984 suggests if it's treated as a poor-man's flexible array member. */
1985 src = TREE_OPERAND (src, 0);
1986 if (TREE_CODE (src) != MEM_REF
1987 && !array_ref_flexible_size_p (src))
1988 {
1989 tree type = TREE_TYPE (src);
1990 tree size = TYPE_SIZE_UNIT (type);
1991 if (size
1992 && TREE_CODE (size) == INTEGER_CST
1993 && !integer_zerop (size))
1994 {
1995 /* Even though such uses of strlen would be undefined,
1996 avoid relying on arrays of arrays in case some genius
1997 decides to call strlen on an unterminated array element
1998 that's followed by a terminated one. Likewise, avoid
1999 assuming that a struct array member is necessarily
2000 nul-terminated (the nul may be in the member that
2001 follows). In those cases, assume that the length
2002 of the string stored in such an array is bounded
2003 by the size of the enclosing object if one can be
2004 determined. */
2005 tree base = get_base_address (src);
2006 if (VAR_P (base))
2007 {
2008 if (tree size = DECL_SIZE_UNIT (base))
2009 if (size
2010 && TREE_CODE (size) == INTEGER_CST
2011 && TREE_CODE (TREE_TYPE (base)) != POINTER_TYPE)
2012 max = wi::to_wide (size);
2013 }
2014 }
2015
2016 /* For strlen() the upper bound above is equal to
2017 the longest string that can be stored in the array
2018 (i.e., it accounts for the terminating nul. For
2019 strnlen() bump up the maximum by one since the array
2020 need not be nul-terminated. */
2021 if (!bound && max != 0)
2022 --max;
2023 }
2024 }
2025
2026 wide_int min = wi::zero (max.get_precision ());
2027 return set_strlen_range (lhs, min, max, bound);
2028 }
2029
2030 /* Diagnose buffer overflow by a STMT writing LEN + PLUS_ONE bytes,
2031 either into a region allocated for the object SI when non-null,
2032 or into an object designated by the LHS of STMT otherwise.
2033 For a call STMT, when CALL_LHS is set use its left hand side
2034 as the destination, otherwise use argument zero.
2035 When nonnull uses RVALS to determine range information.
2036 RAWMEM may be set by memcpy and other raw memory functions
2037 to allow accesses across subobject boundaries. */
2038
2039 void
2040 strlen_pass::maybe_warn_overflow (gimple *stmt, bool call_lhs, tree len,
2041 strinfo *si, bool plus_one, bool rawmem)
2042 {
2043 if (!len || warning_suppressed_p (stmt, OPT_Wstringop_overflow_))
2044 return;
2045
2046 /* The DECL of the function performing the write if it is done
2047 by one. */
2048 tree writefn = NULL_TREE;
2049 /* The destination expression involved in the store or call STMT. */
2050 tree dest = NULL_TREE;
2051
2052 if (is_gimple_assign (stmt))
2053 dest = gimple_assign_lhs (stmt);
2054 else if (is_gimple_call (stmt))
2055 {
2056 if (call_lhs)
2057 dest = gimple_call_lhs (stmt);
2058 else
2059 {
2060 gcc_assert (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL));
2061 dest = gimple_call_arg (stmt, 0);
2062 }
2063
2064 if (!dest)
2065 return;
2066 writefn = gimple_call_fndecl (stmt);
2067 }
2068 else
2069 return;
2070
2071 if (warning_suppressed_p (dest, OPT_Wstringop_overflow_))
2072 return;
2073
2074 const int ostype = rawmem ? 0 : 1;
2075
2076 /* Use maximum precision to avoid overflow in the addition below.
2077 Make sure all operands have the same precision to keep wide_int
2078 from ICE'ing. */
2079
2080 access_ref aref;
2081 /* The size of the destination region (which is smaller than
2082 the destination object for stores at a non-zero offset). */
2083 tree destsize = compute_objsize (dest, stmt, ostype, &aref, &ptr_qry);
2084
2085 if (!destsize)
2086 {
2087 aref.sizrng[0] = 0;
2088 aref.sizrng[1] = wi::to_offset (max_object_size ());
2089 }
2090
2091 /* Return early if the DESTSIZE size expression is the same as LEN
2092 and the offset into the destination is zero. This might happen
2093 in the case of a pair of malloc and memset calls to allocate
2094 an object and clear it as if by calloc. */
2095 if (destsize == len && !plus_one
2096 && aref.offrng[0] == 0 && aref.offrng[0] == aref.offrng[1])
2097 return;
2098
2099 wide_int rng[2];
2100 if (!get_range (len, stmt, rng, ptr_qry.rvals))
2101 return;
2102
2103 widest_int lenrng[2] =
2104 { widest_int::from (rng[0], SIGNED), widest_int::from (rng[1], SIGNED) };
2105
2106 if (plus_one)
2107 {
2108 lenrng[0] += 1;
2109 lenrng[1] += 1;
2110 }
2111
2112 /* The size of the remaining space in the destination computed
2113 as the size of the latter minus the offset into it. */
2114 widest_int spcrng[2];
2115 {
2116 offset_int remrng[2];
2117 remrng[1] = aref.size_remaining (remrng);
2118 spcrng[0] = remrng[0] == -1 ? 0 : widest_int::from (remrng[0], UNSIGNED);
2119 spcrng[1] = widest_int::from (remrng[1], UNSIGNED);
2120 }
2121
2122 if (wi::leu_p (lenrng[0], spcrng[0])
2123 && wi::leu_p (lenrng[1], spcrng[1]))
2124 return;
2125
2126 location_t loc = gimple_or_expr_nonartificial_location (stmt, dest);
2127 bool warned = false;
2128 if (wi::leu_p (lenrng[0], spcrng[1]))
2129 {
2130 if (len != destsize
2131 && (!si || rawmem || !is_strlen_related_p (si->ptr, len)))
2132 return;
2133
2134 warned = (writefn
2135 ? warning_at (loc, OPT_Wstringop_overflow_,
2136 "%qD writing one too many bytes into a region "
2137 "of a size that depends on %<strlen%>",
2138 writefn)
2139 : warning_at (loc, OPT_Wstringop_overflow_,
2140 "writing one too many bytes into a region "
2141 "of a size that depends on %<strlen%>"));
2142 }
2143 else if (lenrng[0] == lenrng[1])
2144 {
2145 if (spcrng[0] == spcrng[1])
2146 warned = (writefn
2147 ? warning_n (loc, OPT_Wstringop_overflow_,
2148 lenrng[0].to_uhwi (),
2149 "%qD writing %wu byte into a region "
2150 "of size %wu",
2151 "%qD writing %wu bytes into a region "
2152 "of size %wu",
2153 writefn, lenrng[0].to_uhwi (),
2154 spcrng[0].to_uhwi ())
2155 : warning_n (loc, OPT_Wstringop_overflow_,
2156 lenrng[0].to_uhwi (),
2157 "writing %wu byte into a region "
2158 "of size %wu",
2159 "writing %wu bytes into a region "
2160 "of size %wu",
2161 lenrng[0].to_uhwi (),
2162 spcrng[0].to_uhwi ()));
2163 else
2164 warned = (writefn
2165 ? warning_n (loc, OPT_Wstringop_overflow_,
2166 lenrng[0].to_uhwi (),
2167 "%qD writing %wu byte into a region "
2168 "of size between %wu and %wu",
2169 "%qD writing %wu bytes into a region "
2170 "of size between %wu and %wu",
2171 writefn, lenrng[0].to_uhwi (),
2172 spcrng[0].to_uhwi (), spcrng[1].to_uhwi ())
2173 : warning_n (loc, OPT_Wstringop_overflow_,
2174 lenrng[0].to_uhwi (),
2175 "writing %wu byte into a region "
2176 "of size between %wu and %wu",
2177 "writing %wu bytes into a region "
2178 "of size between %wu and %wu",
2179 lenrng[0].to_uhwi (),
2180 spcrng[0].to_uhwi (), spcrng[1].to_uhwi ()));
2181 }
2182 else if (spcrng[0] == spcrng[1])
2183 warned = (writefn
2184 ? warning_at (loc, OPT_Wstringop_overflow_,
2185 "%qD writing between %wu and %wu bytes "
2186 "into a region of size %wu",
2187 writefn, lenrng[0].to_uhwi (),
2188 lenrng[1].to_uhwi (),
2189 spcrng[0].to_uhwi ())
2190 : warning_at (loc, OPT_Wstringop_overflow_,
2191 "writing between %wu and %wu bytes "
2192 "into a region of size %wu",
2193 lenrng[0].to_uhwi (),
2194 lenrng[1].to_uhwi (),
2195 spcrng[0].to_uhwi ()));
2196 else
2197 warned = (writefn
2198 ? warning_at (loc, OPT_Wstringop_overflow_,
2199 "%qD writing between %wu and %wu bytes "
2200 "into a region of size between %wu and %wu",
2201 writefn, lenrng[0].to_uhwi (),
2202 lenrng[1].to_uhwi (),
2203 spcrng[0].to_uhwi (), spcrng[1].to_uhwi ())
2204 : warning_at (loc, OPT_Wstringop_overflow_,
2205 "writing between %wu and %wu bytes "
2206 "into a region of size between %wu and %wu",
2207 lenrng[0].to_uhwi (),
2208 lenrng[1].to_uhwi (),
2209 spcrng[0].to_uhwi (), spcrng[1].to_uhwi ()));
2210
2211 if (!warned)
2212 return;
2213
2214 suppress_warning (stmt, OPT_Wstringop_overflow_);
2215
2216 aref.inform_access (access_write_only);
2217 }
2218
2219 /* Convenience wrapper for the above. */
2220
2221 void
2222 strlen_pass::maybe_warn_overflow (gimple *stmt, bool call_lhs,
2223 unsigned HOST_WIDE_INT len,
2224 strinfo *si, bool plus_one, bool rawmem)
2225 {
2226 tree tlen = build_int_cst (size_type_node, len);
2227 maybe_warn_overflow (stmt, call_lhs, tlen, si, plus_one, rawmem);
2228 }
2229
2230 /* Handle a strlen call. If strlen of the argument is known, replace
2231 the strlen call with the known value, otherwise remember that strlen
2232 of the argument is stored in the lhs SSA_NAME. */
2233
2234 void
2235 strlen_pass::handle_builtin_strlen ()
2236 {
2237 gimple *stmt = gsi_stmt (m_gsi);
2238 tree lhs = gimple_call_lhs (stmt);
2239
2240 if (lhs == NULL_TREE)
2241 return;
2242
2243 location_t loc = gimple_location (stmt);
2244 tree callee = gimple_call_fndecl (stmt);
2245 tree src = gimple_call_arg (stmt, 0);
2246 tree bound = (DECL_FUNCTION_CODE (callee) == BUILT_IN_STRNLEN
2247 ? gimple_call_arg (stmt, 1) : NULL_TREE);
2248 int idx = get_stridx (src, stmt);
2249 if (idx || (bound && integer_zerop (bound)))
2250 {
2251 strinfo *si = NULL;
2252 tree rhs;
2253
2254 if (idx < 0)
2255 rhs = build_int_cst (TREE_TYPE (lhs), ~idx);
2256 else if (idx == 0)
2257 rhs = bound;
2258 else
2259 {
2260 rhs = NULL_TREE;
2261 si = get_strinfo (idx);
2262 if (si != NULL)
2263 {
2264 rhs = get_string_length (si);
2265 /* For strnlen, if bound is constant, even if si is not known
2266 to be zero terminated, if we know at least bound bytes are
2267 not zero, the return value will be bound. */
2268 if (rhs == NULL_TREE
2269 && bound != NULL_TREE
2270 && TREE_CODE (bound) == INTEGER_CST
2271 && si->nonzero_chars != NULL_TREE
2272 && TREE_CODE (si->nonzero_chars) == INTEGER_CST
2273 && tree_int_cst_le (bound, si->nonzero_chars))
2274 rhs = bound;
2275 }
2276 }
2277 if (rhs != NULL_TREE)
2278 {
2279 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
2280 {
2281 fprintf (dump_file, "Optimizing: ");
2282 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2283 }
2284 rhs = unshare_expr (rhs);
2285 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs)))
2286 rhs = fold_convert_loc (loc, TREE_TYPE (lhs), rhs);
2287
2288 if (bound)
2289 rhs = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (rhs), rhs, bound);
2290
2291 gimplify_and_update_call_from_tree (&m_gsi, rhs);
2292 stmt = gsi_stmt (m_gsi);
2293 update_stmt (stmt);
2294 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
2295 {
2296 fprintf (dump_file, "into: ");
2297 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2298 }
2299
2300 if (si != NULL
2301 /* Don't update anything for strnlen. */
2302 && bound == NULL_TREE
2303 && TREE_CODE (si->nonzero_chars) != SSA_NAME
2304 && TREE_CODE (si->nonzero_chars) != INTEGER_CST
2305 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
2306 {
2307 si = unshare_strinfo (si);
2308 si->nonzero_chars = lhs;
2309 gcc_assert (si->full_string_p);
2310 }
2311
2312 if (strlen_to_stridx
2313 && (bound == NULL_TREE
2314 /* For strnlen record this only if the call is proven
2315 to return the same value as strlen would. */
2316 || (TREE_CODE (bound) == INTEGER_CST
2317 && TREE_CODE (rhs) == INTEGER_CST
2318 && tree_int_cst_lt (rhs, bound))))
2319 strlen_to_stridx->put (lhs, stridx_strlenloc (idx, loc));
2320
2321 return;
2322 }
2323 }
2324 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
2325 return;
2326
2327 if (idx == 0)
2328 idx = new_stridx (src);
2329 else
2330 {
2331 strinfo *si = get_strinfo (idx);
2332 if (si != NULL)
2333 {
2334 if (!si->full_string_p && !si->stmt)
2335 {
2336 /* Until now we only had a lower bound on the string length.
2337 Install LHS as the actual length. */
2338 si = unshare_strinfo (si);
2339 tree old = si->nonzero_chars;
2340 si->nonzero_chars = lhs;
2341 si->full_string_p = true;
2342 if (old && TREE_CODE (old) == INTEGER_CST)
2343 {
2344 old = fold_convert_loc (loc, TREE_TYPE (lhs), old);
2345 tree adj = fold_build2_loc (loc, MINUS_EXPR,
2346 TREE_TYPE (lhs), lhs, old);
2347 adjust_related_strinfos (loc, si, adj);
2348 /* Use the constant minimum length as the lower bound
2349 of the non-constant length. */
2350 wide_int min = wi::to_wide (old);
2351 wide_int max
2352 = wi::to_wide (TYPE_MAX_VALUE (ptrdiff_type_node)) - 2;
2353 if (wi::gtu_p (min, max))
2354 max = wi::to_wide (TYPE_MAX_VALUE (TREE_TYPE (lhs)));
2355 set_strlen_range (lhs, min, max);
2356 }
2357 else
2358 {
2359 si->first = 0;
2360 si->prev = 0;
2361 si->next = 0;
2362 }
2363 }
2364 return;
2365 }
2366 }
2367 if (idx)
2368 {
2369 if (!bound)
2370 {
2371 /* Only store the new length information for calls to strlen(),
2372 not for those to strnlen(). */
2373 strinfo *si = new_strinfo (src, idx, lhs, true);
2374 set_strinfo (idx, si);
2375 find_equal_ptrs (src, idx);
2376 }
2377
2378 /* For SRC that is an array of N elements, set LHS's range
2379 to [0, min (N, BOUND)]. A constant return value means
2380 the range would have consisted of a single value. In
2381 that case, fold the result into the returned constant. */
2382 if (tree ret = maybe_set_strlen_range (lhs, src, bound))
2383 if (TREE_CODE (ret) == INTEGER_CST)
2384 {
2385 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
2386 {
2387 fprintf (dump_file, "Optimizing: ");
2388 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2389 }
2390 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (ret)))
2391 ret = fold_convert_loc (loc, TREE_TYPE (lhs), ret);
2392 gimplify_and_update_call_from_tree (&m_gsi, ret);
2393 stmt = gsi_stmt (m_gsi);
2394 update_stmt (stmt);
2395 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
2396 {
2397 fprintf (dump_file, "into: ");
2398 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2399 }
2400 }
2401
2402 if (strlen_to_stridx && !bound)
2403 strlen_to_stridx->put (lhs, stridx_strlenloc (idx, loc));
2404 }
2405 }
2406
2407 /* Handle a strchr call. If strlen of the first argument is known, replace
2408 the strchr (x, 0) call with the endptr or x + strlen, otherwise remember
2409 that lhs of the call is endptr and strlen of the argument is endptr - x. */
2410
2411 void
2412 strlen_pass::handle_builtin_strchr ()
2413 {
2414 gimple *stmt = gsi_stmt (m_gsi);
2415 tree lhs = gimple_call_lhs (stmt);
2416
2417 if (lhs == NULL_TREE)
2418 return;
2419
2420 if (!integer_zerop (gimple_call_arg (stmt, 1)))
2421 return;
2422
2423 tree src = gimple_call_arg (stmt, 0);
2424
2425 /* Avoid folding if the first argument is not a nul-terminated array.
2426 Defer warning until later. */
2427 if (!check_nul_terminated_array (NULL_TREE, src))
2428 return;
2429
2430 int idx = get_stridx (src, stmt);
2431 if (idx)
2432 {
2433 strinfo *si = NULL;
2434 tree rhs;
2435
2436 if (idx < 0)
2437 rhs = build_int_cst (size_type_node, ~idx);
2438 else
2439 {
2440 rhs = NULL_TREE;
2441 si = get_strinfo (idx);
2442 if (si != NULL)
2443 rhs = get_string_length (si);
2444 }
2445 if (rhs != NULL_TREE)
2446 {
2447 location_t loc = gimple_location (stmt);
2448
2449 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
2450 {
2451 fprintf (dump_file, "Optimizing: ");
2452 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2453 }
2454 if (si != NULL && si->endptr != NULL_TREE)
2455 {
2456 rhs = unshare_expr (si->endptr);
2457 if (!useless_type_conversion_p (TREE_TYPE (lhs),
2458 TREE_TYPE (rhs)))
2459 rhs = fold_convert_loc (loc, TREE_TYPE (lhs), rhs);
2460 }
2461 else
2462 {
2463 rhs = fold_convert_loc (loc, sizetype, unshare_expr (rhs));
2464 rhs = fold_build2_loc (loc, POINTER_PLUS_EXPR,
2465 TREE_TYPE (src), src, rhs);
2466 if (!useless_type_conversion_p (TREE_TYPE (lhs),
2467 TREE_TYPE (rhs)))
2468 rhs = fold_convert_loc (loc, TREE_TYPE (lhs), rhs);
2469 }
2470 gimplify_and_update_call_from_tree (&m_gsi, rhs);
2471 stmt = gsi_stmt (m_gsi);
2472 update_stmt (stmt);
2473 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
2474 {
2475 fprintf (dump_file, "into: ");
2476 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2477 }
2478 if (si != NULL
2479 && si->endptr == NULL_TREE
2480 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
2481 {
2482 si = unshare_strinfo (si);
2483 si->endptr = lhs;
2484 }
2485 zero_length_string (lhs, si);
2486 return;
2487 }
2488 }
2489 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
2490 return;
2491 if (TREE_CODE (src) != SSA_NAME || !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (src))
2492 {
2493 if (idx == 0)
2494 idx = new_stridx (src);
2495 else if (get_strinfo (idx) != NULL)
2496 {
2497 zero_length_string (lhs, NULL);
2498 return;
2499 }
2500 if (idx)
2501 {
2502 location_t loc = gimple_location (stmt);
2503 tree lhsu = fold_convert_loc (loc, size_type_node, lhs);
2504 tree srcu = fold_convert_loc (loc, size_type_node, src);
2505 tree length = fold_build2_loc (loc, MINUS_EXPR,
2506 size_type_node, lhsu, srcu);
2507 strinfo *si = new_strinfo (src, idx, length, true);
2508 si->endptr = lhs;
2509 set_strinfo (idx, si);
2510 find_equal_ptrs (src, idx);
2511 zero_length_string (lhs, si);
2512 }
2513 }
2514 else
2515 zero_length_string (lhs, NULL);
2516 }
2517
2518 /* Handle a strcpy-like ({st{r,p}cpy,__st{r,p}cpy_chk}) call.
2519 If strlen of the second argument is known, strlen of the first argument
2520 is the same after this call. Furthermore, attempt to convert it to
2521 memcpy. Uses RVALS to determine range information. */
2522
2523 void
2524 strlen_pass::handle_builtin_strcpy (built_in_function bcode)
2525 {
2526 int idx, didx;
2527 tree src, dst, srclen, len, lhs, type, fn, oldlen;
2528 bool success;
2529 gimple *stmt = gsi_stmt (m_gsi);
2530 strinfo *si, *dsi, *olddsi, *zsi;
2531 location_t loc;
2532
2533 src = gimple_call_arg (stmt, 1);
2534 dst = gimple_call_arg (stmt, 0);
2535 lhs = gimple_call_lhs (stmt);
2536 idx = get_stridx (src, stmt);
2537 didx = get_stridx (dst, stmt);
2538 si = NULL;
2539 if (idx > 0)
2540 si = get_strinfo (idx);
2541
2542 olddsi = NULL;
2543 oldlen = NULL_TREE;
2544 if (didx > 0)
2545 olddsi = get_strinfo (didx);
2546 else if (didx < 0)
2547 return;
2548
2549 if (olddsi != NULL)
2550 adjust_last_stmt (olddsi, stmt, false);
2551
2552 srclen = NULL_TREE;
2553 if (si != NULL)
2554 srclen = get_string_length (si);
2555 else if (idx < 0)
2556 srclen = build_int_cst (size_type_node, ~idx);
2557
2558 maybe_warn_overflow (stmt, false, srclen, olddsi, true);
2559
2560 if (olddsi != NULL)
2561 adjust_last_stmt (olddsi, stmt, false);
2562
2563 loc = gimple_location (stmt);
2564 if (srclen == NULL_TREE)
2565 switch (bcode)
2566 {
2567 case BUILT_IN_STRCPY:
2568 case BUILT_IN_STRCPY_CHK:
2569 if (lhs != NULL_TREE || !builtin_decl_implicit_p (BUILT_IN_STPCPY))
2570 return;
2571 break;
2572 case BUILT_IN_STPCPY:
2573 case BUILT_IN_STPCPY_CHK:
2574 if (lhs == NULL_TREE)
2575 return;
2576 else
2577 {
2578 tree lhsuint = fold_convert_loc (loc, size_type_node, lhs);
2579 srclen = fold_convert_loc (loc, size_type_node, dst);
2580 srclen = fold_build2_loc (loc, MINUS_EXPR, size_type_node,
2581 lhsuint, srclen);
2582 }
2583 break;
2584 default:
2585 gcc_unreachable ();
2586 }
2587
2588 if (didx == 0)
2589 {
2590 didx = new_stridx (dst);
2591 if (didx == 0)
2592 return;
2593 }
2594 if (olddsi != NULL)
2595 {
2596 oldlen = olddsi->nonzero_chars;
2597 dsi = unshare_strinfo (olddsi);
2598 dsi->nonzero_chars = srclen;
2599 dsi->full_string_p = (srclen != NULL_TREE);
2600 /* Break the chain, so adjust_related_strinfo on later pointers in
2601 the chain won't adjust this one anymore. */
2602 dsi->next = 0;
2603 dsi->stmt = NULL;
2604 dsi->endptr = NULL_TREE;
2605 }
2606 else
2607 {
2608 dsi = new_strinfo (dst, didx, srclen, srclen != NULL_TREE);
2609 set_strinfo (didx, dsi);
2610 find_equal_ptrs (dst, didx);
2611 }
2612 dsi->writable = true;
2613 dsi->dont_invalidate = true;
2614
2615 if (dsi->nonzero_chars == NULL_TREE)
2616 {
2617 strinfo *chainsi;
2618
2619 /* If string length of src is unknown, use delayed length
2620 computation. If string length of dst will be needed, it
2621 can be computed by transforming this strcpy call into
2622 stpcpy and subtracting dst from the return value. */
2623
2624 /* Look for earlier strings whose length could be determined if
2625 this strcpy is turned into an stpcpy. */
2626
2627 if (dsi->prev != 0 && (chainsi = verify_related_strinfos (dsi)) != NULL)
2628 {
2629 for (; chainsi && chainsi != dsi; chainsi = get_strinfo (chainsi->next))
2630 {
2631 /* When setting a stmt for delayed length computation
2632 prevent all strinfos through dsi from being
2633 invalidated. */
2634 chainsi = unshare_strinfo (chainsi);
2635 chainsi->stmt = stmt;
2636 chainsi->nonzero_chars = NULL_TREE;
2637 chainsi->full_string_p = false;
2638 chainsi->endptr = NULL_TREE;
2639 chainsi->dont_invalidate = true;
2640 }
2641 }
2642 dsi->stmt = stmt;
2643
2644 /* Try to detect overlap before returning. This catches cases
2645 like strcpy (d, d + n) where n is non-constant whose range
2646 is such that (n <= strlen (d) holds).
2647
2648 OLDDSI->NONZERO_chars may have been reset by this point with
2649 oldlen holding it original value. */
2650 if (olddsi && oldlen)
2651 {
2652 /* Add 1 for the terminating NUL. */
2653 tree type = TREE_TYPE (oldlen);
2654 oldlen = fold_build2 (PLUS_EXPR, type, oldlen,
2655 build_int_cst (type, 1));
2656 check_bounds_or_overlap (stmt, olddsi->ptr, src, oldlen, NULL_TREE);
2657 }
2658
2659 return;
2660 }
2661
2662 if (olddsi != NULL)
2663 {
2664 tree adj = NULL_TREE;
2665 if (oldlen == NULL_TREE)
2666 ;
2667 else if (integer_zerop (oldlen))
2668 adj = srclen;
2669 else if (TREE_CODE (oldlen) == INTEGER_CST
2670 || TREE_CODE (srclen) == INTEGER_CST)
2671 adj = fold_build2_loc (loc, MINUS_EXPR,
2672 TREE_TYPE (srclen), srclen,
2673 fold_convert_loc (loc, TREE_TYPE (srclen),
2674 oldlen));
2675 if (adj != NULL_TREE)
2676 adjust_related_strinfos (loc, dsi, adj);
2677 else
2678 dsi->prev = 0;
2679 }
2680 /* strcpy src may not overlap dst, so src doesn't need to be
2681 invalidated either. */
2682 if (si != NULL)
2683 si->dont_invalidate = true;
2684
2685 fn = NULL_TREE;
2686 zsi = NULL;
2687 switch (bcode)
2688 {
2689 case BUILT_IN_STRCPY:
2690 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
2691 if (lhs)
2692 ssa_ver_to_stridx[SSA_NAME_VERSION (lhs)] = didx;
2693 break;
2694 case BUILT_IN_STRCPY_CHK:
2695 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
2696 if (lhs)
2697 ssa_ver_to_stridx[SSA_NAME_VERSION (lhs)] = didx;
2698 break;
2699 case BUILT_IN_STPCPY:
2700 /* This would need adjustment of the lhs (subtract one),
2701 or detection that the trailing '\0' doesn't need to be
2702 written, if it will be immediately overwritten.
2703 fn = builtin_decl_explicit (BUILT_IN_MEMPCPY); */
2704 if (lhs)
2705 {
2706 dsi->endptr = lhs;
2707 zsi = zero_length_string (lhs, dsi);
2708 }
2709 break;
2710 case BUILT_IN_STPCPY_CHK:
2711 /* This would need adjustment of the lhs (subtract one),
2712 or detection that the trailing '\0' doesn't need to be
2713 written, if it will be immediately overwritten.
2714 fn = builtin_decl_explicit (BUILT_IN_MEMPCPY_CHK); */
2715 if (lhs)
2716 {
2717 dsi->endptr = lhs;
2718 zsi = zero_length_string (lhs, dsi);
2719 }
2720 break;
2721 default:
2722 gcc_unreachable ();
2723 }
2724 if (zsi != NULL)
2725 zsi->dont_invalidate = true;
2726
2727 if (fn)
2728 {
2729 tree args = TYPE_ARG_TYPES (TREE_TYPE (fn));
2730 type = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (args)));
2731 }
2732 else
2733 type = size_type_node;
2734
2735 len = fold_convert_loc (loc, type, unshare_expr (srclen));
2736 len = fold_build2_loc (loc, PLUS_EXPR, type, len, build_int_cst (type, 1));
2737
2738 /* Disable warning for the transformed statement? */
2739 opt_code no_warning_opt = no_warning;
2740
2741 if (const strinfo *chksi = si ? olddsi ? olddsi : dsi : NULL)
2742 {
2743 no_warning_opt = check_bounds_or_overlap (stmt, chksi->ptr, si->ptr,
2744 NULL_TREE, len);
2745 if (no_warning_opt)
2746 suppress_warning (stmt, no_warning_opt);
2747 }
2748
2749 if (fn == NULL_TREE)
2750 return;
2751
2752 len = force_gimple_operand_gsi (&m_gsi, len, true, NULL_TREE, true,
2753 GSI_SAME_STMT);
2754 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
2755 {
2756 fprintf (dump_file, "Optimizing: ");
2757 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2758 }
2759 if (gimple_call_num_args (stmt) == 2)
2760 success = update_gimple_call (&m_gsi, fn, 3, dst, src, len);
2761 else
2762 success = update_gimple_call (&m_gsi, fn, 4, dst, src, len,
2763 gimple_call_arg (stmt, 2));
2764 if (success)
2765 {
2766 stmt = gsi_stmt (m_gsi);
2767 update_stmt (stmt);
2768 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
2769 {
2770 fprintf (dump_file, "into: ");
2771 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2772 }
2773 /* Allow adjust_last_stmt to decrease this memcpy's size. */
2774 laststmt.stmt = stmt;
2775 laststmt.len = srclen;
2776 laststmt.stridx = dsi->idx;
2777 }
2778 else if (dump_file && (dump_flags & TDF_DETAILS) != 0)
2779 fprintf (dump_file, "not possible.\n");
2780
2781 if (no_warning_opt)
2782 suppress_warning (stmt, no_warning_opt);
2783 }
2784
2785 /* Check the size argument to the built-in forms of stpncpy and strncpy
2786 for out-of-bounds offsets or overlapping access, and to see if the
2787 size argument is derived from a call to strlen() on the source argument,
2788 and if so, issue an appropriate warning. */
2789
2790 void
2791 strlen_pass::handle_builtin_strncat (built_in_function)
2792 {
2793 /* Same as stxncpy(). */
2794 handle_builtin_stxncpy_strncat (true);
2795 }
2796
2797 /* Return true if LEN depends on a call to strlen(SRC) in an interesting
2798 way. LEN can either be an integer expression, or a pointer (to char).
2799 When it is the latter (such as in recursive calls to self) it is
2800 assumed to be the argument in some call to strlen() whose relationship
2801 to SRC is being ascertained. */
2802
2803 bool
2804 is_strlen_related_p (tree src, tree len)
2805 {
2806 if (TREE_CODE (TREE_TYPE (len)) == POINTER_TYPE
2807 && operand_equal_p (src, len, 0))
2808 return true;
2809
2810 if (TREE_CODE (len) != SSA_NAME)
2811 return false;
2812
2813 if (TREE_CODE (src) == SSA_NAME)
2814 {
2815 gimple *srcdef = SSA_NAME_DEF_STMT (src);
2816 if (is_gimple_assign (srcdef))
2817 {
2818 /* Handle bitwise AND used in conversions from wider size_t
2819 to narrower unsigned types. */
2820 tree_code code = gimple_assign_rhs_code (srcdef);
2821 if (code == BIT_AND_EXPR
2822 || code == NOP_EXPR)
2823 return is_strlen_related_p (gimple_assign_rhs1 (srcdef), len);
2824
2825 return false;
2826 }
2827
2828 if (gimple_call_builtin_p (srcdef, BUILT_IN_NORMAL))
2829 {
2830 /* If SRC is the result of a call to an allocation function
2831 or strlen, use the function's argument instead. */
2832 tree func = gimple_call_fndecl (srcdef);
2833 built_in_function code = DECL_FUNCTION_CODE (func);
2834 if (code == BUILT_IN_ALLOCA
2835 || code == BUILT_IN_ALLOCA_WITH_ALIGN
2836 || code == BUILT_IN_MALLOC
2837 || code == BUILT_IN_STRLEN)
2838 return is_strlen_related_p (gimple_call_arg (srcdef, 0), len);
2839
2840 /* FIXME: Handle other functions with attribute alloc_size. */
2841 return false;
2842 }
2843 }
2844
2845 gimple *lendef = SSA_NAME_DEF_STMT (len);
2846 if (!lendef)
2847 return false;
2848
2849 if (is_gimple_call (lendef))
2850 {
2851 tree func = gimple_call_fndecl (lendef);
2852 if (!valid_builtin_call (lendef)
2853 || DECL_FUNCTION_CODE (func) != BUILT_IN_STRLEN)
2854 return false;
2855
2856 tree arg = gimple_call_arg (lendef, 0);
2857 return is_strlen_related_p (src, arg);
2858 }
2859
2860 if (!is_gimple_assign (lendef))
2861 return false;
2862
2863 tree_code code = gimple_assign_rhs_code (lendef);
2864 tree rhs1 = gimple_assign_rhs1 (lendef);
2865 tree rhstype = TREE_TYPE (rhs1);
2866
2867 if ((TREE_CODE (rhstype) == POINTER_TYPE && code == POINTER_PLUS_EXPR)
2868 || (INTEGRAL_TYPE_P (rhstype)
2869 && (code == BIT_AND_EXPR
2870 || code == NOP_EXPR)))
2871 {
2872 /* Pointer plus (an integer), and truncation are considered among
2873 the (potentially) related expressions to strlen. */
2874 return is_strlen_related_p (src, rhs1);
2875 }
2876
2877 if (tree rhs2 = gimple_assign_rhs2 (lendef))
2878 {
2879 /* Integer subtraction is considered strlen-related when both
2880 arguments are integers and second one is strlen-related. */
2881 rhstype = TREE_TYPE (rhs2);
2882 if (INTEGRAL_TYPE_P (rhstype) && code == MINUS_EXPR)
2883 return is_strlen_related_p (src, rhs2);
2884 }
2885
2886 return false;
2887 }
2888
2889 /* Called by handle_builtin_stxncpy_strncat and by
2890 gimple_fold_builtin_strncpy in gimple-fold.cc.
2891 Check to see if the specified bound is a) equal to the size of
2892 the destination DST and if so, b) if it's immediately followed by
2893 DST[CNT - 1] = '\0'. If a) holds and b) does not, warn. Otherwise,
2894 do nothing. Return true if diagnostic has been issued.
2895
2896 The purpose is to diagnose calls to strncpy and stpncpy that do
2897 not nul-terminate the copy while allowing for the idiom where
2898 such a call is immediately followed by setting the last element
2899 to nul, as in:
2900 char a[32];
2901 strncpy (a, s, sizeof a);
2902 a[sizeof a - 1] = '\0';
2903 */
2904
2905 bool
2906 maybe_diag_stxncpy_trunc (gimple_stmt_iterator gsi, tree src, tree cnt,
2907 pointer_query *ptr_qry /* = NULL */)
2908 {
2909 gimple *stmt = gsi_stmt (gsi);
2910 if (warning_suppressed_p (stmt, OPT_Wstringop_truncation))
2911 return false;
2912
2913 wide_int cntrange[2];
2914 int_range_max r;
2915 if (!get_range_query (cfun)->range_of_expr (r, cnt)
2916 || r.varying_p ()
2917 || r.undefined_p ())
2918 return false;
2919
2920 tree min, max;
2921 value_range_kind kind = get_legacy_range (r, min, max);
2922 cntrange[0] = wi::to_wide (min);
2923 cntrange[1] = wi::to_wide (max);
2924 if (kind == VR_ANTI_RANGE)
2925 {
2926 wide_int maxobjsize = wi::to_wide (TYPE_MAX_VALUE (ptrdiff_type_node));
2927
2928 if (wi::ltu_p (cntrange[1], maxobjsize))
2929 {
2930 cntrange[0] = cntrange[1] + 1;
2931 cntrange[1] = maxobjsize;
2932 }
2933 else
2934 {
2935 cntrange[1] = cntrange[0] - 1;
2936 cntrange[0] = wi::zero (TYPE_PRECISION (TREE_TYPE (cnt)));
2937 }
2938 }
2939
2940 /* Negative value is the constant string length. If it's less than
2941 the lower bound there is no truncation. Avoid calling get_stridx()
2942 when ssa_ver_to_stridx is empty. That implies the caller isn't
2943 running under the control of this pass and ssa_ver_to_stridx hasn't
2944 been created yet. */
2945 int sidx = ssa_ver_to_stridx.length () ? get_stridx (src, stmt) : 0;
2946 if (sidx < 0 && wi::gtu_p (cntrange[0], ~sidx))
2947 return false;
2948
2949 tree dst = gimple_call_arg (stmt, 0);
2950 tree dstdecl = dst;
2951 if (TREE_CODE (dstdecl) == ADDR_EXPR)
2952 dstdecl = TREE_OPERAND (dstdecl, 0);
2953
2954 tree ref = NULL_TREE;
2955
2956 if (!sidx)
2957 {
2958 /* If the source is a non-string return early to avoid warning
2959 for possible truncation (if the truncation is certain SIDX
2960 is non-zero). */
2961 tree srcdecl = gimple_call_arg (stmt, 1);
2962 if (TREE_CODE (srcdecl) == ADDR_EXPR)
2963 srcdecl = TREE_OPERAND (srcdecl, 0);
2964 if (get_attr_nonstring_decl (srcdecl, &ref))
2965 return false;
2966 }
2967
2968 /* Likewise, if the destination refers to an array/pointer declared
2969 nonstring return early. */
2970 if (get_attr_nonstring_decl (dstdecl, &ref))
2971 return false;
2972
2973 /* Look for dst[i] = '\0'; after the stxncpy() call and if found
2974 avoid the truncation warning. */
2975 gsi_next_nondebug (&gsi);
2976 gimple *next_stmt = gsi_stmt (gsi);
2977 if (!next_stmt)
2978 {
2979 /* When there is no statement in the same basic block check
2980 the immediate successor block. */
2981 if (basic_block bb = gimple_bb (stmt))
2982 {
2983 if (single_succ_p (bb))
2984 {
2985 /* For simplicity, ignore blocks with multiple outgoing
2986 edges for now and only consider successor blocks along
2987 normal edges. */
2988 edge e = EDGE_SUCC (bb, 0);
2989 if (!(e->flags & EDGE_ABNORMAL))
2990 {
2991 gsi = gsi_start_bb (e->dest);
2992 next_stmt = gsi_stmt (gsi);
2993 if (next_stmt && is_gimple_debug (next_stmt))
2994 {
2995 gsi_next_nondebug (&gsi);
2996 next_stmt = gsi_stmt (gsi);
2997 }
2998 }
2999 }
3000 }
3001 }
3002
3003 if (next_stmt && is_gimple_assign (next_stmt))
3004 {
3005 tree lhs = gimple_assign_lhs (next_stmt);
3006 tree_code code = TREE_CODE (lhs);
3007 if (code == ARRAY_REF || code == MEM_REF)
3008 lhs = TREE_OPERAND (lhs, 0);
3009
3010 tree func = gimple_call_fndecl (stmt);
3011 if (DECL_FUNCTION_CODE (func) == BUILT_IN_STPNCPY)
3012 {
3013 tree ret = gimple_call_lhs (stmt);
3014 if (ret && operand_equal_p (ret, lhs, 0))
3015 return false;
3016 }
3017
3018 /* Determine the base address and offset of the reference,
3019 ignoring the innermost array index. */
3020 if (TREE_CODE (ref) == ARRAY_REF)
3021 ref = TREE_OPERAND (ref, 0);
3022
3023 poly_int64 dstoff;
3024 tree dstbase = get_addr_base_and_unit_offset (ref, &dstoff);
3025
3026 poly_int64 lhsoff;
3027 tree lhsbase = get_addr_base_and_unit_offset (lhs, &lhsoff);
3028 if (lhsbase
3029 && dstbase
3030 && known_eq (dstoff, lhsoff)
3031 && operand_equal_p (dstbase, lhsbase, 0))
3032 return false;
3033 }
3034
3035 int prec = TYPE_PRECISION (TREE_TYPE (cnt));
3036 wide_int lenrange[2];
3037 if (strinfo *sisrc = sidx > 0 ? get_strinfo (sidx) : NULL)
3038 {
3039 lenrange[0] = (sisrc->nonzero_chars
3040 && TREE_CODE (sisrc->nonzero_chars) == INTEGER_CST
3041 ? wi::to_wide (sisrc->nonzero_chars)
3042 : wi::zero (prec));
3043 lenrange[1] = lenrange[0];
3044 }
3045 else if (sidx < 0)
3046 lenrange[0] = lenrange[1] = wi::shwi (~sidx, prec);
3047 else
3048 {
3049 c_strlen_data lendata = { };
3050 /* Set MAXBOUND to an arbitrary non-null non-integer node as a request
3051 to have it set to the length of the longest string in a PHI. */
3052 lendata.maxbound = src;
3053 get_range_strlen (src, &lendata, /* eltsize = */1);
3054 if (TREE_CODE (lendata.minlen) == INTEGER_CST
3055 && TREE_CODE (lendata.maxbound) == INTEGER_CST)
3056 {
3057 /* When LENDATA.MAXLEN is unknown, reset LENDATA.MINLEN
3058 which stores the length of the shortest known string. */
3059 if (integer_all_onesp (lendata.maxlen))
3060 lenrange[0] = wi::shwi (0, prec);
3061 else
3062 lenrange[0] = wi::to_wide (lendata.minlen, prec);
3063 lenrange[1] = wi::to_wide (lendata.maxbound, prec);
3064 }
3065 else
3066 {
3067 lenrange[0] = wi::shwi (0, prec);
3068 lenrange[1] = wi::shwi (-1, prec);
3069 }
3070 }
3071
3072 location_t callloc = gimple_or_expr_nonartificial_location (stmt, dst);
3073 tree func = gimple_call_fndecl (stmt);
3074
3075 if (lenrange[0] != 0 || !wi::neg_p (lenrange[1]))
3076 {
3077 /* If the longest source string is shorter than the lower bound
3078 of the specified count the copy is definitely nul-terminated. */
3079 if (wi::ltu_p (lenrange[1], cntrange[0]))
3080 return false;
3081
3082 if (wi::neg_p (lenrange[1]))
3083 {
3084 /* The length of one of the strings is unknown but at least
3085 one has non-zero length and that length is stored in
3086 LENRANGE[1]. Swap the bounds to force a "may be truncated"
3087 warning below. */
3088 lenrange[1] = lenrange[0];
3089 lenrange[0] = wi::shwi (0, prec);
3090 }
3091
3092 /* Set to true for strncat whose bound is derived from the length
3093 of the destination (the expected usage pattern). */
3094 bool cat_dstlen_bounded = false;
3095 if (DECL_FUNCTION_CODE (func) == BUILT_IN_STRNCAT)
3096 cat_dstlen_bounded = is_strlen_related_p (dst, cnt);
3097
3098 if (lenrange[0] == cntrange[1] && cntrange[0] == cntrange[1])
3099 return warning_n (callloc, OPT_Wstringop_truncation,
3100 cntrange[0].to_uhwi (),
3101 "%qD output truncated before terminating "
3102 "nul copying %E byte from a string of the "
3103 "same length",
3104 "%qD output truncated before terminating nul "
3105 "copying %E bytes from a string of the same "
3106 "length",
3107 func, cnt);
3108 else if (!cat_dstlen_bounded)
3109 {
3110 if (wi::geu_p (lenrange[0], cntrange[1]))
3111 {
3112 /* The shortest string is longer than the upper bound of
3113 the count so the truncation is certain. */
3114 if (cntrange[0] == cntrange[1])
3115 return warning_n (callloc, OPT_Wstringop_truncation,
3116 cntrange[0].to_uhwi (),
3117 "%qD output truncated copying %E byte "
3118 "from a string of length %wu",
3119 "%qD output truncated copying %E bytes "
3120 "from a string of length %wu",
3121 func, cnt, lenrange[0].to_uhwi ());
3122
3123 return warning_at (callloc, OPT_Wstringop_truncation,
3124 "%qD output truncated copying between %wu "
3125 "and %wu bytes from a string of length %wu",
3126 func, cntrange[0].to_uhwi (),
3127 cntrange[1].to_uhwi (), lenrange[0].to_uhwi ());
3128 }
3129 else if (wi::geu_p (lenrange[1], cntrange[1]))
3130 {
3131 /* The longest string is longer than the upper bound of
3132 the count so the truncation is possible. */
3133 if (cntrange[0] == cntrange[1])
3134 return warning_n (callloc, OPT_Wstringop_truncation,
3135 cntrange[0].to_uhwi (),
3136 "%qD output may be truncated copying %E "
3137 "byte from a string of length %wu",
3138 "%qD output may be truncated copying %E "
3139 "bytes from a string of length %wu",
3140 func, cnt, lenrange[1].to_uhwi ());
3141
3142 return warning_at (callloc, OPT_Wstringop_truncation,
3143 "%qD output may be truncated copying between "
3144 "%wu and %wu bytes from a string of length %wu",
3145 func, cntrange[0].to_uhwi (),
3146 cntrange[1].to_uhwi (), lenrange[1].to_uhwi ());
3147 }
3148 }
3149
3150 if (!cat_dstlen_bounded
3151 && cntrange[0] != cntrange[1]
3152 && wi::leu_p (cntrange[0], lenrange[0])
3153 && wi::leu_p (cntrange[1], lenrange[0] + 1))
3154 {
3155 /* If the source (including the terminating nul) is longer than
3156 the lower bound of the specified count but shorter than the
3157 upper bound the copy may (but need not) be truncated. */
3158 return warning_at (callloc, OPT_Wstringop_truncation,
3159 "%qD output may be truncated copying between "
3160 "%wu and %wu bytes from a string of length %wu",
3161 func, cntrange[0].to_uhwi (),
3162 cntrange[1].to_uhwi (), lenrange[0].to_uhwi ());
3163 }
3164 }
3165
3166 access_ref aref;
3167 if (tree dstsize = compute_objsize (dst, stmt, 1, &aref, ptr_qry))
3168 {
3169 /* The source length is unknown. Try to determine the destination
3170 size and see if it matches the specified bound. If not, bail.
3171 Otherwise go on to see if it should be diagnosed for possible
3172 truncation. */
3173 if (!dstsize)
3174 return false;
3175
3176 if (wi::to_wide (dstsize) != cntrange[1])
3177 return false;
3178
3179 /* Avoid warning for strncpy(a, b, N) calls where the following
3180 equalities hold:
3181 N == sizeof a && N == sizeof b */
3182 if (tree srcsize = compute_objsize (src, stmt, 1, &aref, ptr_qry))
3183 if (wi::to_wide (srcsize) == cntrange[1])
3184 return false;
3185
3186 if (cntrange[0] == cntrange[1])
3187 return warning_at (callloc, OPT_Wstringop_truncation,
3188 "%qD specified bound %E equals destination size",
3189 func, cnt);
3190 }
3191
3192 return false;
3193 }
3194
3195 /* Check the arguments to the built-in forms of stpncpy, strncpy, and
3196 strncat, for out-of-bounds offsets or overlapping access, and to see
3197 if the size is derived from calling strlen() on the source argument,
3198 and if so, issue the appropriate warning.
3199 APPEND_P is true for strncat. */
3200
3201 void
3202 strlen_pass::handle_builtin_stxncpy_strncat (bool append_p)
3203 {
3204 if (!strlen_to_stridx)
3205 return;
3206
3207 gimple *stmt = gsi_stmt (m_gsi);
3208
3209 tree dst = gimple_call_arg (stmt, 0);
3210 tree src = gimple_call_arg (stmt, 1);
3211 tree len = gimple_call_arg (stmt, 2);
3212 /* An upper bound of the size of the destination. */
3213 tree dstsize = NULL_TREE;
3214 /* The length of the destination and source strings (plus 1 for those
3215 whose FULL_STRING_P is set, i.e., whose length is exact rather than
3216 a lower bound). */
3217 tree dstlenp1 = NULL_TREE, srclenp1 = NULL_TREE;;
3218
3219 int didx = get_stridx (dst, stmt);
3220 if (strinfo *sidst = didx > 0 ? get_strinfo (didx) : NULL)
3221 {
3222 /* Compute the size of the destination string including the nul
3223 if it is known to be nul-terminated. */
3224 if (sidst->nonzero_chars)
3225 {
3226 if (sidst->full_string_p)
3227 {
3228 /* String is known to be nul-terminated. */
3229 tree type = TREE_TYPE (sidst->nonzero_chars);
3230 dstlenp1 = fold_build2 (PLUS_EXPR, type, sidst->nonzero_chars,
3231 build_int_cst (type, 1));
3232 }
3233 else
3234 dstlenp1 = sidst->nonzero_chars;
3235 }
3236 else if (TREE_CODE (sidst->ptr) == SSA_NAME)
3237 {
3238 gimple *def_stmt = SSA_NAME_DEF_STMT (sidst->ptr);
3239 dstsize = gimple_call_alloc_size (def_stmt);
3240 }
3241
3242 dst = sidst->ptr;
3243 }
3244
3245 int sidx = get_stridx (src, stmt);
3246 strinfo *sisrc = sidx > 0 ? get_strinfo (sidx) : NULL;
3247 if (sisrc)
3248 {
3249 /* strncat() and strncpy() can modify the source string by writing
3250 over the terminating nul so SISRC->DONT_INVALIDATE must be left
3251 clear. */
3252
3253 /* Compute the size of the source string including the terminating
3254 nul if its known to be nul-terminated. */
3255 if (sisrc->nonzero_chars)
3256 {
3257 if (sisrc->full_string_p)
3258 {
3259 tree type = TREE_TYPE (sisrc->nonzero_chars);
3260 srclenp1 = fold_build2 (PLUS_EXPR, type, sisrc->nonzero_chars,
3261 build_int_cst (type, 1));
3262 }
3263 else
3264 srclenp1 = sisrc->nonzero_chars;
3265 }
3266
3267 src = sisrc->ptr;
3268 }
3269 else
3270 srclenp1 = NULL_TREE;
3271
3272 opt_code opt = check_bounds_or_overlap (stmt, dst, src, dstlenp1, srclenp1);
3273 if (opt != no_warning)
3274 {
3275 suppress_warning (stmt, opt);
3276 return;
3277 }
3278
3279 /* If the length argument was computed from strlen(S) for some string
3280 S retrieve the strinfo index for the string (PSS->FIRST) along with
3281 the location of the strlen() call (PSS->SECOND). */
3282 stridx_strlenloc *pss = strlen_to_stridx->get (len);
3283 if (!pss || pss->first <= 0)
3284 {
3285 if (maybe_diag_stxncpy_trunc (m_gsi, src, len))
3286 suppress_warning (stmt, OPT_Wstringop_truncation);
3287
3288 return;
3289 }
3290
3291 /* Retrieve the strinfo data for the string S that LEN was computed
3292 from as some function F of strlen (S) (i.e., LEN need not be equal
3293 to strlen(S)). */
3294 strinfo *silen = get_strinfo (pss->first);
3295
3296 location_t callloc = gimple_or_expr_nonartificial_location (stmt, dst);
3297
3298 tree func = gimple_call_fndecl (stmt);
3299
3300 bool warned = false;
3301
3302 /* When -Wstringop-truncation is set, try to determine truncation
3303 before diagnosing possible overflow. Truncation is implied by
3304 the LEN argument being equal to strlen(SRC), regardless of
3305 whether its value is known. Otherwise, when appending, or
3306 when copying into a destination of known size, issue the more
3307 generic -Wstringop-overflow which triggers for LEN arguments
3308 that in any meaningful way depend on strlen(SRC). */
3309 if (!append_p
3310 && sisrc == silen
3311 && is_strlen_related_p (src, len)
3312 && warning_at (callloc, OPT_Wstringop_truncation,
3313 "%qD output truncated before terminating nul "
3314 "copying as many bytes from a string as its length",
3315 func))
3316 warned = true;
3317 else if ((append_p || !dstsize || len == dstlenp1)
3318 && silen && is_strlen_related_p (src, silen->ptr))
3319 {
3320 /* Issue -Wstringop-overflow when appending or when writing into
3321 a destination of a known size. Otherwise, when copying into
3322 a destination of an unknown size, it's truncation. */
3323 opt_code opt = (append_p || dstsize
3324 ? OPT_Wstringop_overflow_ : OPT_Wstringop_truncation);
3325 warned = warning_at (callloc, opt,
3326 "%qD specified bound depends on the length "
3327 "of the source argument",
3328 func);
3329 }
3330 if (warned)
3331 {
3332 location_t strlenloc = pss->second;
3333 if (strlenloc != UNKNOWN_LOCATION && strlenloc != callloc)
3334 inform (strlenloc, "length computed here");
3335 }
3336 }
3337
3338 /* Handle a memcpy-like ({mem{,p}cpy,__mem{,p}cpy_chk}) call.
3339 If strlen of the second argument is known and length of the third argument
3340 is that plus one, strlen of the first argument is the same after this
3341 call. Uses RVALS to determine range information. */
3342
3343 void
3344 strlen_pass::handle_builtin_memcpy (built_in_function bcode)
3345 {
3346 tree lhs, oldlen, newlen;
3347 gimple *stmt = gsi_stmt (m_gsi);
3348 strinfo *si, *dsi;
3349
3350 tree len = gimple_call_arg (stmt, 2);
3351 tree src = gimple_call_arg (stmt, 1);
3352 tree dst = gimple_call_arg (stmt, 0);
3353
3354 int didx = get_stridx (dst, stmt);
3355 if (didx < 0)
3356 return;
3357 int idx = get_stridx (src, stmt);
3358 strinfo *olddsi = NULL;
3359 if (didx > 0)
3360 olddsi = get_strinfo (didx);
3361
3362 if (olddsi != NULL
3363 && !integer_zerop (len))
3364 {
3365 maybe_warn_overflow (stmt, false, len, olddsi, false, true);
3366 if (tree_fits_uhwi_p (len))
3367 adjust_last_stmt (olddsi, stmt, false);
3368 }
3369
3370 if (idx == 0)
3371 return;
3372
3373 bool full_string_p;
3374 if (idx > 0)
3375 {
3376 gimple *def_stmt;
3377
3378 /* Handle memcpy (x, y, l) where l's relationship with strlen (y)
3379 is known. */
3380 si = get_strinfo (idx);
3381 if (si == NULL || si->nonzero_chars == NULL_TREE)
3382 return;
3383 if (TREE_CODE (len) == INTEGER_CST
3384 && TREE_CODE (si->nonzero_chars) == INTEGER_CST)
3385 {
3386 if (tree_int_cst_le (len, si->nonzero_chars))
3387 {
3388 /* Copying LEN nonzero characters, where LEN is constant. */
3389 newlen = len;
3390 full_string_p = false;
3391 }
3392 else
3393 {
3394 /* Copying the whole of the analyzed part of SI. */
3395 newlen = si->nonzero_chars;
3396 full_string_p = si->full_string_p;
3397 }
3398 }
3399 else
3400 {
3401 if (!si->full_string_p)
3402 return;
3403 if (TREE_CODE (len) != SSA_NAME)
3404 return;
3405 def_stmt = SSA_NAME_DEF_STMT (len);
3406 if (!is_gimple_assign (def_stmt)
3407 || gimple_assign_rhs_code (def_stmt) != PLUS_EXPR
3408 || gimple_assign_rhs1 (def_stmt) != si->nonzero_chars
3409 || !integer_onep (gimple_assign_rhs2 (def_stmt)))
3410 return;
3411 /* Copying variable-length string SI (and no more). */
3412 newlen = si->nonzero_chars;
3413 full_string_p = true;
3414 }
3415 }
3416 else
3417 {
3418 si = NULL;
3419 /* Handle memcpy (x, "abcd", 5) or
3420 memcpy (x, "abc\0uvw", 7). */
3421 if (!tree_fits_uhwi_p (len))
3422 return;
3423
3424 unsigned HOST_WIDE_INT clen = tree_to_uhwi (len);
3425 unsigned HOST_WIDE_INT nonzero_chars = ~idx;
3426 newlen = build_int_cst (size_type_node, MIN (nonzero_chars, clen));
3427 full_string_p = clen > nonzero_chars;
3428 }
3429
3430 if (!full_string_p
3431 && olddsi
3432 && olddsi->nonzero_chars
3433 && TREE_CODE (olddsi->nonzero_chars) == INTEGER_CST
3434 && tree_int_cst_le (newlen, olddsi->nonzero_chars))
3435 {
3436 /* The SRC substring being written strictly overlaps
3437 a subsequence of the existing string OLDDSI. */
3438 newlen = olddsi->nonzero_chars;
3439 full_string_p = olddsi->full_string_p;
3440 }
3441
3442 if (olddsi != NULL && TREE_CODE (len) == SSA_NAME)
3443 adjust_last_stmt (olddsi, stmt, false);
3444
3445 if (didx == 0)
3446 {
3447 didx = new_stridx (dst);
3448 if (didx == 0)
3449 return;
3450 }
3451 oldlen = NULL_TREE;
3452 if (olddsi != NULL)
3453 {
3454 dsi = unshare_strinfo (olddsi);
3455 oldlen = olddsi->nonzero_chars;
3456 dsi->nonzero_chars = newlen;
3457 dsi->full_string_p = full_string_p;
3458 /* Break the chain, so adjust_related_strinfo on later pointers in
3459 the chain won't adjust this one anymore. */
3460 dsi->next = 0;
3461 dsi->stmt = NULL;
3462 dsi->endptr = NULL_TREE;
3463 }
3464 else
3465 {
3466 dsi = new_strinfo (dst, didx, newlen, full_string_p);
3467 set_strinfo (didx, dsi);
3468 find_equal_ptrs (dst, didx);
3469 }
3470 dsi->writable = true;
3471 dsi->dont_invalidate = true;
3472 if (olddsi != NULL)
3473 {
3474 tree adj = NULL_TREE;
3475 location_t loc = gimple_location (stmt);
3476 if (oldlen == NULL_TREE)
3477 ;
3478 else if (integer_zerop (oldlen))
3479 adj = newlen;
3480 else if (TREE_CODE (oldlen) == INTEGER_CST
3481 || TREE_CODE (newlen) == INTEGER_CST)
3482 adj = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (newlen), newlen,
3483 fold_convert_loc (loc, TREE_TYPE (newlen),
3484 oldlen));
3485 if (adj != NULL_TREE)
3486 adjust_related_strinfos (loc, dsi, adj);
3487 else
3488 dsi->prev = 0;
3489 }
3490 /* memcpy src may not overlap dst, so src doesn't need to be
3491 invalidated either. */
3492 if (si != NULL)
3493 si->dont_invalidate = true;
3494
3495 if (full_string_p)
3496 {
3497 lhs = gimple_call_lhs (stmt);
3498 switch (bcode)
3499 {
3500 case BUILT_IN_MEMCPY:
3501 case BUILT_IN_MEMCPY_CHK:
3502 /* Allow adjust_last_stmt to decrease this memcpy's size. */
3503 laststmt.stmt = stmt;
3504 laststmt.len = dsi->nonzero_chars;
3505 laststmt.stridx = dsi->idx;
3506 if (lhs)
3507 ssa_ver_to_stridx[SSA_NAME_VERSION (lhs)] = didx;
3508 break;
3509 case BUILT_IN_MEMPCPY:
3510 case BUILT_IN_MEMPCPY_CHK:
3511 break;
3512 default:
3513 gcc_unreachable ();
3514 }
3515 }
3516 }
3517
3518 /* Handle a strcat-like ({strcat,__strcat_chk}) call.
3519 If strlen of the second argument is known, strlen of the first argument
3520 is increased by the length of the second argument. Furthermore, attempt
3521 to convert it to memcpy/strcpy if the length of the first argument
3522 is known. */
3523
3524 void
3525 strlen_pass::handle_builtin_strcat (built_in_function bcode)
3526 {
3527 int idx, didx;
3528 tree srclen, args, type, fn, objsz, endptr;
3529 bool success;
3530 gimple *stmt = gsi_stmt (m_gsi);
3531 strinfo *si, *dsi;
3532 location_t loc = gimple_location (stmt);
3533
3534 tree src = gimple_call_arg (stmt, 1);
3535 tree dst = gimple_call_arg (stmt, 0);
3536
3537 /* Bail if the source is the same as destination. It will be diagnosed
3538 elsewhere. */
3539 if (operand_equal_p (src, dst, 0))
3540 return;
3541
3542 tree lhs = gimple_call_lhs (stmt);
3543
3544 didx = get_stridx (dst, stmt);
3545 if (didx < 0)
3546 return;
3547 idx = get_stridx (src, stmt);
3548
3549 dsi = NULL;
3550 if (didx > 0)
3551 dsi = get_strinfo (didx);
3552
3553 srclen = NULL_TREE;
3554 si = NULL;
3555 if (idx < 0)
3556 srclen = build_int_cst (size_type_node, ~idx);
3557 else if (idx > 0)
3558 {
3559 si = get_strinfo (idx);
3560 if (si != NULL)
3561 srclen = get_string_length (si);
3562 }
3563
3564 /* Disable warning for the transformed statement? */
3565 opt_code no_warning_opt = no_warning;
3566
3567 if (dsi == NULL || get_string_length (dsi) == NULL_TREE)
3568 {
3569 {
3570 /* The concatenation always involves copying at least one byte
3571 (the terminating nul), even if the source string is empty.
3572 If the source is unknown assume it's one character long and
3573 used that as both sizes. */
3574 tree slen = srclen;
3575 if (slen)
3576 {
3577 tree type = TREE_TYPE (slen);
3578 slen = fold_build2 (PLUS_EXPR, type, slen, build_int_cst (type, 1));
3579 }
3580
3581 tree sptr = si && si->ptr ? si->ptr : src;
3582 no_warning_opt = check_bounds_or_overlap (stmt, dst, sptr, NULL_TREE,
3583 slen);
3584 if (no_warning_opt)
3585 suppress_warning (stmt, no_warning_opt);
3586 }
3587
3588 /* strcat (p, q) can be transformed into
3589 tmp = p + strlen (p); endptr = stpcpy (tmp, q);
3590 with length endptr - p if we need to compute the length
3591 later on. Don't do this transformation if we don't need
3592 it. */
3593 if (builtin_decl_implicit_p (BUILT_IN_STPCPY) && lhs == NULL_TREE)
3594 {
3595 if (didx == 0)
3596 {
3597 didx = new_stridx (dst);
3598 if (didx == 0)
3599 return;
3600 }
3601 if (dsi == NULL)
3602 {
3603 dsi = new_strinfo (dst, didx, NULL_TREE, false);
3604 set_strinfo (didx, dsi);
3605 find_equal_ptrs (dst, didx);
3606 }
3607 else
3608 {
3609 dsi = unshare_strinfo (dsi);
3610 dsi->nonzero_chars = NULL_TREE;
3611 dsi->full_string_p = false;
3612 dsi->next = 0;
3613 dsi->endptr = NULL_TREE;
3614 }
3615 dsi->writable = true;
3616 dsi->stmt = stmt;
3617 dsi->dont_invalidate = true;
3618 }
3619 return;
3620 }
3621
3622 tree dstlen = dsi->nonzero_chars;
3623 endptr = dsi->endptr;
3624
3625 dsi = unshare_strinfo (dsi);
3626 dsi->endptr = NULL_TREE;
3627 dsi->stmt = NULL;
3628 dsi->writable = true;
3629
3630 if (srclen != NULL_TREE)
3631 {
3632 dsi->nonzero_chars = fold_build2_loc (loc, PLUS_EXPR,
3633 TREE_TYPE (dsi->nonzero_chars),
3634 dsi->nonzero_chars, srclen);
3635 gcc_assert (dsi->full_string_p);
3636 adjust_related_strinfos (loc, dsi, srclen);
3637 dsi->dont_invalidate = true;
3638 }
3639 else
3640 {
3641 dsi->nonzero_chars = NULL;
3642 dsi->full_string_p = false;
3643 if (lhs == NULL_TREE && builtin_decl_implicit_p (BUILT_IN_STPCPY))
3644 dsi->dont_invalidate = true;
3645 }
3646
3647 if (si != NULL)
3648 /* strcat src may not overlap dst, so src doesn't need to be
3649 invalidated either. */
3650 si->dont_invalidate = true;
3651
3652 /* For now. Could remove the lhs from the call and add
3653 lhs = dst; afterwards. */
3654 if (lhs)
3655 return;
3656
3657 fn = NULL_TREE;
3658 objsz = NULL_TREE;
3659 switch (bcode)
3660 {
3661 case BUILT_IN_STRCAT:
3662 if (srclen != NULL_TREE)
3663 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
3664 else
3665 fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3666 break;
3667 case BUILT_IN_STRCAT_CHK:
3668 if (srclen != NULL_TREE)
3669 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
3670 else
3671 fn = builtin_decl_explicit (BUILT_IN_STRCPY_CHK);
3672 objsz = gimple_call_arg (stmt, 2);
3673 break;
3674 default:
3675 gcc_unreachable ();
3676 }
3677
3678 if (fn == NULL_TREE)
3679 return;
3680
3681 if (dsi && dstlen)
3682 {
3683 tree type = TREE_TYPE (dstlen);
3684
3685 /* Compute the size of the source sequence, including the nul. */
3686 tree srcsize = srclen ? srclen : size_zero_node;
3687 tree one = build_int_cst (type, 1);
3688 srcsize = fold_build2 (PLUS_EXPR, type, srcsize, one);
3689 tree dstsize = fold_build2 (PLUS_EXPR, type, dstlen, one);
3690 tree sptr = si && si->ptr ? si->ptr : src;
3691
3692 no_warning_opt = check_bounds_or_overlap (stmt, dst, sptr, dstsize,
3693 srcsize);
3694 if (no_warning_opt)
3695 suppress_warning (stmt, no_warning_opt);
3696 }
3697
3698 tree len = NULL_TREE;
3699 if (srclen != NULL_TREE)
3700 {
3701 args = TYPE_ARG_TYPES (TREE_TYPE (fn));
3702 type = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (args)));
3703
3704 len = fold_convert_loc (loc, type, unshare_expr (srclen));
3705 len = fold_build2_loc (loc, PLUS_EXPR, type, len,
3706 build_int_cst (type, 1));
3707 len = force_gimple_operand_gsi (&m_gsi, len, true, NULL_TREE, true,
3708 GSI_SAME_STMT);
3709 }
3710 if (endptr)
3711 dst = fold_convert_loc (loc, TREE_TYPE (dst), unshare_expr (endptr));
3712 else
3713 dst = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (dst), dst,
3714 fold_convert_loc (loc, sizetype,
3715 unshare_expr (dstlen)));
3716 dst = force_gimple_operand_gsi (&m_gsi, dst, true, NULL_TREE, true,
3717 GSI_SAME_STMT);
3718 if (objsz)
3719 {
3720 objsz = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (objsz), objsz,
3721 fold_convert_loc (loc, TREE_TYPE (objsz),
3722 unshare_expr (dstlen)));
3723 objsz = force_gimple_operand_gsi (&m_gsi, objsz, true, NULL_TREE, true,
3724 GSI_SAME_STMT);
3725 }
3726 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
3727 {
3728 fprintf (dump_file, "Optimizing: ");
3729 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
3730 }
3731 if (srclen != NULL_TREE)
3732 success = update_gimple_call (&m_gsi, fn, 3 + (objsz != NULL_TREE),
3733 dst, src, len, objsz);
3734 else
3735 success = update_gimple_call (&m_gsi, fn, 2 + (objsz != NULL_TREE),
3736 dst, src, objsz);
3737 if (success)
3738 {
3739 stmt = gsi_stmt (m_gsi);
3740 update_stmt (stmt);
3741 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
3742 {
3743 fprintf (dump_file, "into: ");
3744 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
3745 }
3746 /* If srclen == NULL, note that current string length can be
3747 computed by transforming this strcpy into stpcpy. */
3748 if (srclen == NULL_TREE && dsi->dont_invalidate)
3749 dsi->stmt = stmt;
3750 adjust_last_stmt (dsi, stmt, true);
3751 if (srclen != NULL_TREE)
3752 {
3753 laststmt.stmt = stmt;
3754 laststmt.len = srclen;
3755 laststmt.stridx = dsi->idx;
3756 }
3757 }
3758 else if (dump_file && (dump_flags & TDF_DETAILS) != 0)
3759 fprintf (dump_file, "not possible.\n");
3760
3761 if (no_warning_opt)
3762 suppress_warning (stmt, no_warning_opt);
3763 }
3764
3765 /* Handle a call to an allocation function like alloca, malloc or calloc,
3766 or an ordinary allocation function declared with attribute alloc_size. */
3767
3768 void
3769 strlen_pass::handle_alloc_call (built_in_function bcode)
3770 {
3771 gimple *stmt = gsi_stmt (m_gsi);
3772 tree lhs = gimple_call_lhs (stmt);
3773 if (lhs == NULL_TREE)
3774 return;
3775
3776 gcc_assert (get_stridx (lhs, stmt) == 0);
3777 int idx = new_stridx (lhs);
3778 tree length = NULL_TREE;
3779 if (bcode == BUILT_IN_CALLOC)
3780 length = build_int_cst (size_type_node, 0);
3781 strinfo *si = new_strinfo (lhs, idx, length, length != NULL_TREE);
3782 if (bcode == BUILT_IN_CALLOC)
3783 {
3784 /* Only set STMT for calloc and malloc. */
3785 si->stmt = stmt;
3786 /* Only set ENDPTR for calloc. */
3787 si->endptr = lhs;
3788 }
3789 else if (bcode == BUILT_IN_MALLOC)
3790 si->stmt = stmt;
3791
3792 /* Set ALLOC is set for all allocation functions. */
3793 si->alloc = stmt;
3794 set_strinfo (idx, si);
3795 si->writable = true;
3796 si->dont_invalidate = true;
3797 }
3798
3799 /* Handle a call to memset.
3800 After a call to calloc, memset(,0,) is unnecessary.
3801 memset(malloc(n),0,n) is calloc(n,1).
3802 return true when the call is transformed, false otherwise.
3803 When nonnull uses RVALS to determine range information. */
3804
3805 bool
3806 strlen_pass::handle_builtin_memset (bool *zero_write)
3807 {
3808 gimple *memset_stmt = gsi_stmt (m_gsi);
3809 tree ptr = gimple_call_arg (memset_stmt, 0);
3810 tree memset_val = gimple_call_arg (memset_stmt, 1);
3811 tree memset_size = gimple_call_arg (memset_stmt, 2);
3812
3813 /* Set to the non-constant offset added to PTR. */
3814 wide_int offrng[2];
3815 int idx1 = get_stridx (ptr, memset_stmt, offrng, ptr_qry.rvals);
3816 if (idx1 == 0
3817 && TREE_CODE (memset_val) == INTEGER_CST
3818 && ((TREE_CODE (memset_size) == INTEGER_CST
3819 && !integer_zerop (memset_size))
3820 || TREE_CODE (memset_size) == SSA_NAME))
3821 {
3822 unsigned HOST_WIDE_INT mask = (HOST_WIDE_INT_1U << CHAR_TYPE_SIZE) - 1;
3823 bool full_string_p = (wi::to_wide (memset_val) & mask) == 0;
3824
3825 /* We only handle symbolic lengths when writing non-zero values. */
3826 if (full_string_p && TREE_CODE (memset_size) != INTEGER_CST)
3827 return false;
3828
3829 idx1 = new_stridx (ptr);
3830 if (idx1 == 0)
3831 return false;
3832 tree newlen;
3833 if (full_string_p)
3834 newlen = build_int_cst (size_type_node, 0);
3835 else if (TREE_CODE (memset_size) == INTEGER_CST)
3836 newlen = fold_convert (size_type_node, memset_size);
3837 else
3838 newlen = memset_size;
3839
3840 strinfo *dsi = new_strinfo (ptr, idx1, newlen, full_string_p);
3841 set_strinfo (idx1, dsi);
3842 find_equal_ptrs (ptr, idx1);
3843 dsi->dont_invalidate = true;
3844 dsi->writable = true;
3845 return false;
3846 }
3847
3848 if (idx1 <= 0)
3849 return false;
3850 strinfo *si1 = get_strinfo (idx1);
3851 if (!si1)
3852 return false;
3853 gimple *alloc_stmt = si1->alloc;
3854 if (!alloc_stmt || !is_gimple_call (alloc_stmt))
3855 return false;
3856 tree callee1 = gimple_call_fndecl (alloc_stmt);
3857 if (!valid_builtin_call (alloc_stmt))
3858 return false;
3859 tree alloc_size = gimple_call_arg (alloc_stmt, 0);
3860
3861 /* Check for overflow. */
3862 maybe_warn_overflow (memset_stmt, false, memset_size, NULL, false, true);
3863
3864 /* Bail when there is no statement associated with the destination
3865 (the statement may be null even when SI1->ALLOC is not). */
3866 if (!si1->stmt)
3867 return false;
3868
3869 /* Avoid optimizing if store is at a variable offset from the beginning
3870 of the allocated object. */
3871 if (offrng[0] != 0 || offrng[0] != offrng[1])
3872 return false;
3873
3874 /* Bail when the call writes a non-zero value. */
3875 if (!integer_zerop (memset_val))
3876 return false;
3877
3878 /* Let the caller know the memset call cleared the destination. */
3879 *zero_write = true;
3880
3881 enum built_in_function code1 = DECL_FUNCTION_CODE (callee1);
3882 if (code1 == BUILT_IN_CALLOC)
3883 /* Not touching alloc_stmt */ ;
3884 else if (code1 == BUILT_IN_MALLOC
3885 && operand_equal_p (memset_size, alloc_size, 0))
3886 {
3887 /* Replace the malloc + memset calls with calloc. */
3888 gimple_stmt_iterator gsi1 = gsi_for_stmt (si1->stmt);
3889 update_gimple_call (&gsi1, builtin_decl_implicit (BUILT_IN_CALLOC), 2,
3890 alloc_size, build_one_cst (size_type_node));
3891 si1->nonzero_chars = build_int_cst (size_type_node, 0);
3892 si1->full_string_p = true;
3893 si1->stmt = gsi_stmt (gsi1);
3894 }
3895 else
3896 return false;
3897 tree lhs = gimple_call_lhs (memset_stmt);
3898 unlink_stmt_vdef (memset_stmt);
3899 if (lhs)
3900 {
3901 gimple *assign = gimple_build_assign (lhs, ptr);
3902 gsi_replace (&m_gsi, assign, false);
3903 }
3904 else
3905 {
3906 gsi_remove (&m_gsi, true);
3907 release_defs (memset_stmt);
3908 }
3909
3910 return true;
3911 }
3912
3913 /* Return first such statement if RES is used in statements testing its
3914 equality to zero, and null otherwise. If EXCLUSIVE is true, return
3915 nonnull if and only RES is used in such expressions exclusively and
3916 in none other. */
3917
3918 gimple *
3919 use_in_zero_equality (tree res, bool exclusive)
3920 {
3921 gimple *first_use = NULL;
3922
3923 use_operand_p use_p;
3924 imm_use_iterator iter;
3925
3926 FOR_EACH_IMM_USE_FAST (use_p, iter, res)
3927 {
3928 gimple *use_stmt = USE_STMT (use_p);
3929
3930 if (is_gimple_debug (use_stmt))
3931 continue;
3932
3933 if (gimple_code (use_stmt) == GIMPLE_ASSIGN)
3934 {
3935 tree_code code = gimple_assign_rhs_code (use_stmt);
3936 if (code == COND_EXPR)
3937 {
3938 tree cond_expr = gimple_assign_rhs1 (use_stmt);
3939 if ((TREE_CODE (cond_expr) != EQ_EXPR
3940 && (TREE_CODE (cond_expr) != NE_EXPR))
3941 || !integer_zerop (TREE_OPERAND (cond_expr, 1)))
3942 {
3943 if (exclusive)
3944 return NULL;
3945 continue;
3946 }
3947 }
3948 else if (code == EQ_EXPR || code == NE_EXPR)
3949 {
3950 if (!integer_zerop (gimple_assign_rhs2 (use_stmt)))
3951 {
3952 if (exclusive)
3953 return NULL;
3954 continue;
3955 }
3956 }
3957 else if (exclusive)
3958 return NULL;
3959 else
3960 continue;
3961 }
3962 else if (gimple_code (use_stmt) == GIMPLE_COND)
3963 {
3964 tree_code code = gimple_cond_code (use_stmt);
3965 if ((code != EQ_EXPR && code != NE_EXPR)
3966 || !integer_zerop (gimple_cond_rhs (use_stmt)))
3967 {
3968 if (exclusive)
3969 return NULL;
3970 continue;
3971 }
3972 }
3973 else if (exclusive)
3974 return NULL;
3975 else
3976 continue;
3977
3978 if (!first_use)
3979 first_use = use_stmt;
3980 }
3981
3982 return first_use;
3983 }
3984
3985 /* Handle a call to memcmp. We try to handle small comparisons by
3986 converting them to load and compare, and replacing the call to memcmp
3987 with a __builtin_memcmp_eq call where possible.
3988 return true when call is transformed, return false otherwise. */
3989
3990 bool
3991 strlen_pass::handle_builtin_memcmp ()
3992 {
3993 gcall *stmt = as_a <gcall *> (gsi_stmt (m_gsi));
3994 tree res = gimple_call_lhs (stmt);
3995
3996 if (!res || !use_in_zero_equality (res))
3997 return false;
3998
3999 tree arg1 = gimple_call_arg (stmt, 0);
4000 tree arg2 = gimple_call_arg (stmt, 1);
4001 tree len = gimple_call_arg (stmt, 2);
4002 unsigned HOST_WIDE_INT leni;
4003
4004 if (tree_fits_uhwi_p (len)
4005 && (leni = tree_to_uhwi (len)) <= GET_MODE_SIZE (word_mode)
4006 && pow2p_hwi (leni))
4007 {
4008 leni *= CHAR_TYPE_SIZE;
4009 unsigned align1 = get_pointer_alignment (arg1);
4010 unsigned align2 = get_pointer_alignment (arg2);
4011 unsigned align = MIN (align1, align2);
4012 scalar_int_mode mode;
4013 if (int_mode_for_size (leni, 1).exists (&mode)
4014 && (align >= leni || !targetm.slow_unaligned_access (mode, align)))
4015 {
4016 location_t loc = gimple_location (stmt);
4017 tree type, off;
4018 type = build_nonstandard_integer_type (leni, 1);
4019 gcc_assert (known_eq (GET_MODE_BITSIZE (TYPE_MODE (type)), leni));
4020 tree ptrtype = build_pointer_type_for_mode (char_type_node,
4021 ptr_mode, true);
4022 off = build_int_cst (ptrtype, 0);
4023
4024 /* Create unaligned types if needed. */
4025 tree type1 = type, type2 = type;
4026 if (TYPE_ALIGN (type1) > align1)
4027 type1 = build_aligned_type (type1, align1);
4028 if (TYPE_ALIGN (type2) > align2)
4029 type2 = build_aligned_type (type2, align2);
4030
4031 arg1 = build2_loc (loc, MEM_REF, type1, arg1, off);
4032 arg2 = build2_loc (loc, MEM_REF, type2, arg2, off);
4033 tree tem1 = fold_const_aggregate_ref (arg1);
4034 if (tem1)
4035 arg1 = tem1;
4036 tree tem2 = fold_const_aggregate_ref (arg2);
4037 if (tem2)
4038 arg2 = tem2;
4039 res = fold_convert_loc (loc, TREE_TYPE (res),
4040 fold_build2_loc (loc, NE_EXPR,
4041 boolean_type_node,
4042 arg1, arg2));
4043 gimplify_and_update_call_from_tree (&m_gsi, res);
4044 return true;
4045 }
4046 }
4047
4048 gimple_call_set_fndecl (stmt, builtin_decl_explicit (BUILT_IN_MEMCMP_EQ));
4049 return true;
4050 }
4051
4052 /* Given strinfo IDX for ARG, sets LENRNG[] to the range of lengths
4053 of the string(s) referenced by ARG if it can be determined.
4054 If the length cannot be determined, sets *SIZE to the size of
4055 the array the string is stored in, if any. If no such array is
4056 known, sets *SIZE to -1. When the strings are nul-terminated sets
4057 *NULTERM to true, otherwise to false. When nonnull uses RVALS to
4058 determine range information. Returns true on success. */
4059
4060 bool
4061 strlen_pass::get_len_or_size (gimple *stmt, tree arg, int idx,
4062 unsigned HOST_WIDE_INT lenrng[2],
4063 unsigned HOST_WIDE_INT *size, bool *nulterm)
4064 {
4065 /* Invalidate. */
4066 *size = HOST_WIDE_INT_M1U;
4067
4068 if (idx < 0)
4069 {
4070 /* IDX is the inverted constant string length. */
4071 lenrng[0] = ~idx;
4072 lenrng[1] = lenrng[0];
4073 *nulterm = true;
4074 return true;
4075 }
4076
4077 /* Set so that both LEN and ~LEN are invalid lengths, i.e., maximum
4078 possible length + 1. */
4079 lenrng[0] = lenrng[1] = HOST_WIDE_INT_MAX;
4080
4081 if (strinfo *si = idx ? get_strinfo (idx) : NULL)
4082 {
4083 /* FIXME: Handle all this in_range_strlen_dynamic. */
4084 if (!si->nonzero_chars)
4085 ;
4086 else if (tree_fits_uhwi_p (si->nonzero_chars))
4087 {
4088 lenrng[0] = tree_to_uhwi (si->nonzero_chars);
4089 *nulterm = si->full_string_p;
4090 /* Set the upper bound only if the string is known to be
4091 nul-terminated, otherwise leave it at maximum + 1. */
4092 if (*nulterm)
4093 lenrng[1] = lenrng[0];
4094 }
4095 else if (TREE_CODE (si->nonzero_chars) == SSA_NAME)
4096 {
4097 int_range_max r;
4098 if (get_range_query (cfun)->range_of_expr (r, si->nonzero_chars)
4099 && !r.undefined_p ()
4100 && !r.varying_p ())
4101 {
4102 lenrng[0] = r.lower_bound ().to_uhwi ();
4103 lenrng[1] = r.upper_bound ().to_uhwi ();
4104 *nulterm = si->full_string_p;
4105 }
4106 }
4107 }
4108
4109 if (lenrng[0] != HOST_WIDE_INT_MAX)
4110 return true;
4111
4112 /* Compute the minimum and maximum real or possible lengths. */
4113 c_strlen_data lendata = { };
4114 /* Set MAXBOUND to an arbitrary non-null non-integer node as a request
4115 to have it set to the length of the longest string in a PHI. */
4116 lendata.maxbound = arg;
4117 get_range_strlen_dynamic (arg, stmt, &lendata, ptr_qry);
4118
4119 unsigned HOST_WIDE_INT maxbound = HOST_WIDE_INT_M1U;
4120 if (tree_fits_uhwi_p (lendata.maxbound)
4121 && !integer_all_onesp (lendata.maxbound))
4122 maxbound = tree_to_uhwi (lendata.maxbound);
4123
4124 if (tree_fits_uhwi_p (lendata.minlen) && tree_fits_uhwi_p (lendata.maxlen))
4125 {
4126 unsigned HOST_WIDE_INT minlen = tree_to_uhwi (lendata.minlen);
4127 unsigned HOST_WIDE_INT maxlen = tree_to_uhwi (lendata.maxlen);
4128
4129 /* The longest string in this data model. */
4130 const unsigned HOST_WIDE_INT lenmax
4131 = tree_to_uhwi (max_object_size ()) - 2;
4132
4133 if (maxbound == HOST_WIDE_INT_M1U)
4134 {
4135 lenrng[0] = minlen;
4136 lenrng[1] = maxlen;
4137 *nulterm = minlen == maxlen;
4138 }
4139 else if (maxlen < lenmax)
4140 {
4141 *size = maxbound + 1;
4142 *nulterm = false;
4143 }
4144 else
4145 return false;
4146
4147 return true;
4148 }
4149
4150 if (maxbound != HOST_WIDE_INT_M1U
4151 && lendata.maxlen
4152 && !integer_all_onesp (lendata.maxlen))
4153 {
4154 /* Set *SIZE to LENDATA.MAXBOUND which is a conservative estimate
4155 of the longest string based on the sizes of the arrays referenced
4156 by ARG. */
4157 *size = maxbound + 1;
4158 *nulterm = false;
4159 return true;
4160 }
4161
4162 return false;
4163 }
4164
4165 /* If IDX1 and IDX2 refer to strings A and B of unequal lengths, return
4166 the result of 0 == strncmp (A, B, BOUND) (which is the same as strcmp
4167 for a sufficiently large BOUND). If the result is based on the length
4168 of one string being greater than the longest string that would fit in
4169 the array pointer to by the argument, set *PLEN and *PSIZE to
4170 the corresponding length (or its complement when the string is known
4171 to be at least as long and need not be nul-terminated) and size.
4172 Otherwise return null. */
4173
4174 tree
4175 strlen_pass::strxcmp_eqz_result (gimple *stmt, tree arg1, int idx1,
4176 tree arg2, int idx2,
4177 unsigned HOST_WIDE_INT bound,
4178 unsigned HOST_WIDE_INT len[2],
4179 unsigned HOST_WIDE_INT *psize)
4180 {
4181 /* Determine the range the length of each string is in and whether it's
4182 known to be nul-terminated, or the size of the array it's stored in. */
4183 bool nul1, nul2;
4184 unsigned HOST_WIDE_INT siz1, siz2;
4185 unsigned HOST_WIDE_INT len1rng[2], len2rng[2];
4186 if (!get_len_or_size (stmt, arg1, idx1, len1rng, &siz1, &nul1)
4187 || !get_len_or_size (stmt, arg2, idx2, len2rng, &siz2, &nul2))
4188 return NULL_TREE;
4189
4190 /* BOUND is set to HWI_M1U for strcmp and less to strncmp, and LENiRNG
4191 to HWI_MAX when invalid. Adjust the length of each string to consider
4192 to be no more than BOUND. */
4193 if (len1rng[0] < HOST_WIDE_INT_MAX && len1rng[0] > bound)
4194 len1rng[0] = bound;
4195 if (len1rng[1] < HOST_WIDE_INT_MAX && len1rng[1] > bound)
4196 len1rng[1] = bound;
4197 if (len2rng[0] < HOST_WIDE_INT_MAX && len2rng[0] > bound)
4198 len2rng[0] = bound;
4199 if (len2rng[1] < HOST_WIDE_INT_MAX && len2rng[1] > bound)
4200 len2rng[1] = bound;
4201
4202 /* Two empty strings are equal. */
4203 if (len1rng[1] == 0 && len2rng[1] == 0)
4204 return integer_one_node;
4205
4206 /* The strings are definitely unequal when the lower bound of the length
4207 of one of them is greater than the length of the longest string that
4208 would fit into the other array. */
4209 if (len1rng[0] == HOST_WIDE_INT_MAX
4210 && len2rng[0] != HOST_WIDE_INT_MAX
4211 && ((len2rng[0] < bound && len2rng[0] >= siz1)
4212 || len2rng[0] > siz1))
4213 {
4214 *psize = siz1;
4215 len[0] = len1rng[0];
4216 /* Set LEN[0] to the lower bound of ARG1's length when it's
4217 nul-terminated or to the complement of its minimum length
4218 otherwise, */
4219 len[1] = nul2 ? len2rng[0] : ~len2rng[0];
4220 return integer_zero_node;
4221 }
4222
4223 if (len2rng[0] == HOST_WIDE_INT_MAX
4224 && len1rng[0] != HOST_WIDE_INT_MAX
4225 && ((len1rng[0] < bound && len1rng[0] >= siz2)
4226 || len1rng[0] > siz2))
4227 {
4228 *psize = siz2;
4229 len[0] = nul1 ? len1rng[0] : ~len1rng[0];
4230 len[1] = len2rng[0];
4231 return integer_zero_node;
4232 }
4233
4234 /* The strings are also definitely unequal when their lengths are unequal
4235 and at least one is nul-terminated. */
4236 if (len1rng[0] != HOST_WIDE_INT_MAX
4237 && len2rng[0] != HOST_WIDE_INT_MAX
4238 && ((len1rng[1] < len2rng[0] && nul1)
4239 || (len2rng[1] < len1rng[0] && nul2)))
4240 {
4241 if (bound <= len1rng[0] || bound <= len2rng[0])
4242 *psize = bound;
4243 else
4244 *psize = HOST_WIDE_INT_M1U;
4245
4246 len[0] = len1rng[0];
4247 len[1] = len2rng[0];
4248 return integer_zero_node;
4249 }
4250
4251 /* The string lengths may be equal or unequal. Even when equal and
4252 both strings nul-terminated, without the string contents there's
4253 no way to determine whether they are equal. */
4254 return NULL_TREE;
4255 }
4256
4257 /* Diagnose pointless calls to strcmp or strncmp STMT with string
4258 arguments of lengths LEN or size SIZ and (for strncmp) BOUND,
4259 whose result is used in equality expressions that evaluate to
4260 a constant due to one argument being longer than the size of
4261 the other. */
4262
4263 static void
4264 maybe_warn_pointless_strcmp (gimple *stmt, HOST_WIDE_INT bound,
4265 unsigned HOST_WIDE_INT len[2],
4266 unsigned HOST_WIDE_INT siz)
4267 {
4268 tree lhs = gimple_call_lhs (stmt);
4269 gimple *use = use_in_zero_equality (lhs, /* exclusive = */ false);
4270 if (!use)
4271 return;
4272
4273 bool at_least = false;
4274
4275 /* Excessive LEN[i] indicates a lower bound. */
4276 if (len[0] > HOST_WIDE_INT_MAX)
4277 {
4278 at_least = true;
4279 len[0] = ~len[0];
4280 }
4281
4282 if (len[1] > HOST_WIDE_INT_MAX)
4283 {
4284 at_least = true;
4285 len[1] = ~len[1];
4286 }
4287
4288 unsigned HOST_WIDE_INT minlen = MIN (len[0], len[1]);
4289
4290 /* FIXME: Include a note pointing to the declaration of the smaller
4291 array. */
4292 location_t stmt_loc = gimple_or_expr_nonartificial_location (stmt, lhs);
4293
4294 tree callee = gimple_call_fndecl (stmt);
4295 bool warned = false;
4296 if (siz <= minlen && bound == -1)
4297 warned = warning_at (stmt_loc, OPT_Wstring_compare,
4298 (at_least
4299 ? G_("%qD of a string of length %wu or more and "
4300 "an array of size %wu evaluates to nonzero")
4301 : G_("%qD of a string of length %wu and an array "
4302 "of size %wu evaluates to nonzero")),
4303 callee, minlen, siz);
4304 else if (!at_least && siz <= HOST_WIDE_INT_MAX)
4305 {
4306 if (len[0] != HOST_WIDE_INT_MAX && len[1] != HOST_WIDE_INT_MAX)
4307 warned = warning_at (stmt_loc, OPT_Wstring_compare,
4308 "%qD of strings of length %wu and %wu "
4309 "and bound of %wu evaluates to nonzero",
4310 callee, len[0], len[1], bound);
4311 else
4312 warned = warning_at (stmt_loc, OPT_Wstring_compare,
4313 "%qD of a string of length %wu, an array "
4314 "of size %wu and bound of %wu evaluates to "
4315 "nonzero",
4316 callee, minlen, siz, bound);
4317 }
4318
4319 if (!warned)
4320 return;
4321
4322 location_t use_loc = gimple_location (use);
4323 if (LOCATION_LINE (stmt_loc) != LOCATION_LINE (use_loc))
4324 inform (use_loc, "in this expression");
4325 }
4326
4327
4328 /* Optimize a call to strcmp or strncmp either by folding it to a constant
4329 when possible or by transforming the latter to the former. Warn about
4330 calls where the length of one argument is greater than the size of
4331 the array to which the other argument points if the latter's length
4332 is not known. Return true when the call has been transformed into
4333 another and false otherwise. */
4334
4335 bool
4336 strlen_pass::handle_builtin_string_cmp ()
4337 {
4338 gcall *stmt = as_a <gcall *> (gsi_stmt (m_gsi));
4339 tree lhs = gimple_call_lhs (stmt);
4340
4341 if (!lhs)
4342 return false;
4343
4344 tree arg1 = gimple_call_arg (stmt, 0);
4345 tree arg2 = gimple_call_arg (stmt, 1);
4346 int idx1 = get_stridx (arg1, stmt);
4347 int idx2 = get_stridx (arg2, stmt);
4348
4349 /* For strncmp set to the value of the third argument if known. */
4350 HOST_WIDE_INT bound = -1;
4351 tree len = NULL_TREE;
4352 /* Extract the strncmp bound. */
4353 if (gimple_call_num_args (stmt) == 3)
4354 {
4355 len = gimple_call_arg (stmt, 2);
4356 if (tree_fits_shwi_p (len))
4357 bound = tree_to_shwi (len);
4358
4359 /* If the bound argument is NOT known, do nothing. */
4360 if (bound < 0)
4361 return false;
4362 }
4363
4364 /* Avoid folding if either argument is not a nul-terminated array.
4365 Defer warning until later. */
4366 if (!check_nul_terminated_array (NULL_TREE, arg1, len)
4367 || !check_nul_terminated_array (NULL_TREE, arg2, len))
4368 return false;
4369
4370 {
4371 /* Set to the length of one argument (or its complement if it's
4372 the lower bound of a range) and the size of the array storing
4373 the other if the result is based on the former being equal to
4374 or greater than the latter. */
4375 unsigned HOST_WIDE_INT len[2] = { HOST_WIDE_INT_MAX, HOST_WIDE_INT_MAX };
4376 unsigned HOST_WIDE_INT siz = HOST_WIDE_INT_M1U;
4377
4378 /* Try to determine if the two strings are either definitely equal
4379 or definitely unequal and if so, either fold the result to zero
4380 (when equal) or set the range of the result to ~[0, 0] otherwise. */
4381 if (tree eqz = strxcmp_eqz_result (stmt, arg1, idx1, arg2, idx2, bound,
4382 len, &siz))
4383 {
4384 if (integer_zerop (eqz))
4385 {
4386 maybe_warn_pointless_strcmp (stmt, bound, len, siz);
4387
4388 /* When the lengths of the first two string arguments are
4389 known to be unequal set the range of the result to non-zero.
4390 This allows the call to be eliminated if its result is only
4391 used in tests for equality to zero. */
4392 int_range_max nz;
4393 nz.set_nonzero (TREE_TYPE (lhs));
4394 set_range_info (lhs, nz);
4395 return false;
4396 }
4397 /* When the two strings are definitely equal (such as when they
4398 are both empty) fold the call to the constant result. */
4399 replace_call_with_value (&m_gsi, integer_zero_node);
4400 return true;
4401 }
4402 }
4403
4404 /* Return if nothing is known about the strings pointed to by ARG1
4405 and ARG2. */
4406 if (idx1 == 0 && idx2 == 0)
4407 return false;
4408
4409 /* Determine either the length or the size of each of the strings,
4410 whichever is available. */
4411 HOST_WIDE_INT cstlen1 = -1, cstlen2 = -1;
4412 HOST_WIDE_INT arysiz1 = -1, arysiz2 = -1;
4413
4414 {
4415 unsigned HOST_WIDE_INT len1rng[2], len2rng[2];
4416 unsigned HOST_WIDE_INT arsz1, arsz2;
4417 bool nulterm[2];
4418
4419 if (!get_len_or_size (stmt, arg1, idx1, len1rng, &arsz1, nulterm)
4420 || !get_len_or_size (stmt, arg2, idx2, len2rng, &arsz2, nulterm + 1))
4421 return false;
4422
4423 if (len1rng[0] == len1rng[1] && len1rng[0] < HOST_WIDE_INT_MAX)
4424 cstlen1 = len1rng[0];
4425 else if (arsz1 < HOST_WIDE_INT_M1U)
4426 arysiz1 = arsz1;
4427
4428 if (len2rng[0] == len2rng[1] && len2rng[0] < HOST_WIDE_INT_MAX)
4429 cstlen2 = len2rng[0];
4430 else if (arsz2 < HOST_WIDE_INT_M1U)
4431 arysiz2 = arsz2;
4432 }
4433
4434 /* Bail if neither the string length nor the size of the array
4435 it is stored in can be determined. */
4436 if ((cstlen1 < 0 && arysiz1 < 0)
4437 || (cstlen2 < 0 && arysiz2 < 0)
4438 || (cstlen1 < 0 && cstlen2 < 0))
4439 return false;
4440
4441 if (cstlen1 >= 0)
4442 ++cstlen1;
4443 if (cstlen2 >= 0)
4444 ++cstlen2;
4445
4446 /* The exact number of characters to compare. */
4447 HOST_WIDE_INT cmpsiz;
4448 if (cstlen1 >= 0 && cstlen2 >= 0)
4449 cmpsiz = MIN (cstlen1, cstlen2);
4450 else if (cstlen1 >= 0)
4451 cmpsiz = cstlen1;
4452 else
4453 cmpsiz = cstlen2;
4454 if (bound >= 0)
4455 cmpsiz = MIN (cmpsiz, bound);
4456 /* The size of the array in which the unknown string is stored. */
4457 HOST_WIDE_INT varsiz = arysiz1 < 0 ? arysiz2 : arysiz1;
4458
4459 if ((varsiz < 0 || cmpsiz < varsiz) && use_in_zero_equality (lhs))
4460 {
4461 /* If the known length is less than the size of the other array
4462 and the strcmp result is only used to test equality to zero,
4463 transform the call to the equivalent _eq call. */
4464 if (tree fn = builtin_decl_implicit (bound < 0 ? BUILT_IN_STRCMP_EQ
4465 : BUILT_IN_STRNCMP_EQ))
4466 {
4467 tree n = build_int_cst (size_type_node, cmpsiz);
4468 update_gimple_call (&m_gsi, fn, 3, arg1, arg2, n);
4469 return true;
4470 }
4471 }
4472
4473 return false;
4474 }
4475
4476 /* Handle a POINTER_PLUS_EXPR statement.
4477 For p = "abcd" + 2; compute associated length, or if
4478 p = q + off is pointing to a '\0' character of a string, call
4479 zero_length_string on it. */
4480
4481 void
4482 strlen_pass::handle_pointer_plus ()
4483 {
4484 gimple *stmt = gsi_stmt (m_gsi);
4485 tree lhs = gimple_assign_lhs (stmt), off;
4486 int idx = get_stridx (gimple_assign_rhs1 (stmt), stmt);
4487 strinfo *si, *zsi;
4488
4489 if (idx == 0)
4490 return;
4491
4492 if (idx < 0)
4493 {
4494 tree off = gimple_assign_rhs2 (stmt);
4495 if (tree_fits_uhwi_p (off)
4496 && tree_to_uhwi (off) <= (unsigned HOST_WIDE_INT) ~idx)
4497 ssa_ver_to_stridx[SSA_NAME_VERSION (lhs)]
4498 = ~(~idx - (int) tree_to_uhwi (off));
4499 return;
4500 }
4501
4502 si = get_strinfo (idx);
4503 if (si == NULL || si->nonzero_chars == NULL_TREE)
4504 return;
4505
4506 off = gimple_assign_rhs2 (stmt);
4507 zsi = NULL;
4508 if (si->full_string_p && operand_equal_p (si->nonzero_chars, off, 0))
4509 zsi = zero_length_string (lhs, si);
4510 else if (TREE_CODE (off) == SSA_NAME)
4511 {
4512 gimple *def_stmt = SSA_NAME_DEF_STMT (off);
4513 if (gimple_assign_single_p (def_stmt)
4514 && si->full_string_p
4515 && operand_equal_p (si->nonzero_chars,
4516 gimple_assign_rhs1 (def_stmt), 0))
4517 zsi = zero_length_string (lhs, si);
4518 }
4519 if (zsi != NULL
4520 && si->endptr != NULL_TREE
4521 && si->endptr != lhs
4522 && TREE_CODE (si->endptr) == SSA_NAME)
4523 {
4524 enum tree_code rhs_code
4525 = useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (si->endptr))
4526 ? SSA_NAME : NOP_EXPR;
4527 gimple_assign_set_rhs_with_ops (&m_gsi, rhs_code, si->endptr);
4528 gcc_assert (gsi_stmt (m_gsi) == stmt);
4529 update_stmt (stmt);
4530 }
4531 }
4532
4533 /* Set LENRANGE to the number of nonzero bytes for a store of TYPE and
4534 clear all flags. Return true on success and false on failure. */
4535
4536 static bool
4537 nonzero_bytes_for_type (tree type, unsigned lenrange[3],
4538 bool *nulterm, bool *allnul, bool *allnonnul)
4539 {
4540 /* Use the size of the type of the expression as the size of the store,
4541 and set the upper bound of the length range to that of the size.
4542 Nothing is known about the contents so clear all flags. */
4543 tree typesize = TYPE_SIZE_UNIT (type);
4544 if (!type)
4545 return false;
4546
4547 if (!tree_fits_uhwi_p (typesize))
4548 return false;
4549
4550 unsigned HOST_WIDE_INT sz = tree_to_uhwi (typesize);
4551 if (sz > UINT_MAX)
4552 return false;
4553
4554 lenrange[2] = sz;
4555 lenrange[1] = lenrange[2] ? lenrange[2] - 1 : 0;
4556 lenrange[0] = 0;
4557 *nulterm = false;
4558 *allnul = false;
4559 *allnonnul = false;
4560 return true;
4561 }
4562
4563 /* Recursively determine the minimum and maximum number of leading nonzero
4564 bytes in the representation of EXP at memory state VUSE and set
4565 LENRANGE[0] and LENRANGE[1] to each.
4566 Sets LENRANGE[2] to the total size of the access (which may be less
4567 than LENRANGE[1] when what's being referenced by EXP is a pointer
4568 rather than an array).
4569 Sets *NULTERM if the representation contains a zero byte, sets *ALLNUL
4570 if all the bytes are zero, and *ALLNONNUL is all are nonzero.
4571 OFFSET and NBYTES are the offset into the representation and
4572 the size of the access to it determined from an ADDR_EXPR (i.e.,
4573 a pointer) or MEM_REF or zero for other expressions.
4574 Uses RVALS to determine range information.
4575 Avoids recursing deeper than the limits in SNLIM allow.
4576 Returns true on success and false otherwise. */
4577
4578 bool
4579 strlen_pass::count_nonzero_bytes (tree exp, tree vuse, gimple *stmt,
4580 unsigned HOST_WIDE_INT offset,
4581 unsigned HOST_WIDE_INT nbytes,
4582 unsigned lenrange[3], bool *nulterm,
4583 bool *allnul, bool *allnonnul,
4584 ssa_name_limit_t &snlim)
4585 {
4586 if (TREE_CODE (exp) == SSA_NAME)
4587 {
4588 /* Handle non-zero single-character stores specially. */
4589 tree type = TREE_TYPE (exp);
4590 if (TREE_CODE (type) == INTEGER_TYPE
4591 && TYPE_MODE (type) == TYPE_MODE (char_type_node)
4592 && TYPE_PRECISION (type) == TYPE_PRECISION (char_type_node)
4593 && tree_expr_nonzero_p (exp))
4594 {
4595 /* If the character EXP is known to be non-zero (even if its
4596 exact value is not known) recurse once to set the range
4597 for an arbitrary constant. */
4598 exp = build_int_cst (type, 1);
4599 return count_nonzero_bytes (exp, vuse, stmt,
4600 offset, 1, lenrange,
4601 nulterm, allnul, allnonnul, snlim);
4602 }
4603
4604 gimple *g = SSA_NAME_DEF_STMT (exp);
4605 if (gimple_assign_single_p (g))
4606 {
4607 exp = gimple_assign_rhs1 (g);
4608 if (!DECL_P (exp)
4609 && TREE_CODE (exp) != CONSTRUCTOR
4610 && TREE_CODE (exp) != MEM_REF)
4611 return false;
4612 /* Handle DECLs, CONSTRUCTOR and MEM_REF below. */
4613 stmt = g;
4614 }
4615 else if (gimple_code (g) == GIMPLE_PHI)
4616 {
4617 /* Avoid processing an SSA_NAME that has already been visited
4618 or if an SSA_NAME limit has been reached. Indicate success
4619 if the former and failure if the latter. */
4620 if (int res = snlim.next_phi (exp))
4621 return res > 0;
4622
4623 /* Determine the minimum and maximum from the PHI arguments. */
4624 unsigned int n = gimple_phi_num_args (g);
4625 for (unsigned i = 0; i != n; i++)
4626 {
4627 tree def = gimple_phi_arg_def (g, i);
4628 if (!count_nonzero_bytes (def, vuse, g,
4629 offset, nbytes, lenrange, nulterm,
4630 allnul, allnonnul, snlim))
4631 return false;
4632 }
4633
4634 return true;
4635 }
4636 }
4637
4638 if (TREE_CODE (exp) == CONSTRUCTOR)
4639 {
4640 if (nbytes)
4641 /* If NBYTES has already been determined by an outer MEM_REF
4642 fail rather than overwriting it (this shouldn't happen). */
4643 return false;
4644
4645 tree type = TREE_TYPE (exp);
4646 tree size = TYPE_SIZE_UNIT (type);
4647 if (!size || !tree_fits_uhwi_p (size))
4648 return false;
4649
4650 unsigned HOST_WIDE_INT byte_size = tree_to_uhwi (size);
4651 if (byte_size <= offset)
4652 return false;
4653
4654 nbytes = byte_size - offset;
4655 }
4656
4657 if (TREE_CODE (exp) == MEM_REF)
4658 {
4659 if (nbytes)
4660 return false;
4661
4662 tree arg = TREE_OPERAND (exp, 0);
4663 tree off = TREE_OPERAND (exp, 1);
4664
4665 if (TREE_CODE (off) != INTEGER_CST || !tree_fits_uhwi_p (off))
4666 return false;
4667
4668 unsigned HOST_WIDE_INT wioff = tree_to_uhwi (off);
4669 if (INT_MAX < wioff)
4670 return false;
4671
4672 offset += wioff;
4673 if (INT_MAX < offset)
4674 return false;
4675
4676 /* The size of the MEM_REF access determines the number of bytes. */
4677 tree type = TREE_TYPE (exp);
4678 tree typesize = TYPE_SIZE_UNIT (type);
4679 if (!typesize || !tree_fits_uhwi_p (typesize))
4680 return false;
4681 nbytes = tree_to_uhwi (typesize);
4682 if (!nbytes)
4683 return false;
4684
4685 /* Handle MEM_REF = SSA_NAME types of assignments. */
4686 return count_nonzero_bytes_addr (arg, vuse, stmt,
4687 offset, nbytes, lenrange, nulterm,
4688 allnul, allnonnul, snlim);
4689 }
4690
4691 if (VAR_P (exp) || TREE_CODE (exp) == CONST_DECL)
4692 {
4693 /* If EXP can be folded into a constant use the result. Otherwise
4694 proceed to use EXP to determine a range of the result. */
4695 if (tree fold_exp = ctor_for_folding (exp))
4696 if (fold_exp != error_mark_node)
4697 exp = fold_exp;
4698 }
4699
4700 const char *prep = NULL;
4701 if (TREE_CODE (exp) == STRING_CST)
4702 {
4703 unsigned nchars = TREE_STRING_LENGTH (exp);
4704 if (nchars <= offset)
4705 return false;
4706
4707 if (!nbytes)
4708 /* If NBYTES hasn't been determined earlier, either from ADDR_EXPR
4709 (i.e., it's the size of a pointer), or from MEM_REF (as the size
4710 of the access), set it here to the size of the string, including
4711 all internal and trailing nuls if the string has any. */
4712 nbytes = nchars - offset;
4713 else if (nchars - offset < nbytes)
4714 return false;
4715
4716 prep = TREE_STRING_POINTER (exp) + offset;
4717 }
4718
4719 unsigned char buf[256];
4720 if (!prep)
4721 {
4722 if (CHAR_BIT != 8 || BITS_PER_UNIT != 8 || offset > INT_MAX)
4723 return false;
4724 /* If the pointer to representation hasn't been set above
4725 for STRING_CST point it at the buffer. */
4726 prep = reinterpret_cast <char *>(buf);
4727 /* Try to extract the representation of the constant object
4728 or expression starting from the offset. */
4729 unsigned repsize = native_encode_expr (exp, buf, sizeof buf, offset);
4730 if (repsize < nbytes)
4731 {
4732 /* Handle vector { 0x12345678, 0x23003412, x_1(D), y_2(D) }
4733 and similar cases. Even when not all the elements are constant,
4734 we can perhaps figure out something from the constant ones
4735 and assume the others can be anything. */
4736 if (TREE_CODE (exp) == CONSTRUCTOR
4737 && CONSTRUCTOR_NELTS (exp)
4738 && VECTOR_TYPE_P (TREE_TYPE (exp))
4739 && nbytes <= sizeof buf)
4740 {
4741 tree v0 = CONSTRUCTOR_ELT (exp, 0)->value;
4742 unsigned HOST_WIDE_INT elt_sz
4743 = int_size_in_bytes (TREE_TYPE (v0));
4744 unsigned int i, s = 0;
4745 tree v, idx;
4746 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (exp), i, idx, v)
4747 {
4748 if (idx
4749 && (VECTOR_TYPE_P (TREE_TYPE (v0))
4750 || !tree_fits_uhwi_p (idx)
4751 || tree_to_uhwi (idx) != i))
4752 {
4753 s = 0;
4754 break;
4755 }
4756 if ((i + 1) * elt_sz <= offset)
4757 continue;
4758 unsigned int o = 0;
4759 if (i * elt_sz < offset)
4760 o = offset % elt_sz;
4761 repsize = native_encode_expr (v, buf + s,
4762 sizeof (buf) - s, o);
4763 if (repsize != elt_sz - o)
4764 break;
4765 s += repsize;
4766 }
4767 if (s != 0 && s < nbytes)
4768 {
4769 unsigned HOST_WIDE_INT n = strnlen (prep, s);
4770 if (n < lenrange[0])
4771 lenrange[0] = n;
4772 if (lenrange[1] < n && n != s)
4773 lenrange[1] = n;
4774 if (lenrange[2] < nbytes)
4775 lenrange[2] = nbytes;
4776 /* We haven't processed all bytes, the rest are unknown.
4777 So, clear NULTERM if none of the initial bytes are
4778 zero, and clear ALLNUL and ALLNONNULL because we don't
4779 know about the remaining bytes. */
4780 if (n == s)
4781 *nulterm = false;
4782 *allnul = false;
4783 *allnonnul = false;
4784 return true;
4785 }
4786 else if (s != nbytes)
4787 {
4788 /* See below. */
4789 lenrange[0] = 0;
4790 prep = NULL;
4791 }
4792 }
4793 else
4794 {
4795 /* This should only happen when REPSIZE is zero because EXP
4796 doesn't denote an object with a known initializer, except
4797 perhaps when the reference reads past its end. */
4798 lenrange[0] = 0;
4799 prep = NULL;
4800 }
4801 }
4802 else if (!nbytes)
4803 nbytes = repsize;
4804 else if (nbytes < repsize)
4805 return false;
4806 }
4807
4808 if (!nbytes)
4809 return nonzero_bytes_for_type (TREE_TYPE (exp), lenrange,
4810 nulterm, allnul, allnonnul);
4811
4812 /* Compute the number of leading nonzero bytes in the representation
4813 and update the minimum and maximum. */
4814 unsigned HOST_WIDE_INT n = prep ? strnlen (prep, nbytes) : nbytes;
4815
4816 if (n < lenrange[0])
4817 lenrange[0] = n;
4818 if (lenrange[1] < n)
4819 lenrange[1] = n;
4820
4821 /* Set the size of the representation. */
4822 if (lenrange[2] < nbytes)
4823 lenrange[2] = nbytes;
4824
4825 /* Clear NULTERM if none of the bytes is zero. */
4826 if (n == nbytes)
4827 *nulterm = false;
4828
4829 if (n)
4830 {
4831 /* When the initial number of non-zero bytes N is non-zero, reset
4832 *ALLNUL; if N is less than that the size of the representation
4833 also clear *ALLNONNUL. */
4834 *allnul = false;
4835 if (n < nbytes)
4836 *allnonnul = false;
4837 }
4838 else if (*allnul || *allnonnul)
4839 {
4840 *allnonnul = false;
4841
4842 if (*allnul)
4843 {
4844 /* When either ALLNUL is set and N is zero, also determine
4845 whether all subsequent bytes after the first one (which
4846 is nul) are zero or nonzero and clear ALLNUL if not. */
4847 for (const char *p = prep; p != prep + nbytes; ++p)
4848 if (*p)
4849 {
4850 *allnul = false;
4851 break;
4852 }
4853 }
4854 }
4855
4856 return true;
4857 }
4858
4859 /* Like count_nonzero_bytes, but instead of counting bytes in EXP, count
4860 bytes that are pointed to by EXP, which should be a pointer. */
4861
4862 bool
4863 strlen_pass::count_nonzero_bytes_addr (tree exp, tree vuse, gimple *stmt,
4864 unsigned HOST_WIDE_INT offset,
4865 unsigned HOST_WIDE_INT nbytes,
4866 unsigned lenrange[3], bool *nulterm,
4867 bool *allnul, bool *allnonnul,
4868 ssa_name_limit_t &snlim)
4869 {
4870 int idx = get_stridx (exp, stmt);
4871 if (idx > 0)
4872 {
4873 /* get_strinfo reflects string lengths before the current statement,
4874 where the current statement is the outermost count_nonzero_bytes
4875 stmt. If there are any stores in between stmt and that
4876 current statement, the string length information might describe
4877 something significantly different. */
4878 if (gimple_vuse (stmt) != vuse)
4879 return false;
4880
4881 strinfo *si = get_strinfo (idx);
4882 if (!si)
4883 return false;
4884
4885 /* Handle both constant lengths as well non-constant lengths
4886 in some range. */
4887 unsigned HOST_WIDE_INT minlen, maxlen;
4888 if (tree_fits_shwi_p (si->nonzero_chars))
4889 minlen = maxlen = tree_to_shwi (si->nonzero_chars);
4890 else if (si->nonzero_chars
4891 && TREE_CODE (si->nonzero_chars) == SSA_NAME)
4892 {
4893 int_range_max vr;
4894 if (!ptr_qry.rvals->range_of_expr (vr, si->nonzero_chars, stmt)
4895 || vr.undefined_p ()
4896 || vr.varying_p ())
4897 return false;
4898
4899 minlen = vr.lower_bound ().to_uhwi ();
4900 maxlen = vr.upper_bound ().to_uhwi ();
4901 }
4902 else
4903 return false;
4904
4905 if (maxlen < offset)
4906 return false;
4907
4908 minlen = minlen < offset ? 0 : minlen - offset;
4909 maxlen -= offset;
4910 if (maxlen + 1 < nbytes)
4911 return false;
4912
4913 if (nbytes <= minlen || !si->full_string_p)
4914 *nulterm = false;
4915
4916 if (nbytes < minlen)
4917 {
4918 minlen = nbytes;
4919 if (nbytes < maxlen)
4920 maxlen = nbytes;
4921 }
4922
4923 if (!si->full_string_p)
4924 maxlen = nbytes;
4925
4926 if (minlen < lenrange[0])
4927 lenrange[0] = minlen;
4928 if (lenrange[1] < maxlen)
4929 lenrange[1] = maxlen;
4930
4931 if (lenrange[2] < nbytes)
4932 lenrange[2] = nbytes;
4933
4934 /* Since only the length of the string are known and not its contents,
4935 clear ALLNUL and ALLNONNUL purely on the basis of the length. */
4936 *allnul = false;
4937 if (minlen < nbytes)
4938 *allnonnul = false;
4939
4940 return true;
4941 }
4942
4943 if (TREE_CODE (exp) == ADDR_EXPR)
4944 return count_nonzero_bytes (TREE_OPERAND (exp, 0), vuse, stmt,
4945 offset, nbytes,
4946 lenrange, nulterm, allnul, allnonnul, snlim);
4947
4948 if (TREE_CODE (exp) == SSA_NAME)
4949 {
4950 gimple *g = SSA_NAME_DEF_STMT (exp);
4951 if (gimple_code (g) == GIMPLE_PHI)
4952 {
4953 /* Avoid processing an SSA_NAME that has already been visited
4954 or if an SSA_NAME limit has been reached. Indicate success
4955 if the former and failure if the latter. */
4956 if (int res = snlim.next_phi (exp))
4957 return res > 0;
4958
4959 /* Determine the minimum and maximum from the PHI arguments. */
4960 unsigned int n = gimple_phi_num_args (g);
4961 for (unsigned i = 0; i != n; i++)
4962 {
4963 tree def = gimple_phi_arg_def (g, i);
4964 if (!count_nonzero_bytes_addr (def, vuse, g,
4965 offset, nbytes, lenrange,
4966 nulterm, allnul, allnonnul,
4967 snlim))
4968 return false;
4969 }
4970
4971 return true;
4972 }
4973 }
4974
4975 /* Otherwise we don't know anything. */
4976 lenrange[0] = 0;
4977 if (lenrange[1] < nbytes)
4978 lenrange[1] = nbytes;
4979 if (lenrange[2] < nbytes)
4980 lenrange[2] = nbytes;
4981 *nulterm = false;
4982 *allnul = false;
4983 *allnonnul = false;
4984 return true;
4985 }
4986
4987 /* Same as above except with an implicit SSA_NAME limit. When EXPR_OR_TYPE
4988 is a type rather than an expression use its size to compute the range.
4989 RVALS is used to determine ranges of dynamically computed string lengths
4990 (the results of strlen). */
4991
4992 bool
4993 strlen_pass::count_nonzero_bytes (tree expr_or_type, gimple *stmt,
4994 unsigned lenrange[3], bool *nulterm,
4995 bool *allnul, bool *allnonnul)
4996 {
4997 if (TYPE_P (expr_or_type))
4998 return nonzero_bytes_for_type (expr_or_type, lenrange,
4999 nulterm, allnul, allnonnul);
5000
5001 /* Set to optimistic values so the caller doesn't have to worry about
5002 initializing these and to what. On success, the function will clear
5003 these if it determines their values are different but being recursive
5004 it never sets either to true. On failure, their values are
5005 unspecified. */
5006 *nulterm = true;
5007 *allnul = true;
5008 *allnonnul = true;
5009
5010 ssa_name_limit_t snlim;
5011 tree expr = expr_or_type;
5012 return count_nonzero_bytes (expr, gimple_vuse (stmt), stmt,
5013 0, 0, lenrange, nulterm, allnul, allnonnul,
5014 snlim);
5015 }
5016
5017 /* Handle a single or multibyte store other than by a built-in function,
5018 either via a single character assignment or by multi-byte assignment
5019 either via MEM_REF or via a type other than char (such as in
5020 '*(int*)a = 12345'). Return true to let the caller advance *GSI to
5021 the next statement in the basic block and false otherwise. */
5022
5023 bool
5024 strlen_pass::handle_store (bool *zero_write)
5025 {
5026 gimple *stmt = gsi_stmt (m_gsi);
5027 /* The LHS and RHS of the store. The RHS is null if STMT is a function
5028 call. STORETYPE is the type of the store (determined from either
5029 the RHS of the assignment statement or the LHS of a function call. */
5030 tree lhs, rhs, storetype;
5031 if (is_gimple_assign (stmt))
5032 {
5033 lhs = gimple_assign_lhs (stmt);
5034 rhs = gimple_assign_rhs1 (stmt);
5035 storetype = TREE_TYPE (rhs);
5036 }
5037 else if (is_gimple_call (stmt))
5038 {
5039 lhs = gimple_call_lhs (stmt);
5040 rhs = NULL_TREE;
5041 storetype = TREE_TYPE (lhs);
5042 }
5043 else
5044 return true;
5045
5046 tree ssaname = NULL_TREE;
5047 strinfo *si = NULL;
5048 int idx = -1;
5049
5050 range_query *const rvals = ptr_qry.rvals;
5051
5052 /* The offset of the first byte in LHS modified by the store. */
5053 unsigned HOST_WIDE_INT offset = 0;
5054
5055 if (TREE_CODE (lhs) == MEM_REF
5056 && TREE_CODE (TREE_OPERAND (lhs, 0)) == SSA_NAME)
5057 {
5058 tree mem_offset = TREE_OPERAND (lhs, 1);
5059 if (tree_fits_uhwi_p (mem_offset))
5060 {
5061 /* Get the strinfo for the base, and use it if it starts with at
5062 least OFFSET nonzero characters. This is trivially true if
5063 OFFSET is zero. */
5064 offset = tree_to_uhwi (mem_offset);
5065 idx = get_stridx (TREE_OPERAND (lhs, 0), stmt);
5066 if (idx > 0)
5067 si = get_strinfo (idx);
5068 if (offset == 0)
5069 ssaname = TREE_OPERAND (lhs, 0);
5070 else if (si == NULL
5071 || compare_nonzero_chars (si, stmt, offset, rvals) < 0)
5072 {
5073 *zero_write = rhs ? initializer_zerop (rhs) : false;
5074
5075 bool dummy;
5076 unsigned lenrange[] = { UINT_MAX, 0, 0 };
5077 if (count_nonzero_bytes (rhs ? rhs : storetype, stmt, lenrange,
5078 &dummy, &dummy, &dummy))
5079 maybe_warn_overflow (stmt, true, lenrange[2]);
5080
5081 return true;
5082 }
5083 }
5084 }
5085 else
5086 {
5087 idx = get_addr_stridx (lhs, stmt, NULL_TREE, &offset, rvals);
5088 if (idx > 0)
5089 si = get_strinfo (idx);
5090 }
5091
5092 /* Minimum and maximum leading non-zero bytes and the size of the store. */
5093 unsigned lenrange[] = { UINT_MAX, 0, 0 };
5094
5095 /* Set to the minimum length of the string being assigned if known. */
5096 unsigned HOST_WIDE_INT rhs_minlen;
5097
5098 /* STORING_NONZERO_P is true iff not all stored characters are zero.
5099 STORING_ALL_NONZERO_P is true if all stored characters are zero.
5100 STORING_ALL_ZEROS_P is true iff all stored characters are zero.
5101 Both are false when it's impossible to determine which is true. */
5102 bool storing_nonzero_p;
5103 bool storing_all_nonzero_p;
5104 bool storing_all_zeros_p;
5105 /* FULL_STRING_P is set when the stored sequence of characters form
5106 a nul-terminated string. */
5107 bool full_string_p;
5108
5109 const bool ranges_valid
5110 = count_nonzero_bytes (rhs ? rhs : storetype, stmt,
5111 lenrange, &full_string_p,
5112 &storing_all_zeros_p, &storing_all_nonzero_p);
5113
5114 if (ranges_valid)
5115 {
5116 rhs_minlen = lenrange[0];
5117 storing_nonzero_p = lenrange[1] > 0;
5118 *zero_write = storing_all_zeros_p;
5119
5120 maybe_warn_overflow (stmt, true, lenrange[2]);
5121 }
5122 else
5123 {
5124 rhs_minlen = HOST_WIDE_INT_M1U;
5125 full_string_p = false;
5126 storing_nonzero_p = false;
5127 storing_all_zeros_p = false;
5128 storing_all_nonzero_p = false;
5129 }
5130
5131 if (si != NULL)
5132 {
5133 /* The count_nonzero_bytes call above might have unshared si.
5134 Fetch it again from the vector. */
5135 si = get_strinfo (idx);
5136 /* The corresponding element is set to 1 if the first and last
5137 element, respectively, of the sequence of characters being
5138 written over the string described by SI ends before
5139 the terminating nul (if it has one), to zero if the nul is
5140 being overwritten but not beyond, or negative otherwise. */
5141 int store_before_nul[2];
5142 if (ranges_valid)
5143 {
5144 /* The offset of the last stored byte. */
5145 unsigned HOST_WIDE_INT endoff = offset + lenrange[2] - 1;
5146 store_before_nul[0]
5147 = compare_nonzero_chars (si, stmt, offset, rvals);
5148 if (endoff == offset)
5149 store_before_nul[1] = store_before_nul[0];
5150 else
5151 store_before_nul[1]
5152 = compare_nonzero_chars (si, stmt, endoff, rvals);
5153 }
5154 else
5155 {
5156 store_before_nul[0]
5157 = compare_nonzero_chars (si, stmt, offset, rvals);
5158 store_before_nul[1] = store_before_nul[0];
5159 gcc_assert (offset == 0 || store_before_nul[0] >= 0);
5160 }
5161
5162 if (storing_all_zeros_p
5163 && store_before_nul[0] == 0
5164 && store_before_nul[1] == 0
5165 && si->full_string_p)
5166 {
5167 /* When overwriting a '\0' with a '\0', the store can be removed
5168 if we know it has been stored in the current function. */
5169 if (!stmt_could_throw_p (cfun, stmt) && si->writable)
5170 {
5171 unlink_stmt_vdef (stmt);
5172 release_defs (stmt);
5173 gsi_remove (&m_gsi, true);
5174 return false;
5175 }
5176 else
5177 {
5178 si->writable = true;
5179 gsi_next (&m_gsi);
5180 return false;
5181 }
5182 }
5183
5184 if (store_before_nul[1] > 0
5185 && storing_nonzero_p
5186 && lenrange[0] == lenrange[1]
5187 && lenrange[0] == lenrange[2]
5188 && TREE_CODE (storetype) == INTEGER_TYPE)
5189 {
5190 /* Handle a store of one or more non-nul characters that ends
5191 before the terminating nul of the destination and so does
5192 not affect its length
5193 If si->nonzero_chars > OFFSET, we aren't overwriting '\0',
5194 and if we aren't storing '\0', we know that the length of
5195 the string and any other zero terminated string in memory
5196 remains the same. In that case we move to the next gimple
5197 statement and return to signal the caller that it shouldn't
5198 invalidate anything.
5199
5200 This is beneficial for cases like:
5201
5202 char p[20];
5203 void foo (char *q)
5204 {
5205 strcpy (p, "foobar");
5206 size_t len = strlen (p); // can be folded to 6
5207 size_t len2 = strlen (q); // has to be computed
5208 p[0] = 'X';
5209 size_t len3 = strlen (p); // can be folded to 6
5210 size_t len4 = strlen (q); // can be folded to len2
5211 bar (len, len2, len3, len4);
5212 } */
5213 gsi_next (&m_gsi);
5214 return false;
5215 }
5216
5217 if (storing_nonzero_p
5218 || storing_all_zeros_p
5219 || (full_string_p && lenrange[1] == 0)
5220 || (offset != 0 && store_before_nul[1] > 0))
5221 {
5222 /* When STORING_NONZERO_P, we know that the string will start
5223 with at least OFFSET + 1 nonzero characters. If storing
5224 a single character, set si->NONZERO_CHARS to the result.
5225 If storing multiple characters, try to determine the number
5226 of leading non-zero characters and set si->NONZERO_CHARS to
5227 the result instead.
5228
5229 When STORING_ALL_ZEROS_P, or the first byte written is zero,
5230 i.e. FULL_STRING_P && LENRANGE[1] == 0, we know that the
5231 string is now OFFSET characters long.
5232
5233 Otherwise, we're storing an unknown value at offset OFFSET,
5234 so need to clip the nonzero_chars to OFFSET.
5235 Use the minimum length of the string (or individual character)
5236 being stored if it's known. Otherwise, STORING_NONZERO_P
5237 guarantees it's at least 1. */
5238 HOST_WIDE_INT len
5239 = storing_nonzero_p && ranges_valid ? lenrange[0] : 1;
5240 location_t loc = gimple_location (stmt);
5241 tree oldlen = si->nonzero_chars;
5242 if (store_before_nul[1] == 0 && si->full_string_p)
5243 /* We're overwriting the nul terminator with a nonzero or
5244 unknown character. If the previous stmt was a memcpy,
5245 its length may be decreased. */
5246 adjust_last_stmt (si, stmt, false);
5247 si = unshare_strinfo (si);
5248 if (storing_nonzero_p)
5249 {
5250 gcc_assert (len >= 0);
5251 si->nonzero_chars = build_int_cst (size_type_node, offset + len);
5252 }
5253 else
5254 si->nonzero_chars = build_int_cst (size_type_node, offset);
5255
5256 /* Set FULL_STRING_P only if the length of the strings being
5257 written is the same, and clear it if the strings have
5258 different lengths. In the latter case the length stored
5259 in si->NONZERO_CHARS becomes the lower bound.
5260 FIXME: Handle the upper bound of the length if possible. */
5261 si->full_string_p = full_string_p && lenrange[0] == lenrange[1];
5262
5263 if (storing_all_zeros_p
5264 && ssaname
5265 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ssaname))
5266 si->endptr = ssaname;
5267 else
5268 si->endptr = NULL;
5269 si->next = 0;
5270 si->stmt = NULL;
5271 si->writable = true;
5272 si->dont_invalidate = true;
5273 if (oldlen)
5274 {
5275 tree adj = fold_build2_loc (loc, MINUS_EXPR, size_type_node,
5276 si->nonzero_chars, oldlen);
5277 adjust_related_strinfos (loc, si, adj);
5278 }
5279 else
5280 si->prev = 0;
5281 }
5282 }
5283 else if (idx == 0 && (storing_all_zeros_p || storing_nonzero_p))
5284 {
5285 if (ssaname)
5286 idx = new_stridx (ssaname);
5287 else
5288 idx = new_addr_stridx (lhs);
5289 if (idx != 0)
5290 {
5291 tree ptr = (ssaname ? ssaname : build_fold_addr_expr (lhs));
5292
5293 HOST_WIDE_INT slen;
5294 if (storing_all_zeros_p)
5295 slen = 0;
5296 else if (storing_nonzero_p && ranges_valid)
5297 {
5298 /* FIXME: Handle the upper bound of the length when
5299 LENRANGE[0] != LENRANGE[1]. */
5300 slen = lenrange[0];
5301 if (lenrange[0] != lenrange[1])
5302 /* Set the minimum length but ignore the maximum
5303 for now. */
5304 full_string_p = false;
5305 }
5306 else
5307 slen = -1;
5308
5309 tree len = (slen <= 0
5310 ? size_zero_node
5311 : build_int_cst (size_type_node, slen));
5312 si = new_strinfo (ptr, idx, len, slen >= 0 && full_string_p);
5313 set_strinfo (idx, si);
5314 if (storing_all_zeros_p
5315 && ssaname
5316 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ssaname))
5317 si->endptr = ssaname;
5318 si->dont_invalidate = true;
5319 si->writable = true;
5320 }
5321 }
5322 else if (idx == 0
5323 && rhs_minlen < HOST_WIDE_INT_M1U
5324 && ssaname == NULL_TREE
5325 && TREE_CODE (TREE_TYPE (lhs)) == ARRAY_TYPE)
5326 {
5327 HOST_WIDE_INT a = int_size_in_bytes (TREE_TYPE (lhs));
5328 if (a > 0 && (unsigned HOST_WIDE_INT) a > rhs_minlen)
5329 {
5330 int idx = new_addr_stridx (lhs);
5331 if (idx != 0)
5332 {
5333 si = new_strinfo (build_fold_addr_expr (lhs), idx,
5334 build_int_cst (size_type_node, rhs_minlen),
5335 full_string_p);
5336 set_strinfo (idx, si);
5337 si->dont_invalidate = true;
5338 }
5339 }
5340 }
5341
5342 if (si != NULL && offset == 0 && storing_all_zeros_p && lenrange[2] == 1)
5343 {
5344 /* For single-byte stores only, allow adjust_last_stmt to remove
5345 the statement if the stored '\0' is immediately overwritten. */
5346 laststmt.stmt = stmt;
5347 laststmt.len = build_int_cst (size_type_node, 1);
5348 laststmt.stridx = si->idx;
5349 }
5350 return true;
5351 }
5352
5353 /* Try to fold strstr (s, t) eq/ne s to strncmp (s, t, strlen (t)) eq/ne 0. */
5354
5355 static void
5356 fold_strstr_to_strncmp (tree rhs1, tree rhs2, gimple *stmt)
5357 {
5358 if (TREE_CODE (rhs1) != SSA_NAME
5359 || TREE_CODE (rhs2) != SSA_NAME)
5360 return;
5361
5362 gimple *call_stmt = NULL;
5363 for (int pass = 0; pass < 2; pass++)
5364 {
5365 gimple *g = SSA_NAME_DEF_STMT (rhs1);
5366 if (gimple_call_builtin_p (g, BUILT_IN_STRSTR)
5367 && has_single_use (rhs1)
5368 && gimple_call_arg (g, 0) == rhs2)
5369 {
5370 call_stmt = g;
5371 break;
5372 }
5373 std::swap (rhs1, rhs2);
5374 }
5375
5376 if (call_stmt)
5377 {
5378 tree arg0 = gimple_call_arg (call_stmt, 0);
5379
5380 if (arg0 == rhs2)
5381 {
5382 tree arg1 = gimple_call_arg (call_stmt, 1);
5383 tree arg1_len = NULL_TREE;
5384 int idx = get_stridx (arg1, call_stmt);
5385
5386 if (idx)
5387 {
5388 if (idx < 0)
5389 arg1_len = build_int_cst (size_type_node, ~idx);
5390 else
5391 {
5392 strinfo *si = get_strinfo (idx);
5393 if (si)
5394 arg1_len = get_string_length (si);
5395 }
5396 }
5397
5398 if (arg1_len != NULL_TREE)
5399 {
5400 gimple_stmt_iterator gsi = gsi_for_stmt (call_stmt);
5401 tree strncmp_decl = builtin_decl_explicit (BUILT_IN_STRNCMP);
5402
5403 if (!is_gimple_val (arg1_len))
5404 {
5405 tree arg1_len_tmp = make_ssa_name (TREE_TYPE (arg1_len));
5406 gassign *arg1_stmt = gimple_build_assign (arg1_len_tmp,
5407 arg1_len);
5408 gsi_insert_before (&gsi, arg1_stmt, GSI_SAME_STMT);
5409 arg1_len = arg1_len_tmp;
5410 }
5411
5412 gcall *strncmp_call = gimple_build_call (strncmp_decl, 3,
5413 arg0, arg1, arg1_len);
5414 tree strncmp_lhs = make_ssa_name (integer_type_node);
5415 gimple_set_vuse (strncmp_call, gimple_vuse (call_stmt));
5416 gimple_call_set_lhs (strncmp_call, strncmp_lhs);
5417 gsi_remove (&gsi, true);
5418 gsi_insert_before (&gsi, strncmp_call, GSI_SAME_STMT);
5419 tree zero = build_zero_cst (TREE_TYPE (strncmp_lhs));
5420
5421 if (is_gimple_assign (stmt))
5422 {
5423 if (gimple_assign_rhs_code (stmt) == COND_EXPR)
5424 {
5425 tree cond = gimple_assign_rhs1 (stmt);
5426 TREE_OPERAND (cond, 0) = strncmp_lhs;
5427 TREE_OPERAND (cond, 1) = zero;
5428 }
5429 else
5430 {
5431 gimple_assign_set_rhs1 (stmt, strncmp_lhs);
5432 gimple_assign_set_rhs2 (stmt, zero);
5433 }
5434 }
5435 else
5436 {
5437 gcond *cond = as_a<gcond *> (stmt);
5438 gimple_cond_set_lhs (cond, strncmp_lhs);
5439 gimple_cond_set_rhs (cond, zero);
5440 }
5441 update_stmt (stmt);
5442 }
5443 }
5444 }
5445 }
5446
5447 /* Return true if TYPE corresponds to a narrow character type. */
5448
5449 static bool
5450 is_char_type (tree type)
5451 {
5452 return (TREE_CODE (type) == INTEGER_TYPE
5453 && TYPE_MODE (type) == TYPE_MODE (char_type_node)
5454 && TYPE_PRECISION (type) == TYPE_PRECISION (char_type_node));
5455 }
5456
5457 /* Check the built-in call at GSI for validity and optimize it.
5458 Uses RVALS to determine range information.
5459 Return true to let the caller advance *GSI to the next statement
5460 in the basic block and false otherwise. */
5461
5462 bool
5463 strlen_pass::check_and_optimize_call (bool *zero_write)
5464 {
5465 gimple *stmt = gsi_stmt (m_gsi);
5466
5467 if (!gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
5468 {
5469 tree fntype = gimple_call_fntype (stmt);
5470 if (!fntype)
5471 return true;
5472
5473 if (lookup_attribute ("alloc_size", TYPE_ATTRIBUTES (fntype)))
5474 {
5475 handle_alloc_call (BUILT_IN_NONE);
5476 return true;
5477 }
5478
5479 if (tree lhs = gimple_call_lhs (stmt))
5480 handle_assign (lhs, zero_write);
5481
5482 /* Proceed to handle user-defined formatting functions. */
5483 }
5484
5485 /* When not optimizing we must be checking printf calls which
5486 we do even for user-defined functions when they are declared
5487 with attribute format. */
5488 if (!flag_optimize_strlen
5489 || !strlen_optimize
5490 || !valid_builtin_call (stmt))
5491 return !handle_printf_call (&m_gsi, ptr_qry);
5492
5493 tree callee = gimple_call_fndecl (stmt);
5494 switch (DECL_FUNCTION_CODE (callee))
5495 {
5496 case BUILT_IN_STRLEN:
5497 case BUILT_IN_STRNLEN:
5498 handle_builtin_strlen ();
5499 break;
5500 case BUILT_IN_STRCHR:
5501 handle_builtin_strchr ();
5502 break;
5503 case BUILT_IN_STRCPY:
5504 case BUILT_IN_STRCPY_CHK:
5505 case BUILT_IN_STPCPY:
5506 case BUILT_IN_STPCPY_CHK:
5507 handle_builtin_strcpy (DECL_FUNCTION_CODE (callee));
5508 break;
5509
5510 case BUILT_IN_STRNCAT:
5511 case BUILT_IN_STRNCAT_CHK:
5512 handle_builtin_strncat (DECL_FUNCTION_CODE (callee));
5513 break;
5514
5515 case BUILT_IN_STPNCPY:
5516 case BUILT_IN_STPNCPY_CHK:
5517 case BUILT_IN_STRNCPY:
5518 case BUILT_IN_STRNCPY_CHK:
5519 handle_builtin_stxncpy_strncat (false);
5520 break;
5521
5522 case BUILT_IN_MEMCPY:
5523 case BUILT_IN_MEMCPY_CHK:
5524 case BUILT_IN_MEMPCPY:
5525 case BUILT_IN_MEMPCPY_CHK:
5526 handle_builtin_memcpy (DECL_FUNCTION_CODE (callee));
5527 break;
5528 case BUILT_IN_STRCAT:
5529 case BUILT_IN_STRCAT_CHK:
5530 handle_builtin_strcat (DECL_FUNCTION_CODE (callee));
5531 break;
5532 case BUILT_IN_ALLOCA:
5533 case BUILT_IN_ALLOCA_WITH_ALIGN:
5534 case BUILT_IN_MALLOC:
5535 case BUILT_IN_CALLOC:
5536 handle_alloc_call (DECL_FUNCTION_CODE (callee));
5537 break;
5538 case BUILT_IN_MEMSET:
5539 if (handle_builtin_memset (zero_write))
5540 return false;
5541 break;
5542 case BUILT_IN_MEMCMP:
5543 if (handle_builtin_memcmp ())
5544 return false;
5545 break;
5546 case BUILT_IN_STRCMP:
5547 case BUILT_IN_STRNCMP:
5548 if (handle_builtin_string_cmp ())
5549 return false;
5550 break;
5551 default:
5552 if (handle_printf_call (&m_gsi, ptr_qry))
5553 return false;
5554 break;
5555 }
5556
5557 return true;
5558 }
5559
5560 /* Handle an assignment statement at *GSI to a LHS of integral type.
5561 If GSI's basic block needs clean-up of EH, set *CLEANUP_EH to true. */
5562
5563 void
5564 strlen_pass::handle_integral_assign (bool *cleanup_eh)
5565 {
5566 gimple *stmt = gsi_stmt (m_gsi);
5567 tree lhs = gimple_assign_lhs (stmt);
5568 tree lhs_type = TREE_TYPE (lhs);
5569
5570 enum tree_code code = gimple_assign_rhs_code (stmt);
5571 if (code == COND_EXPR)
5572 {
5573 tree cond = gimple_assign_rhs1 (stmt);
5574 enum tree_code cond_code = TREE_CODE (cond);
5575
5576 if (cond_code == EQ_EXPR || cond_code == NE_EXPR)
5577 fold_strstr_to_strncmp (TREE_OPERAND (cond, 0),
5578 TREE_OPERAND (cond, 1), stmt);
5579 }
5580 else if (code == EQ_EXPR || code == NE_EXPR)
5581 fold_strstr_to_strncmp (gimple_assign_rhs1 (stmt),
5582 gimple_assign_rhs2 (stmt), stmt);
5583 else if (gimple_assign_load_p (stmt)
5584 && TREE_CODE (lhs_type) == INTEGER_TYPE
5585 && TYPE_MODE (lhs_type) == TYPE_MODE (char_type_node)
5586 && (TYPE_PRECISION (lhs_type)
5587 == TYPE_PRECISION (char_type_node))
5588 && !gimple_has_volatile_ops (stmt))
5589 {
5590 tree off = integer_zero_node;
5591 unsigned HOST_WIDE_INT coff = 0;
5592 int idx = 0;
5593 tree rhs1 = gimple_assign_rhs1 (stmt);
5594 if (code == MEM_REF)
5595 {
5596 idx = get_stridx (TREE_OPERAND (rhs1, 0), stmt);
5597 if (idx > 0)
5598 {
5599 strinfo *si = get_strinfo (idx);
5600 if (si
5601 && si->nonzero_chars
5602 && TREE_CODE (si->nonzero_chars) == INTEGER_CST
5603 && (wi::to_widest (si->nonzero_chars)
5604 >= wi::to_widest (off)))
5605 off = TREE_OPERAND (rhs1, 1);
5606 else
5607 /* This case is not useful. See if get_addr_stridx
5608 returns something usable. */
5609 idx = 0;
5610 }
5611 }
5612 if (idx <= 0)
5613 idx = get_addr_stridx (rhs1, stmt, NULL_TREE, &coff);
5614 if (idx > 0)
5615 {
5616 strinfo *si = get_strinfo (idx);
5617 if (si
5618 && si->nonzero_chars
5619 && TREE_CODE (si->nonzero_chars) == INTEGER_CST)
5620 {
5621 widest_int w1 = wi::to_widest (si->nonzero_chars);
5622 widest_int w2 = wi::to_widest (off) + coff;
5623 if (w1 == w2
5624 && si->full_string_p)
5625 {
5626 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
5627 {
5628 fprintf (dump_file, "Optimizing: ");
5629 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
5630 }
5631
5632 /* Reading the final '\0' character. */
5633 tree zero = build_int_cst (lhs_type, 0);
5634 gimple_set_vuse (stmt, NULL_TREE);
5635 gimple_assign_set_rhs_from_tree (&m_gsi, zero);
5636 *cleanup_eh
5637 |= maybe_clean_or_replace_eh_stmt (stmt,
5638 gsi_stmt (m_gsi));
5639 stmt = gsi_stmt (m_gsi);
5640 update_stmt (stmt);
5641
5642 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
5643 {
5644 fprintf (dump_file, "into: ");
5645 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
5646 }
5647 }
5648 else if (w1 > w2)
5649 {
5650 /* Reading a character before the final '\0'
5651 character. Just set the value range to ~[0, 0]
5652 if we don't have anything better. */
5653 int_range_max r;
5654 if (!get_range_query (cfun)->range_of_expr (r, lhs)
5655 || r.varying_p ())
5656 {
5657 r.set_nonzero (lhs_type);
5658 set_range_info (lhs, r);
5659 }
5660 }
5661 }
5662 }
5663 }
5664 else if (code == MEM_REF && TREE_CODE (lhs) == SSA_NAME)
5665 {
5666 if (int idx = new_stridx (lhs))
5667 {
5668 /* Record multi-byte assignments from MEM_REFs. */
5669 bool storing_all_nonzero_p;
5670 bool storing_all_zeros_p;
5671 bool full_string_p;
5672 unsigned lenrange[] = { UINT_MAX, 0, 0 };
5673 tree rhs = gimple_assign_rhs1 (stmt);
5674 const bool ranges_valid
5675 = count_nonzero_bytes (rhs, stmt,
5676 lenrange, &full_string_p,
5677 &storing_all_zeros_p,
5678 &storing_all_nonzero_p);
5679 if (ranges_valid)
5680 {
5681 tree length = build_int_cst (sizetype, lenrange[0]);
5682 strinfo *si = new_strinfo (lhs, idx, length, full_string_p);
5683 set_strinfo (idx, si);
5684 si->writable = true;
5685 si->dont_invalidate = true;
5686 }
5687 }
5688 }
5689
5690 if (strlen_to_stridx)
5691 {
5692 tree rhs1 = gimple_assign_rhs1 (stmt);
5693 if (stridx_strlenloc *ps = strlen_to_stridx->get (rhs1))
5694 strlen_to_stridx->put (lhs, stridx_strlenloc (*ps));
5695 }
5696 }
5697
5698 /* Handle assignment statement at *GSI to LHS. Set *ZERO_WRITE if
5699 the assignment stores all zero bytes. */
5700
5701 bool
5702 strlen_pass::handle_assign (tree lhs, bool *zero_write)
5703 {
5704 tree type = TREE_TYPE (lhs);
5705 if (TREE_CODE (type) == ARRAY_TYPE)
5706 type = TREE_TYPE (type);
5707
5708 bool is_char_store = is_char_type (type);
5709 if (!is_char_store && TREE_CODE (lhs) == MEM_REF)
5710 {
5711 /* To consider stores into char objects via integer types other
5712 than char but not those to non-character objects, determine
5713 the type of the destination rather than just the type of
5714 the access. */
5715 for (int i = 0; i != 2; ++i)
5716 {
5717 tree ref = TREE_OPERAND (lhs, i);
5718 type = TREE_TYPE (ref);
5719 if (TREE_CODE (type) == POINTER_TYPE)
5720 type = TREE_TYPE (type);
5721 if (TREE_CODE (type) == ARRAY_TYPE)
5722 type = TREE_TYPE (type);
5723 if (is_char_type (type))
5724 {
5725 is_char_store = true;
5726 break;
5727 }
5728 }
5729 }
5730
5731 /* Handle a single or multibyte assignment. */
5732 if (is_char_store && !handle_store (zero_write))
5733 return false;
5734
5735 return true;
5736 }
5737
5738
5739 /* Attempt to check for validity of the performed access a single statement
5740 at *GSI using string length knowledge, and to optimize it.
5741 If the given basic block needs clean-up of EH, CLEANUP_EH is set to
5742 true. Return true to let the caller advance *GSI to the next statement
5743 in the basic block and false otherwise. */
5744
5745 bool
5746 strlen_pass::check_and_optimize_stmt (bool *cleanup_eh)
5747 {
5748 gimple *stmt = gsi_stmt (m_gsi);
5749
5750 /* For statements that modify a string, set to true if the write
5751 is only zeros. */
5752 bool zero_write = false;
5753
5754 if (is_gimple_call (stmt))
5755 {
5756 if (!check_and_optimize_call (&zero_write))
5757 return false;
5758 }
5759 else if (!flag_optimize_strlen || !strlen_optimize)
5760 return true;
5761 else if (is_gimple_assign (stmt) && !gimple_clobber_p (stmt))
5762 {
5763 /* Handle non-clobbering assignment. */
5764 tree lhs = gimple_assign_lhs (stmt);
5765 tree lhs_type = TREE_TYPE (lhs);
5766
5767 if (TREE_CODE (lhs) == SSA_NAME && POINTER_TYPE_P (lhs_type))
5768 {
5769 if (gimple_assign_single_p (stmt)
5770 || (gimple_assign_cast_p (stmt)
5771 && POINTER_TYPE_P (TREE_TYPE (gimple_assign_rhs1 (stmt)))))
5772 {
5773 int idx = get_stridx (gimple_assign_rhs1 (stmt), stmt);
5774 ssa_ver_to_stridx[SSA_NAME_VERSION (lhs)] = idx;
5775 }
5776 else if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR)
5777 handle_pointer_plus ();
5778 }
5779 else if (TREE_CODE (lhs) == SSA_NAME && INTEGRAL_TYPE_P (lhs_type))
5780 /* Handle assignment to a character. */
5781 handle_integral_assign (cleanup_eh);
5782 else if (TREE_CODE (lhs) != SSA_NAME && !TREE_SIDE_EFFECTS (lhs))
5783 if (!handle_assign (lhs, &zero_write))
5784 return false;
5785 }
5786 else if (gcond *cond = dyn_cast<gcond *> (stmt))
5787 {
5788 enum tree_code code = gimple_cond_code (cond);
5789 if (code == EQ_EXPR || code == NE_EXPR)
5790 fold_strstr_to_strncmp (gimple_cond_lhs (stmt),
5791 gimple_cond_rhs (stmt), stmt);
5792 }
5793
5794 if (gimple_vdef (stmt))
5795 maybe_invalidate (stmt, zero_write);
5796 return true;
5797 }
5798
5799 /* Recursively call maybe_invalidate on stmts that might be executed
5800 in between dombb and current bb and that contain a vdef. Stop when
5801 *count stmts are inspected, or if the whole strinfo vector has
5802 been invalidated. */
5803
5804 static void
5805 do_invalidate (basic_block dombb, gimple *phi, bitmap visited, int *count)
5806 {
5807 unsigned int i, n = gimple_phi_num_args (phi);
5808
5809 for (i = 0; i < n; i++)
5810 {
5811 tree vuse = gimple_phi_arg_def (phi, i);
5812 gimple *stmt = SSA_NAME_DEF_STMT (vuse);
5813 basic_block bb = gimple_bb (stmt);
5814 if (bb == NULL
5815 || bb == dombb
5816 || !bitmap_set_bit (visited, bb->index)
5817 || !dominated_by_p (CDI_DOMINATORS, bb, dombb))
5818 continue;
5819 while (1)
5820 {
5821 if (gimple_code (stmt) == GIMPLE_PHI)
5822 {
5823 do_invalidate (dombb, stmt, visited, count);
5824 if (*count == 0)
5825 return;
5826 break;
5827 }
5828 if (--*count == 0)
5829 return;
5830 if (!maybe_invalidate (stmt))
5831 {
5832 *count = 0;
5833 return;
5834 }
5835 vuse = gimple_vuse (stmt);
5836 stmt = SSA_NAME_DEF_STMT (vuse);
5837 if (gimple_bb (stmt) != bb)
5838 {
5839 bb = gimple_bb (stmt);
5840 if (bb == NULL
5841 || bb == dombb
5842 || !bitmap_set_bit (visited, bb->index)
5843 || !dominated_by_p (CDI_DOMINATORS, bb, dombb))
5844 break;
5845 }
5846 }
5847 }
5848 }
5849
5850 /* Release pointer_query cache. */
5851
5852 strlen_pass::~strlen_pass ()
5853 {
5854 ptr_qry.flush_cache ();
5855 }
5856
5857 /* Callback for walk_dominator_tree. Attempt to optimize various
5858 string ops by remembering string lengths pointed by pointer SSA_NAMEs. */
5859
5860 edge
5861 strlen_pass::before_dom_children (basic_block bb)
5862 {
5863 basic_block dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
5864
5865 if (dombb == NULL)
5866 stridx_to_strinfo = NULL;
5867 else
5868 {
5869 stridx_to_strinfo = ((vec<strinfo *, va_heap, vl_embed> *) dombb->aux);
5870 if (stridx_to_strinfo)
5871 {
5872 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
5873 gsi_next (&gsi))
5874 {
5875 gphi *phi = gsi.phi ();
5876 if (virtual_operand_p (gimple_phi_result (phi)))
5877 {
5878 bitmap visited = BITMAP_ALLOC (NULL);
5879 int count_vdef = 100;
5880 do_invalidate (dombb, phi, visited, &count_vdef);
5881 BITMAP_FREE (visited);
5882 if (count_vdef == 0)
5883 {
5884 /* If there were too many vdefs in between immediate
5885 dominator and current bb, invalidate everything.
5886 If stridx_to_strinfo has been unshared, we need
5887 to free it, otherwise just set it to NULL. */
5888 if (!strinfo_shared ())
5889 {
5890 unsigned int i;
5891 strinfo *si;
5892
5893 for (i = 1;
5894 vec_safe_iterate (stridx_to_strinfo, i, &si);
5895 ++i)
5896 {
5897 free_strinfo (si);
5898 (*stridx_to_strinfo)[i] = NULL;
5899 }
5900 }
5901 else
5902 stridx_to_strinfo = NULL;
5903 }
5904 break;
5905 }
5906 }
5907 }
5908 }
5909
5910 /* If all PHI arguments have the same string index, the PHI result
5911 has it as well. */
5912 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
5913 gsi_next (&gsi))
5914 {
5915 gphi *phi = gsi.phi ();
5916 tree result = gimple_phi_result (phi);
5917 if (!virtual_operand_p (result) && POINTER_TYPE_P (TREE_TYPE (result)))
5918 {
5919 int idx = get_stridx (gimple_phi_arg_def (phi, 0), phi);
5920 if (idx != 0)
5921 {
5922 unsigned int i, n = gimple_phi_num_args (phi);
5923 for (i = 1; i < n; i++)
5924 if (idx != get_stridx (gimple_phi_arg_def (phi, i), phi))
5925 break;
5926 if (i == n)
5927 ssa_ver_to_stridx[SSA_NAME_VERSION (result)] = idx;
5928 }
5929 }
5930 }
5931
5932 bool cleanup_eh = false;
5933
5934 /* Attempt to optimize individual statements. */
5935 for (m_gsi = gsi_start_bb (bb); !gsi_end_p (m_gsi); )
5936 {
5937 /* Reset search depth performance counter. */
5938 ptr_qry.depth = 0;
5939
5940 if (check_and_optimize_stmt (&cleanup_eh))
5941 gsi_next (&m_gsi);
5942 }
5943
5944 if (cleanup_eh && gimple_purge_dead_eh_edges (bb))
5945 m_cleanup_cfg = true;
5946
5947 bb->aux = stridx_to_strinfo;
5948 if (vec_safe_length (stridx_to_strinfo) && !strinfo_shared ())
5949 (*stridx_to_strinfo)[0] = (strinfo *) bb;
5950 return NULL;
5951 }
5952
5953 /* Callback for walk_dominator_tree. Free strinfo vector if it is
5954 owned by the current bb, clear bb->aux. */
5955
5956 void
5957 strlen_pass::after_dom_children (basic_block bb)
5958 {
5959 if (bb->aux)
5960 {
5961 stridx_to_strinfo = ((vec<strinfo *, va_heap, vl_embed> *) bb->aux);
5962 if (vec_safe_length (stridx_to_strinfo)
5963 && (*stridx_to_strinfo)[0] == (strinfo *) bb)
5964 {
5965 unsigned int i;
5966 strinfo *si;
5967
5968 for (i = 1; vec_safe_iterate (stridx_to_strinfo, i, &si); ++i)
5969 free_strinfo (si);
5970 vec_free (stridx_to_strinfo);
5971 }
5972 bb->aux = NULL;
5973 }
5974 }
5975
5976 namespace {
5977
5978 static unsigned int
5979 printf_strlen_execute (function *fun, bool warn_only)
5980 {
5981 strlen_optimize = !warn_only;
5982
5983 calculate_dominance_info (CDI_DOMINATORS);
5984 loop_optimizer_init (LOOPS_NORMAL);
5985 scev_initialize ();
5986
5987 gcc_assert (!strlen_to_stridx);
5988 if (warn_stringop_overflow || warn_stringop_truncation)
5989 strlen_to_stridx = new hash_map<tree, stridx_strlenloc> ();
5990
5991 /* This has to happen after initializing the loop optimizer
5992 and initializing SCEV as they create new SSA_NAMEs. */
5993 ssa_ver_to_stridx.safe_grow_cleared (num_ssa_names, true);
5994 max_stridx = 1;
5995
5996 enable_ranger (fun);
5997 /* String length optimization is implemented as a walk of the dominator
5998 tree and a forward walk of statements within each block. */
5999 strlen_pass walker (fun, CDI_DOMINATORS);
6000 walker.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));
6001
6002 if (dump_file && (dump_flags & TDF_DETAILS))
6003 walker.ptr_qry.dump (dump_file, true);
6004
6005 ssa_ver_to_stridx.release ();
6006 strinfo_pool.release ();
6007 if (decl_to_stridxlist_htab)
6008 {
6009 obstack_free (&stridx_obstack, NULL);
6010 delete decl_to_stridxlist_htab;
6011 decl_to_stridxlist_htab = NULL;
6012 }
6013 laststmt.stmt = NULL;
6014 laststmt.len = NULL_TREE;
6015 laststmt.stridx = 0;
6016
6017 if (strlen_to_stridx)
6018 {
6019 strlen_to_stridx->empty ();
6020 delete strlen_to_stridx;
6021 strlen_to_stridx = NULL;
6022 }
6023
6024 disable_ranger (fun);
6025 scev_finalize ();
6026 loop_optimizer_finalize ();
6027
6028 return walker.m_cleanup_cfg ? TODO_cleanup_cfg : 0;
6029 }
6030
6031 /* This file defines two passes: one for warnings that runs only when
6032 optimization is disabled, and another that implements optimizations
6033 and also issues warnings. */
6034
6035 const pass_data pass_data_warn_printf =
6036 {
6037 GIMPLE_PASS, /* type */
6038 "warn-printf", /* name */
6039 OPTGROUP_NONE, /* optinfo_flags */
6040 TV_NONE, /* tv_id */
6041 /* Normally an optimization pass would require PROP_ssa but because
6042 this pass runs early, with no optimization, to do sprintf format
6043 checking, it only requires PROP_cfg. */
6044 PROP_cfg, /* properties_required */
6045 0, /* properties_provided */
6046 0, /* properties_destroyed */
6047 0, /* todo_flags_start */
6048 0, /* todo_flags_finish */
6049 };
6050
6051 class pass_warn_printf : public gimple_opt_pass
6052 {
6053 public:
6054 pass_warn_printf (gcc::context *ctxt)
6055 : gimple_opt_pass (pass_data_warn_printf, ctxt)
6056 {}
6057
6058 bool gate (function *) final override;
6059 unsigned int execute (function *fun) final override
6060 {
6061 return printf_strlen_execute (fun, true);
6062 }
6063 };
6064
6065
6066 /* Return true to run the warning pass only when not optimizing and
6067 iff either -Wformat-overflow or -Wformat-truncation is specified. */
6068
6069 bool
6070 pass_warn_printf::gate (function *)
6071 {
6072 return !optimize && (warn_format_overflow > 0 || warn_format_trunc > 0);
6073 }
6074
6075 const pass_data pass_data_strlen =
6076 {
6077 GIMPLE_PASS, /* type */
6078 "strlen", /* name */
6079 OPTGROUP_NONE, /* optinfo_flags */
6080 TV_TREE_STRLEN, /* tv_id */
6081 PROP_cfg | PROP_ssa, /* properties_required */
6082 0, /* properties_provided */
6083 0, /* properties_destroyed */
6084 0, /* todo_flags_start */
6085 0, /* todo_flags_finish */
6086 };
6087
6088 class pass_strlen : public gimple_opt_pass
6089 {
6090 public:
6091 pass_strlen (gcc::context *ctxt)
6092 : gimple_opt_pass (pass_data_strlen, ctxt)
6093 {}
6094
6095 opt_pass * clone () final override { return new pass_strlen (m_ctxt); }
6096
6097 bool gate (function *) final override;
6098 unsigned int execute (function *fun) final override
6099 {
6100 return printf_strlen_execute (fun, false);
6101 }
6102 };
6103
6104 /* Return true to run the pass only when the sprintf and/or strlen
6105 optimizations are enabled and -Wformat-overflow or -Wformat-truncation
6106 are specified. */
6107
6108 bool
6109 pass_strlen::gate (function *)
6110 {
6111 return ((warn_format_overflow > 0
6112 || warn_format_trunc > 0
6113 || warn_restrict > 0
6114 || flag_optimize_strlen > 0
6115 || flag_printf_return_value)
6116 && optimize > 0);
6117 }
6118
6119 } // anon namespace
6120
6121 gimple_opt_pass *
6122 make_pass_warn_printf (gcc::context *ctxt)
6123 {
6124 return new pass_warn_printf (ctxt);
6125 }
6126
6127 gimple_opt_pass *
6128 make_pass_strlen (gcc::context *ctxt)
6129 {
6130 return new pass_strlen (ctxt);
6131 }