LCOV - code coverage report
Current view: top level - gcc - tree-ssa-strlen.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 90.8 % 2831 2570
Test Date: 2026-08-22 16:33:35 Functions: 98.7 % 79 78
Legend: Lines:     hit not hit

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

Generated by: LCOV version 2.4-beta

LCOV profile is generated on x86_64 machine using following configure options: configure --disable-bootstrap --enable-coverage=opt --enable-languages=c,c++,fortran,go,jit,lto,rust,m2 --enable-host-shared. GCC test suite is run with the built compiler.