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