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