LCOV - code coverage report
Current view: top level - gcc - gimple-ssa-sprintf.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 94.1 % 1791 1685
Test Date: 2026-11-14 16:39:50 Functions: 98.0 % 51 50
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /* Copyright (C) 2016-2026 Free Software Foundation, Inc.
       2              :    Contributed by Martin Sebor <msebor@redhat.com>.
       3              : 
       4              : This file is part of GCC.
       5              : 
       6              : GCC is free software; you can redistribute it and/or modify it under
       7              : the terms of the GNU General Public License as published by the Free
       8              : Software Foundation; either version 3, or (at your option) any later
       9              : version.
      10              : 
      11              : GCC is distributed in the hope that it will be useful, but WITHOUT ANY
      12              : WARRANTY; without even the implied warranty of MERCHANTABILITY or
      13              : FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
      14              : for more details.
      15              : 
      16              : You should have received a copy of the GNU General Public License
      17              : along with GCC; see the file COPYING3.  If not see
      18              : <http://www.gnu.org/licenses/>.  */
      19              : 
      20              : /* This file implements the printf-return-value pass.  The pass does
      21              :    two things: 1) it analyzes calls to formatted output functions like
      22              :    sprintf looking for possible buffer overflows and calls to bounded
      23              :    functions like snprintf for early truncation (and under the control
      24              :    of the -Wformat-length option issues warnings), and 2) under the
      25              :    control of the -fprintf-return-value option it folds the return
      26              :    value of safe calls into constants, making it possible to eliminate
      27              :    code that depends on the value of those constants.
      28              : 
      29              :    For all functions (bounded or not) the pass uses the size of the
      30              :    destination object.  That means that it will diagnose calls to
      31              :    snprintf not on the basis of the size specified by the function's
      32              :    second argument but rather on the basis of the size the first
      33              :    argument points to (if possible).  For bound-checking built-ins
      34              :    like __builtin___snprintf_chk the pass uses the size typically
      35              :    determined by __builtin_object_size and passed to the built-in
      36              :    by the Glibc inline wrapper.
      37              : 
      38              :    The pass handles all forms standard sprintf format directives,
      39              :    including character, integer, floating point, pointer, and strings,
      40              :    with the standard C flags, widths, and precisions.  For integers
      41              :    and strings it computes the length of output itself.  For floating
      42              :    point it uses MPFR to format known constants with up and down
      43              :    rounding and uses the resulting range of output lengths.  For
      44              :    strings it uses the length of string literals and the sizes of
      45              :    character arrays that a character pointer may point to as a bound
      46              :    on the longest string.  */
      47              : 
      48              : #include "config.h"
      49              : #include "system.h"
      50              : #include "coretypes.h"
      51              : #include "backend.h"
      52              : #include "tree.h"
      53              : #include "gimple.h"
      54              : #include "tree-pass.h"
      55              : #include "ssa.h"
      56              : #include "gimple-iterator.h"
      57              : #include "gimple-fold.h"
      58              : #include "gimple-pretty-print.h"
      59              : #include "diagnostic-core.h"
      60              : #include "fold-const.h"
      61              : #include "tree-ssa.h"
      62              : #include "tree-object-size.h"
      63              : #include "tree-cfg.h"
      64              : #include "tree-ssa-propagate.h"
      65              : #include "calls.h"
      66              : #include "cfgloop.h"
      67              : #include "tree-scalar-evolution.h"
      68              : #include "tree-ssa-loop.h"
      69              : #include "intl.h"
      70              : #include "langhooks.h"
      71              : 
      72              : #include "attribs.h"
      73              : #include "builtins.h"
      74              : #include "pointer-query.h"
      75              : #include "stor-layout.h"
      76              : 
      77              : #include "realmpfr.h"
      78              : #include "target.h"
      79              : 
      80              : #include "cpplib.h"
      81              : #include "input.h"
      82              : #include "toplev.h"
      83              : #include "substring-locations.h"
      84              : #include "diagnostic.h"
      85              : #include "domwalk.h"
      86              : #include "alloc-pool.h"
      87              : #include "vr-values.h"
      88              : #include "tree-ssa-strlen.h"
      89              : #include "tree-dfa.h"
      90              : 
      91              : /* The likely worst case value of MB_LEN_MAX for the target, large enough
      92              :    for UTF-8.  Ideally, this would be obtained by a target hook if it were
      93              :    to be used for optimization but it's good enough as is for warnings.  */
      94              : #define target_mb_len_max()   6
      95              : 
      96              : /* The maximum number of bytes a single non-string directive can result
      97              :    in.  This is the result of printf("%.*Lf", INT_MAX, -LDBL_MAX) for
      98              :    LDBL_MAX_10_EXP of 4932.  */
      99              : #define IEEE_MAX_10_EXP    4932
     100              : #define target_dir_max()   (target_int_max () + IEEE_MAX_10_EXP + 2)
     101              : 
     102              : namespace {
     103              : 
     104              : /* Set to the warning level for the current function which is equal
     105              :    either to warn_format_trunc for bounded functions or to
     106              :    warn_format_overflow otherwise.  */
     107              : 
     108              : static int warn_level;
     109              : 
     110              : /* The minimum, maximum, likely, and unlikely maximum number of bytes
     111              :    of output either a formatting function or an individual directive
     112              :    can result in.  */
     113              : 
     114              : struct result_range
     115              : {
     116              :   /* The absolute minimum number of bytes.  The result of a successful
     117              :      conversion is guaranteed to be no less than this.  (An erroneous
     118              :      conversion can be indicated by MIN > HOST_WIDE_INT_MAX.)  */
     119              :   unsigned HOST_WIDE_INT min;
     120              :   /* The likely maximum result that is used in diagnostics.  In most
     121              :      cases MAX is the same as the worst case UNLIKELY result.  */
     122              :   unsigned HOST_WIDE_INT max;
     123              :   /* The likely result used to trigger diagnostics.  For conversions
     124              :      that result in a range of bytes [MIN, MAX], LIKELY is somewhere
     125              :      in that range.  */
     126              :   unsigned HOST_WIDE_INT likely;
     127              :   /* In rare cases (e.g., for multibyte characters) UNLIKELY gives
     128              :      the worst cases maximum result of a directive.  In most cases
     129              :      UNLIKELY == MAX.  UNLIKELY is used to control the return value
     130              :      optimization but not in diagnostics.  */
     131              :   unsigned HOST_WIDE_INT unlikely;
     132              : };
     133              : 
     134              : /* Return the value of INT_MIN for the target.  */
     135              : 
     136              : static inline HOST_WIDE_INT
     137       811498 : target_int_min ()
     138              : {
     139       811498 :   return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node));
     140              : }
     141              : 
     142              : /* Return the value of INT_MAX for the target.  */
     143              : 
     144              : static inline unsigned HOST_WIDE_INT
     145      2631059 : target_int_max ()
     146              : {
     147      2631059 :   return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node));
     148              : }
     149              : 
     150              : /* Return the value of SIZE_MAX for the target.  */
     151              : 
     152              : static inline unsigned HOST_WIDE_INT
     153       291474 : target_size_max ()
     154              : {
     155       291474 :   return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node));
     156              : }
     157              : 
     158              : /* A straightforward mapping from the execution character set to the host
     159              :    character set indexed by execution character.  */
     160              : 
     161              : static char target_to_host_charmap[256];
     162              : 
     163              : /* Initialize a mapping from the execution character set to the host
     164              :    character set.  */
     165              : 
     166              : static bool
     167      5056667 : init_target_to_host_charmap ()
     168              : {
     169              :   /* If the percent sign is non-zero the mapping has already been
     170              :      initialized.  */
     171      5056667 :   if (target_to_host_charmap['%'])
     172              :     return true;
     173              : 
     174              :   /* Initialize the target_percent character (done elsewhere).  */
     175       114948 :   if (!init_target_chars ())
     176              :     return false;
     177              : 
     178              :   /* The subset of the source character set used by printf conversion
     179              :      specifications (strictly speaking, not all letters are used but
     180              :      they are included here for the sake of simplicity).  The dollar
     181              :      sign must be included even though it's not in the basic source
     182              :      character set.  */
     183       114948 :   const char srcset[] = " 0123456789!\"#%&'()*+,-./:;<=>?[\\]^_{|}~$"
     184              :     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
     185              : 
     186              :   /* Set the mapping for all characters to some ordinary value (i,e.,
     187              :      not none used in printf conversion specifications) and overwrite
     188              :      those that are used by conversion specifications with their
     189              :      corresponding values.  */
     190       114948 :   memset (target_to_host_charmap + 1, '?', sizeof target_to_host_charmap - 1);
     191              : 
     192              :   /* Are the two sets of characters the same?  */
     193       114948 :   bool all_same_p = true;
     194              : 
     195     10805112 :   for (const char *pc = srcset; *pc; ++pc)
     196              :     {
     197              :       /* Slice off the high end bits in case target characters are
     198              :          signed.  All values are expected to be non-nul, otherwise
     199              :          there's a problem.  */
     200     10690164 :       if (unsigned char tc = lang_hooks.to_target_charset (*pc))
     201              :         {
     202     10690164 :           target_to_host_charmap[tc] = *pc;
     203     10690164 :           if (tc != *pc)
     204          279 :             all_same_p = false;
     205              :         }
     206              :       else
     207              :         return false;
     208              : 
     209              :     }
     210              : 
     211              :   /* Set the first element to a non-zero value if the mapping
     212              :      is 1-to-1, otherwise leave it clear (NUL is assumed to be
     213              :      the same in both character sets).  */
     214       114948 :   target_to_host_charmap[0] = all_same_p;
     215              : 
     216       114948 :   return true;
     217              : }
     218              : 
     219              : /* Return the host source character corresponding to the character
     220              :    CH in the execution character set if one exists, or some innocuous
     221              :    (non-special, non-nul) source character otherwise.  */
     222              : 
     223              : static inline unsigned char
     224      3604286 : target_to_host (unsigned char ch)
     225              : {
     226      3604286 :   return target_to_host_charmap[ch];
     227              : }
     228              : 
     229              : /* Convert an initial substring of the string TARGSTR consisting of
     230              :    characters in the execution character set into a string in the
     231              :    source character set on the host and store up to HOSTSZ characters
     232              :    in the buffer pointed to by HOSTR.  Return HOSTR.  */
     233              : 
     234              : static const char*
     235         5604 : target_to_host (char *hostr, size_t hostsz, const char *targstr)
     236              : {
     237              :   /* Make sure the buffer is reasonably big.  */
     238         5604 :   gcc_assert (hostsz > 4);
     239              : 
     240              :   /* The interesting subset of source and execution characters are
     241              :      the same so no conversion is necessary.  However, truncate
     242              :      overlong strings just like the translated strings are.  */
     243         5604 :   if (target_to_host_charmap['\0'] == 1)
     244              :     {
     245         5541 :       size_t len = strlen (targstr);
     246         5541 :       if (len >= hostsz)
     247              :         {
     248          326 :           memcpy (hostr, targstr, hostsz - 4);
     249          326 :           strcpy (hostr + hostsz - 4, "...");
     250              :         }
     251              :       else
     252         5215 :         memcpy (hostr, targstr, len + 1);
     253              :       return hostr;
     254              :     }
     255              : 
     256              :   /* Convert the initial substring of TARGSTR to the corresponding
     257              :      characters in the host set, appending "..." if TARGSTR is too
     258              :      long to fit.  Using the static buffer assumes the function is
     259              :      not called in between sequence points (which it isn't).  */
     260          330 :   for (char *ph = hostr; ; ++targstr)
     261              :     {
     262          393 :       *ph++ = target_to_host (*targstr);
     263          393 :       if (!*targstr)
     264              :         break;
     265              : 
     266          331 :       if (size_t (ph - hostr) == hostsz)
     267              :         {
     268            1 :           strcpy (ph - 4, "...");
     269            1 :           break;
     270              :         }
     271              :     }
     272              : 
     273              :   return hostr;
     274              : }
     275              : 
     276              : /* Convert the sequence of decimal digits in the execution character
     277              :    starting at *PS to a HOST_WIDE_INT, analogously to strtol.  Return
     278              :    the result and set *PS to one past the last converted character.
     279              :    On range error set ERANGE to the digit that caused it.  */
     280              : 
     281              : static inline HOST_WIDE_INT
     282         2534 : target_strtowi (const char **ps, const char **erange)
     283              : {
     284         2534 :   unsigned HOST_WIDE_INT val = 0;
     285        11046 :   for ( ; ; ++*ps)
     286              :     {
     287         6790 :       unsigned char c = target_to_host (**ps);
     288         6790 :       if (ISDIGIT (c))
     289              :         {
     290         4258 :           c -= '0';
     291              : 
     292              :           /* Check for overflow.  */
     293         4258 :           if (val > ((unsigned HOST_WIDE_INT) HOST_WIDE_INT_MAX - c) / 10LU)
     294              :             {
     295            2 :               val = HOST_WIDE_INT_MAX;
     296            2 :               *erange = *ps;
     297              : 
     298              :               /* Skip the remaining digits.  */
     299            2 :               do
     300            2 :                 c = target_to_host (*++*ps);
     301            2 :               while (ISDIGIT (c));
     302              :               break;
     303              :             }
     304              :           else
     305         4256 :             val = val * 10 + c;
     306              :         }
     307              :       else
     308              :         break;
     309         4256 :     }
     310              : 
     311         2534 :   return val;
     312              : }
     313              : 
     314              : /* Given FORMAT, set *PLOC to the source location of the format string
     315              :    and return the format string if it is known or null otherwise.  */
     316              : 
     317              : static const char*
     318       154220 : get_format_string (tree format, location_t *ploc)
     319              : {
     320       154220 :   *ploc = EXPR_LOC_OR_LOC (format, input_location);
     321              : 
     322       154220 :   return c_getstr (format);
     323              : }
     324              : 
     325              : /* For convenience and brevity, shorter named entrypoints of
     326              :    format_string_diagnostic_t::emit_warning_va and
     327              :    format_string_diagnostic_t::emit_warning_n_va.
     328              :    These have to be functions with the attribute so that exgettext
     329              :    works properly.  */
     330              : 
     331              : static bool
     332              : ATTRIBUTE_GCC_DIAG (5, 6)
     333         6117 : fmtwarn (const substring_loc &fmt_loc, location_t param_loc,
     334              :          const char *corrected_substring, opt_code opt,
     335              :          const char *gmsgid, ...)
     336              : {
     337         6117 :   format_string_diagnostic_t diag (fmt_loc, NULL, param_loc, NULL,
     338         6117 :                                    corrected_substring);
     339         6117 :   va_list ap;
     340         6117 :   va_start (ap, gmsgid);
     341         6117 :   bool warned = diag.emit_warning_va (opt, gmsgid, &ap);
     342         6117 :   va_end (ap);
     343              : 
     344         6117 :   return warned;
     345              : }
     346              : 
     347              : static bool
     348              : ATTRIBUTE_GCC_DIAG (6, 8) ATTRIBUTE_GCC_DIAG (7, 8)
     349          548 : fmtwarn_n (const substring_loc &fmt_loc, location_t param_loc,
     350              :            const char *corrected_substring, opt_code opt,
     351              :            unsigned HOST_WIDE_INT n,
     352              :            const char *singular_gmsgid, const char *plural_gmsgid, ...)
     353              : {
     354          548 :   format_string_diagnostic_t diag (fmt_loc, NULL, param_loc, NULL,
     355          548 :                                    corrected_substring);
     356          548 :   va_list ap;
     357          548 :   va_start (ap, plural_gmsgid);
     358          548 :   bool warned = diag.emit_warning_n_va (opt, n, singular_gmsgid, plural_gmsgid,
     359              :                                         &ap);
     360          548 :   va_end (ap);
     361              : 
     362          548 :   return warned;
     363              : }
     364              : 
     365              : /* Format length modifiers.  */
     366              : 
     367              : enum format_lengths
     368              : {
     369              :   FMT_LEN_none,
     370              :   FMT_LEN_hh,    // char argument
     371              :   FMT_LEN_h,     // short
     372              :   FMT_LEN_l,     // long
     373              :   FMT_LEN_ll,    // long long
     374              :   FMT_LEN_L,     // long double (and GNU long long)
     375              :   FMT_LEN_z,     // size_t
     376              :   FMT_LEN_t,     // ptrdiff_t
     377              :   FMT_LEN_j      // intmax_t
     378              : };
     379              : 
     380              : 
     381              : /* Description of the result of conversion either of a single directive
     382              :    or the whole format string.  */
     383              : 
     384              : class fmtresult
     385              : {
     386              : public:
     387              :   /* Construct a FMTRESULT object with all counters initialized
     388              :      to MIN.  KNOWNRANGE is set when MIN is valid.  */
     389      1181096 :   fmtresult (unsigned HOST_WIDE_INT min = HOST_WIDE_INT_MAX)
     390      1181096 :   : argmin (), argmax (), dst_offset (HOST_WIDE_INT_MIN), nonstr (),
     391      1179446 :     knownrange (min < HOST_WIDE_INT_MAX),
     392      1181096 :     mayfail (), nullp ()
     393              :   {
     394      1181096 :     range.min = min;
     395      1181096 :     range.max = min;
     396      1181096 :     range.likely = min;
     397      1181096 :     range.unlikely = min;
     398              :   }
     399              : 
     400              :   /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
     401              :      KNOWNRANGE is set when both MIN and MAX are valid.   */
     402       283819 :   fmtresult (unsigned HOST_WIDE_INT min, unsigned HOST_WIDE_INT max,
     403              :              unsigned HOST_WIDE_INT likely = HOST_WIDE_INT_MAX)
     404       283819 :   : argmin (), argmax (), dst_offset (HOST_WIDE_INT_MIN), nonstr (),
     405       283819 :     knownrange (min < HOST_WIDE_INT_MAX && max < HOST_WIDE_INT_MAX),
     406       283819 :     mayfail (), nullp ()
     407              :   {
     408       283819 :     range.min = min;
     409       283819 :     range.max = max;
     410       283819 :     range.likely = max < likely ? min : likely;
     411       283819 :     range.unlikely = max;
     412              :   }
     413              : 
     414              :   /* Adjust result upward to reflect the RANGE of values the specified
     415              :      width or precision is known to be in.  */
     416              :   fmtresult& adjust_for_width_or_precision (const HOST_WIDE_INT[2],
     417              :                                             tree = NULL_TREE,
     418              :                                             unsigned = 0, unsigned = 0);
     419              : 
     420              :   /* Return the maximum number of decimal digits a value of TYPE
     421              :      formats as on output.  */
     422              :   static unsigned type_max_digits (tree, int);
     423              : 
     424              :   /* The range a directive's argument is in.  */
     425              :   tree argmin, argmax;
     426              : 
     427              :   /* The starting offset into the destination of the formatted function
     428              :      call of the %s argument that points into (aliases with) the same
     429              :      destination array.  */
     430              :   HOST_WIDE_INT dst_offset;
     431              : 
     432              :   /* The minimum and maximum number of bytes that a directive
     433              :      results in on output for an argument in the range above.  */
     434              :   result_range range;
     435              : 
     436              :   /* Non-nul when the argument of a string directive is not a nul
     437              :      terminated string.  */
     438              :   tree nonstr;
     439              : 
     440              :   /* True when the range above is obtained from a known value of
     441              :      a directive's argument or its bounds and not the result of
     442              :      heuristics that depend on warning levels.  */
     443              :   bool knownrange;
     444              : 
     445              :   /* True for a directive that may fail (such as wide character
     446              :      directives).  */
     447              :   bool mayfail;
     448              : 
     449              :   /* True when the argument is a null pointer.  */
     450              :   bool nullp;
     451              : };
     452              : 
     453              : /* Adjust result upward to reflect the range ADJUST of values the
     454              :    specified width or precision is known to be in.  When non-null,
     455              :    TYPE denotes the type of the directive whose result is being
     456              :    adjusted, BASE gives the base of the directive (octal, decimal,
     457              :    or hex), and ADJ denotes the additional adjustment to the LIKELY
     458              :    counter that may need to be added when ADJUST is a range.  */
     459              : 
     460              : fmtresult&
     461       816512 : fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust[2],
     462              :                                           tree type /* = NULL_TREE */,
     463              :                                           unsigned base /* = 0 */,
     464              :                                           unsigned adj /* = 0 */)
     465              : {
     466       816512 :   bool minadjusted = false;
     467              : 
     468              :   /* Adjust the minimum and likely counters.  */
     469       816512 :   if (adjust[0] >= 0)
     470              :     {
     471         5014 :       if (range.min < (unsigned HOST_WIDE_INT)adjust[0])
     472              :         {
     473         1530 :           range.min = adjust[0];
     474         1530 :           minadjusted = true;
     475              :         }
     476              : 
     477              :       /* Adjust the likely counter.  */
     478         5014 :       if (range.likely < range.min)
     479         1373 :         range.likely = range.min;
     480              :     }
     481       811498 :   else if (adjust[0] == target_int_min ()
     482       811498 :            && (unsigned HOST_WIDE_INT)adjust[1] == target_int_max ())
     483            0 :     knownrange = false;
     484              : 
     485              :   /* Adjust the maximum counter.  */
     486       816512 :   if (adjust[1] > 0)
     487              :     {
     488         5057 :       if (range.max < (unsigned HOST_WIDE_INT)adjust[1])
     489              :         {
     490         1669 :           range.max = adjust[1];
     491              : 
     492              :           /* Set KNOWNRANGE if both the minimum and maximum have been
     493              :              adjusted.  Otherwise leave it at what it was before.  */
     494         1669 :           knownrange = minadjusted;
     495              :         }
     496              :     }
     497              : 
     498       816512 :   if (warn_level > 1 && type)
     499              :     {
     500              :       /* For large non-constant width or precision whose range spans
     501              :          the maximum number of digits produced by the directive for
     502              :          any argument, set the likely number of bytes to be at most
     503              :          the number digits plus other adjustment determined by the
     504              :          caller (one for sign or two for the hexadecimal "0x"
     505              :          prefix).  */
     506          904 :       unsigned dirdigs = type_max_digits (type, base);
     507          904 :       if (adjust[0] < dirdigs && dirdigs < adjust[1]
     508           28 :           && range.likely < dirdigs)
     509           16 :         range.likely = dirdigs + adj;
     510              :     }
     511       815608 :   else if (range.likely < (range.min ? range.min : 1))
     512              :     {
     513              :       /* Conservatively, set LIKELY to at least MIN but no less than
     514              :          1 unless MAX is zero.  */
     515        13501 :       range.likely = (range.min
     516        13501 :                       ? range.min
     517        12825 :                       : range.max && (range.max < HOST_WIDE_INT_MAX
     518        26048 :                                       || warn_level > 1) ? 1 : 0);
     519              :     }
     520              : 
     521              :   /* Finally adjust the unlikely counter to be at least as large as
     522              :      the maximum.  */
     523       816512 :   if (range.unlikely < range.max)
     524         1798 :     range.unlikely = range.max;
     525              : 
     526       816512 :   return *this;
     527              : }
     528              : 
     529              : /* Return the maximum number of digits a value of TYPE formats in
     530              :    BASE on output, not counting base prefix .  */
     531              : 
     532              : unsigned
     533          904 : fmtresult::type_max_digits (tree type, int base)
     534              : {
     535          904 :   unsigned prec = TYPE_PRECISION (type);
     536          904 :   switch (base)
     537              :     {
     538              :     case 2:
     539              :       return prec;
     540            0 :     case 8:
     541            0 :       return (prec + 2) / 3;
     542          904 :     case 10:
     543              :       /* Decimal approximation: yields 3, 5, 10, and 20 for precision
     544              :          of 8, 16, 32, and 64 bits.  */
     545          904 :       return prec * 301 / 1000 + 1;
     546            0 :     case 16:
     547            0 :       return prec / 4;
     548              :     }
     549              : 
     550            0 :   gcc_unreachable ();
     551              : }
     552              : 
     553              : static bool
     554              : get_int_range (tree, gimple *, HOST_WIDE_INT *, HOST_WIDE_INT *,
     555              :                bool, HOST_WIDE_INT, range_query *);
     556              : 
     557              : struct call_info;
     558              : 
     559              : /* Description of a format directive.  A directive is either a plain
     560              :    string or a conversion specification that starts with '%'.  */
     561              : 
     562              : struct directive
     563              : {
     564      1054931 :   directive (const call_info *inf, unsigned dno)
     565      1054931 :     : info (inf), dirno (dno), argno (), beg (), len (), flags (),
     566      1054931 :     width (), prec (),  modifier (), specifier (), arg (), fmtfunc ()
     567      1054931 :   { }
     568              : 
     569              :   /* Reference to the info structure describing the call that this
     570              :      directive is a part of.  */
     571              :   const call_info *info;
     572              : 
     573              :   /* The 1-based directive number (for debugging).  */
     574              :   unsigned dirno;
     575              : 
     576              :   /* The zero-based argument number of the directive's argument ARG in
     577              :      the function's argument list.  */
     578              :   unsigned argno;
     579              : 
     580              :   /* The first character of the directive and its length.  */
     581              :   const char *beg;
     582              :   size_t len;
     583              : 
     584              :   /* A bitmap of flags, one for each character.  */
     585              :   unsigned flags[256 / sizeof (int)];
     586              : 
     587              :   /* The range of values of the specified width, or -1 if not specified.  */
     588              :   HOST_WIDE_INT width[2];
     589              :   /* The range of values of the specified precision, or -1 if not
     590              :      specified.  */
     591              :   HOST_WIDE_INT prec[2];
     592              : 
     593              :   /* Length modifier.  */
     594              :   format_lengths modifier;
     595              : 
     596              :   /* Format specifier character.  */
     597              :   char specifier;
     598              : 
     599              :   /* The argument of the directive or null when the directive doesn't
     600              :      take one or when none is available (such as for vararg functions).  */
     601              :   tree arg;
     602              : 
     603              :   /* Format conversion function that given a directive and an argument
     604              :      returns the formatting result.  */
     605              :   fmtresult (*fmtfunc) (const directive &, tree, pointer_query &);
     606              : 
     607              :   /* Return True when the format flag CHR has been used.  */
     608       503156 :   bool get_flag (char chr) const
     609              :   {
     610       503156 :     unsigned char c = chr & 0xff;
     611       503156 :     return (flags[c / (CHAR_BIT * sizeof *flags)]
     612       503156 :             & (1U << (c % (CHAR_BIT * sizeof *flags))));
     613              :   }
     614              : 
     615              :   /* Make a record of the format flag CHR having been used.  */
     616         1823 :   void set_flag (char chr)
     617              :   {
     618         1823 :     unsigned char c = chr & 0xff;
     619         1823 :     flags[c / (CHAR_BIT * sizeof *flags)]
     620         1823 :       |= (1U << (c % (CHAR_BIT * sizeof *flags)));
     621              :   }
     622              : 
     623              :   /* Reset the format flag CHR.  */
     624              :   void clear_flag (char chr)
     625              :   {
     626              :     unsigned char c = chr & 0xff;
     627              :     flags[c / (CHAR_BIT * sizeof *flags)]
     628              :       &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
     629              :   }
     630              : 
     631              :   /* Set both bounds of the width range to VAL.  */
     632       443640 :   void set_width (HOST_WIDE_INT val)
     633              :   {
     634       443640 :     width[0] = width[1] = val;
     635              :   }
     636              : 
     637              :   /* Set the width range according to ARG, with both bounds being
     638              :      no less than 0.  For a constant ARG set both bounds to its value
     639              :      or 0, whichever is greater.  For a non-constant ARG in some range
     640              :      set width to its range adjusting each bound to -1 if it's less.
     641              :      For an indeterminate ARG set width to [0, INT_MAX].  */
     642              :   void set_width (tree arg, range_query *);
     643              : 
     644              :   /* Set both bounds of the precision range to VAL.  */
     645       443483 :   void set_precision (HOST_WIDE_INT val)
     646              :   {
     647       443483 :     prec[0] = prec[1] = val;
     648              :   }
     649              : 
     650              :   /* Set the precision range according to ARG, with both bounds being
     651              :      no less than -1.  For a constant ARG set both bounds to its value
     652              :      or -1 whichever is greater.  For a non-constant ARG in some range
     653              :      set precision to its range adjusting each bound to -1 if it's less.
     654              :      For an indeterminate ARG set precision to [-1, INT_MAX].  */
     655              :   void set_precision (tree arg, range_query *query);
     656              : 
     657              :   /* Return true if both width and precision are known to be
     658              :      either constant or in some range, false otherwise.  */
     659        19408 :   bool known_width_and_precision () const
     660              :   {
     661        19408 :     return ((width[1] < 0
     662          297 :              || (unsigned HOST_WIDE_INT)width[1] <= target_int_max ())
     663        19675 :             && (prec[1] < 0
     664          163 :                 || (unsigned HOST_WIDE_INT)prec[1] < target_int_max ()));
     665              :   }
     666              : };
     667              : 
     668              : /* The result of a call to a formatted function.  */
     669              : 
     670              : struct format_result
     671              : {
     672       148895 :   format_result ()
     673       148895 :     : range (), aliases (), alias_count (), knownrange (), posunder4k (),
     674       148895 :     floating (), warned () { /* No-op.  */ }
     675              : 
     676       148895 :   ~format_result ()
     677              :   {
     678       148895 :     XDELETEVEC (aliases);
     679       148895 :   }
     680              : 
     681              :   /* Range of characters written by the formatted function.
     682              :      Setting the minimum to HOST_WIDE_INT_MAX disables all
     683              :      length tracking for the remainder of the format string.  */
     684              :   result_range range;
     685              : 
     686              :   struct alias_info
     687              :   {
     688              :     directive dir;          /* The directive that aliases the destination.  */
     689              :     HOST_WIDE_INT offset;   /* The offset at which it aliases it.  */
     690              :     result_range range;     /* The raw result of the directive.  */
     691              :   };
     692              : 
     693              :   /* An array of directives whose pointer argument aliases a part
     694              :      of the destination object of the formatted function.  */
     695              :   alias_info *aliases;
     696              :   unsigned alias_count;
     697              : 
     698              :   /* True when the range above is obtained from known values of
     699              :      directive arguments, or bounds on the amount of output such
     700              :      as width and precision, and not the result of  heuristics that
     701              :      depend on warning levels.  It's used to issue stricter diagnostics
     702              :      in cases where strings of unknown lengths are bounded by the arrays
     703              :      they are determined to refer to.  KNOWNRANGE must not be used for
     704              :      the return value optimization.  */
     705              :   bool knownrange;
     706              : 
     707              :   /* True if no individual directive could fail or result in more than
     708              :      4095 bytes of output (the total NUMBER_CHARS_{MIN,MAX} might be
     709              :      greater).  Implementations are not required to handle directives
     710              :      that produce more than 4K bytes (leading to undefined behavior)
     711              :      and so when one is found it disables the return value optimization.
     712              :      Similarly, directives that can fail (such as wide character
     713              :      directives) disable the optimization.  */
     714              :   bool posunder4k;
     715              : 
     716              :   /* True when a floating point directive has been seen in the format
     717              :      string.  */
     718              :   bool floating;
     719              : 
     720              :   /* True when an intermediate result has caused a warning.  Used to
     721              :      avoid issuing duplicate warnings while finishing the processing
     722              :      of a call.  WARNED also disables the return value optimization.  */
     723              :   bool warned;
     724              : 
     725              :   /* Preincrement the number of output characters by 1.  */
     726              :   format_result& operator++ ()
     727              :   {
     728              :     return *this += 1;
     729              :   }
     730              : 
     731              :   /* Increment the number of output characters by N.  */
     732              :   format_result& operator+= (unsigned HOST_WIDE_INT);
     733              : 
     734              :   /* Add a directive to the sequence of those with potentially aliasing
     735              :      arguments.  */
     736              :   void append_alias (const directive &, HOST_WIDE_INT, const result_range &);
     737              : 
     738              : private:
     739              :   /* Not copyable or assignable.  */
     740              :   format_result (format_result&);
     741              :   void operator= (format_result&);
     742              : };
     743              : 
     744              : format_result&
     745            0 : format_result::operator+= (unsigned HOST_WIDE_INT n)
     746              : {
     747            0 :   gcc_assert (n < HOST_WIDE_INT_MAX);
     748              : 
     749            0 :   if (range.min < HOST_WIDE_INT_MAX)
     750            0 :     range.min += n;
     751              : 
     752            0 :   if (range.max < HOST_WIDE_INT_MAX)
     753            0 :     range.max += n;
     754              : 
     755            0 :   if (range.likely < HOST_WIDE_INT_MAX)
     756            0 :     range.likely += n;
     757              : 
     758            0 :   if (range.unlikely < HOST_WIDE_INT_MAX)
     759            0 :     range.unlikely += n;
     760              : 
     761            0 :   return *this;
     762              : }
     763              : 
     764              : void
     765          262 : format_result::append_alias (const directive &d, HOST_WIDE_INT off,
     766              :                              const result_range &resrng)
     767              : {
     768          262 :   unsigned cnt = alias_count + 1;
     769          262 :   alias_info *ar = XNEWVEC (alias_info, cnt);
     770              : 
     771          528 :   for (unsigned i = 0; i != alias_count; ++i)
     772            4 :     ar[i] = aliases[i];
     773              : 
     774          262 :   ar[alias_count].dir = d;
     775          262 :   ar[alias_count].offset = off;
     776          262 :   ar[alias_count].range = resrng;
     777              : 
     778          262 :   XDELETEVEC (aliases);
     779              : 
     780          262 :   alias_count = cnt;
     781          262 :   aliases = ar;
     782          262 : }
     783              : 
     784              : /* Return the logarithm of X in BASE.  */
     785              : 
     786              : static int
     787       214206 : ilog (unsigned HOST_WIDE_INT x, int base)
     788              : {
     789            0 :   int res = 0;
     790       988902 :   do
     791              :     {
     792       988902 :       ++res;
     793       988902 :       x /= base;
     794       988902 :     } while (x);
     795       214206 :   return res;
     796              : }
     797              : 
     798              : /* Return the number of bytes resulting from converting into a string
     799              :    the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
     800              :    PLUS indicates whether 1 for a plus sign should be added for positive
     801              :    numbers, and PREFIX whether the length of an octal ('0') or hexadecimal
     802              :    ('0x') or binary ('0b') prefix should be added for nonzero numbers.
     803              :    Return -1 if X cannot be represented.  */
     804              : 
     805              : static HOST_WIDE_INT
     806       214206 : tree_digits (tree x, int base, HOST_WIDE_INT prec, bool plus, bool prefix)
     807              : {
     808       214206 :   unsigned HOST_WIDE_INT absval;
     809              : 
     810       214206 :   HOST_WIDE_INT res;
     811              : 
     812       214206 :   if (TYPE_UNSIGNED (TREE_TYPE (x)))
     813              :     {
     814        13115 :       if (tree_fits_uhwi_p (x))
     815              :         {
     816        13115 :           absval = tree_to_uhwi (x);
     817        13115 :           res = plus;
     818              :         }
     819              :       else
     820              :         return -1;
     821              :     }
     822              :   else
     823              :     {
     824       201091 :       if (tree_fits_shwi_p (x))
     825              :         {
     826       201091 :           HOST_WIDE_INT i = tree_to_shwi (x);
     827       201091 :          if (HOST_WIDE_INT_MIN == i)
     828              :            {
     829              :              /* Avoid undefined behavior due to negating a minimum.  */
     830              :              absval = HOST_WIDE_INT_MAX;
     831              :              res = 1;
     832              :            }
     833       196811 :          else if (i < 0)
     834              :            {
     835        26851 :              absval = -i;
     836        26851 :              res = 1;
     837              :            }
     838              :          else
     839              :            {
     840       169960 :              absval = i;
     841       169960 :              res = plus;
     842              :            }
     843              :         }
     844              :       else
     845              :         return -1;
     846              :     }
     847              : 
     848       214206 :   int ndigs = ilog (absval, base);
     849              : 
     850       214206 :   res += prec < ndigs ? ndigs : prec;
     851              : 
     852              :   /* Adjust a non-zero value for the base prefix, either hexadecimal,
     853              :      or, unless precision has resulted in a leading zero, also octal.  */
     854       214206 :   if (prefix && absval)
     855              :     {
     856          421 :       if (base == 8 && prec <= ndigs)
     857          141 :         res += 1;
     858          280 :       else if (base == 16 || base == 2) /* 0x...(0X...) or 0b...(0B...).  */
     859          247 :         res += 2;
     860              :     }
     861              : 
     862              :   return res;
     863              : }
     864              : 
     865              : /* Description of a call to a formatted function.  */
     866              : 
     867              : struct call_info
     868              : {
     869              :   /* Function call statement.  */
     870              :   gimple *callstmt;
     871              : 
     872              :   /* Function called.  */
     873              :   tree func;
     874              : 
     875              :   /* Called built-in function code.  */
     876              :   built_in_function fncode;
     877              : 
     878              :   /* The "origin" of the destination pointer argument, which is either
     879              :      the DECL of the destination buffer being written into or a pointer
     880              :      that points to it, plus some offset.  */
     881              :   tree dst_origin;
     882              : 
     883              :   /* For a destination pointing to a struct array member, the offset of
     884              :      the member.  */
     885              :   HOST_WIDE_INT dst_field;
     886              : 
     887              :   /* The offset into the destination buffer.  */
     888              :   HOST_WIDE_INT dst_offset;
     889              : 
     890              :   /* Format argument and format string extracted from it.  */
     891              :   tree format;
     892              :   const char *fmtstr;
     893              : 
     894              :   /* The location of the format argument.  */
     895              :   location_t fmtloc;
     896              : 
     897              :   /* The destination object size for __builtin___xxx_chk functions
     898              :      typically determined by __builtin_object_size, or -1 if unknown.  */
     899              :   unsigned HOST_WIDE_INT objsize;
     900              : 
     901              :   /* Number of the first variable argument.  */
     902              :   unsigned HOST_WIDE_INT argidx;
     903              : 
     904              :   /* True for functions like snprintf that specify the size of
     905              :      the destination, false for others like sprintf that don't.  */
     906              :   bool bounded;
     907              : 
     908              :   /* True for bounded functions like snprintf that specify a zero-size
     909              :      buffer as a request to compute the size of output without actually
     910              :      writing any.  NOWRITE is cleared in response to the %n directive
     911              :      which has side-effects similar to writing output.  */
     912              :   bool nowrite;
     913              : 
     914              :   /* Return true if the called function's return value is used.  */
     915       139582 :   bool retval_used () const
     916              :   {
     917         2441 :     return gimple_get_lhs (callstmt);
     918              :   }
     919              : 
     920              :   /* Return the warning option corresponding to the called function.  */
     921         8532 :   opt_code warnopt () const
     922              :   {
     923         5801 :     return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
     924              :   }
     925              : 
     926              :   /* Return true for calls to file formatted functions.  */
     927              :   bool is_file_func () const
     928              :   {
     929              :     return (fncode == BUILT_IN_FPRINTF
     930              :             || fncode == BUILT_IN_FPRINTF_CHK
     931              :             || fncode == BUILT_IN_FPRINTF_UNLOCKED
     932              :             || fncode == BUILT_IN_VFPRINTF
     933              :             || fncode == BUILT_IN_VFPRINTF_CHK);
     934              :   }
     935              : 
     936              :   /* Return true for calls to string formatted functions.  */
     937         1382 :   bool is_string_func () const
     938              :   {
     939         1382 :     return (fncode == BUILT_IN_SPRINTF
     940         1382 :             || fncode == BUILT_IN_SPRINTF_CHK
     941         1229 :             || fncode == BUILT_IN_SNPRINTF
     942          985 :             || fncode == BUILT_IN_SNPRINTF_CHK
     943          985 :             || fncode == BUILT_IN_VSPRINTF
     944          985 :             || fncode == BUILT_IN_VSPRINTF_CHK
     945          985 :             || fncode == BUILT_IN_VSNPRINTF
     946         2367 :             || fncode == BUILT_IN_VSNPRINTF_CHK);
     947              :   }
     948              : };
     949              : 
     950              : void
     951          787 : directive::set_width (tree arg, range_query *query)
     952              : {
     953          787 :   get_int_range (arg, info->callstmt, width, width + 1, true, 0, query);
     954          787 : }
     955              : 
     956              : void
     957          935 : directive::set_precision (tree arg, range_query *query)
     958              : {
     959          935 :   get_int_range (arg, info->callstmt, prec, prec + 1, false, -1, query);
     960          935 : }
     961              : 
     962              : /* Return the result of formatting a no-op directive (such as '%n').  */
     963              : 
     964              : static fmtresult
     965           77 : format_none (const directive &, tree, pointer_query &)
     966              : {
     967           77 :   fmtresult res (0);
     968           77 :   return res;
     969              : }
     970              : 
     971              : /* Return the result of formatting the '%%' directive.  */
     972              : 
     973              : static fmtresult
     974           88 : format_percent (const directive &, tree, pointer_query &)
     975              : {
     976           88 :   fmtresult res (1);
     977           88 :   return res;
     978              : }
     979              : 
     980              : 
     981              : /* Compute intmax_type_node and uintmax_type_node similarly to how
     982              :    tree.cc builds size_type_node.  */
     983              : 
     984              : static void
     985          122 : build_intmax_type_nodes (tree *pintmax, tree *puintmax)
     986              : {
     987          122 :   if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
     988              :     {
     989            0 :       *pintmax = integer_type_node;
     990            0 :       *puintmax = unsigned_type_node;
     991              :     }
     992          122 :   else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
     993              :     {
     994          122 :       *pintmax = long_integer_type_node;
     995          122 :       *puintmax = long_unsigned_type_node;
     996              :     }
     997            0 :   else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
     998              :     {
     999            0 :       *pintmax = long_long_integer_type_node;
    1000            0 :       *puintmax = long_long_unsigned_type_node;
    1001              :     }
    1002              :   else
    1003              :     {
    1004            0 :       for (int i = 0; i < NUM_INT_N_ENTS; i++)
    1005            0 :         if (int_n_enabled_p[i])
    1006              :           {
    1007            0 :             char name[50], altname[50];
    1008            0 :             sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
    1009            0 :             sprintf (altname, "__int%d__ unsigned", int_n_data[i].bitsize);
    1010              : 
    1011            0 :             if (strcmp (name, UINTMAX_TYPE) == 0
    1012            0 :                 || strcmp (altname, UINTMAX_TYPE) == 0)
    1013              :               {
    1014            0 :                 *pintmax = int_n_trees[i].signed_type;
    1015            0 :                 *puintmax = int_n_trees[i].unsigned_type;
    1016            0 :                 return;
    1017              :               }
    1018              :           }
    1019            0 :       gcc_unreachable ();
    1020              :     }
    1021              : }
    1022              : 
    1023              : /* Determine the range [*PMIN, *PMAX] that the expression ARG is
    1024              :    in and that is representable in type int.
    1025              :    Return true when the range is a subrange of that of int.
    1026              :    When ARG is null it is as if it had the full range of int.
    1027              :    When ABSOLUTE is true the range reflects the absolute value of
    1028              :    the argument.  When ABSOLUTE is false, negative bounds of
    1029              :    the determined range are replaced with NEGBOUND.  */
    1030              : 
    1031              : static bool
    1032         1849 : get_int_range (tree arg, gimple *stmt,
    1033              :                HOST_WIDE_INT *pmin, HOST_WIDE_INT *pmax,
    1034              :                bool absolute, HOST_WIDE_INT negbound,
    1035              :                range_query *query)
    1036              : {
    1037              :   /* The type of the result.  */
    1038         2317 :   const_tree type = integer_type_node;
    1039              : 
    1040         2317 :   bool knownrange = false;
    1041              : 
    1042         2317 :   if (!arg)
    1043              :     {
    1044          479 :       *pmin = tree_to_shwi (TYPE_MIN_VALUE (type));
    1045          479 :       *pmax = tree_to_shwi (TYPE_MAX_VALUE (type));
    1046              :     }
    1047         1838 :   else if (TREE_CODE (arg) == INTEGER_CST
    1048         1838 :            && TYPE_PRECISION (TREE_TYPE (arg)) <= TYPE_PRECISION (type))
    1049              :     {
    1050              :       /* For a constant argument return its value adjusted as specified
    1051              :          by NEGATIVE and NEGBOUND and return true to indicate that the
    1052              :          result is known.  */
    1053          750 :       *pmin = tree_fits_shwi_p (arg) ? tree_to_shwi (arg) : tree_to_uhwi (arg);
    1054          750 :       *pmax = *pmin;
    1055          750 :       knownrange = true;
    1056              :     }
    1057              :   else
    1058              :     {
    1059              :       /* True if the argument's range cannot be determined.  */
    1060         1088 :       bool unknown = true;
    1061              : 
    1062         1088 :       tree argtype = TREE_TYPE (arg);
    1063              : 
    1064              :       /* Ignore invalid arguments with greater precision that that
    1065              :          of the expected type (e.g., in sprintf("%*i", 12LL, i)).
    1066              :          They will have been detected and diagnosed by -Wformat and
    1067              :          so it's not important to complicate this code to try to deal
    1068              :          with them again.  */
    1069         1088 :       if (TREE_CODE (arg) == SSA_NAME
    1070         1084 :           && INTEGRAL_TYPE_P (argtype)
    1071         2170 :           && TYPE_PRECISION (argtype) <= TYPE_PRECISION (type))
    1072              :         {
    1073              :           /* Try to determine the range of values of the integer argument.  */
    1074         1025 :           int_range_max vr;
    1075         1025 :           query->range_of_expr (vr, arg, stmt);
    1076              : 
    1077         1025 :           if (!vr.undefined_p () && !vr.varying_p ())
    1078              :             {
    1079          620 :               HOST_WIDE_INT type_min
    1080          620 :                 = (TYPE_UNSIGNED (argtype)
    1081          620 :                    ? tree_to_uhwi (TYPE_MIN_VALUE (argtype))
    1082          620 :                    : tree_to_shwi (TYPE_MIN_VALUE (argtype)));
    1083              : 
    1084          620 :               HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (argtype));
    1085              : 
    1086          620 :               tree type = TREE_TYPE (arg);
    1087          620 :               tree tmin = wide_int_to_tree (type, vr.lower_bound ());
    1088          620 :               tree tmax = wide_int_to_tree (type, vr.upper_bound ());
    1089          620 :               *pmin = TREE_INT_CST_LOW (tmin);
    1090          620 :               *pmax = TREE_INT_CST_LOW (tmax);
    1091              : 
    1092          620 :               if (*pmin < *pmax)
    1093              :                 {
    1094              :                   /* Return true if the adjusted range is a subrange of
    1095              :                      the full range of the argument's type.  *PMAX may
    1096              :                      be less than *PMIN when the argument is unsigned
    1097              :                      and its upper bound is in excess of TYPE_MAX.  In
    1098              :                      that (invalid) case disregard the range and use that
    1099              :                      of the expected type instead.  */
    1100          620 :                   knownrange = type_min < *pmin || *pmax < type_max;
    1101              : 
    1102              :                   unknown = false;
    1103              :                 }
    1104              :             }
    1105         1025 :         }
    1106              : 
    1107              :       /* Handle an argument with an unknown range as if none had been
    1108              :          provided.  */
    1109         1025 :       if (unknown)
    1110          468 :         return get_int_range (NULL_TREE, NULL, pmin, pmax, absolute,
    1111          468 :                               negbound, query);
    1112              :     }
    1113              : 
    1114              :   /* Adjust each bound as specified by ABSOLUTE and NEGBOUND.  */
    1115         1849 :   if (absolute)
    1116              :     {
    1117          787 :       if (*pmin < 0)
    1118              :         {
    1119          309 :           if (*pmin == *pmax)
    1120           24 :             *pmin = *pmax = -*pmin;
    1121              :           else
    1122              :             {
    1123              :               /* Make sure signed overflow is avoided.  */
    1124          285 :               gcc_assert (*pmin != HOST_WIDE_INT_MIN);
    1125              : 
    1126          285 :               HOST_WIDE_INT tmp = -*pmin;
    1127          285 :               *pmin = 0;
    1128          285 :               if (*pmax < tmp)
    1129          267 :                 *pmax = tmp;
    1130              :             }
    1131              :         }
    1132              :     }
    1133         1062 :   else if (*pmin < negbound)
    1134          432 :     *pmin = negbound;
    1135              : 
    1136              :   return knownrange;
    1137              : }
    1138              : 
    1139              : /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
    1140              :    argument, due to the conversion from either *ARGMIN or *ARGMAX to
    1141              :    the type of the directive's formal argument it's possible for both
    1142              :    to result in the same number of bytes or a range of bytes that's
    1143              :    less than the number of bytes that would result from formatting
    1144              :    some other value in the range [*ARGMIN, *ARGMAX].  This can be
    1145              :    determined by checking for the actual argument being in the range
    1146              :    of the type of the directive.  If it isn't it must be assumed to
    1147              :    take on the full range of the directive's type.
    1148              :    Return true when the range has been adjusted to the full range
    1149              :    of DIRTYPE, and false otherwise.  */
    1150              : 
    1151              : static bool
    1152        42434 : adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
    1153              : {
    1154        42434 :   tree argtype = TREE_TYPE (*argmin);
    1155        42434 :   unsigned argprec = TYPE_PRECISION (argtype);
    1156        42434 :   unsigned dirprec = TYPE_PRECISION (dirtype);
    1157              : 
    1158              :   /* If the actual argument and the directive's argument have the same
    1159              :      precision and sign there can be no overflow and so there is nothing
    1160              :      to adjust.  */
    1161        42434 :   if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
    1162              :     return false;
    1163              : 
    1164              :   /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
    1165              :      branch in the extract_range_from_unary_expr function in tree-vrp.cc.  */
    1166              : 
    1167         4951 :   if (TREE_CODE (*argmin) == INTEGER_CST
    1168         4951 :       && TREE_CODE (*argmax) == INTEGER_CST
    1169         9902 :       && (dirprec >= argprec
    1170         1866 :           || integer_zerop (int_const_binop (RSHIFT_EXPR,
    1171         1866 :                                              int_const_binop (MINUS_EXPR,
    1172              :                                                               *argmax,
    1173              :                                                               *argmin),
    1174         6817 :                                              size_int (dirprec)))))
    1175              :     {
    1176         3512 :       unsigned int maxprec = MAX (argprec, dirprec);
    1177         3512 :       *argmin = force_fit_type (dirtype,
    1178         3512 :                                 wide_int::from (wi::to_wide (*argmin), maxprec,
    1179         3512 :                                                 TYPE_SIGN (argtype)),
    1180              :                                 0, false);
    1181         3512 :       *argmax = force_fit_type (dirtype,
    1182         3512 :                                 wide_int::from (wi::to_wide (*argmax), maxprec,
    1183         3512 :                                                 TYPE_SIGN (argtype)),
    1184              :                                 0, false);
    1185              : 
    1186              :       /* If *ARGMIN is still less than *ARGMAX the conversion above
    1187              :          is safe.  Otherwise, it has overflowed and would be unsafe.  */
    1188         3512 :       if (tree_int_cst_le (*argmin, *argmax))
    1189              :         return false;
    1190              :     }
    1191              : 
    1192         2810 :   *argmin = TYPE_MIN_VALUE (dirtype);
    1193         2810 :   *argmax = TYPE_MAX_VALUE (dirtype);
    1194         2810 :   return true;
    1195              : }
    1196              : 
    1197              : /* Return a range representing the minimum and maximum number of bytes
    1198              :    that the format directive DIR will output for any argument given
    1199              :    the WIDTH and PRECISION (extracted from DIR).  This function is
    1200              :    used when the directive argument or its value isn't known.  */
    1201              : 
    1202              : static fmtresult
    1203       256707 : format_integer (const directive &dir, tree arg, pointer_query &ptr_qry)
    1204              : {
    1205       256707 :   tree intmax_type_node;
    1206       256707 :   tree uintmax_type_node;
    1207              : 
    1208              :   /* Base to format the number in.  */
    1209       256707 :   int base;
    1210              : 
    1211              :   /* True when a conversion is preceded by a prefix indicating the base
    1212              :      of the argument (octal or hexadecimal).  */
    1213       256707 :   const bool maybebase = dir.get_flag ('#');
    1214              : 
    1215              :   /* True when a signed conversion is preceded by a sign or space.  */
    1216       256707 :   bool maybesign = false;
    1217              : 
    1218              :   /* True for signed conversions (i.e., 'd' and 'i').  */
    1219       256707 :   bool sign = false;
    1220              : 
    1221       256707 :   switch (dir.specifier)
    1222              :     {
    1223       238824 :     case 'd':
    1224       238824 :     case 'i':
    1225              :       /* Space and '+' are  only meaningful for signed conversions.  */
    1226       238824 :       maybesign = dir.get_flag (' ') | dir.get_flag ('+');
    1227       238824 :       sign = true;
    1228       238824 :       base = 10;
    1229       238824 :       break;
    1230              :     case 'u':
    1231              :       base = 10;
    1232              :       break;
    1233          240 :     case 'b':
    1234          240 :     case 'B':
    1235          240 :       base = 2;
    1236          240 :       break;
    1237          808 :     case 'o':
    1238          808 :       base = 8;
    1239          808 :       break;
    1240         5580 :     case 'X':
    1241         5580 :     case 'x':
    1242         5580 :       base = 16;
    1243         5580 :       break;
    1244            0 :     default:
    1245            0 :       gcc_unreachable ();
    1246              :     }
    1247              : 
    1248       256707 :   const unsigned adj = (sign | maybebase) + (base == 2 || base == 16);
    1249              : 
    1250              :   /* The type of the "formal" argument expected by the directive.  */
    1251       256707 :   tree dirtype = NULL_TREE;
    1252              : 
    1253              :   /* Determine the expected type of the argument from the length
    1254              :      modifier.  */
    1255       256707 :   switch (dir.modifier)
    1256              :     {
    1257       189439 :     case FMT_LEN_none:
    1258       189439 :       if (dir.specifier == 'p')
    1259              :         dirtype = ptr_type_node;
    1260              :       else
    1261       189439 :         dirtype = sign ? integer_type_node : unsigned_type_node;
    1262              :       break;
    1263              : 
    1264          770 :     case FMT_LEN_h:
    1265          770 :       dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
    1266              :       break;
    1267              : 
    1268         1916 :     case FMT_LEN_hh:
    1269         1916 :       dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
    1270              :       break;
    1271              : 
    1272        56644 :     case FMT_LEN_l:
    1273        56644 :       dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
    1274              :       break;
    1275              : 
    1276         2516 :     case FMT_LEN_L:
    1277         2516 :     case FMT_LEN_ll:
    1278         2516 :       dirtype = (sign
    1279         2516 :                  ? long_long_integer_type_node
    1280              :                  : long_long_unsigned_type_node);
    1281              :       break;
    1282              : 
    1283         5239 :     case FMT_LEN_z:
    1284         5239 :       dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
    1285         5239 :       break;
    1286              : 
    1287           61 :     case FMT_LEN_t:
    1288           61 :       dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
    1289           61 :       break;
    1290              : 
    1291          122 :     case FMT_LEN_j:
    1292          122 :       build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
    1293          122 :       dirtype = sign ? intmax_type_node : uintmax_type_node;
    1294              :       break;
    1295              : 
    1296            0 :     default:
    1297            0 :       return fmtresult ();
    1298              :     }
    1299              : 
    1300              :   /* The type of the argument to the directive, either deduced from
    1301              :      the actual non-constant argument if one is known, or from
    1302              :      the directive itself when none has been provided because it's
    1303              :      a va_list.  */
    1304       256707 :   tree argtype = NULL_TREE;
    1305              : 
    1306       256707 :   if (!arg)
    1307              :     {
    1308              :       /* When the argument has not been provided, use the type of
    1309              :          the directive's argument as an approximation.  This will
    1310              :          result in false positives for directives like %i with
    1311              :          arguments with smaller precision (such as short or char).  */
    1312              :       argtype = dirtype;
    1313              :     }
    1314       256394 :   else if (TREE_CODE (arg) == INTEGER_CST)
    1315              :     {
    1316              :       /* When a constant argument has been provided use its value
    1317              :          rather than type to determine the length of the output.  */
    1318       214247 :       fmtresult res;
    1319              : 
    1320       214247 :       if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
    1321              :         {
    1322              :           /* As a special case, a precision of zero with a zero argument
    1323              :              results in zero bytes except in base 8 when the '#' flag is
    1324              :              specified, and for signed conversions in base 8 and 10 when
    1325              :              either the space or '+' flag has been specified and it results
    1326              :              in just one byte (with width having the normal effect).  This
    1327              :              must extend to the case of a specified precision with
    1328              :              an unknown value because it can be zero.  */
    1329          219 :           res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
    1330          219 :           if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
    1331              :             {
    1332           96 :               res.range.max = 1;
    1333           96 :               res.range.likely = 1;
    1334              :             }
    1335              :           else
    1336              :             {
    1337          123 :               res.range.max = res.range.min;
    1338          123 :               res.range.likely = res.range.min;
    1339              :             }
    1340              :         }
    1341              :       else
    1342              :         {
    1343              :           /* Convert the argument to the type of the directive.  */
    1344       214028 :           arg = fold_convert (dirtype, arg);
    1345              : 
    1346       214028 :           res.range.min = tree_digits (arg, base, dir.prec[0],
    1347              :                                        maybesign, maybebase);
    1348       214028 :           if (dir.prec[0] == dir.prec[1])
    1349              :             res.range.max = res.range.min;
    1350              :           else
    1351          178 :             res.range.max = tree_digits (arg, base, dir.prec[1],
    1352              :                                          maybesign, maybebase);
    1353       214028 :           res.range.likely = res.range.min;
    1354       214028 :           res.knownrange = true;
    1355              :         }
    1356              : 
    1357       214247 :       res.range.unlikely = res.range.max;
    1358              : 
    1359              :       /* Bump up the counters if WIDTH is greater than LEN.  */
    1360       214247 :       res.adjust_for_width_or_precision (dir.width, dirtype, base, adj);
    1361              :       /* Bump up the counters again if PRECision is greater still.  */
    1362       214247 :       res.adjust_for_width_or_precision (dir.prec, dirtype, base, adj);
    1363              : 
    1364       214247 :       return res;
    1365              :     }
    1366        84284 :   else if (INTEGRAL_TYPE_P (TREE_TYPE (arg))
    1367        42413 :            || POINTER_TYPE_P (TREE_TYPE (arg)))
    1368              :     /* Determine the type of the provided non-constant argument.  */
    1369        42122 :     argtype = TREE_TYPE (arg);
    1370              :   else
    1371              :     /* Don't bother with invalid arguments since they likely would
    1372              :        have already been diagnosed, and disable any further checking
    1373              :        of the format string by returning [-1, -1].  */
    1374           25 :     return fmtresult ();
    1375              : 
    1376        42435 :   fmtresult res;
    1377              : 
    1378              :   /* Using either the range the non-constant argument is in, or its
    1379              :      type (either "formal" or actual), create a range of values that
    1380              :      constrain the length of output given the warning level.  */
    1381        42435 :   tree argmin = NULL_TREE;
    1382        42435 :   tree argmax = NULL_TREE;
    1383              : 
    1384        42435 :   if (arg
    1385        42122 :       && TREE_CODE (arg) == SSA_NAME
    1386        42094 :       && INTEGRAL_TYPE_P (argtype))
    1387              :     {
    1388              :       /* Try to determine the range of values of the integer argument
    1389              :          (range information is not available for pointers).  */
    1390        41881 :       int_range_max vr;
    1391        41881 :       ptr_qry.rvals->range_of_expr (vr, arg, dir.info->callstmt);
    1392              : 
    1393        41881 :       if (!vr.varying_p () && !vr.undefined_p ())
    1394              :         {
    1395        20882 :           argmin = wide_int_to_tree (TREE_TYPE (arg), vr.lower_bound ());
    1396        20882 :           argmax = wide_int_to_tree (TREE_TYPE (arg), vr.upper_bound ());
    1397              : 
    1398              :           /* Set KNOWNRANGE if the argument is in a known subrange
    1399              :              of the directive's type and neither width nor precision
    1400              :              is unknown.  (KNOWNRANGE may be reset below).  */
    1401        20882 :           res.knownrange
    1402        20882 :             = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
    1403         3682 :                 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax))
    1404        22489 :                && dir.known_width_and_precision ());
    1405              : 
    1406        20882 :           res.argmin = argmin;
    1407        20882 :           res.argmax = argmax;
    1408              :         }
    1409              :       else
    1410              :         {
    1411              :           /* The argument here may be the result of promoting the actual
    1412              :              argument to int.  Try to determine the type of the actual
    1413              :              argument before promotion and narrow down its range that
    1414              :              way.  */
    1415        20999 :           gimple *def = SSA_NAME_DEF_STMT (arg);
    1416        20999 :           if (is_gimple_assign (def))
    1417              :             {
    1418        11523 :               tree_code code = gimple_assign_rhs_code (def);
    1419        11523 :               if (code == INTEGER_CST)
    1420              :                 {
    1421            1 :                   arg = gimple_assign_rhs1 (def);
    1422            1 :                   return format_integer (dir, arg, ptr_qry);
    1423              :                 }
    1424              : 
    1425        11522 :               if (code == NOP_EXPR)
    1426              :                 {
    1427          968 :                   tree type = TREE_TYPE (gimple_assign_rhs1 (def));
    1428          968 :                   if (INTEGRAL_TYPE_P (type)
    1429          968 :                       || POINTER_TYPE_P (type))
    1430        41880 :                     argtype = type;
    1431              :                 }
    1432              :             }
    1433              :         }
    1434        41881 :     }
    1435              : 
    1436        42434 :   if (!argmin)
    1437              :     {
    1438        21552 :       if (POINTER_TYPE_P (argtype))
    1439              :         {
    1440          284 :           argmin = build_int_cst (pointer_sized_int_node, 0);
    1441          284 :           argmax = build_all_ones_cst (pointer_sized_int_node);
    1442              :         }
    1443              :       else
    1444              :         {
    1445        21268 :           argmin = TYPE_MIN_VALUE (argtype);
    1446        21268 :           argmax = TYPE_MAX_VALUE (argtype);
    1447              :         }
    1448              :     }
    1449              : 
    1450              :   /* Clear KNOWNRANGE if the range has been adjusted to the maximum
    1451              :      of the directive.  If it has been cleared then since ARGMIN and/or
    1452              :      ARGMAX have been adjusted also adjust the corresponding ARGMIN and
    1453              :      ARGMAX in the result to include in diagnostics.  */
    1454        42434 :   if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
    1455              :     {
    1456         2810 :       res.knownrange = false;
    1457         2810 :       res.argmin = argmin;
    1458         2810 :       res.argmax = argmax;
    1459              :     }
    1460              : 
    1461              :   /* Recursively compute the minimum and maximum from the known range.  */
    1462        42434 :   if (TYPE_UNSIGNED (dirtype) || tree_int_cst_sgn (argmin) >= 0)
    1463              :     {
    1464              :       /* For unsigned conversions/directives or signed when
    1465              :          the minimum is positive, use the minimum and maximum to compute
    1466              :          the shortest and longest output, respectively.  */
    1467        11577 :       res.range.min = format_integer (dir, argmin, ptr_qry).range.min;
    1468        11577 :       res.range.max = format_integer (dir, argmax, ptr_qry).range.max;
    1469              :     }
    1470        30857 :   else if (tree_int_cst_sgn (argmax) < 0)
    1471              :     {
    1472              :       /* For signed conversions/directives if maximum is negative,
    1473              :          use the minimum as the longest output and maximum as the
    1474              :          shortest output.  */
    1475           25 :       res.range.min = format_integer (dir, argmax, ptr_qry).range.min;
    1476           25 :       res.range.max = format_integer (dir, argmin, ptr_qry).range.max;
    1477              :     }
    1478              :   else
    1479              :     {
    1480              :       /* Otherwise, 0 is inside of the range and minimum negative.  Use 0
    1481              :          as the shortest output and for the longest output compute the
    1482              :          length of the output of both minimum and maximum and pick the
    1483              :          longer.  */
    1484        30832 :       unsigned HOST_WIDE_INT max1
    1485        30832 :         = format_integer (dir, argmin, ptr_qry).range.max;
    1486        30832 :       unsigned HOST_WIDE_INT max2
    1487        30832 :         = format_integer (dir, argmax, ptr_qry).range.max;
    1488        30832 :       res.range.min
    1489        30832 :         = format_integer (dir, integer_zero_node, ptr_qry).range.min;
    1490        30832 :       res.range.max = MAX (max1, max2);
    1491              :     }
    1492              : 
    1493              :   /* If the range is known, use the maximum as the likely length.  */
    1494        42434 :   if (res.knownrange)
    1495        18392 :     res.range.likely = res.range.max;
    1496              :   else
    1497              :     {
    1498              :       /* Otherwise, use the minimum.  Except for the case where for %#x or
    1499              :          %#o the minimum is just for a single value in the range (0) and
    1500              :          for all other values it is something longer, like 0x1 or 01.
    1501              :           Use the length for value 1 in that case instead as the likely
    1502              :           length.  */
    1503        24042 :       res.range.likely = res.range.min;
    1504        24042 :       if (maybebase
    1505        24042 :           && base != 10
    1506        24042 :           && (tree_int_cst_sgn (argmin) < 0 || tree_int_cst_sgn (argmax) > 0))
    1507              :         {
    1508          222 :           if (res.range.min == 1)
    1509          308 :             res.range.likely += base == 8 ? 1 : 2;
    1510           36 :           else if (res.range.min == 2
    1511           12 :                    && (base == 16 || base == 2)
    1512            5 :                    && (dir.width[0] == 2 || dir.prec[0] == 2))
    1513            5 :             ++res.range.likely;
    1514              :         }
    1515              :     }
    1516              : 
    1517        42434 :   res.range.unlikely = res.range.max;
    1518        42434 :   res.adjust_for_width_or_precision (dir.width, dirtype, base, adj);
    1519        42434 :   res.adjust_for_width_or_precision (dir.prec, dirtype, base, adj);
    1520              : 
    1521        42434 :   return res;
    1522              : }
    1523              : 
    1524              : /* Return the number of bytes that a format directive consisting of FLAGS,
    1525              :    PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
    1526              :    would result for argument X under ideal conditions (i.e., if PREC
    1527              :    weren't excessive).  MPFR 3.1 allocates large amounts of memory for
    1528              :    values of PREC with large magnitude and can fail (see MPFR bug #21056).
    1529              :    This function works around those problems.  */
    1530              : 
    1531              : static unsigned HOST_WIDE_INT
    1532         5844 : get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
    1533              :                         char spec, char rndspec)
    1534              : {
    1535         5844 :   char fmtstr[40];
    1536              : 
    1537         5844 :   HOST_WIDE_INT len = strlen (flags);
    1538              : 
    1539         5844 :   fmtstr[0] = '%';
    1540         5844 :   memcpy (fmtstr + 1, flags, len);
    1541         5844 :   memcpy (fmtstr + 1 + len, ".*R", 3);
    1542         5844 :   fmtstr[len + 4] = rndspec;
    1543         5844 :   fmtstr[len + 5] = spec;
    1544         5844 :   fmtstr[len + 6] = '\0';
    1545              : 
    1546         5844 :   spec = TOUPPER (spec);
    1547         5844 :   if (spec == 'E' || spec == 'F')
    1548              :     {
    1549              :       /* For %e, specify the precision explicitly since mpfr_sprintf
    1550              :          does its own thing just to be different (see MPFR bug 21088).  */
    1551         4158 :       if (prec < 0)
    1552         5844 :         prec = 6;
    1553              :     }
    1554              :   else
    1555              :     {
    1556              :       /* Avoid passing negative precisions with larger magnitude to MPFR
    1557              :          to avoid exposing its bugs.  (A negative precision is supposed
    1558              :          to be ignored.)  */
    1559         1686 :       if (prec < 0)
    1560         5844 :         prec = -1;
    1561              :     }
    1562              : 
    1563         5844 :   HOST_WIDE_INT p = prec;
    1564              : 
    1565         5844 :   if (spec == 'G' && !strchr (flags, '#'))
    1566              :     {
    1567              :       /* For G/g without the pound flag, precision gives the maximum number
    1568              :          of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
    1569              :          a 128 bit IEEE extended precision, 4932.  Using twice as much here
    1570              :          should be more than sufficient for any real format.  */
    1571         1445 :       if ((IEEE_MAX_10_EXP * 2) < prec)
    1572           18 :         prec = IEEE_MAX_10_EXP * 2;
    1573              :       p = prec;
    1574              :     }
    1575              :   else
    1576              :     {
    1577              :       /* Cap precision arbitrarily at 1KB and add the difference
    1578              :          (if any) to the MPFR result.  */
    1579         4399 :       if (prec > 1024)
    1580              :         p = 1024;
    1581              :     }
    1582              : 
    1583         5844 :   len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
    1584              : 
    1585              :   /* Handle the unlikely (impossible?) error by returning more than
    1586              :      the maximum dictated by the function's return type.  */
    1587         5844 :   if (len < 0)
    1588            0 :     return target_dir_max () + 1;
    1589              : 
    1590              :   /* Adjust the return value by the difference.  */
    1591         5844 :   if (p < prec)
    1592          158 :     len += prec - p;
    1593              : 
    1594         5844 :   return len;
    1595              : }
    1596              : 
    1597              : /* Return the number of bytes to format using the format specifier
    1598              :    SPEC and the precision PREC the largest value in the real floating
    1599              :    TYPE.  */
    1600              : 
    1601              : static unsigned HOST_WIDE_INT
    1602         4682 : format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
    1603              : {
    1604         4682 :   machine_mode mode = TYPE_MODE (type);
    1605              : 
    1606              :   /* IBM Extended mode.  */
    1607        32774 :   if (MODE_COMPOSITE_P (mode))
    1608            0 :     mode = DFmode;
    1609              : 
    1610              :   /* Get the real type format description for the target.  */
    1611         4682 :   const real_format *rfmt = REAL_MODE_FORMAT (mode);
    1612         4682 :   REAL_VALUE_TYPE rv;
    1613              : 
    1614         4682 :   real_maxval (&rv, 0, mode);
    1615              : 
    1616              :   /* Convert the GCC real value representation with the precision
    1617              :      of the real type to the mpfr_t format with the GCC default
    1618              :      round-to-nearest mode.  */
    1619         4682 :   mpfr_t x;
    1620         4682 :   mpfr_init2 (x, rfmt->p);
    1621         4682 :   mpfr_from_real (x, &rv, MPFR_RNDN);
    1622              : 
    1623              :   /* Return a value one greater to account for the leading minus sign.  */
    1624         4682 :   unsigned HOST_WIDE_INT r
    1625         4682 :     = 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
    1626         4682 :   mpfr_clear (x);
    1627         4682 :   return r;
    1628              : }
    1629              : 
    1630              : /* Return a range representing the minimum and maximum number of bytes
    1631              :    that the directive DIR will output for any argument.  PREC gives
    1632              :    the adjusted precision range to account for negative precisions
    1633              :    meaning the default 6.  This function is used when the directive
    1634              :    argument or its value isn't known.  */
    1635              : 
    1636              : static fmtresult
    1637         4774 : format_floating (const directive &dir, const HOST_WIDE_INT prec[2])
    1638              : {
    1639         4774 :   tree type;
    1640              : 
    1641         4774 :   switch (dir.modifier)
    1642              :     {
    1643         4379 :     case FMT_LEN_l:
    1644         4379 :     case FMT_LEN_none:
    1645         4379 :       type = double_type_node;
    1646         4379 :       break;
    1647              : 
    1648          285 :     case FMT_LEN_L:
    1649          285 :       type = long_double_type_node;
    1650          285 :       break;
    1651              : 
    1652           18 :     case FMT_LEN_ll:
    1653           18 :       type = long_double_type_node;
    1654           18 :       break;
    1655              : 
    1656           92 :     default:
    1657           92 :       return fmtresult ();
    1658              :     }
    1659              : 
    1660              :   /* The minimum and maximum number of bytes produced by the directive.  */
    1661         4682 :   fmtresult res;
    1662              : 
    1663              :   /* The minimum output as determined by flags.  It's always at least 1.
    1664              :      When plus or space are set the output is preceded by either a sign
    1665              :      or a space.  */
    1666         4682 :   unsigned flagmin = (1 /* for the first digit */
    1667         4682 :                       + (dir.get_flag ('+') | dir.get_flag (' ')));
    1668              : 
    1669              :   /* The minimum is 3 for "inf" and "nan" for all specifiers, plus 1
    1670              :      for the plus sign/space with the '+' and ' ' flags, respectively,
    1671              :      unless reduced below.  */
    1672         4682 :   res.range.min = 2 + flagmin;
    1673              : 
    1674              :   /* When the pound flag is set the decimal point is included in output
    1675              :      regardless of precision.  Whether or not a decimal point is included
    1676              :      otherwise depends on the specification and precision.  */
    1677         4682 :   bool radix = dir.get_flag ('#');
    1678              : 
    1679         4682 :   switch (dir.specifier)
    1680              :     {
    1681          115 :     case 'A':
    1682          115 :     case 'a':
    1683          115 :       {
    1684          115 :         HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
    1685          115 :         if (dir.prec[0] <= 0)
    1686              :           minprec = 0;
    1687           24 :         else if (dir.prec[0] > 0)
    1688           24 :           minprec = dir.prec[0] + !radix /* decimal point */;
    1689              : 
    1690          115 :         res.range.likely = (2 /* 0x */
    1691              :                             + flagmin
    1692          115 :                             + radix
    1693          115 :                             + minprec
    1694          115 :                             + 3 /* p+0 */);
    1695              : 
    1696          115 :         res.range.max = format_floating_max (type, 'a', prec[1]);
    1697              : 
    1698              :         /* The unlikely maximum accounts for the longest multibyte
    1699              :            decimal point character.  */
    1700          115 :         res.range.unlikely = res.range.max;
    1701          115 :         if (dir.prec[1] > 0)
    1702           38 :           res.range.unlikely += target_mb_len_max () - 1;
    1703              : 
    1704              :         break;
    1705              :       }
    1706              : 
    1707          311 :     case 'E':
    1708          311 :     case 'e':
    1709          311 :       {
    1710              :         /* Minimum output attributable to precision and, when it's
    1711              :            non-zero, decimal point.  */
    1712          311 :         HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
    1713              : 
    1714              :         /* The likely minimum output is "[-+]1.234567e+00" regardless
    1715              :            of the value of the actual argument.  */
    1716          311 :         res.range.likely = (flagmin
    1717          311 :                             + radix
    1718          311 :                             + minprec
    1719          311 :                             + 2 /* e+ */ + 2);
    1720              : 
    1721          311 :         res.range.max = format_floating_max (type, 'e', prec[1]);
    1722              : 
    1723              :         /* The unlikely maximum accounts for the longest multibyte
    1724              :            decimal point character.  */
    1725          311 :         if (dir.prec[0] != dir.prec[1]
    1726          261 :             || dir.prec[0] == -1 || dir.prec[0] > 0)
    1727          270 :           res.range.unlikely = res.range.max + target_mb_len_max () -1;
    1728              :         else
    1729           41 :           res.range.unlikely = res.range.max;
    1730              :         break;
    1731              :       }
    1732              : 
    1733         2964 :     case 'F':
    1734         2964 :     case 'f':
    1735         2964 :       {
    1736              :         /* Minimum output attributable to precision and, when it's non-zero,
    1737              :            decimal point.  */
    1738         2964 :         HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
    1739              : 
    1740              :         /* For finite numbers (i.e., not infinity or NaN) the lower bound
    1741              :            when precision isn't specified is 8 bytes ("1.23456" since
    1742              :            precision is taken to be 6).  When precision is zero, the lower
    1743              :            bound is 1 byte (e.g., "1").  Otherwise, when precision is greater
    1744              :            than zero, then the lower bound is 2 plus precision (plus flags).
    1745              :            But in all cases, the lower bound is no greater than 3.  */
    1746         2964 :         unsigned HOST_WIDE_INT min = flagmin + radix + minprec;
    1747         2964 :         if (min < res.range.min)
    1748          162 :           res.range.min = min;
    1749              : 
    1750              :         /* Compute the upper bound for -TYPE_MAX.  */
    1751         2964 :         res.range.max = format_floating_max (type, 'f', prec[1]);
    1752              : 
    1753              :         /* The minimum output with unknown precision is a single byte
    1754              :            (e.g., "0") but the more likely output is 3 bytes ("0.0").  */
    1755         2964 :         if (dir.prec[0] < 0 && dir.prec[1] > 0)
    1756           44 :           res.range.likely = 3;
    1757              :         else
    1758         2920 :           res.range.likely = min;
    1759              : 
    1760              :         /* The unlikely maximum accounts for the longest multibyte
    1761              :            decimal point character.  */
    1762         2964 :         if (dir.prec[0] != dir.prec[1]
    1763         2917 :             || dir.prec[0] == -1 || dir.prec[0] > 0)
    1764         2847 :           res.range.unlikely = res.range.max + target_mb_len_max () - 1;
    1765              :         break;
    1766              :       }
    1767              : 
    1768         1292 :     case 'G':
    1769         1292 :     case 'g':
    1770         1292 :       {
    1771              :         /* The %g output depends on precision and the exponent of
    1772              :            the argument.  Since the value of the argument isn't known
    1773              :            the lower bound on the range of bytes (not counting flags
    1774              :            or width) is 1 plus radix (i.e., either "0" or "0." for
    1775              :            "%g" and "%#g", respectively, with a zero argument).  */
    1776         1292 :         unsigned HOST_WIDE_INT min = flagmin + radix;
    1777         1292 :         if (min < res.range.min)
    1778         1292 :           res.range.min = min;
    1779              : 
    1780         1292 :         char spec = 'g';
    1781         1292 :         HOST_WIDE_INT maxprec = dir.prec[1];
    1782         1292 :         if (radix && maxprec)
    1783              :           {
    1784              :             /* When the pound flag (radix) is set, trailing zeros aren't
    1785              :                trimmed and so the longest output is the same as for %e,
    1786              :                except with precision minus 1 (as specified in C11).  */
    1787           19 :             spec = 'e';
    1788           19 :             if (maxprec > 0)
    1789            8 :               --maxprec;
    1790              :             else if (maxprec < 0)
    1791              :               maxprec = 5;
    1792              :           }
    1793              :         else
    1794         1273 :           maxprec = prec[1];
    1795              : 
    1796         1292 :         res.range.max = format_floating_max (type, spec, maxprec);
    1797              : 
    1798              :         /* The likely output is either the maximum computed above
    1799              :            minus 1 (assuming the maximum is positive) when precision
    1800              :            is known (or unspecified), or the same minimum as for %e
    1801              :            (which is computed for a non-negative argument).  Unlike
    1802              :            for the other specifiers above the likely output isn't
    1803              :            the minimum because for %g that's 1 which is unlikely.  */
    1804         1292 :         if (dir.prec[1] < 0
    1805         1292 :             || (unsigned HOST_WIDE_INT)dir.prec[1] < target_int_max ())
    1806         1278 :           res.range.likely = res.range.max - 1;
    1807              :         else
    1808              :           {
    1809           14 :             HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
    1810           14 :             res.range.likely = (flagmin
    1811           14 :                                 + radix
    1812           14 :                                 + minprec
    1813           14 :                                 + 2 /* e+ */ + 2);
    1814              :           }
    1815              : 
    1816              :         /* The unlikely maximum accounts for the longest multibyte
    1817              :            decimal point character.  */
    1818         1292 :         res.range.unlikely = res.range.max + target_mb_len_max () - 1;
    1819         1292 :         break;
    1820              :       }
    1821              : 
    1822            0 :     default:
    1823            0 :       return fmtresult ();
    1824              :     }
    1825              : 
    1826              :   /* Bump up the byte counters if WIDTH is greater.  */
    1827         4682 :   res.adjust_for_width_or_precision (dir.width);
    1828         4682 :   return res;
    1829              : }
    1830              : 
    1831              : /* Return a range representing the minimum and maximum number of bytes
    1832              :    that the directive DIR will write on output for the floating argument
    1833              :    ARG.  */
    1834              : 
    1835              : static fmtresult
    1836         5375 : format_floating (const directive &dir, tree arg, pointer_query &)
    1837              : {
    1838         5375 :   HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
    1839         5375 :   tree type = (dir.modifier == FMT_LEN_L || dir.modifier == FMT_LEN_ll
    1840         5375 :                ? long_double_type_node : double_type_node);
    1841              : 
    1842              :   /* For an indeterminate precision the lower bound must be assumed
    1843              :      to be zero.  */
    1844         5375 :   if (TOUPPER (dir.specifier) == 'A')
    1845              :     {
    1846              :       /* Get the number of fractional decimal digits needed to represent
    1847              :          the argument without a loss of accuracy.  */
    1848          195 :       unsigned fmtprec
    1849          195 :         = REAL_MODE_FORMAT (TYPE_MODE (type))->p;
    1850              : 
    1851              :       /* The precision of the IEEE 754 double format is 53.
    1852              :          The precision of all other GCC binary double formats
    1853              :          is 56 or less.  */
    1854          195 :       unsigned maxprec = fmtprec <= 56 ? 13 : 15;
    1855              : 
    1856              :       /* For %a, leave the minimum precision unspecified to let
    1857              :          MFPR trim trailing zeros (as it and many other systems
    1858              :          including Glibc happen to do) and set the maximum
    1859              :          precision to reflect what it would be with trailing zeros
    1860              :          present (as Solaris and derived systems do).  */
    1861          195 :       if (dir.prec[1] < 0)
    1862              :         {
    1863              :           /* Both bounds are negative implies that precision has
    1864              :              not been specified.  */
    1865           98 :           prec[0] = maxprec;
    1866           98 :           prec[1] = -1;
    1867              :         }
    1868           97 :       else if (dir.prec[0] < 0)
    1869              :         {
    1870              :           /* With a negative lower bound and a non-negative upper
    1871              :              bound set the minimum precision to zero and the maximum
    1872              :              to the greater of the maximum precision (i.e., with
    1873              :              trailing zeros present) and the specified upper bound.  */
    1874           21 :           prec[0] = 0;
    1875           21 :           prec[1] = dir.prec[1] < maxprec ? maxprec : dir.prec[1];
    1876              :         }
    1877              :     }
    1878         5180 :   else if (dir.prec[0] < 0)
    1879              :     {
    1880         4677 :       if (dir.prec[1] < 0)
    1881              :         {
    1882              :           /* A precision in a strictly negative range is ignored and
    1883              :              the default of 6 is used instead.  */
    1884         4544 :           prec[0] = prec[1] = 6;
    1885              :         }
    1886              :       else
    1887              :         {
    1888              :           /* For a precision in a partly negative range, the lower bound
    1889              :              must be assumed to be zero and the new upper bound is the
    1890              :              greater of 6 (the default precision used when the specified
    1891              :              precision is negative) and the upper bound of the specified
    1892              :              range.  */
    1893          133 :           prec[0] = 0;
    1894          133 :           prec[1] = dir.prec[1] < 6 ? 6 : dir.prec[1];
    1895              :         }
    1896              :     }
    1897              : 
    1898         5375 :   if (!arg
    1899         5276 :       || TREE_CODE (arg) != REAL_CST
    1900         5977 :       || !useless_type_conversion_p (type, TREE_TYPE (arg)))
    1901         4774 :     return format_floating (dir, prec);
    1902              : 
    1903              :   /* The minimum and maximum number of bytes produced by the directive.  */
    1904          601 :   fmtresult res;
    1905              : 
    1906              :   /* Get the real type format description for the target.  */
    1907          601 :   const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
    1908          601 :   const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
    1909              : 
    1910          601 :   if (!real_isfinite (rvp))
    1911              :     {
    1912              :       /* The format for Infinity and NaN is "[-]inf"/"[-]infinity"
    1913              :          and "[-]nan" with the choice being implementation-defined
    1914              :          but not locale dependent.  */
    1915           20 :       bool sign = dir.get_flag ('+') || real_isneg (rvp);
    1916           20 :       res.range.min = 3 + sign;
    1917              : 
    1918           20 :       res.range.likely = res.range.min;
    1919           20 :       res.range.max = res.range.min;
    1920              :       /* The unlikely maximum is "[-/+]infinity" or "[-/+][qs]nan".
    1921              :          For NaN, the C/POSIX standards specify two formats:
    1922              :            "[-/+]nan"
    1923              :          and
    1924              :            "[-/+]nan(n-char-sequence)"
    1925              :          No known printf implementation outputs the latter format but AIX
    1926              :          outputs QNaN and SNaN for quiet and signalling NaN, respectively,
    1927              :          so the unlikely maximum reflects that.  */
    1928           20 :       res.range.unlikely = sign + (real_isinf (rvp) ? 8 : 4);
    1929              : 
    1930              :       /* The range for infinity and NaN is known unless either width
    1931              :          or precision is unknown.  Width has the same effect regardless
    1932              :          of whether the argument is finite.  Precision is either ignored
    1933              :          (e.g., Glibc) or can have an effect on the short vs long format
    1934              :          such as inf/infinity (e.g., Solaris).  */
    1935           20 :       res.knownrange = dir.known_width_and_precision ();
    1936              : 
    1937              :       /* Adjust the range for width but ignore precision.  */
    1938           20 :       res.adjust_for_width_or_precision (dir.width);
    1939              : 
    1940           20 :       return res;
    1941              :     }
    1942              : 
    1943              :   char fmtstr [40];
    1944              :   char *pfmt = fmtstr;
    1945              : 
    1946              :   /* Append flags.  */
    1947         3486 :   for (const char *pf = "-+ #0"; *pf; ++pf)
    1948         2905 :     if (dir.get_flag (*pf))
    1949           12 :       *pfmt++ = *pf;
    1950              : 
    1951          581 :   *pfmt = '\0';
    1952              : 
    1953          581 :   {
    1954              :     /* Set up an array to easily iterate over.  */
    1955          581 :     unsigned HOST_WIDE_INT* const minmax[] = {
    1956              :       &res.range.min, &res.range.max
    1957          581 :     };
    1958              : 
    1959         1743 :     for (int i = 0; i != ARRAY_SIZE (minmax); ++i)
    1960              :       {
    1961              :         /* Convert the GCC real value representation with the precision
    1962              :            of the real type to the mpfr_t format rounding down in the
    1963              :            first iteration that computes the minimum and up in the second
    1964              :            that computes the maximum.  This order is arbitrary because
    1965              :            rounding in either direction can result in longer output.  */
    1966         1162 :         mpfr_t mpfrval;
    1967         1162 :         mpfr_init2 (mpfrval, rfmt->p);
    1968         1743 :         mpfr_from_real (mpfrval, rvp, i ? MPFR_RNDU : MPFR_RNDD);
    1969              : 
    1970              :         /* Use the MPFR rounding specifier to round down in the first
    1971              :            iteration and then up.  In most but not all cases this will
    1972              :            result in the same number of bytes.  */
    1973         1162 :         char rndspec = "DU"[i];
    1974              : 
    1975              :         /* Format it and store the result in the corresponding member
    1976              :            of the result struct.  */
    1977         2324 :         *minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
    1978         1162 :                                              dir.specifier, rndspec);
    1979         1162 :         mpfr_clear (mpfrval);
    1980              :       }
    1981              :   }
    1982              : 
    1983              :   /* Make sure the minimum is less than the maximum (MPFR rounding
    1984              :      in the call to mpfr_snprintf can result in the reverse.  */
    1985          581 :   if (res.range.max < res.range.min)
    1986              :     {
    1987           34 :       unsigned HOST_WIDE_INT tmp = res.range.min;
    1988           34 :       res.range.min = res.range.max;
    1989           34 :       res.range.max = tmp;
    1990              :     }
    1991              : 
    1992              :   /* The range is known unless either width or precision is unknown.  */
    1993          581 :   res.knownrange = dir.known_width_and_precision ();
    1994              : 
    1995              :   /* For the same floating point constant, unless width or precision
    1996              :      is unknown, use the longer output as the likely maximum since
    1997              :      with round to nearest either is equally likely.  Otherwise, when
    1998              :      precision is unknown, use the greater of the minimum and 3 as
    1999              :      the likely output (for "0.0" since zero precision is unlikely).  */
    2000          581 :   if (res.knownrange)
    2001          539 :     res.range.likely = res.range.max;
    2002           42 :   else if (res.range.min < 3
    2003           17 :            && dir.prec[0] < 0
    2004           57 :            && (unsigned HOST_WIDE_INT)dir.prec[1] == target_int_max ())
    2005           13 :     res.range.likely = 3;
    2006              :   else
    2007           29 :     res.range.likely = res.range.min;
    2008              : 
    2009          581 :   res.range.unlikely = res.range.max;
    2010              : 
    2011          581 :   if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
    2012              :     {
    2013              :       /* Unless the precision is zero output longer than 2 bytes may
    2014              :          include the decimal point which must be a single character
    2015              :          up to MB_LEN_MAX in length.  This is overly conservative
    2016              :          since in some conversions some constants result in no decimal
    2017              :          point (e.g., in %g).  */
    2018          528 :       res.range.unlikely += target_mb_len_max () - 1;
    2019              :     }
    2020              : 
    2021          581 :   res.adjust_for_width_or_precision (dir.width);
    2022          581 :   return res;
    2023              : }
    2024              : 
    2025              : /* Return a FMTRESULT struct set to the lengths of the shortest and longest
    2026              :    strings referenced by the expression STR, or (-1, -1) when not known.
    2027              :    Used by the format_string function below.  */
    2028              : 
    2029              : static fmtresult
    2030       296851 : get_string_length (tree str, gimple *stmt, unsigned HOST_WIDE_INT max_size,
    2031              :                    unsigned eltsize, pointer_query &ptr_qry)
    2032              : {
    2033       296851 :   if (!str)
    2034          575 :     return fmtresult ();
    2035              : 
    2036              :   /* Try to determine the dynamic string length first.
    2037              :      Set MAXBOUND to an arbitrary non-null non-integer node as a request
    2038              :      to have it set to the length of the longest string in a PHI.  */
    2039       296276 :   c_strlen_data lendata = { };
    2040       296276 :   lendata.maxbound = str;
    2041       296276 :   if (eltsize == 1)
    2042       295976 :     get_range_strlen_dynamic (str, stmt, &lendata, ptr_qry);
    2043              :   else
    2044              :     {
    2045              :       /* Determine the length of the shortest and longest string referenced
    2046              :          by STR.  Strings of unknown lengths are bounded by the sizes of
    2047              :          arrays that subexpressions of STR may refer to.  Pointers that
    2048              :          aren't known to point any such arrays result in LENDATA.MAXLEN
    2049              :          set to SIZE_MAX.  */
    2050          300 :       get_range_strlen (str, &lendata, eltsize);
    2051              :     }
    2052              : 
    2053              :   /* If LENDATA.MAXBOUND is not equal to .MINLEN it corresponds to the bound
    2054              :      of the largest array STR refers to, if known, or it's set to SIZE_MAX
    2055              :      otherwise.  */
    2056              : 
    2057              :   /* Return the default result when nothing is known about the string.  */
    2058       296276 :   if ((lendata.maxbound && !tree_fits_uhwi_p (lendata.maxbound))
    2059       296276 :       || !tree_fits_uhwi_p (lendata.maxlen))
    2060              :     {
    2061            0 :       fmtresult res;
    2062            0 :       res.nonstr = lendata.decl;
    2063            0 :       return res;
    2064              :     }
    2065              : 
    2066       296276 :   unsigned HOST_WIDE_INT lenmax = tree_to_uhwi (max_object_size ()) - 2;
    2067       296276 :   if (integer_zerop (lendata.minlen)
    2068        18919 :       && (!lendata.maxbound || lenmax <= tree_to_uhwi (lendata.maxbound))
    2069       308773 :       && lenmax <= tree_to_uhwi (lendata.maxlen))
    2070              :     {
    2071        12491 :       if (max_size > 0 && max_size < HOST_WIDE_INT_MAX)
    2072              :         {
    2073              :           /* Adjust the conservative unknown/unbounded result if MAX_SIZE
    2074              :              is valid.  Set UNLIKELY to maximum in case MAX_SIZE refers
    2075              :              to a subobject.
    2076              :              TODO: This is overly conservative.  Set UNLIKELY to the size
    2077              :              of the outermost enclosing declared object.  */
    2078           34 :           fmtresult res (0, max_size - 1);
    2079           34 :           res.nonstr = lendata.decl;
    2080           34 :           res.range.likely = res.range.max;
    2081           34 :           res.range.unlikely = HOST_WIDE_INT_MAX;
    2082           34 :           return res;
    2083              :         }
    2084              : 
    2085        12457 :       fmtresult res;
    2086        12457 :       res.nonstr = lendata.decl;
    2087        12457 :       return res;
    2088              :     }
    2089              : 
    2090              :   /* The minimum length of the string.  */
    2091       851355 :   HOST_WIDE_INT min
    2092       283785 :     = (tree_fits_uhwi_p (lendata.minlen)
    2093       283785 :        ? tree_to_uhwi (lendata.minlen)
    2094              :        : 0);
    2095              : 
    2096              :   /* The maximum length of the string; initially set to MAXBOUND which
    2097              :      may be less than MAXLEN, but may be adjusted up below.  */
    2098       567559 :   HOST_WIDE_INT max
    2099       283774 :     = (lendata.maxbound && tree_fits_uhwi_p (lendata.maxbound)
    2100       567559 :        ? tree_to_uhwi (lendata.maxbound)
    2101              :        : HOST_WIDE_INT_M1U);
    2102              : 
    2103              :   /* True if either the maximum length is unknown or (conservatively)
    2104              :      the array bound is less than the maximum length.  That can happen
    2105              :      when the length of the string is unknown but the array in which
    2106              :      the string is stored is a member of a struct.  The warning uses
    2107              :      the size of the member as the upper bound but the optimization
    2108              :      doesn't.  The optimization could still use the size of
    2109              :      enclosing object as the upper bound but that's not done here.  */
    2110       283785 :   const bool unbounded
    2111       283785 :     = (integer_all_onesp (lendata.maxlen)
    2112       283785 :        || (lendata.maxbound
    2113       282786 :            && tree_int_cst_lt (lendata.maxbound, lendata.maxlen)));
    2114              : 
    2115              :   /* Set the max/likely counters to unbounded when a minimum is known
    2116              :      but the maximum length isn't bounded.  This implies that STR is
    2117              :      a conditional expression involving a string of known length and
    2118              :      an expression of unknown/unbounded length.  */
    2119       283785 :   if (min
    2120       283785 :       && (unsigned HOST_WIDE_INT)min < HOST_WIDE_INT_M1U
    2121       277357 :       && unbounded)
    2122       283785 :     max = HOST_WIDE_INT_M1U;
    2123              : 
    2124              :   /* get_range_strlen() returns the target value of SIZE_MAX for
    2125              :      strings of unknown length.  Bump it up to HOST_WIDE_INT_M1U
    2126              :      which may be bigger.  */
    2127       283785 :   if ((unsigned HOST_WIDE_INT)min == target_size_max ())
    2128            0 :     min = HOST_WIDE_INT_M1U;
    2129       283785 :   if ((unsigned HOST_WIDE_INT)max == target_size_max ())
    2130          157 :     max = HOST_WIDE_INT_M1U;
    2131              : 
    2132       283785 :   fmtresult res (min, max);
    2133       283785 :   res.nonstr = lendata.decl;
    2134              : 
    2135              :   /* Set RES.KNOWNRANGE to true if and only if all strings referenced
    2136              :      by STR are known to be bounded (though not necessarily by their
    2137              :      actual length but perhaps by their maximum possible length).  */
    2138       283785 :   if (res.range.max < target_int_max ())
    2139              :     {
    2140              :       res.knownrange = true;
    2141              :       /* When the length of the longest string is known and not
    2142              :          excessive use it as the likely length of the string(s).  */
    2143              :       res.range.likely = res.range.max;
    2144              :     }
    2145              :   else
    2146              :     {
    2147              :       /* When the upper bound is unknown (it can be zero or excessive)
    2148              :          set the likely length to the greater of 1.  If MAXBOUND is
    2149              :          known, also reset the length of the lower bound to zero.  */
    2150          178 :       res.range.likely = res.range.min ? res.range.min : warn_level > 1;
    2151          178 :       if (lendata.maxbound && !integer_all_onesp (lendata.maxbound))
    2152              :         res.range.min = 0;
    2153              :     }
    2154              : 
    2155       283785 :   res.range.unlikely = unbounded ? HOST_WIDE_INT_MAX : res.range.max;
    2156              : 
    2157       283785 :   return res;
    2158              : }
    2159              : 
    2160              : /* Return the minimum and maximum number of characters formatted
    2161              :    by the '%c' format directives and its wide character form for
    2162              :    the argument ARG.  ARG can be null (for functions such as
    2163              :    vsprinf).  */
    2164              : 
    2165              : static fmtresult
    2166         1049 : format_character (const directive &dir, tree arg, pointer_query &ptr_qry)
    2167              : {
    2168         1049 :   fmtresult res;
    2169              : 
    2170         1049 :   res.knownrange = true;
    2171              : 
    2172         1049 :   if (dir.specifier == 'C' || dir.modifier == FMT_LEN_l)
    2173              :     {
    2174              :       /* A wide character can result in as few as zero bytes.  */
    2175          127 :       res.range.min = 0;
    2176              : 
    2177          127 :       HOST_WIDE_INT min, max;
    2178          127 :       if (get_int_range (arg, dir.info->callstmt, &min, &max, false, 0,
    2179              :                          ptr_qry.rvals))
    2180              :         {
    2181           66 :           if (min == 0 && max == 0)
    2182              :             {
    2183              :               /* In strict reading of older ISO C or POSIX, this required
    2184              :                  no characters to be emitted.  ISO C23 changes that, so
    2185              :                  does POSIX, to match what has been implemented in most of the
    2186              :                  implementations, namely emitting a single NUL character.
    2187              :                  Let's use 0 for minimum and 1 for all the other values.  */
    2188           23 :               res.range.max = 1;
    2189           23 :               res.range.likely = res.range.unlikely = 1;
    2190              :             }
    2191           43 :           else if (min >= 0 && min < 128)
    2192              :             {
    2193              :               /* Be conservative if the target execution character set
    2194              :                  is not a 1-to-1 mapping to the source character set or
    2195              :                  if the source set is not ASCII.  */
    2196           36 :               bool one_2_one_ascii
    2197           36 :                 = (target_to_host_charmap[0] == 1
    2198           36 :                    && target_to_host ('a') == 97);
    2199              : 
    2200              :               /* A wide character in the ASCII range most likely results
    2201              :                  in a single byte, and only unlikely in up to MB_LEN_MAX.  */
    2202           36 :               res.range.max = one_2_one_ascii ? 1 : target_mb_len_max ();
    2203           36 :               res.range.likely = 1;
    2204           36 :               res.range.unlikely = target_mb_len_max ();
    2205           36 :               res.mayfail = !one_2_one_ascii;
    2206              :             }
    2207              :           else
    2208              :             {
    2209              :               /* A wide character outside the ASCII range likely results
    2210              :                  in up to two bytes, and only unlikely in up to MB_LEN_MAX.  */
    2211            7 :               res.range.max = target_mb_len_max ();
    2212            7 :               res.range.likely = 2;
    2213            7 :               res.range.unlikely = res.range.max;
    2214              :               /* Converting such a character may fail.  */
    2215            7 :               res.mayfail = true;
    2216              :             }
    2217              :         }
    2218              :       else
    2219              :         {
    2220              :           /* An unknown wide character is treated the same as a wide
    2221              :              character outside the ASCII range.  */
    2222           61 :           res.range.max = target_mb_len_max ();
    2223           61 :           res.range.likely = 2;
    2224           61 :           res.range.unlikely = res.range.max;
    2225           61 :           res.mayfail = true;
    2226              :         }
    2227          127 :     }
    2228              :   else
    2229              :     {
    2230              :       /* A plain '%c' directive.  Its output is exactly 1.  */
    2231          922 :       res.range.min = res.range.max = 1;
    2232          922 :       res.range.likely = res.range.unlikely = 1;
    2233              :     }
    2234              : 
    2235              :   /* Bump up the byte counters if WIDTH is greater.  */
    2236         1049 :   return res.adjust_for_width_or_precision (dir.width);
    2237              : }
    2238              : 
    2239              : /* If TYPE is an array or struct or union, increment *FLDOFF by the starting
    2240              :    offset of the member that *OFF points into if one can be determined and
    2241              :    set *FLDSIZE to its size in bytes and decrement *OFF by the same.
    2242              :    Otherwise do nothing.  */
    2243              : 
    2244              : static void
    2245         3963 : set_aggregate_size_and_offset (tree type, HOST_WIDE_INT *fldoff,
    2246              :                                HOST_WIDE_INT *fldsize, HOST_WIDE_INT *off)
    2247              : {
    2248              :   /* The byte offset of the most basic struct member the byte
    2249              :      offset *OFF corresponds to, or for a (multidimensional)
    2250              :      array member, the byte offset of the array element.  */
    2251         3963 :   if (TREE_CODE (type) == ARRAY_TYPE
    2252         3963 :       && TREE_CODE (TREE_TYPE (type)) == ARRAY_TYPE)
    2253              :     {
    2254           32 :       HOST_WIDE_INT index = 0, arrsize = 0;
    2255           32 :       if (array_elt_at_offset (type, *off, &index, &arrsize))
    2256              :         {
    2257           16 :           *fldoff += index;
    2258           16 :           *fldsize = arrsize;
    2259              :         }
    2260              :       /* Otherwise leave *FLDOFF et al. unchanged.  */
    2261              :     }
    2262         3931 :   else if (RECORD_OR_UNION_TYPE_P (type))
    2263              :     {
    2264          701 :       HOST_WIDE_INT index = 0;
    2265          701 :       tree sub = field_at_offset (type, NULL_TREE, *off, &index);
    2266          701 :       if (sub)
    2267              :         {
    2268          687 :           tree subsize = DECL_SIZE_UNIT (sub);
    2269          687 :           if (*fldsize < HOST_WIDE_INT_MAX
    2270          687 :               && subsize
    2271          678 :               && tree_fits_uhwi_p (subsize))
    2272          678 :             *fldsize = tree_to_uhwi (subsize);
    2273              :           else
    2274            9 :             *fldsize = HOST_WIDE_INT_MAX;
    2275          687 :           *fldoff += index;
    2276          687 :           *off -= index;
    2277              :         }
    2278              :       /* Otherwise leave *FLDOFF et al. unchanged.  */
    2279              :     }
    2280         3963 : }
    2281              : 
    2282              : /* For an expression X of pointer type, recursively try to find its origin
    2283              :    (either object DECL or pointer such as PARM_DECL) Y and return such a Y.
    2284              :    When X refers to an array element or struct member, set *FLDOFF to
    2285              :    the offset of the element or member from the beginning of the "most
    2286              :    derived" object and *FLDSIZE to its size.  When nonnull, set *OFF to
    2287              :    the overall offset from the beginning of the object so that
    2288              :    *FLDOFF <= *OFF.  */
    2289              : 
    2290              : static tree
    2291        25695 : get_origin_and_offset_r (tree x, HOST_WIDE_INT *fldoff, HOST_WIDE_INT *fldsize,
    2292              :                          HOST_WIDE_INT *off)
    2293              : {
    2294        25695 :   HOST_WIDE_INT sizebuf = -1;
    2295        25695 :   if (!fldsize)
    2296         2189 :     fldsize = &sizebuf;
    2297              : 
    2298        25695 :   if (DECL_P (x))
    2299              :     {
    2300              :       /* Set the size if it hasn't been set yet.  */
    2301         6318 :       if (tree size = DECL_SIZE_UNIT (x))
    2302         5113 :         if (*fldsize < 0 && tree_fits_shwi_p (size))
    2303         5042 :           *fldsize = tree_to_shwi (size);
    2304              :       return x;
    2305              :     }
    2306              : 
    2307        19377 :   switch (TREE_CODE (x))
    2308              :     {
    2309         6451 :     case ADDR_EXPR:
    2310         6451 :       x = TREE_OPERAND (x, 0);
    2311         6451 :       return get_origin_and_offset_r (x, fldoff, fldsize, off);
    2312              : 
    2313         4632 :     case ARRAY_REF:
    2314         4632 :       {
    2315         4632 :         tree sub = TREE_OPERAND (x, 1);
    2316         4632 :         unsigned HOST_WIDE_INT idx =
    2317         4632 :           tree_fits_uhwi_p (sub) ? tree_to_uhwi (sub) : HOST_WIDE_INT_MAX;
    2318              : 
    2319         4632 :         tree elsz = array_ref_element_size (x);
    2320        13896 :         unsigned HOST_WIDE_INT elbytes =
    2321         4632 :           tree_fits_shwi_p (elsz) ? tree_to_shwi (elsz) : HOST_WIDE_INT_MAX;
    2322              : 
    2323         4632 :         unsigned HOST_WIDE_INT byteoff = idx * elbytes;
    2324              : 
    2325         4632 :         if (byteoff < HOST_WIDE_INT_MAX
    2326         4632 :             && elbytes < HOST_WIDE_INT_MAX
    2327         4632 :             && (elbytes == 0 || byteoff / elbytes == idx))
    2328              :           {
    2329              :             /* For in-bounds constant offsets into constant-sized arrays
    2330              :                bump up *OFF, and for what's likely arrays or structs of
    2331              :                arrays, also *FLDOFF, as necessary.  */
    2332         4632 :             if (off)
    2333         4632 :               *off += byteoff;
    2334         4632 :             if (elbytes > 1)
    2335         4580 :               *fldoff += byteoff;
    2336              :           }
    2337              :         else
    2338            0 :           *fldoff = HOST_WIDE_INT_MAX;
    2339              : 
    2340         4632 :         x = TREE_OPERAND (x, 0);
    2341         4632 :         return get_origin_and_offset_r (x, fldoff, fldsize, off);
    2342              :       }
    2343              : 
    2344         1648 :     case MEM_REF:
    2345         1648 :       if (off)
    2346              :         {
    2347         1648 :           tree offset = TREE_OPERAND (x, 1);
    2348         3296 :           *off = (tree_fits_uhwi_p (offset)
    2349         1648 :                   ? tree_to_uhwi (offset) : HOST_WIDE_INT_MAX);
    2350              :         }
    2351              : 
    2352         1648 :       x = TREE_OPERAND (x, 0);
    2353              : 
    2354         1648 :       if (off)
    2355              :         {
    2356         1648 :           tree xtype
    2357         1648 :             = (TREE_CODE (x) == ADDR_EXPR
    2358         1648 :                ? TREE_TYPE (TREE_OPERAND (x, 0)) : TREE_TYPE (TREE_TYPE (x)));
    2359              : 
    2360         1648 :           set_aggregate_size_and_offset (xtype, fldoff, fldsize, off);
    2361              :         }
    2362              : 
    2363         1648 :       return get_origin_and_offset_r (x, fldoff, fldsize, nullptr);
    2364              : 
    2365         2189 :     case COMPONENT_REF:
    2366         2189 :       {
    2367         2189 :         tree foff = component_ref_field_offset (x);
    2368         2189 :         tree fld = TREE_OPERAND (x, 1);
    2369         2189 :         if (!tree_fits_shwi_p (foff)
    2370         4378 :             || !tree_fits_shwi_p (DECL_FIELD_BIT_OFFSET (fld)))
    2371              :           return x;
    2372         2189 :         *fldoff += (tree_to_shwi (foff)
    2373         2189 :                     + (tree_to_shwi (DECL_FIELD_BIT_OFFSET (fld))
    2374         2189 :                        / BITS_PER_UNIT));
    2375              : 
    2376         2189 :         get_origin_and_offset_r (fld, fldoff, fldsize, off);
    2377         2189 :         x = TREE_OPERAND (x, 0);
    2378         2189 :         return get_origin_and_offset_r (x, fldoff, nullptr, off);
    2379              :       }
    2380              : 
    2381         3495 :     case SSA_NAME:
    2382         3495 :       {
    2383         3495 :         gimple *def = SSA_NAME_DEF_STMT (x);
    2384         3495 :         if (is_gimple_assign (def))
    2385              :           {
    2386         1842 :             tree_code code = gimple_assign_rhs_code (def);
    2387         1842 :             if (code == ADDR_EXPR)
    2388              :               {
    2389          555 :                 x = gimple_assign_rhs1 (def);
    2390          555 :                 return get_origin_and_offset_r (x, fldoff, fldsize, off);
    2391              :               }
    2392              : 
    2393         1287 :             if (code == POINTER_PLUS_EXPR)
    2394              :               {
    2395          378 :                 tree offset = gimple_assign_rhs2 (def);
    2396          378 :                 if (off && tree_fits_uhwi_p (offset))
    2397          163 :                   *off = tree_to_uhwi (offset);
    2398              : 
    2399          378 :                 x = gimple_assign_rhs1 (def);
    2400          378 :                 x = get_origin_and_offset_r (x, fldoff, fldsize, off);
    2401          378 :                 if (off && !tree_fits_uhwi_p (offset))
    2402          212 :                   *off = HOST_WIDE_INT_MAX;
    2403          212 :                 if (off)
    2404              :                   {
    2405          375 :                     tree xtype = TREE_TYPE (x);
    2406          375 :                     set_aggregate_size_and_offset (xtype, fldoff, fldsize, off);
    2407              :                   }
    2408              :                 return x;
    2409              :               }
    2410          909 :             else if (code == VAR_DECL)
    2411              :               {
    2412           86 :                 x = gimple_assign_rhs1 (def);
    2413           86 :                 return get_origin_and_offset_r (x, fldoff, fldsize, off);
    2414              :               }
    2415              :           }
    2416         1653 :         else if (gimple_nop_p (def) && SSA_NAME_VAR (x))
    2417              :           x = SSA_NAME_VAR (x);
    2418              : 
    2419         2476 :         tree xtype = TREE_TYPE (x);
    2420         2476 :         if (POINTER_TYPE_P (xtype))
    2421         2462 :           xtype = TREE_TYPE (xtype);
    2422              : 
    2423         2476 :         if (off)
    2424         1940 :           set_aggregate_size_and_offset (xtype, fldoff, fldsize, off);
    2425              :       }
    2426              : 
    2427              :     default:
    2428              :       break;
    2429              :     }
    2430              : 
    2431              :   return x;
    2432              : }
    2433              : 
    2434              : /* Nonrecursive version of the above.
    2435              :    The function never returns null unless X is null to begin with.  */
    2436              : 
    2437              : static tree
    2438        40276 : get_origin_and_offset (tree x, HOST_WIDE_INT *fldoff, HOST_WIDE_INT *off,
    2439              :                        HOST_WIDE_INT *fldsize = nullptr)
    2440              : {
    2441        40276 :   if (!x)
    2442              :     return NULL_TREE;
    2443              : 
    2444         7567 :   HOST_WIDE_INT sizebuf;
    2445         7567 :   if (!fldsize)
    2446         4233 :     fldsize = &sizebuf;
    2447              : 
    2448              :   /* Invalidate *FLDSIZE.  */
    2449         7567 :   *fldsize = -1;
    2450         7567 :   *fldoff = *off = 0;
    2451              : 
    2452         7567 :   return get_origin_and_offset_r (x, fldoff, fldsize, off);
    2453              : }
    2454              : 
    2455              : /* If ARG refers to the same (sub)object or array element as described
    2456              :    by DST and DST_FLD, return the byte offset into the struct member or
    2457              :    array element referenced by ARG and set *ARG_SIZE to the size of
    2458              :    the (sub)object.  Otherwise return HOST_WIDE_INT_MIN to indicate
    2459              :    that ARG and DST do not refer to the same object.  */
    2460              : 
    2461              : static HOST_WIDE_INT
    2462        21434 : alias_offset (tree arg, HOST_WIDE_INT *arg_size,
    2463              :               tree dst, HOST_WIDE_INT dst_fld)
    2464              : {
    2465              :   /* See if the argument refers to the same base object as the destination
    2466              :      of the formatted function call, and if so, try to determine if they
    2467              :      can alias.  */
    2468        21434 :   if (!arg || !dst || !ptr_derefs_may_alias_p (arg, dst))
    2469              :     return HOST_WIDE_INT_MIN;
    2470              : 
    2471              :   /* The two arguments may refer to the same object.  If they both refer
    2472              :      to a struct member, see if the members are one and the same.  If so,
    2473              :      return the offset into the member.  */
    2474         3334 :   HOST_WIDE_INT arg_off = 0, arg_fld = 0;
    2475              : 
    2476         3334 :   tree arg_orig = get_origin_and_offset (arg, &arg_fld, &arg_off, arg_size);
    2477              : 
    2478         3334 :   if (arg_orig == dst && arg_fld == dst_fld)
    2479          262 :     return arg_off;
    2480              : 
    2481              :   return HOST_WIDE_INT_MIN;
    2482              : }
    2483              : 
    2484              : /* Return the minimum and maximum number of characters formatted
    2485              :    by the '%s' format directive and its wide character form for
    2486              :    the argument ARG.  ARG can be null (for functions such as
    2487              :    vsprinf).  */
    2488              : 
    2489              : static fmtresult
    2490       296851 : format_string (const directive &dir, tree arg, pointer_query &ptr_qry)
    2491              : {
    2492       296851 :   fmtresult res;
    2493              : 
    2494              :   /* The size of the (sub)object ARG refers to.  Used to adjust
    2495              :      the conservative get_string_length() result.  */
    2496       296851 :   HOST_WIDE_INT arg_size = 0;
    2497              : 
    2498       296851 :   if (warn_restrict)
    2499              :     {
    2500              :       /* See if ARG might alias the destination of the call with
    2501              :          DST_ORIGIN and DST_FIELD.  If so, store the starting offset
    2502              :          so that the overlap can be determined for certain later,
    2503              :          when the amount of output of the call (including subsequent
    2504              :          directives) has been computed.  Otherwise, store HWI_MIN.  */
    2505        42868 :       res.dst_offset = alias_offset (arg, &arg_size, dir.info->dst_origin,
    2506        21434 :                                      dir.info->dst_field);
    2507        21434 :       if (res.dst_offset >= 0 && res.dst_offset <= arg_size)
    2508          140 :         arg_size -= res.dst_offset;
    2509              :       else
    2510        21294 :         arg_size = 0;
    2511              :     }
    2512              : 
    2513              :   /* Compute the range the argument's length can be in.  */
    2514       296851 :   int count_by = 1;
    2515       296851 :   if (dir.specifier == 'S' || dir.modifier == FMT_LEN_l)
    2516              :     {
    2517              :       /* Get a node for a C type that will be the same size
    2518              :          as a wchar_t on the target.  */
    2519          300 :       tree node = get_typenode_from_name (MODIFIED_WCHAR_TYPE);
    2520              : 
    2521              :       /* Now that we have a suitable node, get the number of
    2522              :          bytes it occupies.  */
    2523          300 :       count_by = int_size_in_bytes (node);
    2524          300 :       gcc_checking_assert (count_by == 2 || count_by == 4);
    2525              :     }
    2526              : 
    2527       296851 :   fmtresult slen =
    2528       296851 :     get_string_length (arg, dir.info->callstmt, arg_size, count_by, ptr_qry);
    2529       296851 :   if (slen.range.min == slen.range.max
    2530       290138 :       && slen.range.min < HOST_WIDE_INT_MAX)
    2531              :     {
    2532              :       /* The argument is either a string constant or it refers
    2533              :          to one of a number of strings of the same length.  */
    2534              : 
    2535              :       /* A '%s' directive with a string argument with constant length.  */
    2536       277106 :       res.range = slen.range;
    2537              : 
    2538       277106 :       if (dir.specifier == 'S'
    2539       277102 :           || dir.modifier == FMT_LEN_l)
    2540              :         {
    2541              :           /* In the worst case the length of output of a wide string S
    2542              :              is bounded by MB_LEN_MAX * wcslen (S).  */
    2543          116 :           res.range.max *= target_mb_len_max ();
    2544          116 :           res.range.unlikely = res.range.max;
    2545              :           /* It's likely that the total length is not more that
    2546              :              2 * wcslen (S).*/
    2547          116 :           res.range.likely = res.range.min * 2;
    2548              : 
    2549          116 :           if (dir.prec[1] >= 0
    2550           57 :               && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
    2551              :             {
    2552           51 :               res.range.max = dir.prec[1];
    2553           51 :               res.range.likely = dir.prec[1];
    2554           51 :               res.range.unlikely = dir.prec[1];
    2555              :             }
    2556              : 
    2557          116 :           if (dir.prec[0] < 0 && dir.prec[1] > -1)
    2558              :             res.range.min = 0;
    2559          112 :           else if (dir.prec[0] >= 0)
    2560           53 :             res.range.likely = dir.prec[0];
    2561              : 
    2562              :           /* Even a non-empty wide character string need not convert into
    2563              :              any bytes.  */
    2564          116 :           res.range.min = 0;
    2565              : 
    2566              :           /* A non-empty wide character conversion may fail.  */
    2567          116 :           if (slen.range.max > 0)
    2568           80 :             res.mayfail = true;
    2569              :         }
    2570              :       else
    2571              :         {
    2572       276990 :           res.knownrange = true;
    2573              : 
    2574       276990 :           if (dir.prec[0] < 0 && dir.prec[1] > -1)
    2575           16 :             res.range.min = 0;
    2576       276974 :           else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
    2577           65 :             res.range.min = dir.prec[0];
    2578              : 
    2579       276990 :           if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
    2580              :             {
    2581           47 :               res.range.max = dir.prec[1];
    2582           47 :               res.range.likely = dir.prec[1];
    2583           47 :               res.range.unlikely = dir.prec[1];
    2584              :             }
    2585              :         }
    2586              :     }
    2587        19745 :   else if (arg && integer_zerop (arg))
    2588              :     {
    2589              :       /* Handle null pointer argument.  */
    2590              : 
    2591           33 :       fmtresult res (0);
    2592           33 :       res.nullp = true;
    2593           33 :       return res;
    2594              :     }
    2595              :   else
    2596              :     {
    2597              :       /* For a '%s' and '%ls' directive with a non-constant string (either
    2598              :          one of a number of strings of known length or an unknown string)
    2599              :          the minimum number of characters is lesser of PRECISION[0] and
    2600              :          the length of the shortest known string or zero, and the maximum
    2601              :          is the lesser of the length of the longest known string or
    2602              :          PTRDIFF_MAX and PRECISION[1].  The likely length is either
    2603              :          the minimum at level 1 and the greater of the minimum and 1
    2604              :          at level 2.  This result is adjust upward for width (if it's
    2605              :          specified).  */
    2606              : 
    2607        19712 :       if (dir.specifier == 'S'
    2608        19677 :           || dir.modifier == FMT_LEN_l)
    2609              :         {
    2610              :           /* A wide character converts to as few as zero bytes.  */
    2611          178 :           slen.range.min = 0;
    2612          178 :           if (slen.range.max < target_int_max ())
    2613           43 :             slen.range.max *= target_mb_len_max ();
    2614              : 
    2615          178 :           if (slen.range.likely < target_int_max ())
    2616           50 :             slen.range.likely *= 2;
    2617              : 
    2618          178 :           if (slen.range.unlikely < target_int_max ())
    2619           42 :             slen.range.unlikely *= target_mb_len_max ();
    2620              : 
    2621              :           /* A non-empty wide character conversion may fail.  */
    2622          178 :           if (slen.range.max > 0)
    2623          178 :             res.mayfail = true;
    2624              :         }
    2625              : 
    2626        19712 :       res.range = slen.range;
    2627              : 
    2628        19712 :       if (dir.prec[0] >= 0)
    2629              :         {
    2630              :           /* Adjust the minimum to zero if the string length is unknown,
    2631              :              or at most the lower bound of the precision otherwise.  */
    2632          298 :           if (slen.range.min >= target_int_max ())
    2633          138 :             res.range.min = 0;
    2634          160 :           else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
    2635           21 :             res.range.min = dir.prec[0];
    2636              : 
    2637              :           /* Make both maxima no greater than the upper bound of precision.  */
    2638          298 :           if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
    2639          298 :               || slen.range.max >= target_int_max ())
    2640              :             {
    2641          228 :               res.range.max = dir.prec[1];
    2642          228 :               res.range.unlikely = dir.prec[1];
    2643              :             }
    2644              : 
    2645              :           /* If precision is constant, set the likely counter to the lesser
    2646              :              of it and the maximum string length.  Otherwise, if the lower
    2647              :              bound of precision is greater than zero, set the likely counter
    2648              :              to the minimum.  Otherwise set it to zero or one based on
    2649              :              the warning level.  */
    2650          298 :           if (dir.prec[0] == dir.prec[1])
    2651          162 :             res.range.likely
    2652          162 :               = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
    2653          162 :                  ? dir.prec[0] : slen.range.max);
    2654          136 :           else if (dir.prec[0] > 0)
    2655           39 :             res.range.likely = res.range.min;
    2656              :           else
    2657           97 :             res.range.likely = warn_level > 1;
    2658              :         }
    2659        19414 :       else if (dir.prec[1] >= 0)
    2660              :         {
    2661           98 :           res.range.min = 0;
    2662           98 :           if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
    2663           98 :             res.range.max = dir.prec[1];
    2664           98 :           res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
    2665           98 :           if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.unlikely)
    2666           98 :             res.range.unlikely = dir.prec[1];
    2667              :         }
    2668        19316 :       else if (slen.range.min >= target_int_max ())
    2669              :         {
    2670        12649 :           res.range.min = 0;
    2671        12649 :           res.range.max = HOST_WIDE_INT_MAX;
    2672              :           /* At level 1 strings of unknown length are assumed to be
    2673              :              empty, while at level 1 they are assumed to be one byte
    2674              :              long.  */
    2675        12649 :           res.range.likely = warn_level > 1;
    2676        12649 :           res.range.unlikely = HOST_WIDE_INT_MAX;
    2677              :         }
    2678              :       else
    2679              :         {
    2680              :           /* A string of unknown length unconstrained by precision is
    2681              :              assumed to be empty at level 1 and just one character long
    2682              :              at higher levels.  */
    2683         6667 :           if (res.range.likely >= target_int_max ())
    2684          115 :             res.range.likely = warn_level > 1;
    2685              :         }
    2686              :     }
    2687              : 
    2688              :   /* If the argument isn't a nul-terminated string and the number
    2689              :      of bytes on output isn't bounded by precision, set NONSTR.  */
    2690       296818 :   if (slen.nonstr && slen.range.min < (unsigned HOST_WIDE_INT)dir.prec[0])
    2691          141 :     res.nonstr = slen.nonstr;
    2692              : 
    2693              :   /* Bump up the byte counters if WIDTH is greater.  */
    2694       296818 :   return res.adjust_for_width_or_precision (dir.width);
    2695              : }
    2696              : 
    2697              : /* Format plain string (part of the format string itself).  */
    2698              : 
    2699              : static fmtresult
    2700       607884 : format_plain (const directive &dir, tree, pointer_query &)
    2701              : {
    2702       607884 :   fmtresult res (dir.len);
    2703       607884 :   return res;
    2704              : }
    2705              : 
    2706              : /* Return true if the RESULT of a directive in a call describe by INFO
    2707              :    should be diagnosed given the AVAILable space in the destination.  */
    2708              : 
    2709              : static bool
    2710      1050717 : should_warn_p (const call_info &info,
    2711              :                const result_range &avail, const result_range &result)
    2712              : {
    2713      1050717 :   if (result.max <= avail.min)
    2714              :     {
    2715              :       /* The least amount of space remaining in the destination is big
    2716              :          enough for the longest output.  */
    2717              :       return false;
    2718              :     }
    2719              : 
    2720        16517 :   if (info.bounded)
    2721              :     {
    2722         1404 :       if (warn_format_trunc == 1 && result.min <= avail.max
    2723         3388 :           && info.retval_used ())
    2724              :         {
    2725              :           /* The likely amount of space remaining in the destination is big
    2726              :              enough for the least output and the return value is used.  */
    2727              :           return false;
    2728              :         }
    2729              : 
    2730         1218 :       if (warn_format_trunc == 1 && result.likely <= avail.likely
    2731         2909 :           && !info.retval_used ())
    2732              :         {
    2733              :           /* The likely amount of space remaining in the destination is big
    2734              :              enough for the likely output and the return value is unused.  */
    2735              :           return false;
    2736              :         }
    2737              : 
    2738          761 :       if (warn_format_trunc == 2
    2739           84 :           && result.likely <= avail.min
    2740           69 :           && (result.max <= avail.min
    2741           69 :               || result.max > HOST_WIDE_INT_MAX))
    2742              :         {
    2743              :           /* The minimum amount of space remaining in the destination is big
    2744              :              enough for the longest output.  */
    2745           69 :           return false;
    2746              :         }
    2747              :     }
    2748              :   else
    2749              :     {
    2750        14496 :       if (warn_level == 1 && result.likely <= avail.likely)
    2751              :         {
    2752              :           /* The likely amount of space remaining in the destination is big
    2753              :              enough for the likely output.  */
    2754              :           return false;
    2755              :         }
    2756              : 
    2757         5787 :       if (warn_level == 2
    2758          301 :           && result.likely <= avail.min
    2759              :           && (result.max <= avail.min
    2760          183 :               || result.max > HOST_WIDE_INT_MAX))
    2761              :         {
    2762              :           /* The minimum amount of space remaining in the destination is big
    2763              :              enough for the longest output.  */
    2764          130 :           return false;
    2765              :         }
    2766              :     }
    2767              : 
    2768              :   return true;
    2769              : }
    2770              : 
    2771              : /* At format string location describe by DIRLOC in a call described
    2772              :    by INFO, issue a warning for a directive DIR whose output may be
    2773              :    in excess of the available space AVAIL_RANGE in the destination
    2774              :    given the formatting result FMTRES.  This function does nothing
    2775              :    except decide whether to issue a warning for a possible write
    2776              :    past the end or truncation and, if so, format the warning.
    2777              :    Return true if a warning has been issued.  */
    2778              : 
    2779              : static bool
    2780      1050717 : maybe_warn (substring_loc &dirloc, location_t argloc,
    2781              :             const call_info &info,
    2782              :             const result_range &avail_range, const result_range &res,
    2783              :             const directive &dir)
    2784              : {
    2785      1050717 :   if (!should_warn_p (info, avail_range, res))
    2786              :     return false;
    2787              : 
    2788              :   /* A warning will definitely be issued below.  */
    2789              : 
    2790              :   /* The maximum byte count to reference in the warning.  Larger counts
    2791              :      imply that the upper bound is unknown (and could be anywhere between
    2792              :      RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
    2793              :      than "between N and X" where X is some huge number.  */
    2794         6349 :   unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
    2795              : 
    2796              :   /* True when there is enough room in the destination for the least
    2797              :      amount of a directive's output but not enough for its likely or
    2798              :      maximum output.  */
    2799        12698 :   bool maybe = (res.min <= avail_range.max
    2800         6349 :                 && (avail_range.min < res.likely
    2801         3649 :                     || (res.max < HOST_WIDE_INT_MAX
    2802          244 :                         && avail_range.min < res.max)));
    2803              : 
    2804              :   /* Buffer for the directive in the host character set (used when
    2805              :      the source character set is different).  */
    2806         6349 :   char hostdir[32];
    2807              : 
    2808         6349 :   if (avail_range.min == avail_range.max)
    2809              :     {
    2810              :       /* The size of the destination region is exact.  */
    2811         5530 :       unsigned HOST_WIDE_INT navail = avail_range.max;
    2812              : 
    2813         5530 :       if (target_to_host (*dir.beg) != '%')
    2814              :         {
    2815              :           /* For plain character directives (i.e., the format string itself)
    2816              :              but not others, point the caret at the first character that's
    2817              :              past the end of the destination.  */
    2818          644 :           if (navail < dir.len)
    2819          644 :             dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
    2820              :         }
    2821              : 
    2822         5530 :       if (*dir.beg == '\0')
    2823              :         {
    2824              :           /* This is the terminating nul.  */
    2825          588 :           gcc_assert (res.min == 1 && res.min == res.max);
    2826              : 
    2827          588 :           return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
    2828          588 :                           info.bounded
    2829              :                           ? (maybe
    2830          140 :                              ? G_("%qE output may be truncated before the "
    2831              :                                   "last format character")
    2832              :                              : G_("%qE output truncated before the last "
    2833              :                                   "format character"))
    2834              :                           : (maybe
    2835          448 :                              ? G_("%qE may write a terminating nul past the "
    2836              :                                   "end of the destination")
    2837              :                              : G_("%qE writing a terminating nul past the "
    2838              :                                   "end of the destination")),
    2839         1176 :                           info.func);
    2840              :         }
    2841              : 
    2842         4942 :       if (res.min == res.max)
    2843              :         {
    2844          399 :           const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
    2845          399 :           if (!info.bounded)
    2846          349 :             return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
    2847              :                               "%<%.*s%> directive writing %wu byte into a "
    2848              :                               "region of size %wu",
    2849              :                               "%<%.*s%> directive writing %wu bytes into a "
    2850              :                               "region of size %wu",
    2851          349 :                               (int) dir.len, d, res.min, navail);
    2852           50 :           else if (maybe)
    2853            0 :             return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
    2854              :                               "%<%.*s%> directive output may be truncated "
    2855              :                               "writing %wu byte into a region of size %wu",
    2856              :                               "%<%.*s%> directive output may be truncated "
    2857              :                               "writing %wu bytes into a region of size %wu",
    2858            0 :                               (int) dir.len, d, res.min, navail);
    2859              :           else
    2860           50 :             return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
    2861              :                               "%<%.*s%> directive output truncated writing "
    2862              :                               "%wu byte into a region of size %wu",
    2863              :                               "%<%.*s%> directive output truncated writing "
    2864              :                               "%wu bytes into a region of size %wu",
    2865           50 :                               (int) dir.len, d, res.min, navail);
    2866              :         }
    2867         4543 :       if (res.min == 0 && res.max < maxbytes)
    2868          582 :         return fmtwarn (dirloc, argloc, NULL,
    2869              :                         info.warnopt (),
    2870          291 :                         info.bounded
    2871              :                         ? (maybe
    2872           87 :                            ? G_("%<%.*s%> directive output may be truncated "
    2873              :                                 "writing up to %wu bytes into a region of "
    2874              :                                 "size %wu")
    2875              :                            : G_("%<%.*s%> directive output truncated writing "
    2876              :                                 "up to %wu bytes into a region of size %wu"))
    2877              :                         : G_("%<%.*s%> directive writing up to %wu bytes "
    2878          291 :                              "into a region of size %wu"), (int) dir.len,
    2879              :                         target_to_host (hostdir, sizeof hostdir, dir.beg),
    2880          291 :                         res.max, navail);
    2881              : 
    2882         4252 :       if (res.min == 0 && maxbytes <= res.max)
    2883              :         /* This is a special case to avoid issuing the potentially
    2884              :            confusing warning:
    2885              :              writing 0 or more bytes into a region of size 0.  */
    2886         3409 :         return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
    2887         3409 :                         info.bounded
    2888              :                         ? (maybe
    2889          171 :                            ? G_("%<%.*s%> directive output may be truncated "
    2890              :                                 "writing likely %wu or more bytes into a "
    2891              :                                 "region of size %wu")
    2892              :                            : G_("%<%.*s%> directive output truncated writing "
    2893              :                                 "likely %wu or more bytes into a region of "
    2894              :                                 "size %wu"))
    2895              :                         : G_("%<%.*s%> directive writing likely %wu or more "
    2896         3409 :                              "bytes into a region of size %wu"), (int) dir.len,
    2897              :                         target_to_host (hostdir, sizeof hostdir, dir.beg),
    2898         6818 :                         res.likely, navail);
    2899              : 
    2900          843 :       if (res.max < maxbytes)
    2901         1670 :         return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
    2902          835 :                         info.bounded
    2903              :                         ? (maybe
    2904           76 :                            ? G_("%<%.*s%> directive output may be truncated "
    2905              :                                 "writing between %wu and %wu bytes into a "
    2906              :                                 "region of size %wu")
    2907              :                            : G_("%<%.*s%> directive output truncated "
    2908              :                                 "writing between %wu and %wu bytes into a "
    2909              :                                 "region of size %wu"))
    2910              :                         : G_("%<%.*s%> directive writing between %wu and "
    2911              :                              "%wu bytes into a region of size %wu"),
    2912          835 :                         (int) dir.len,
    2913              :                         target_to_host (hostdir, sizeof hostdir, dir.beg),
    2914          835 :                         res.min, res.max, navail);
    2915              : 
    2916           16 :       return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
    2917            8 :                       info.bounded
    2918              :                       ? (maybe
    2919            3 :                          ? G_("%<%.*s%> directive output may be truncated "
    2920              :                               "writing %wu or more bytes into a region of "
    2921              :                               "size %wu")
    2922              :                          : G_("%<%.*s%> directive output truncated writing "
    2923              :                               "%wu or more bytes into a region of size %wu"))
    2924              :                       : G_("%<%.*s%> directive writing %wu or more bytes "
    2925            8 :                            "into a region of size %wu"), (int) dir.len,
    2926              :                       target_to_host (hostdir, sizeof hostdir, dir.beg),
    2927            8 :                       res.min, navail);
    2928              :     }
    2929              : 
    2930              :   /* The size of the destination region is a range.  */
    2931              : 
    2932          819 :   if (target_to_host (*dir.beg) != '%')
    2933              :     {
    2934          620 :       unsigned HOST_WIDE_INT navail = avail_range.max;
    2935              : 
    2936              :       /* For plain character directives (i.e., the format string itself)
    2937              :          but not others, point the caret at the first character that's
    2938              :          past the end of the destination.  */
    2939          620 :       if (navail < dir.len)
    2940            1 :         dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
    2941              :     }
    2942              : 
    2943          819 :   if (*dir.beg == '\0')
    2944              :     {
    2945          473 :       gcc_assert (res.min == 1 && res.min == res.max);
    2946              : 
    2947          473 :       return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
    2948          473 :                       info.bounded
    2949              :                       ? (maybe
    2950           90 :                          ? G_("%qE output may be truncated before the last "
    2951              :                               "format character")
    2952              :                          : G_("%qE output truncated before the last format "
    2953              :                               "character"))
    2954              :                       : (maybe
    2955          383 :                          ? G_("%qE may write a terminating nul past the end "
    2956              :                               "of the destination")
    2957              :                          : G_("%qE writing a terminating nul past the end "
    2958          946 :                               "of the destination")), info.func);
    2959              :     }
    2960              : 
    2961          346 :   if (res.min == res.max)
    2962              :     {
    2963          149 :       const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
    2964          149 :       if (!info.bounded)
    2965          133 :         return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
    2966              :                           "%<%.*s%> directive writing %wu byte into a region "
    2967              :                           "of size between %wu and %wu",
    2968              :                           "%<%.*s%> directive writing %wu bytes into a region "
    2969          133 :                           "of size between %wu and %wu", (int) dir.len, d,
    2970          133 :                           res.min, avail_range.min, avail_range.max);
    2971           16 :       else if (maybe)
    2972           15 :         return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
    2973              :                           "%<%.*s%> directive output may be truncated writing "
    2974              :                           "%wu byte into a region of size between %wu and %wu",
    2975              :                           "%<%.*s%> directive output may be truncated writing "
    2976              :                           "%wu bytes into a region of size between %wu and "
    2977           15 :                           "%wu", (int) dir.len, d, res.min, avail_range.min,
    2978           15 :                           avail_range.max);
    2979              :       else
    2980            1 :         return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
    2981              :                           "%<%.*s%> directive output truncated writing %wu "
    2982              :                           "byte into a region of size between %wu and %wu",
    2983              :                           "%<%.*s%> directive output truncated writing %wu "
    2984              :                           "bytes into a region of size between %wu and %wu",
    2985            1 :                           (int) dir.len, d, res.min, avail_range.min,
    2986            1 :                           avail_range.max);
    2987              :     }
    2988              : 
    2989          197 :   if (res.min == 0 && res.max < maxbytes)
    2990            6 :     return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
    2991            3 :                     info.bounded
    2992              :                     ? (maybe
    2993            0 :                        ? G_("%<%.*s%> directive output may be truncated "
    2994              :                             "writing up to %wu bytes into a region of size "
    2995              :                             "between %wu and %wu")
    2996              :                        : G_("%<%.*s%> directive output truncated writing "
    2997              :                             "up to %wu bytes into a region of size between "
    2998              :                             "%wu and %wu"))
    2999              :                     : G_("%<%.*s%> directive writing up to %wu bytes "
    3000              :                          "into a region of size between %wu and %wu"),
    3001            3 :                     (int) dir.len,
    3002              :                     target_to_host (hostdir, sizeof hostdir, dir.beg),
    3003            3 :                     res.max, avail_range.min, avail_range.max);
    3004              : 
    3005          194 :   if (res.min == 0 && maxbytes <= res.max)
    3006              :     /* This is a special case to avoid issuing the potentially confusing
    3007              :        warning:
    3008              :          writing 0 or more bytes into a region of size between 0 and N.  */
    3009            1 :     return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
    3010            1 :                     info.bounded
    3011              :                     ? (maybe
    3012            0 :                        ? G_("%<%.*s%> directive output may be truncated "
    3013              :                             "writing likely %wu or more bytes into a region "
    3014              :                             "of size between %wu and %wu")
    3015              :                        : G_("%<%.*s%> directive output truncated writing "
    3016              :                             "likely %wu or more bytes into a region of size "
    3017              :                             "between %wu and %wu"))
    3018              :                     : G_("%<%.*s%> directive writing likely %wu or more bytes "
    3019              :                          "into a region of size between %wu and %wu"),
    3020            1 :                     (int) dir.len,
    3021              :                     target_to_host (hostdir, sizeof hostdir, dir.beg),
    3022            2 :                     res.likely, avail_range.min, avail_range.max);
    3023              : 
    3024          193 :   if (res.max < maxbytes)
    3025          386 :     return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
    3026          193 :                     info.bounded
    3027              :                     ? (maybe
    3028           59 :                        ? G_("%<%.*s%> directive output may be truncated "
    3029              :                             "writing between %wu and %wu bytes into a region "
    3030              :                             "of size between %wu and %wu")
    3031              :                        : G_("%<%.*s%> directive output truncated writing "
    3032              :                             "between %wu and %wu bytes into a region of size "
    3033              :                             "between %wu and %wu"))
    3034              :                     : G_("%<%.*s%> directive writing between %wu and "
    3035              :                          "%wu bytes into a region of size between %wu and "
    3036          193 :                          "%wu"), (int) dir.len,
    3037              :                     target_to_host (hostdir, sizeof hostdir, dir.beg),
    3038          193 :                     res.min, res.max, avail_range.min, avail_range.max);
    3039              : 
    3040            0 :   return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
    3041            0 :                   info.bounded
    3042              :                   ? (maybe
    3043            0 :                      ? G_("%<%.*s%> directive output may be truncated writing "
    3044              :                           "%wu or more bytes into a region of size between "
    3045              :                           "%wu and %wu")
    3046              :                      : G_("%<%.*s%> directive output truncated writing "
    3047              :                           "%wu or more bytes into a region of size between "
    3048              :                           "%wu and %wu"))
    3049              :                   : G_("%<%.*s%> directive writing %wu or more bytes "
    3050              :                        "into a region of size between %wu and %wu"),
    3051            0 :                   (int) dir.len,
    3052              :                   target_to_host (hostdir, sizeof hostdir, dir.beg),
    3053            0 :                   res.min, avail_range.min, avail_range.max);
    3054              : }
    3055              : 
    3056              : /* Given the formatting result described by RES and NAVAIL, the number
    3057              :    of available bytes in the destination, return the range of bytes
    3058              :    remaining in the destination.  */
    3059              : 
    3060              : static inline result_range
    3061      1052180 : bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
    3062              : {
    3063      1052180 :   result_range range;
    3064              : 
    3065      1052180 :   if (HOST_WIDE_INT_MAX <= navail)
    3066              :     {
    3067      1032275 :       range.min = range.max = range.likely = range.unlikely = navail;
    3068      1032275 :       return range;
    3069              :     }
    3070              : 
    3071              :   /* The lower bound of the available range is the available size
    3072              :      minus the maximum output size, and the upper bound is the size
    3073              :      minus the minimum.  */
    3074        19905 :   range.max = res.range.min < navail ? navail - res.range.min : 0;
    3075              : 
    3076        19905 :   range.likely = res.range.likely < navail ? navail - res.range.likely : 0;
    3077              : 
    3078        19905 :   if (res.range.max < HOST_WIDE_INT_MAX)
    3079        14599 :     range.min = res.range.max < navail ? navail - res.range.max : 0;
    3080              :   else
    3081         5306 :     range.min = range.likely;
    3082              : 
    3083        39810 :   range.unlikely = (res.range.unlikely < navail
    3084        19905 :                     ? navail - res.range.unlikely : 0);
    3085              : 
    3086        19905 :   return range;
    3087              : }
    3088              : 
    3089              : /* Compute the length of the output resulting from the directive DIR
    3090              :    in a call described by INFO and update the overall result of the call
    3091              :    in *RES.  Return true if the directive has been handled.  */
    3092              : 
    3093              : static bool
    3094      1054931 : format_directive (const call_info &info,
    3095              :                   format_result *res, const directive &dir,
    3096              :                   pointer_query &ptr_qry)
    3097              : {
    3098              :   /* Offset of the beginning of the directive from the beginning
    3099              :      of the format string.  */
    3100      1054931 :   size_t offset = dir.beg - info.fmtstr;
    3101      1054931 :   size_t start = offset;
    3102      1054931 :   size_t length = offset + dir.len - !!dir.len;
    3103              : 
    3104              :   /* Create a location for the whole directive from the % to the format
    3105              :      specifier.  */
    3106      2109862 :   substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
    3107      1054931 :                         offset, start, length);
    3108              : 
    3109              :   /* Also get the location of the argument if possible.
    3110              :      This doesn't work for integer literals or function calls.  */
    3111      1054931 :   location_t argloc = UNKNOWN_LOCATION;
    3112      1054931 :   if (dir.arg)
    3113       443162 :     argloc = EXPR_LOCATION (dir.arg);
    3114              : 
    3115              :   /* Bail when there is no function to compute the output length,
    3116              :      or when minimum length checking has been disabled.   */
    3117      1054931 :   if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
    3118              :     return false;
    3119              : 
    3120              :   /* Compute the range of lengths of the formatted output.  */
    3121      1052330 :   fmtresult fmtres = dir.fmtfunc (dir, dir.arg, ptr_qry);
    3122              : 
    3123              :   /* Record whether the output of all directives is known to be
    3124              :      bounded by some maximum, implying that their arguments are
    3125              :      either known exactly or determined to be in a known range
    3126              :      or, for strings, limited by the upper bounds of the arrays
    3127              :      they refer to.  */
    3128      1052330 :   res->knownrange &= fmtres.knownrange;
    3129              : 
    3130      1052330 :   if (!fmtres.knownrange)
    3131              :     {
    3132              :       /* Only when the range is known, check it against the host value
    3133              :          of INT_MAX + (the number of bytes of the "%.*Lf" directive with
    3134              :          INT_MAX precision, which is the longest possible output of any
    3135              :          single directive).  That's the largest valid byte count (though
    3136              :          not valid call to a printf-like function because it can never
    3137              :          return such a count).  Otherwise, the range doesn't correspond
    3138              :          to known values of the argument.  */
    3139        48896 :       if (fmtres.range.max > target_dir_max ())
    3140              :         {
    3141              :           /* Normalize the MAX counter to avoid having to deal with it
    3142              :              later.  The counter can be less than HOST_WIDE_INT_M1U
    3143              :              when compiling for an ILP32 target on an LP64 host.  */
    3144        13046 :           fmtres.range.max = HOST_WIDE_INT_M1U;
    3145              :           /* Disable exact and maximum length checking after a failure
    3146              :              to determine the maximum number of characters (for example
    3147              :              for wide characters or wide character strings) but continue
    3148              :              tracking the minimum number of characters.  */
    3149        13046 :           res->range.max = HOST_WIDE_INT_M1U;
    3150              :         }
    3151              : 
    3152        48896 :       if (fmtres.range.min > target_dir_max ())
    3153              :         {
    3154              :           /* Disable exact length checking after a failure to determine
    3155              :              even the minimum number of characters (it shouldn't happen
    3156              :              except in an error) but keep tracking the minimum and maximum
    3157              :              number of characters.  */
    3158              :           return true;
    3159              :         }
    3160              :     }
    3161              : 
    3162              :   /* Buffer for the directive in the host character set (used when
    3163              :      the source character set is different).  */
    3164      1052213 :   char hostdir[32];
    3165              : 
    3166      1052213 :   int dirlen = dir.len;
    3167              : 
    3168      1052213 :   if (fmtres.nullp)
    3169              :     {
    3170           62 :       fmtwarn (dirloc, argloc, NULL, info.warnopt (),
    3171              :                "%<%.*s%> directive argument is null",
    3172           33 :                dirlen, target_to_host (hostdir, sizeof hostdir, dir.beg));
    3173              : 
    3174              :       /* Don't bother processing the rest of the format string.  */
    3175           33 :       res->warned = true;
    3176           33 :       res->range.min = HOST_WIDE_INT_M1U;
    3177           33 :       res->range.max = HOST_WIDE_INT_M1U;
    3178           33 :       return false;
    3179              :     }
    3180              : 
    3181              :   /* Compute the number of available bytes in the destination.  There
    3182              :      must always be at least one byte of space for the terminating
    3183              :      NUL that's appended after the format string has been processed.  */
    3184      1052180 :   result_range avail_range = bytes_remaining (info.objsize, *res);
    3185              : 
    3186              :   /* If the argument aliases a part of the destination of the formatted
    3187              :      call at offset FMTRES.DST_OFFSET append the directive and its result
    3188              :      to the set of aliases for later processing.  */
    3189      1052180 :   if (fmtres.dst_offset != HOST_WIDE_INT_MIN)
    3190          262 :     res->append_alias (dir, fmtres.dst_offset, fmtres.range);
    3191              : 
    3192      1052180 :   bool warned = res->warned;
    3193              : 
    3194      1052180 :   if (!warned)
    3195      1050717 :     warned = maybe_warn (dirloc, argloc, info, avail_range,
    3196              :                          fmtres.range, dir);
    3197              : 
    3198              :   /* Bump up the total maximum if it isn't too big.  */
    3199      1052180 :   if (res->range.max < HOST_WIDE_INT_MAX
    3200      1009444 :       && fmtres.range.max < HOST_WIDE_INT_MAX)
    3201      1009442 :     res->range.max += fmtres.range.max;
    3202              : 
    3203              :   /* Raise the total unlikely maximum by the larger of the maximum
    3204              :      and the unlikely maximum.  */
    3205      1052180 :   unsigned HOST_WIDE_INT save = res->range.unlikely;
    3206      1052180 :   if (fmtres.range.max < fmtres.range.unlikely)
    3207         7894 :     res->range.unlikely += fmtres.range.unlikely;
    3208              :   else
    3209      1044286 :     res->range.unlikely += fmtres.range.max;
    3210              : 
    3211      1052180 :   if (res->range.unlikely < save)
    3212        40627 :     res->range.unlikely = HOST_WIDE_INT_M1U;
    3213              : 
    3214      1052180 :   res->range.min += fmtres.range.min;
    3215      1052180 :   res->range.likely += fmtres.range.likely;
    3216              : 
    3217              :   /* Has the minimum directive output length exceeded the maximum
    3218              :      of 4095 bytes required to be supported?  */
    3219      1052180 :   bool minunder4k = fmtres.range.min < 4096;
    3220      1052180 :   bool maxunder4k = fmtres.range.max < 4096;
    3221              :   /* Clear POSUNDER4K in the overall result if the maximum has exceeded
    3222              :      the 4k (this is necessary to avoid the return value optimization
    3223              :      that may not be safe in the maximum case).  */
    3224      1052180 :   if (!maxunder4k)
    3225        13783 :     res->posunder4k = false;
    3226              :   /* Also clear POSUNDER4K if the directive may fail.  */
    3227      1052180 :   if (fmtres.mayfail)
    3228          331 :     res->posunder4k = false;
    3229              : 
    3230      1052180 :   if (!warned
    3231              :       /* Only warn at level 2.  */
    3232      1048817 :       && warn_level > 1
    3233              :       /* Only warn for string functions.  */
    3234         1156 :       && info.is_string_func ()
    3235      1052566 :       && (!minunder4k
    3236          384 :           || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
    3237              :     {
    3238              :       /* The directive output may be longer than the maximum required
    3239              :          to be handled by an implementation according to 7.21.6.1, p15
    3240              :          of C11.  Warn on this only at level 2 but remember this and
    3241              :          prevent folding the return value when done.  This allows for
    3242              :          the possibility of the actual libc call failing due to ENOMEM
    3243              :          (like Glibc does with very large precision or width).
    3244              :          Issue the "may exceed" warning only for string functions and
    3245              :          not for fprintf or printf.  */
    3246              : 
    3247            6 :       if (fmtres.range.min == fmtres.range.max)
    3248            2 :         warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
    3249              :                           "%<%.*s%> directive output of %wu bytes exceeds "
    3250              :                           "minimum required size of 4095", dirlen,
    3251            2 :                           target_to_host (hostdir, sizeof hostdir, dir.beg),
    3252              :                           fmtres.range.min);
    3253            4 :       else if (!minunder4k)
    3254            0 :         warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
    3255              :                           "%<%.*s%> directive output between %wu and %wu "
    3256              :                           "bytes exceeds minimum required size of 4095",
    3257              :                           dirlen,
    3258            0 :                           target_to_host (hostdir, sizeof hostdir, dir.beg),
    3259              :                           fmtres.range.min, fmtres.range.max);
    3260            4 :       else if (!info.retval_used () && info.is_string_func ())
    3261            2 :         warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
    3262              :                           "%<%.*s%> directive output between %wu and %wu "
    3263              :                           "bytes may exceed minimum required size of "
    3264              :                           "4095",
    3265              :                           dirlen,
    3266            2 :                           target_to_host (hostdir, sizeof hostdir, dir.beg),
    3267              :                           fmtres.range.min, fmtres.range.max);
    3268              :     }
    3269              : 
    3270              :   /* Has the likely and maximum directive output exceeded INT_MAX?  */
    3271      1052180 :   bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
    3272              :   /* Don't consider the maximum to be in excess when it's the result
    3273              :      of a string of unknown length (i.e., whose maximum has been set
    3274              :      to be greater than or equal to HOST_WIDE_INT_MAX.  */
    3275      1052180 :   bool maxximax = (*dir.beg
    3276       906060 :                    && res->range.max > target_int_max ()
    3277      1083414 :                    && res->range.max < HOST_WIDE_INT_MAX);
    3278              : 
    3279      1052180 :   if (!warned
    3280              :       /* Warn for the likely output size at level 1.  */
    3281      1048813 :       && (likelyximax
    3282              :           /* But only warn for the maximum at level 2.  */
    3283      1048675 :           || (warn_level > 1
    3284         1048 :               && maxximax
    3285           84 :               && fmtres.range.max < HOST_WIDE_INT_MAX)))
    3286              :     {
    3287          222 :       if (fmtres.range.min > target_int_max ())
    3288              :         {
    3289              :           /* The directive output exceeds INT_MAX bytes.  */
    3290           32 :           if (fmtres.range.min == fmtres.range.max)
    3291           40 :             warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
    3292              :                               "%<%.*s%> directive output of %wu bytes exceeds "
    3293              :                               "%<INT_MAX%>", dirlen,
    3294              :                               target_to_host (hostdir, sizeof hostdir, dir.beg),
    3295              :                               fmtres.range.min);
    3296              :           else
    3297           24 :             warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
    3298              :                               "%<%.*s%> directive output between %wu and "
    3299              :                               "%wu bytes exceeds %<INT_MAX%>", dirlen,
    3300              :                               target_to_host (hostdir, sizeof hostdir, dir.beg),
    3301              :                               fmtres.range.min, fmtres.range.max);
    3302              :         }
    3303          190 :       else if (res->range.min > target_int_max ())
    3304              :         {
    3305              :           /* The directive output is under INT_MAX but causes the result
    3306              :              to exceed INT_MAX bytes.  */
    3307          104 :           if (fmtres.range.min == fmtres.range.max)
    3308          182 :             warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
    3309              :                               "%<%.*s%> directive output of %wu bytes causes "
    3310              :                               "result to exceed %<INT_MAX%>", dirlen,
    3311              :                               target_to_host (hostdir, sizeof hostdir, dir.beg),
    3312              :                               fmtres.range.min);
    3313              :           else
    3314           26 :             warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
    3315              :                               "%<%.*s%> directive output between %wu and "
    3316              :                               "%wu bytes causes result to exceed %<INT_MAX%>",
    3317              :                               dirlen,
    3318              :                               target_to_host (hostdir, sizeof hostdir, dir.beg),
    3319              :                               fmtres.range.min, fmtres.range.max);
    3320              :         }
    3321           86 :       else if ((!info.retval_used () || !info.bounded)
    3322           86 :                && (info.is_string_func ()))
    3323              :         /* Warn for calls to string functions that either aren't bounded
    3324              :            (sprintf) or whose return value isn't used.  */
    3325            0 :         warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
    3326              :                           "%<%.*s%> directive output between %wu and "
    3327              :                           "%wu bytes may cause result to exceed "
    3328              :                           "%<INT_MAX%>", dirlen,
    3329            0 :                           target_to_host (hostdir, sizeof hostdir, dir.beg),
    3330              :                           fmtres.range.min, fmtres.range.max);
    3331              :     }
    3332              : 
    3333      1048813 :   if (!warned && fmtres.nonstr)
    3334              :     {
    3335          274 :       warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
    3336              :                         "%<%.*s%> directive argument is not a nul-terminated "
    3337              :                         "string",
    3338              :                         dirlen,
    3339          141 :                         target_to_host (hostdir, sizeof hostdir, dir.beg));
    3340          141 :       if (warned && DECL_P (fmtres.nonstr))
    3341           51 :         inform (DECL_SOURCE_LOCATION (fmtres.nonstr),
    3342              :                 "referenced argument declared here");
    3343              :       return false;
    3344              :     }
    3345              : 
    3346         3503 :   if (warned && fmtres.range.min < fmtres.range.likely
    3347          653 :       && fmtres.range.likely < fmtres.range.max)
    3348          333 :     inform_n (info.fmtloc, fmtres.range.likely,
    3349              :               "assuming directive output of %wu byte",
    3350              :               "assuming directive output of %wu bytes",
    3351              :               fmtres.range.likely);
    3352              : 
    3353         3503 :   if (warned && fmtres.argmin)
    3354              :     {
    3355          387 :       if (fmtres.argmin == fmtres.argmax)
    3356            2 :         inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
    3357          385 :       else if (fmtres.knownrange)
    3358          179 :         inform (info.fmtloc, "directive argument in the range [%E, %E]",
    3359              :                 fmtres.argmin, fmtres.argmax);
    3360              :       else
    3361          206 :         inform (info.fmtloc,
    3362              :                 "using the range [%E, %E] for directive argument",
    3363              :                 fmtres.argmin, fmtres.argmax);
    3364              :     }
    3365              : 
    3366      1052039 :   res->warned |= warned;
    3367              : 
    3368      1052039 :   if (!dir.beg[0] && res->warned)
    3369              :     {
    3370         2038 :       location_t callloc = gimple_location (info.callstmt);
    3371              : 
    3372         2038 :       unsigned HOST_WIDE_INT min = res->range.min;
    3373         2038 :       unsigned HOST_WIDE_INT max = res->range.max;
    3374              : 
    3375         2038 :       if (info.objsize < HOST_WIDE_INT_MAX)
    3376              :         {
    3377              :           /* If a warning has been issued for buffer overflow or truncation
    3378              :              help the user figure out how big a buffer they need.  */
    3379              : 
    3380         1900 :           if (min == max)
    3381          675 :             inform_n (callloc, min,
    3382              :                       "%qE output %wu byte into a destination of size %wu",
    3383              :                       "%qE output %wu bytes into a destination of size %wu",
    3384          675 :                       info.func, min, info.objsize);
    3385         1225 :           else if (max < HOST_WIDE_INT_MAX)
    3386         1180 :             inform (callloc,
    3387              :                     "%qE output between %wu and %wu bytes into "
    3388              :                     "a destination of size %wu",
    3389         1180 :                     info.func, min, max, info.objsize);
    3390           45 :           else if (min < res->range.likely && res->range.likely < max)
    3391           25 :             inform (callloc,
    3392              :                     "%qE output %wu or more bytes (assuming %wu) into "
    3393              :                     "a destination of size %wu",
    3394           25 :                     info.func, min, res->range.likely, info.objsize);
    3395              :           else
    3396           20 :             inform (callloc,
    3397              :                     "%qE output %wu or more bytes into a destination of size "
    3398              :                     "%wu",
    3399           20 :                     info.func, min, info.objsize);
    3400              :         }
    3401          138 :       else if (!info.is_string_func ())
    3402              :         {
    3403              :           /* If the warning is for a file function like fprintf
    3404              :              of printf with no destination size just print the computed
    3405              :              result.  */
    3406          129 :           if (min == max)
    3407           77 :             inform_n (callloc, min,
    3408              :                       "%qE output %wu byte", "%qE output %wu bytes",
    3409           77 :                       info.func, min);
    3410           52 :           else if (max < HOST_WIDE_INT_MAX)
    3411           12 :             inform (callloc,
    3412              :                     "%qE output between %wu and %wu bytes",
    3413           12 :                     info.func, min, max);
    3414           40 :           else if (min < res->range.likely && res->range.likely < max)
    3415            0 :             inform (callloc,
    3416              :                     "%qE output %wu or more bytes (assuming %wu)",
    3417            0 :                     info.func, min, res->range.likely);
    3418              :           else
    3419           40 :             inform (callloc,
    3420              :                     "%qE output %wu or more bytes",
    3421           40 :                     info.func, min);
    3422              :         }
    3423              :     }
    3424              : 
    3425      1052039 :   if (dump_file && *dir.beg)
    3426              :     {
    3427            0 :       fprintf (dump_file,
    3428              :                "    Result: "
    3429              :                HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
    3430              :                HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC " ("
    3431              :                HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
    3432              :                HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ")\n",
    3433              :                fmtres.range.min, fmtres.range.likely,
    3434              :                fmtres.range.max, fmtres.range.unlikely,
    3435              :                res->range.min, res->range.likely,
    3436              :                res->range.max, res->range.unlikely);
    3437              :     }
    3438              : 
    3439              :   return true;
    3440              : }
    3441              : 
    3442              : /* Parse a format directive in function call described by INFO starting
    3443              :    at STR and populate DIR structure.  Bump up *ARGNO by the number of
    3444              :    arguments extracted for the directive.  Return the length of
    3445              :    the directive.  */
    3446              : 
    3447              : static size_t
    3448      1054931 : parse_directive (call_info &info,
    3449              :                  directive &dir, format_result *res,
    3450              :                  const char *str, unsigned *argno,
    3451              :                  range_query *query)
    3452              : {
    3453      1054931 :   const char *pcnt = strchr (str, target_percent);
    3454      1054931 :   dir.beg = str;
    3455              : 
    3456      1054931 :   if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
    3457              :     {
    3458              :       /* This directive is either a plain string or the terminating nul
    3459              :          (which isn't really a directive but it simplifies things to
    3460              :          handle it as if it were).  */
    3461       607886 :       dir.len = len;
    3462       607886 :       dir.fmtfunc = format_plain;
    3463              : 
    3464       607886 :       if (dump_file)
    3465              :         {
    3466            0 :           fprintf (dump_file, "  Directive %u at offset "
    3467              :                    HOST_WIDE_INT_PRINT_UNSIGNED ": \"%.*s\", "
    3468              :                    "length = " HOST_WIDE_INT_PRINT_UNSIGNED "\n",
    3469              :                    dir.dirno,
    3470            0 :                    (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
    3471              :                    (int)dir.len, dir.beg, (unsigned HOST_WIDE_INT) dir.len);
    3472              :         }
    3473              : 
    3474       607886 :       return len - !*str;
    3475              :     }
    3476              : 
    3477              :   /* Set the directive argument's number to correspond to its position
    3478              :      in the formatted function call's argument list.  */
    3479       447045 :   dir.argno = *argno;
    3480              : 
    3481       447045 :   const char *pf = pcnt + 1;
    3482              : 
    3483              :     /* POSIX numbered argument index or zero when none.  */
    3484       447045 :   HOST_WIDE_INT dollar = 0;
    3485              : 
    3486              :   /* With and precision.  -1 when not specified, HOST_WIDE_INT_MIN
    3487              :      when given by a va_list argument, and a non-negative value
    3488              :      when specified in the format string itself.  */
    3489       447045 :   HOST_WIDE_INT width = -1;
    3490       447045 :   HOST_WIDE_INT precision = -1;
    3491              : 
    3492              :   /* Pointers to the beginning of the width and precision decimal
    3493              :      string (if any) within the directive.  */
    3494       447045 :   const char *pwidth = 0;
    3495       447045 :   const char *pprec = 0;
    3496              : 
    3497              :   /* When the value of the decimal string that specifies width or
    3498              :      precision is out of range, points to the digit that causes
    3499              :      the value to exceed the limit.  */
    3500       447045 :   const char *werange = NULL;
    3501       447045 :   const char *perange = NULL;
    3502              : 
    3503              :   /* Width specified via the asterisk.  Need not be INTEGER_CST.
    3504              :      For vararg functions set to void_node.  */
    3505       447045 :   tree star_width = NULL_TREE;
    3506              : 
    3507              :   /* Width specified via the asterisk.  Need not be INTEGER_CST.
    3508              :      For vararg functions set to void_node.  */
    3509       447045 :   tree star_precision = NULL_TREE;
    3510              : 
    3511       447045 :   if (ISDIGIT (target_to_host (*pf)))
    3512              :     {
    3513              :       /* This could be either a POSIX positional argument, the '0'
    3514              :          flag, or a width, depending on what follows.  Store it as
    3515              :          width and sort it out later after the next character has
    3516              :          been seen.  */
    3517         1284 :       pwidth = pf;
    3518         1284 :       width = target_strtowi (&pf, &werange);
    3519              :     }
    3520       445761 :   else if (target_to_host (*pf) == '*')
    3521              :     {
    3522              :       /* Similarly to the block above, this could be either a POSIX
    3523              :          positional argument or a width, depending on what follows.  */
    3524          768 :       if (*argno < gimple_call_num_args (info.callstmt))
    3525          756 :         star_width = gimple_call_arg (info.callstmt, (*argno)++);
    3526              :       else
    3527           12 :         star_width = void_node;
    3528          768 :       ++pf;
    3529              :     }
    3530              : 
    3531       447045 :   if (target_to_host (*pf) == '$')
    3532              :     {
    3533              :       /* Handle the POSIX dollar sign which references the 1-based
    3534              :          positional argument number.  */
    3535          110 :       if (width != -1)
    3536          110 :         dollar = width + info.argidx;
    3537            0 :       else if (star_width
    3538            0 :                && TREE_CODE (star_width) == INTEGER_CST
    3539            0 :                && (TYPE_PRECISION (TREE_TYPE (star_width))
    3540            0 :                    <= TYPE_PRECISION (integer_type_node)))
    3541            0 :         dollar = width + tree_to_shwi (star_width);
    3542              : 
    3543              :       /* Bail when the numbered argument is out of range (it will
    3544              :          have already been diagnosed by -Wformat).  */
    3545          110 :       if (dollar == 0
    3546          106 :           || dollar == (int)info.argidx
    3547          214 :           || dollar > gimple_call_num_args (info.callstmt))
    3548              :         return false;
    3549              : 
    3550           96 :       --dollar;
    3551              : 
    3552           96 :       star_width = NULL_TREE;
    3553           96 :       width = -1;
    3554           96 :       ++pf;
    3555              :     }
    3556              : 
    3557       447031 :   if (dollar || !star_width)
    3558              :     {
    3559       446263 :       if (width != -1)
    3560              :         {
    3561         1174 :           if (width == 0)
    3562              :             {
    3563              :               /* The '0' that has been interpreted as a width above is
    3564              :                  actually a flag.  Reset HAVE_WIDTH, set the '0' flag,
    3565              :                  and continue processing other flags.  */
    3566          146 :               width = -1;
    3567          146 :               dir.set_flag ('0');
    3568              :             }
    3569         1028 :           else if (!dollar)
    3570              :             {
    3571              :               /* (Non-zero) width has been seen.  The next character
    3572              :                  is either a period or a digit.  */
    3573         1028 :               goto start_precision;
    3574              :             }
    3575              :         }
    3576              :       /* When either '$' has been seen, or width has not been seen,
    3577              :          the next field is the optional flags followed by an optional
    3578              :          width.  */
    3579       448589 :       for ( ; ; ) {
    3580       446912 :         switch (target_to_host (*pf))
    3581              :           {
    3582         1677 :           case ' ':
    3583         1677 :           case '0':
    3584         1677 :           case '+':
    3585         1677 :           case '-':
    3586         1677 :           case '#':
    3587         1677 :             dir.set_flag (target_to_host (*pf++));
    3588         1677 :             break;
    3589              : 
    3590       445235 :           default:
    3591       445235 :             goto start_width;
    3592              :           }
    3593              :       }
    3594              : 
    3595       445235 :     start_width:
    3596       445235 :       if (ISDIGIT (target_to_host (*pf)))
    3597              :         {
    3598          319 :           werange = 0;
    3599          319 :           pwidth = pf;
    3600          319 :           width = target_strtowi (&pf, &werange);
    3601              :         }
    3602       444916 :       else if (target_to_host (*pf) == '*')
    3603              :         {
    3604           60 :           if (*argno < gimple_call_num_args (info.callstmt))
    3605           60 :             star_width = gimple_call_arg (info.callstmt, (*argno)++);
    3606              :           else
    3607              :             {
    3608              :               /* This is (likely) a va_list.  It could also be an invalid
    3609              :                  call with insufficient arguments.  */
    3610            0 :               star_width = void_node;
    3611              :             }
    3612           60 :           ++pf;
    3613              :         }
    3614       444856 :       else if (target_to_host (*pf) == '\'')
    3615              :         {
    3616              :           /* The POSIX apostrophe indicating a numeric grouping
    3617              :              in the current locale.  Even though it's possible to
    3618              :              estimate the upper bound on the size of the output
    3619              :              based on the number of digits it probably isn't worth
    3620              :              continuing.  */
    3621              :           return 0;
    3622              :         }
    3623              :     }
    3624              : 
    3625          768 :  start_precision:
    3626       446997 :   if (target_to_host (*pf) == '.')
    3627              :     {
    3628         1981 :       ++pf;
    3629              : 
    3630         1981 :       if (ISDIGIT (target_to_host (*pf)))
    3631              :         {
    3632          931 :           pprec = pf;
    3633          931 :           precision = target_strtowi (&pf, &perange);
    3634              :         }
    3635         1050 :       else if (target_to_host (*pf) == '*')
    3636              :         {
    3637          974 :           if (*argno < gimple_call_num_args (info.callstmt))
    3638          951 :             star_precision = gimple_call_arg (info.callstmt, (*argno)++);
    3639              :           else
    3640              :             {
    3641              :               /* This is (likely) a va_list.  It could also be an invalid
    3642              :                  call with insufficient arguments.  */
    3643           23 :               star_precision = void_node;
    3644              :             }
    3645          974 :           ++pf;
    3646              :         }
    3647              :       else
    3648              :         {
    3649              :           /* The decimal precision or the asterisk are optional.
    3650              :              When neither is specified it's taken to be zero.  */
    3651              :           precision = 0;
    3652              :         }
    3653              :     }
    3654              : 
    3655       446997 :   switch (target_to_host (*pf))
    3656              :     {
    3657         1090 :     case 'h':
    3658         1090 :       if (target_to_host (pf[1]) == 'h')
    3659              :         {
    3660          732 :           ++pf;
    3661          732 :           dir.modifier = FMT_LEN_hh;
    3662              :         }
    3663              :       else
    3664              :         dir.modifier = FMT_LEN_h;
    3665         1090 :       ++pf;
    3666         1090 :       break;
    3667              : 
    3668          108 :     case 'j':
    3669          108 :       dir.modifier = FMT_LEN_j;
    3670          108 :       ++pf;
    3671          108 :       break;
    3672              : 
    3673          440 :     case 'L':
    3674          440 :       dir.modifier = FMT_LEN_L;
    3675          440 :       ++pf;
    3676          440 :       break;
    3677              : 
    3678        15976 :     case 'l':
    3679        15976 :       if (target_to_host (pf[1]) == 'l')
    3680              :         {
    3681          736 :           ++pf;
    3682          736 :           dir.modifier = FMT_LEN_ll;
    3683              :         }
    3684              :       else
    3685              :         dir.modifier = FMT_LEN_l;
    3686        15976 :       ++pf;
    3687        15976 :       break;
    3688              : 
    3689           49 :     case 't':
    3690           49 :       dir.modifier = FMT_LEN_t;
    3691           49 :       ++pf;
    3692           49 :       break;
    3693              : 
    3694         1870 :     case 'z':
    3695         1870 :       dir.modifier = FMT_LEN_z;
    3696         1870 :       ++pf;
    3697         1870 :       break;
    3698              :     }
    3699              : 
    3700       446997 :   switch (target_to_host (*pf))
    3701              :     {
    3702              :       /* Handle a sole '%' character the same as "%%" but since it's
    3703              :          undefined prevent the result from being folded.  */
    3704            0 :     case '\0':
    3705            0 :       --pf;
    3706            0 :       res->range.min = res->range.max = HOST_WIDE_INT_M1U;
    3707              :       /* FALLTHRU */
    3708           88 :     case '%':
    3709           88 :       dir.fmtfunc = format_percent;
    3710           88 :       break;
    3711              : 
    3712         5375 :     case 'a':
    3713         5375 :     case 'A':
    3714         5375 :     case 'e':
    3715         5375 :     case 'E':
    3716         5375 :     case 'f':
    3717         5375 :     case 'F':
    3718         5375 :     case 'g':
    3719         5375 :     case 'G':
    3720         5375 :       res->floating = true;
    3721         5375 :       dir.fmtfunc = format_floating;
    3722         5375 :       break;
    3723              : 
    3724       140926 :     case 'd':
    3725       140926 :     case 'i':
    3726       140926 :     case 'o':
    3727       140926 :     case 'u':
    3728       140926 :     case 'x':
    3729       140926 :     case 'X':
    3730       140926 :       dir.fmtfunc = format_integer;
    3731       140926 :       break;
    3732              : 
    3733           80 :     case 'b':
    3734           80 :     case 'B':
    3735           80 :       dir.fmtfunc = format_integer;
    3736           80 :       break;
    3737              : 
    3738              :     case 'p':
    3739              :       /* The %p output is implementation-defined.  It's possible
    3740              :          to determine this format but due to extensions (especially
    3741              :          those of the Linux kernel -- see bug 78512) the first %p
    3742              :          in the format string disables any further processing.  */
    3743              :       return false;
    3744              : 
    3745           77 :     case 'n':
    3746              :       /* %n has side-effects even when nothing is actually printed to
    3747              :          any buffer.  */
    3748           77 :       info.nowrite = false;
    3749           77 :       dir.fmtfunc = format_none;
    3750           77 :       break;
    3751              : 
    3752         1049 :     case 'C':
    3753         1049 :     case 'c':
    3754              :       /* POSIX wide character and C/POSIX narrow character.  */
    3755         1049 :       dir.fmtfunc = format_character;
    3756         1049 :       break;
    3757              : 
    3758       296851 :     case 'S':
    3759       296851 :     case 's':
    3760              :       /* POSIX wide string and C/POSIX narrow character string.  */
    3761       296851 :       dir.fmtfunc = format_string;
    3762       296851 :       break;
    3763              : 
    3764              :     default:
    3765              :       /* Unknown conversion specification.  */
    3766              :       return 0;
    3767              :     }
    3768              : 
    3769       444446 :   dir.specifier = target_to_host (*pf++);
    3770              : 
    3771              :   /* Store the length of the format directive.  */
    3772       444446 :   dir.len = pf - pcnt;
    3773              : 
    3774              :   /* Buffer for the directive in the host character set (used when
    3775              :      the source character set is different).  */
    3776       444446 :   char hostdir[32];
    3777              : 
    3778       444446 :   if (star_width)
    3779              :     {
    3780          806 :       if (INTEGRAL_TYPE_P (TREE_TYPE (star_width)))
    3781          787 :         dir.set_width (star_width, query);
    3782              :       else
    3783              :         {
    3784              :           /* Width specified by a va_list takes on the range [0, -INT_MIN]
    3785              :              (width is the absolute value of that specified).  */
    3786           19 :           dir.width[0] = 0;
    3787           19 :           dir.width[1] = target_int_max () + 1;
    3788              :         }
    3789              :     }
    3790              :   else
    3791              :     {
    3792       443640 :       if (width == HOST_WIDE_INT_MAX && werange)
    3793              :         {
    3794            1 :           size_t begin = dir.beg - info.fmtstr + (pwidth - pcnt);
    3795            1 :           size_t caret = begin + (werange - pcnt);
    3796            1 :           size_t end = pf - info.fmtstr - 1;
    3797              : 
    3798              :           /* Create a location for the width part of the directive,
    3799              :              pointing the caret at the first out-of-range digit.  */
    3800            1 :           substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
    3801            1 :                                 caret, begin, end);
    3802              : 
    3803            2 :           fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
    3804            1 :                    "%<%.*s%> directive width out of range", (int) dir.len,
    3805              :                    target_to_host (hostdir, sizeof hostdir, dir.beg));
    3806              :         }
    3807              : 
    3808       443640 :       dir.set_width (width);
    3809              :     }
    3810              : 
    3811       444446 :   if (star_precision)
    3812              :     {
    3813          963 :       if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision)))
    3814          935 :         dir.set_precision (star_precision, query);
    3815              :       else
    3816              :         {
    3817              :           /* Precision specified by a va_list takes on the range [-1, INT_MAX]
    3818              :              (unlike width, negative precision is ignored).  */
    3819           28 :           dir.prec[0] = -1;
    3820           28 :           dir.prec[1] = target_int_max ();
    3821              :         }
    3822              :     }
    3823              :   else
    3824              :     {
    3825       443483 :       if (precision == HOST_WIDE_INT_MAX && perange)
    3826              :         {
    3827            1 :           size_t begin = dir.beg - info.fmtstr + (pprec - pcnt) - 1;
    3828            1 :           size_t caret = dir.beg - info.fmtstr + (perange - pcnt) - 1;
    3829            1 :           size_t end = pf - info.fmtstr - 2;
    3830              : 
    3831              :           /* Create a location for the precision part of the directive,
    3832              :              including the leading period, pointing the caret at the first
    3833              :              out-of-range digit .  */
    3834            1 :           substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
    3835            1 :                                 caret, begin, end);
    3836              : 
    3837            2 :           fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
    3838            1 :                    "%<%.*s%> directive precision out of range", (int) dir.len,
    3839              :                    target_to_host (hostdir, sizeof hostdir, dir.beg));
    3840              :         }
    3841              : 
    3842       443483 :       dir.set_precision (precision);
    3843              :     }
    3844              : 
    3845              :   /* Extract the argument if the directive takes one and if it's
    3846              :      available (e.g., the function doesn't take a va_list).  Treat
    3847              :      missing arguments the same as va_list, even though they will
    3848              :      have likely already been diagnosed by -Wformat.  */
    3849       444446 :   if (dir.specifier != '%'
    3850       444446 :       && *argno < gimple_call_num_args (info.callstmt))
    3851       443162 :     dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
    3852              : 
    3853       444446 :   if (dump_file)
    3854              :     {
    3855            0 :       fprintf (dump_file,
    3856              :                "  Directive %u at offset " HOST_WIDE_INT_PRINT_UNSIGNED
    3857              :                ": \"%.*s\"",
    3858              :                dir.dirno,
    3859            0 :                (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
    3860            0 :                (int)dir.len, dir.beg);
    3861            0 :       if (star_width)
    3862              :         {
    3863            0 :           if (dir.width[0] == dir.width[1])
    3864            0 :             fprintf (dump_file, ", width = " HOST_WIDE_INT_PRINT_DEC,
    3865              :                      dir.width[0]);
    3866              :           else
    3867            0 :             fprintf (dump_file,
    3868              :                      ", width in range [" HOST_WIDE_INT_PRINT_DEC
    3869              :                      ", " HOST_WIDE_INT_PRINT_DEC "]",
    3870              :                      dir.width[0], dir.width[1]);
    3871              :         }
    3872              : 
    3873            0 :       if (star_precision)
    3874              :         {
    3875            0 :           if (dir.prec[0] == dir.prec[1])
    3876            0 :             fprintf (dump_file, ", precision = " HOST_WIDE_INT_PRINT_DEC,
    3877              :                      dir.prec[0]);
    3878              :           else
    3879            0 :             fprintf (dump_file,
    3880              :                      ", precision in range [" HOST_WIDE_INT_PRINT_DEC
    3881              :                      HOST_WIDE_INT_PRINT_DEC "]",
    3882              :                      dir.prec[0], dir.prec[1]);
    3883              :         }
    3884            0 :       fputc ('\n', dump_file);
    3885              :     }
    3886              : 
    3887       444446 :   return dir.len;
    3888              : }
    3889              : 
    3890              : /* Diagnose overlap between destination and %s directive arguments.  */
    3891              : 
    3892              : static void
    3893       146120 : maybe_warn_overlap (call_info &info, format_result *res)
    3894              : {
    3895              :   /* Two vectors of 1-based indices corresponding to either certainly
    3896              :      or possibly aliasing arguments.  */
    3897       730600 :   auto_vec<int, 16> aliasarg[2];
    3898              : 
    3899              :   /* Go through the array of potentially aliasing directives and collect
    3900              :      argument numbers of those that do or may overlap the destination
    3901              :      object given the full result.  */
    3902       146382 :   for (unsigned i = 0; i != res->alias_count; ++i)
    3903              :     {
    3904          262 :       const format_result::alias_info &alias = res->aliases[i];
    3905              : 
    3906          262 :       enum { possible = -1, none = 0, certain = 1 } overlap = none;
    3907              : 
    3908              :       /* If the precision is zero there is no overlap.  (This only
    3909              :          considers %s directives and ignores %n.)  */
    3910          262 :       if (alias.dir.prec[0] == 0 && alias.dir.prec[1] == 0)
    3911            6 :         continue;
    3912              : 
    3913          256 :       if (alias.offset == HOST_WIDE_INT_MAX
    3914          200 :           || info.dst_offset == HOST_WIDE_INT_MAX)
    3915              :         overlap = possible;
    3916          182 :       else if (alias.offset == info.dst_offset)
    3917           79 :         overlap = alias.dir.prec[0] == 0 ? possible : certain;
    3918              :       else
    3919              :         {
    3920              :           /* Determine overlap from the range of output and offsets
    3921              :              into the same destination as the source, and rule out
    3922              :              impossible overlap.  */
    3923          103 :           unsigned HOST_WIDE_INT albeg = alias.offset;
    3924          103 :           unsigned HOST_WIDE_INT dstbeg = info.dst_offset;
    3925              : 
    3926          103 :           unsigned HOST_WIDE_INT alend = albeg + alias.range.min;
    3927          103 :           unsigned HOST_WIDE_INT dstend = dstbeg + res->range.min - 1;
    3928              : 
    3929          103 :           if ((albeg <= dstbeg && alend > dstbeg)
    3930           99 :               || (albeg >= dstbeg && albeg < dstend))
    3931              :             overlap = certain;
    3932              :           else
    3933              :             {
    3934           95 :               alend = albeg + alias.range.max;
    3935           95 :               if (alend < albeg)
    3936           13 :                 alend = HOST_WIDE_INT_M1U;
    3937              : 
    3938           95 :               dstend = dstbeg + res->range.max - 1;
    3939           95 :               if (dstend < dstbeg)
    3940            4 :                 dstend = HOST_WIDE_INT_M1U;
    3941              : 
    3942           95 :               if ((albeg >= dstbeg && albeg <= dstend)
    3943           56 :                   || (alend >= dstbeg && alend <= dstend))
    3944              :                 overlap = possible;
    3945              :             }
    3946              :         }
    3947              : 
    3948           20 :       if (overlap == none)
    3949           20 :         continue;
    3950              : 
    3951              :       /* Append the 1-based argument number.  */
    3952          236 :       aliasarg[overlap != certain].safe_push (alias.dir.argno + 1);
    3953              : 
    3954              :       /* Disable any kind of optimization.  */
    3955          236 :       res->range.unlikely = HOST_WIDE_INT_M1U;
    3956              :     }
    3957              : 
    3958       146120 :   tree arg0 = gimple_call_arg (info.callstmt, 0);
    3959       146120 :   location_t loc = gimple_location (info.callstmt);
    3960              : 
    3961       146120 :   bool aliaswarn = false;
    3962              : 
    3963       146120 :   unsigned ncertain = aliasarg[0].length ();
    3964       146120 :   unsigned npossible = aliasarg[1].length ();
    3965       146120 :   if (ncertain && npossible)
    3966              :     {
    3967              :       /* If there are multiple arguments that overlap, some certainly
    3968              :          and some possibly, handle both sets in a single diagnostic.  */
    3969            1 :       aliaswarn
    3970            3 :         = warning_at (loc, OPT_Wrestrict,
    3971              :                       "%qE arguments %Z and maybe %Z overlap destination "
    3972              :                       "object %qE",
    3973              :                       info.func, aliasarg[0].address (), ncertain,
    3974              :                       aliasarg[1].address (), npossible,
    3975              :                       info.dst_origin);
    3976              :     }
    3977       146119 :   else if (ncertain)
    3978              :     {
    3979              :       /* There is only one set of two or more arguments and they all
    3980              :          certainly overlap the destination.  */
    3981           84 :       aliaswarn
    3982          168 :         = warning_n (loc, OPT_Wrestrict, ncertain,
    3983              :                      "%qE argument %Z overlaps destination object %qE",
    3984              :                      "%qE arguments %Z overlap destination object %qE",
    3985              :                      info.func, aliasarg[0].address (), ncertain,
    3986              :                      info.dst_origin);
    3987              :     }
    3988       146035 :   else if (npossible)
    3989              :     {
    3990              :       /* There is only one set of two or more arguments and they all
    3991              :          may overlap (but need not).  */
    3992          148 :       aliaswarn
    3993          296 :         = warning_n (loc, OPT_Wrestrict, npossible,
    3994              :                      "%qE argument %Z may overlap destination object %qE",
    3995              :                      "%qE arguments %Z may overlap destination object %qE",
    3996              :                      info.func, aliasarg[1].address (), npossible,
    3997              :                      info.dst_origin);
    3998              :     }
    3999              : 
    4000          233 :   if (aliaswarn)
    4001              :     {
    4002          233 :       res->warned = true;
    4003              : 
    4004          233 :       if (info.dst_origin != arg0)
    4005              :         {
    4006              :           /* If its location is different from the first argument of the call
    4007              :              point either at the destination object itself or at the expression
    4008              :              that was used to determine the overlap.  */
    4009          221 :           loc = (DECL_P (info.dst_origin)
    4010          233 :                  ? DECL_SOURCE_LOCATION (info.dst_origin)
    4011           12 :                  : EXPR_LOCATION (info.dst_origin));
    4012          221 :           if (loc != UNKNOWN_LOCATION)
    4013          221 :             inform (loc,
    4014              :                     "destination object referenced by %<restrict%>-qualified "
    4015              :                     "argument 1 was declared here");
    4016              :         }
    4017              :     }
    4018       438360 : }
    4019              : 
    4020              : /* Compute the length of the output resulting from the call to a formatted
    4021              :    output function described by INFO and store the result of the call in
    4022              :    *RES.  Issue warnings for detected past the end writes.  Return true
    4023              :    if the complete format string has been processed and *RES can be relied
    4024              :    on, false otherwise (e.g., when a unknown or unhandled directive was seen
    4025              :    that caused the processing to be terminated early).  */
    4026              : 
    4027              : static bool
    4028       148895 : compute_format_length (call_info &info, format_result *res,
    4029              :                        pointer_query &ptr_qry)
    4030              : {
    4031       148895 :   if (dump_file)
    4032              :     {
    4033            0 :       location_t callloc = gimple_location (info.callstmt);
    4034            0 :       fprintf (dump_file, "%s:%i: ",
    4035            0 :                LOCATION_FILE (callloc), LOCATION_LINE (callloc));
    4036            0 :       print_generic_expr (dump_file, info.func, dump_flags);
    4037              : 
    4038            0 :       fprintf (dump_file,
    4039              :                ": objsize = " HOST_WIDE_INT_PRINT_UNSIGNED
    4040              :                ", fmtstr = \"%s\"\n",
    4041              :                info.objsize, info.fmtstr);
    4042              :     }
    4043              : 
    4044              :   /* Reset the minimum and maximum byte counters.  */
    4045       148895 :   res->range.min = res->range.max = 0;
    4046              : 
    4047              :   /* No directive has been seen yet so the length of output is bounded
    4048              :      by the known range [0, 0] (with no conversion resulting in a failure
    4049              :      or producing more than 4K bytes) until determined otherwise.  */
    4050       148895 :   res->knownrange = true;
    4051       148895 :   res->floating = false;
    4052       148895 :   res->warned = false;
    4053              : 
    4054              :   /* 1-based directive counter.  */
    4055       148895 :   unsigned dirno = 1;
    4056              : 
    4057              :   /* The variadic argument counter.  */
    4058       148895 :   unsigned argno = info.argidx;
    4059              : 
    4060       148895 :   bool success = true;
    4061              : 
    4062       148895 :   for (const char *pf = info.fmtstr; ; ++dirno)
    4063              :     {
    4064      1054931 :       directive dir (&info, dirno);
    4065              : 
    4066      1054931 :       size_t n = parse_directive (info, dir, res, pf, &argno, ptr_qry.rvals);
    4067              : 
    4068              :       /* Return failure if the format function fails.  */
    4069      1054931 :       if (!format_directive (info, res, dir, ptr_qry))
    4070         2775 :         return false;
    4071              : 
    4072              :       /* Return success when the directive is zero bytes long and it's
    4073              :          the last thing in the format string (i.e., it's the terminating
    4074              :          nul, which isn't really a directive but handling it as one makes
    4075              :          things simpler).  */
    4076      1052156 :       if (!n)
    4077              :         {
    4078       146120 :           success = *pf == '\0';
    4079       146120 :           break;
    4080              :         }
    4081              : 
    4082       906036 :       pf += n;
    4083       906036 :     }
    4084              : 
    4085       146120 :   maybe_warn_overlap (info, res);
    4086              : 
    4087              :   /* The complete format string was processed (with or without warnings).  */
    4088       146120 :   return success;
    4089              : }
    4090              : 
    4091              : /* Return the size of the object referenced by the expression DEST in
    4092              :    statement STMT, if available, or the maximum possible size otherwise.  */
    4093              : 
    4094              : static unsigned HOST_WIDE_INT
    4095       149902 : get_destination_size (tree dest, gimple *stmt, pointer_query &ptr_qry)
    4096              : {
    4097              :   /* When there is no destination return the maximum.  */
    4098       149902 :   if (!dest)
    4099              :     return HOST_WIDE_INT_MAX;
    4100              : 
    4101              :   /* Use compute_objsize to determine the size of the destination object.  */
    4102         8657 :   access_ref aref;
    4103         8657 :   if (!ptr_qry.get_ref (dest, stmt, &aref))
    4104              :     return HOST_WIDE_INT_MAX;
    4105              : 
    4106         8657 :   offset_int remsize = aref.size_remaining ();
    4107         8657 :   if (!wi::fits_uhwi_p (remsize))
    4108              :     return HOST_WIDE_INT_MAX;
    4109              : 
    4110         8657 :   return remsize.to_uhwi ();
    4111              : }
    4112              : 
    4113              : /* Return true if the call described by INFO with result RES safe to
    4114              :    optimize (i.e., no undefined behavior), and set RETVAL to the range
    4115              :    of its return values.  */
    4116              : 
    4117              : static bool
    4118       274094 : is_call_safe (const call_info &info,
    4119              :               const format_result &res, bool under4k,
    4120              :               unsigned HOST_WIDE_INT retval[2])
    4121              : {
    4122       274094 :   if (under4k && !res.posunder4k)
    4123              :     return false;
    4124              : 
    4125              :   /* The minimum return value.  */
    4126       139925 :   retval[0] = res.range.min;
    4127              : 
    4128              :   /* The maximum return value is in most cases bounded by RES.RANGE.MAX
    4129              :      but in cases involving multibyte characters could be as large as
    4130              :      RES.RANGE.UNLIKELY.  */
    4131       139925 :   retval[1]
    4132       139925 :     = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
    4133              : 
    4134              :   /* Adjust the number of bytes which includes the terminating nul
    4135              :      to reflect the return value of the function which does not.
    4136              :      Because the valid range of the function is [INT_MIN, INT_MAX],
    4137              :      a valid range before the adjustment below is [0, INT_MAX + 1]
    4138              :      (the functions only return negative values on error or undefined
    4139              :      behavior).  */
    4140       139925 :   if (retval[0] <= target_int_max () + 1)
    4141       139795 :     --retval[0];
    4142       139925 :   if (retval[1] <= target_int_max () + 1)
    4143       125683 :     --retval[1];
    4144              : 
    4145              :   /* Avoid the return value optimization when the behavior of the call
    4146              :      is undefined either because any directive may have produced 4K or
    4147              :      more of output, or the return value exceeds INT_MAX, or because
    4148              :      the output overflows the destination object (but leave it enabled
    4149              :      when the function is bounded because then the behavior is well-
    4150              :      defined).  */
    4151       139925 :   if (retval[0] == retval[1]
    4152       103734 :       && (info.bounded || retval[0] < info.objsize)
    4153       243173 :       && retval[0] <= target_int_max ())
    4154              :     return true;
    4155              : 
    4156        34694 :   if ((info.bounded || retval[1] < info.objsize)
    4157        56362 :       && (retval[0] < target_int_max ()
    4158        21569 :           && retval[1] < target_int_max ()))
    4159              :     return true;
    4160              : 
    4161        16285 :   if (!under4k && (info.bounded || retval[0] < info.objsize))
    4162        13374 :     return true;
    4163              : 
    4164              :   return false;
    4165              : }
    4166              : 
    4167              : /* Given a suitable result RES of a call to a formatted output function
    4168              :    described by INFO, substitute the result for the return value of
    4169              :    the call.  The result is suitable if the number of bytes it represents
    4170              :    is known and exact.  A result that isn't suitable for substitution may
    4171              :    have its range set to the range of return values, if that is known.
    4172              :    Return true if the call is removed and gsi_next should not be performed
    4173              :    in the caller.  */
    4174              : 
    4175              : static bool
    4176       137043 : try_substitute_return_value (gimple_stmt_iterator *gsi,
    4177              :                              const call_info &info,
    4178              :                              const format_result &res)
    4179              : {
    4180       137043 :   tree lhs = gimple_get_lhs (info.callstmt);
    4181              : 
    4182              :   /* Set to true when the entire call has been removed.  */
    4183       137043 :   bool removed = false;
    4184              : 
    4185              :   /* The minimum and maximum return value.  */
    4186       137043 :   unsigned HOST_WIDE_INT retval[2] = {0};
    4187       137043 :   bool safe = is_call_safe (info, res, true, retval);
    4188              : 
    4189       137043 :   if (safe
    4190         2609 :       && retval[0] == retval[1]
    4191              :       /* Not prepared to handle possibly throwing calls here; they shouldn't
    4192              :          appear in non-artificial testcases, except when the __*_chk routines
    4193              :          are badly declared.  */
    4194       138275 :       && !stmt_ends_bb_p (info.callstmt))
    4195              :     {
    4196         1202 :       tree cst = build_int_cst (lhs ? TREE_TYPE (lhs) : integer_type_node,
    4197         1202 :                                 retval[0]);
    4198              : 
    4199         1202 :       if (lhs == NULL_TREE && info.nowrite)
    4200              :         {
    4201              :           /* Remove the call to the bounded function with a zero size
    4202              :              (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs.  */
    4203           13 :           unlink_stmt_vdef (info.callstmt);
    4204           13 :           gsi_remove (gsi, true);
    4205           13 :           removed = true;
    4206              :         }
    4207         1189 :       else if (info.nowrite)
    4208              :         {
    4209              :           /* Replace the call to the bounded function with a zero size
    4210              :              (e.g., snprintf(0, 0, "%i", 123) with the constant result
    4211              :              of the function.  */
    4212          167 :           gimplify_and_update_call_from_tree (gsi, cst);
    4213          167 :           gimple *callstmt = gsi_stmt (*gsi);
    4214          167 :           update_stmt (callstmt);
    4215              :         }
    4216         1022 :       else if (lhs)
    4217              :         {
    4218              :           /* Replace the left-hand side of the call with the constant
    4219              :              result of the formatted function.  */
    4220          488 :           gimple_call_set_lhs (info.callstmt, NULL_TREE);
    4221          488 :           gimple *g = gimple_build_assign (lhs, cst);
    4222          488 :           gsi_insert_after (gsi, g, GSI_NEW_STMT);
    4223          488 :           update_stmt (info.callstmt);
    4224              :         }
    4225              : 
    4226         1202 :       if (dump_file)
    4227              :         {
    4228            0 :           if (removed)
    4229            0 :             fprintf (dump_file, "  Removing call statement.");
    4230              :           else
    4231              :             {
    4232            0 :               fprintf (dump_file, "  Substituting ");
    4233            0 :               print_generic_expr (dump_file, cst, dump_flags);
    4234            0 :               fprintf (dump_file, " for %s.\n",
    4235            0 :                        info.nowrite ? "statement" : "return value");
    4236              :             }
    4237              :         }
    4238              :     }
    4239       135841 :   else if (lhs && types_compatible_p (TREE_TYPE (lhs), integer_type_node))
    4240              :     {
    4241         2489 :       bool setrange = false;
    4242              : 
    4243         2489 :       if (safe
    4244          538 :           && (info.bounded || retval[1] < info.objsize)
    4245         3027 :           && (retval[0] < target_int_max ()
    4246          538 :               && retval[1] < target_int_max ()))
    4247              :         {
    4248              :           /* If the result is in a valid range bounded by the size of
    4249              :              the destination set it so that it can be used for subsequent
    4250              :              optimizations.  */
    4251          538 :           int prec = TYPE_PRECISION (integer_type_node);
    4252              : 
    4253          538 :           wide_int min = wi::shwi (retval[0], prec);
    4254          538 :           wide_int max = wi::shwi (retval[1], prec);
    4255          538 :           int_range_max r (TREE_TYPE (lhs), min, max);
    4256          538 :           set_range_info (lhs, r);
    4257              : 
    4258          538 :           setrange = true;
    4259          538 :         }
    4260              : 
    4261         2489 :       if (dump_file)
    4262              :         {
    4263            0 :           const char *inbounds
    4264            0 :             = (retval[0] < info.objsize
    4265            0 :                ? (retval[1] < info.objsize
    4266            0 :                   ? "in" : "potentially out-of")
    4267              :                : "out-of");
    4268              : 
    4269            0 :           const char *what = setrange ? "Setting" : "Discarding";
    4270            0 :           if (retval[0] != retval[1])
    4271            0 :             fprintf (dump_file,
    4272              :                      "  %s %s-bounds return value range ["
    4273              :                      HOST_WIDE_INT_PRINT_UNSIGNED ", "
    4274              :                      HOST_WIDE_INT_PRINT_UNSIGNED "].\n",
    4275              :                      what, inbounds, retval[0], retval[1]);
    4276              :           else
    4277            0 :             fprintf (dump_file, "  %s %s-bounds return value "
    4278              :                      HOST_WIDE_INT_PRINT_UNSIGNED ".\n",
    4279              :                      what, inbounds, retval[0]);
    4280              :         }
    4281              :     }
    4282              : 
    4283       137043 :   if (dump_file)
    4284            0 :     fputc ('\n', dump_file);
    4285              : 
    4286       137043 :   return removed;
    4287              : }
    4288              : 
    4289              : /* Try to simplify a s{,n}printf call described by INFO with result
    4290              :    RES by replacing it with a simpler and presumably more efficient
    4291              :    call (such as strcpy).  */
    4292              : 
    4293              : static bool
    4294       137051 : try_simplify_call (gimple_stmt_iterator *gsi,
    4295              :                    const call_info &info,
    4296              :                    const format_result &res)
    4297              : {
    4298       137051 :   unsigned HOST_WIDE_INT dummy[2];
    4299       137051 :   if (!is_call_safe (info, res, info.retval_used (), dummy))
    4300              :     return false;
    4301              : 
    4302       134405 :   switch (info.fncode)
    4303              :     {
    4304         1878 :     case BUILT_IN_SNPRINTF:
    4305         1878 :       return gimple_fold_builtin_snprintf (gsi);
    4306              : 
    4307         2344 :     case BUILT_IN_SPRINTF:
    4308         2344 :       return gimple_fold_builtin_sprintf (gsi);
    4309              : 
    4310              :     default:
    4311              :       ;
    4312              :     }
    4313              : 
    4314              :   return false;
    4315              : }
    4316              : 
    4317              : /* Return the zero-based index of the format string argument of a printf
    4318              :    like function and set *IDX_ARGS to the first format argument.  When
    4319              :    no such index exists return UINT_MAX.  */
    4320              : 
    4321              : static unsigned
    4322      3905454 : get_user_idx_format (tree fndecl, unsigned *idx_args)
    4323              : {
    4324      3905454 :   tree attrs = lookup_attribute ("format", DECL_ATTRIBUTES (fndecl));
    4325      3905454 :   if (!attrs)
    4326      3905454 :     attrs = lookup_attribute ("format", TYPE_ATTRIBUTES (TREE_TYPE (fndecl)));
    4327              : 
    4328      3905454 :   if (!attrs)
    4329              :     return UINT_MAX;
    4330              : 
    4331        20489 :   attrs = TREE_VALUE (attrs);
    4332              : 
    4333        20489 :   tree archetype = TREE_VALUE (attrs);
    4334        20489 :   if (strcmp ("printf", IDENTIFIER_POINTER (archetype)))
    4335              :     return UINT_MAX;
    4336              : 
    4337        16807 :   attrs = TREE_CHAIN (attrs);
    4338        16807 :   tree fmtarg = TREE_VALUE (attrs);
    4339              : 
    4340        16807 :   attrs = TREE_CHAIN (attrs);
    4341        16807 :   tree elliparg = TREE_VALUE (attrs);
    4342              : 
    4343              :   /* Attribute argument indices are 1-based but we use zero-based.  */
    4344        16807 :   *idx_args = tree_to_uhwi (elliparg) - 1;
    4345        16807 :   return tree_to_uhwi (fmtarg) - 1;
    4346              : }
    4347              : 
    4348              : }   /* Unnamed namespace.  */
    4349              : 
    4350              : /* Determine if a GIMPLE call at *GSI is to one of the sprintf-like built-in
    4351              :    functions and if so, handle it.  Return true if the call is removed and
    4352              :    gsi_next should not be performed in the caller.  */
    4353              : 
    4354              : bool
    4355      5056667 : handle_printf_call (gimple_stmt_iterator *gsi, pointer_query &ptr_qry)
    4356              : {
    4357      5056667 :   init_target_to_host_charmap ();
    4358              : 
    4359      5056667 :   call_info info = call_info ();
    4360              : 
    4361      5056667 :   info.callstmt = gsi_stmt (*gsi);
    4362      5056667 :   info.func = gimple_call_fndecl (info.callstmt);
    4363      5056667 :   if (!info.func)
    4364              :     return false;
    4365              : 
    4366              :   /* Format string argument number (valid for all functions).  */
    4367      4876494 :   unsigned idx_format = UINT_MAX;
    4368      4876494 :   if (gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
    4369       971040 :     info.fncode = DECL_FUNCTION_CODE (info.func);
    4370              :   else
    4371              :     {
    4372      3905454 :       unsigned idx_args;
    4373      3905454 :       idx_format = get_user_idx_format (info.func, &idx_args);
    4374      3905454 :       if (idx_format == UINT_MAX
    4375        16807 :           || idx_format >= gimple_call_num_args (info.callstmt)
    4376        16807 :           || idx_args > gimple_call_num_args (info.callstmt)
    4377      3922233 :           || !POINTER_TYPE_P (TREE_TYPE (gimple_call_arg (info.callstmt,
    4378              :                                                           idx_format))))
    4379      3888675 :         return false;
    4380        16779 :       info.fncode = BUILT_IN_NONE;
    4381        16779 :       info.argidx = idx_args;
    4382              :     }
    4383              : 
    4384              :   /* The size of the destination as in snprintf(dest, size, ...).  */
    4385       987819 :   unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
    4386              : 
    4387              :   /* The size of the destination determined by __builtin_object_size.  */
    4388       987819 :   unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
    4389              : 
    4390              :   /* Zero-based buffer size argument number (snprintf and vsnprintf).  */
    4391       987819 :   unsigned idx_dstsize = UINT_MAX;
    4392              : 
    4393              :   /* Object size argument number (snprintf_chk and vsnprintf_chk).  */
    4394       987819 :   unsigned idx_objsize = UINT_MAX;
    4395              : 
    4396              :   /* Destination argument number (valid for sprintf functions only).  */
    4397       987819 :   unsigned idx_dstptr = 0;
    4398              : 
    4399       987819 :   switch (info.fncode)
    4400              :     {
    4401              :     case BUILT_IN_NONE:
    4402              :       // User-defined function with attribute format (printf).
    4403              :       idx_dstptr = -1;
    4404              :       break;
    4405              : 
    4406        94781 :     case BUILT_IN_FPRINTF:
    4407              :       // Signature:
    4408              :       //   __builtin_fprintf (FILE*, format, ...)
    4409        94781 :       idx_format = 1;
    4410        94781 :       info.argidx = 2;
    4411        94781 :       idx_dstptr = -1;
    4412        94781 :       break;
    4413              : 
    4414          147 :     case BUILT_IN_FPRINTF_CHK:
    4415              :       // Signature:
    4416              :       //   __builtin_fprintf_chk (FILE*, ost, format, ...)
    4417          147 :       idx_format = 2;
    4418          147 :       info.argidx = 3;
    4419          147 :       idx_dstptr = -1;
    4420          147 :       break;
    4421              : 
    4422           64 :     case BUILT_IN_FPRINTF_UNLOCKED:
    4423              :       // Signature:
    4424              :       //   __builtin_fprintf_unnlocked (FILE*, format, ...)
    4425           64 :       idx_format = 1;
    4426           64 :       info.argidx = 2;
    4427           64 :       idx_dstptr = -1;
    4428           64 :       break;
    4429              : 
    4430        28542 :     case BUILT_IN_PRINTF:
    4431              :       // Signature:
    4432              :       //   __builtin_printf (format, ...)
    4433        28542 :       idx_format = 0;
    4434        28542 :       info.argidx = 1;
    4435        28542 :       idx_dstptr = -1;
    4436        28542 :       break;
    4437              : 
    4438          151 :     case BUILT_IN_PRINTF_CHK:
    4439              :       // Signature:
    4440              :       //   __builtin_printf_chk (ost, format, ...)
    4441          151 :       idx_format = 1;
    4442          151 :       info.argidx = 2;
    4443          151 :       idx_dstptr = -1;
    4444          151 :       break;
    4445              : 
    4446           63 :     case BUILT_IN_PRINTF_UNLOCKED:
    4447              :       // Signature:
    4448              :       //   __builtin_printf (format, ...)
    4449           63 :       idx_format = 0;
    4450           63 :       info.argidx = 1;
    4451           63 :       idx_dstptr = -1;
    4452           63 :       break;
    4453              : 
    4454         4296 :     case BUILT_IN_SPRINTF:
    4455              :       // Signature:
    4456              :       //   __builtin_sprintf (dst, format, ...)
    4457         4296 :       idx_format = 1;
    4458         4296 :       info.argidx = 2;
    4459         4296 :       break;
    4460              : 
    4461         1118 :     case BUILT_IN_SPRINTF_CHK:
    4462              :       // Signature:
    4463              :       //   __builtin___sprintf_chk (dst, ost, objsize, format, ...)
    4464         1118 :       idx_objsize = 2;
    4465         1118 :       idx_format = 3;
    4466         1118 :       info.argidx = 4;
    4467         1118 :       break;
    4468              : 
    4469         2487 :     case BUILT_IN_SNPRINTF:
    4470              :       // Signature:
    4471              :       //   __builtin_snprintf (dst, size, format, ...)
    4472         2487 :       idx_dstsize = 1;
    4473         2487 :       idx_format = 2;
    4474         2487 :       info.argidx = 3;
    4475         2487 :       info.bounded = true;
    4476         2487 :       break;
    4477              : 
    4478          139 :     case BUILT_IN_SNPRINTF_CHK:
    4479              :       // Signature:
    4480              :       //   __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
    4481          139 :       idx_dstsize = 1;
    4482          139 :       idx_objsize = 3;
    4483          139 :       idx_format = 4;
    4484          139 :       info.argidx = 5;
    4485          139 :       info.bounded = true;
    4486          139 :       break;
    4487              : 
    4488          374 :     case BUILT_IN_VFPRINTF:
    4489              :       // Signature:
    4490              :       //   __builtin_vprintf (FILE*, format, va_list)
    4491          374 :       idx_format = 1;
    4492          374 :       info.argidx = -1;
    4493          374 :       idx_dstptr = -1;
    4494          374 :       break;
    4495              : 
    4496          139 :     case BUILT_IN_VFPRINTF_CHK:
    4497              :       // Signature:
    4498              :       //   __builtin___vfprintf_chk (FILE*, ost, format, va_list)
    4499          139 :       idx_format = 2;
    4500          139 :       info.argidx = -1;
    4501          139 :       idx_dstptr = -1;
    4502          139 :       break;
    4503              : 
    4504           58 :     case BUILT_IN_VPRINTF:
    4505              :       // Signature:
    4506              :       //   __builtin_vprintf (format, va_list)
    4507           58 :       idx_format = 0;
    4508           58 :       info.argidx = -1;
    4509           58 :       idx_dstptr = -1;
    4510           58 :       break;
    4511              : 
    4512          147 :     case BUILT_IN_VPRINTF_CHK:
    4513              :       // Signature:
    4514              :       //   __builtin___vprintf_chk (ost, format, va_list)
    4515          147 :       idx_format = 1;
    4516          147 :       info.argidx = -1;
    4517          147 :       idx_dstptr = -1;
    4518          147 :       break;
    4519              : 
    4520         1638 :     case BUILT_IN_VSNPRINTF:
    4521              :       // Signature:
    4522              :       //   __builtin_vsprintf (dst, size, format, va)
    4523         1638 :       idx_dstsize = 1;
    4524         1638 :       idx_format = 2;
    4525         1638 :       info.argidx = -1;
    4526         1638 :       info.bounded = true;
    4527         1638 :       break;
    4528              : 
    4529          131 :     case BUILT_IN_VSNPRINTF_CHK:
    4530              :       // Signature:
    4531              :       //   __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
    4532          131 :       idx_dstsize = 1;
    4533          131 :       idx_objsize = 3;
    4534          131 :       idx_format = 4;
    4535          131 :       info.argidx = -1;
    4536          131 :       info.bounded = true;
    4537          131 :       break;
    4538              : 
    4539         3067 :     case BUILT_IN_VSPRINTF:
    4540              :       // Signature:
    4541              :       //   __builtin_vsprintf (dst, format, va)
    4542         3067 :       idx_format = 1;
    4543         3067 :       info.argidx = -1;
    4544         3067 :       break;
    4545              : 
    4546          176 :     case BUILT_IN_VSPRINTF_CHK:
    4547              :       // Signature:
    4548              :       //   __builtin___vsprintf_chk (dst, ost, objsize, format, va)
    4549          176 :       idx_format = 3;
    4550          176 :       idx_objsize = 2;
    4551          176 :       info.argidx = -1;
    4552          176 :       break;
    4553              : 
    4554              :     default:
    4555              :       return false;
    4556              :     }
    4557              : 
    4558              :   /* Set the global warning level for this function.  */
    4559       154297 :   warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
    4560              : 
    4561              :   /* For all string functions the first argument is a pointer to
    4562              :      the destination.  */
    4563       154297 :   tree dstptr = (idx_dstptr < gimple_call_num_args (info.callstmt)
    4564       154297 :                  ? gimple_call_arg (info.callstmt, 0) : NULL_TREE);
    4565              : 
    4566       154297 :   info.format = gimple_call_arg (info.callstmt, idx_format);
    4567              : 
    4568              :   /* True when the destination size is constant as opposed to the lower
    4569              :      or upper bound of a range.  */
    4570       154297 :   bool dstsize_cst_p = true;
    4571       154297 :   bool posunder4k = true;
    4572              : 
    4573       154297 :   if (idx_dstsize == UINT_MAX)
    4574              :     {
    4575              :       /* For non-bounded functions like sprintf, determine the size
    4576              :          of the destination from the object or pointer passed to it
    4577              :          as the first argument.  */
    4578       149902 :       dstsize = get_destination_size (dstptr, info.callstmt, ptr_qry);
    4579              :     }
    4580         4395 :   else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
    4581              :     {
    4582              :       /* For bounded functions try to get the size argument.  */
    4583              : 
    4584         4395 :       if (TREE_CODE (size) == INTEGER_CST)
    4585              :         {
    4586         3764 :           dstsize = tree_to_uhwi (size);
    4587              :           /* No object can be larger than SIZE_MAX bytes (half the address
    4588              :              space) on the target.
    4589              :              The functions are defined only for output of at most INT_MAX
    4590              :              bytes.  Specifying a bound in excess of that limit effectively
    4591              :              defeats the bounds checking (and on some implementations such
    4592              :              as Solaris cause the function to fail with EINVAL).  */
    4593         3764 :           if (dstsize > target_size_max () / 2)
    4594              :             {
    4595              :               /* Avoid warning if -Wstringop-overflow is specified since
    4596              :                  it also warns for the same thing though only for the
    4597              :                  checking built-ins.  */
    4598           10 :               if ((idx_objsize == UINT_MAX
    4599            1 :                    || !warn_stringop_overflow))
    4600            9 :                 warning_at (gimple_location (info.callstmt), info.warnopt (),
    4601              :                             "specified bound %wu exceeds maximum object size "
    4602              :                             "%wu",
    4603              :                             dstsize, target_size_max () / 2);
    4604              :               /* POSIX requires snprintf to fail if DSTSIZE is greater
    4605              :                  than INT_MAX.  Even though not all POSIX implementations
    4606              :                  conform to the requirement, avoid folding in this case.  */
    4607              :               posunder4k = false;
    4608              :             }
    4609         3754 :           else if (dstsize > target_int_max ())
    4610              :             {
    4611           16 :               warning_at (gimple_location (info.callstmt), info.warnopt (),
    4612              :                           "specified bound %wu exceeds %<INT_MAX%>",
    4613              :                           dstsize);
    4614              :               /* POSIX requires snprintf to fail if DSTSIZE is greater
    4615              :                  than INT_MAX.  Avoid folding in that case.  */
    4616           16 :               posunder4k = false;
    4617              :             }
    4618              :         }
    4619          631 :       else if (TREE_CODE (size) == SSA_NAME)
    4620              :         {
    4621              :           /* Try to determine the range of values of the argument
    4622              :              and use the greater of the two at level 1 and the smaller
    4623              :              of them at level 2.  */
    4624          631 :           int_range_max vr;
    4625          631 :           ptr_qry.rvals->range_of_expr (vr, size, info.callstmt);
    4626              : 
    4627          631 :           if (!vr.undefined_p ())
    4628              :             {
    4629          631 :               tree type = TREE_TYPE (size);
    4630          631 :               tree tmin = wide_int_to_tree (type, vr.lower_bound ());
    4631          631 :               tree tmax = wide_int_to_tree (type, vr.upper_bound ());
    4632          631 :               unsigned HOST_WIDE_INT minsize = TREE_INT_CST_LOW (tmin);
    4633          631 :               unsigned HOST_WIDE_INT maxsize = TREE_INT_CST_LOW (tmax);
    4634          631 :               dstsize = warn_level < 2 ? maxsize : minsize;
    4635              : 
    4636          631 :               if (minsize > target_int_max ())
    4637            8 :                 warning_at (gimple_location (info.callstmt), info.warnopt (),
    4638              :                             "specified bound range [%wu, %wu] exceeds "
    4639              :                             "%<INT_MAX%>",
    4640              :                             minsize, maxsize);
    4641              : 
    4642              :               /* POSIX requires snprintf to fail if DSTSIZE is greater
    4643              :                  than INT_MAX.  Avoid folding if that's possible.  */
    4644          631 :               if (maxsize > target_int_max ())
    4645          592 :                 posunder4k = false;
    4646              :             }
    4647              : 
    4648              :           /* The destination size is not constant.  If the function is
    4649              :              bounded (e.g., snprintf) a lower bound of zero doesn't
    4650              :              necessarily imply it can be eliminated.  */
    4651          631 :           dstsize_cst_p = false;
    4652          631 :         }
    4653              :     }
    4654              : 
    4655       154297 :   if (idx_objsize != UINT_MAX)
    4656         1564 :     if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
    4657         1564 :       if (tree_fits_uhwi_p (size))
    4658         1551 :         objsize = tree_to_uhwi (size);
    4659              : 
    4660       154297 :   if (info.bounded && !dstsize)
    4661              :     {
    4662              :       /* As a special case, when the explicitly specified destination
    4663              :          size argument (to a bounded function like snprintf) is zero
    4664              :          it is a request to determine the number of bytes on output
    4665              :          without actually producing any.  Pretend the size is
    4666              :          unlimited in this case.  */
    4667          461 :       info.objsize = HOST_WIDE_INT_MAX;
    4668          461 :       info.nowrite = dstsize_cst_p;
    4669              :     }
    4670              :   else
    4671              :     {
    4672              :       /* For calls to non-bounded functions or to those of bounded
    4673              :          functions with a non-zero size, warn if the destination
    4674              :          pointer is null.  */
    4675       153836 :       if (dstptr && integer_zerop (dstptr))
    4676              :         {
    4677              :           /* This is diagnosed with -Wformat only when the null is a constant
    4678              :              pointer.  The warning here diagnoses instances where the pointer
    4679              :              is not constant.  */
    4680           19 :           location_t loc = gimple_location (info.callstmt);
    4681           29 :           warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
    4682           19 :                       info.warnopt (), "null destination pointer");
    4683           19 :           return false;
    4684              :         }
    4685              : 
    4686              :       /* Set the object size to the smaller of the two arguments
    4687              :          of both have been specified and they're not equal.  */
    4688       153817 :       info.objsize = dstsize < objsize ? dstsize : objsize;
    4689              : 
    4690       153817 :       if (info.bounded
    4691         3925 :           && dstsize < target_size_max () / 2 && objsize < dstsize
    4692              :           /* Avoid warning if -Wstringop-overflow is specified since
    4693              :              it also warns for the same thing though only for the
    4694              :              checking built-ins.  */
    4695       153887 :           && (idx_objsize == UINT_MAX
    4696           70 :               || !warn_stringop_overflow))
    4697              :         {
    4698            3 :           warning_at (gimple_location (info.callstmt), info.warnopt (),
    4699              :                       "specified bound %wu exceeds the size %wu "
    4700              :                       "of the destination object", dstsize, objsize);
    4701              :         }
    4702              :     }
    4703              : 
    4704              :   /* Determine if the format argument may be null and warn if not
    4705              :      and if the argument is null.  */
    4706       154278 :   if (integer_zerop (info.format)
    4707       154278 :       && gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
    4708              :     {
    4709           58 :       location_t loc = gimple_location (info.callstmt);
    4710          108 :       warning_at (EXPR_LOC_OR_LOC (info.format, loc),
    4711           58 :                   info.warnopt (), "null format string");
    4712           58 :       return false;
    4713              :     }
    4714              : 
    4715       154220 :   info.fmtstr = get_format_string (info.format, &info.fmtloc);
    4716       154220 :   if (!info.fmtstr)
    4717              :     return false;
    4718              : 
    4719       148895 :   if (warn_restrict)
    4720              :     {
    4721              :       /* Compute the origin of the destination pointer and its offset
    4722              :          from the base object/pointer if possible.  */
    4723        36942 :       info.dst_offset = 0;
    4724        36942 :       info.dst_origin = get_origin_and_offset (dstptr, &info.dst_field,
    4725              :                                                &info.dst_offset);
    4726              :     }
    4727              : 
    4728              :   /* The result is the number of bytes output by the formatted function,
    4729              :      including the terminating NUL.  */
    4730       297790 :   format_result res;
    4731              : 
    4732              :   /* I/O functions with no destination argument (i.e., all forms of fprintf
    4733              :      and printf) may fail under any conditions.  Others (i.e., all forms of
    4734              :      sprintf) may only fail under specific conditions determined for each
    4735              :      directive.  Clear POSUNDER4K for the former set of functions and set
    4736              :      it to true for the latter (it can only be cleared later, but it is
    4737              :      never set to true again).  */
    4738       148895 :   res.posunder4k = posunder4k && dstptr;
    4739              : 
    4740       148895 :   bool success = compute_format_length (info, &res, ptr_qry);
    4741       148895 :   if (res.warned)
    4742         4442 :     suppress_warning (info.callstmt, info.warnopt ());
    4743              : 
    4744              :   /* When optimizing and the printf return value optimization is enabled,
    4745              :      attempt to substitute the computed result for the return value of
    4746              :      the call.  Avoid this optimization when -frounding-math is in effect
    4747              :      and the format string contains a floating point directive.  */
    4748       148895 :   bool call_removed = false;
    4749       148895 :   if (success && optimize > 0)
    4750              :     {
    4751              :       /* Save a copy of the iterator pointing at the call.  The iterator
    4752              :          may change to point past the call in try_substitute_return_value
    4753              :          but the original value is needed in try_simplify_call.  */
    4754       137064 :       gimple_stmt_iterator gsi_call = *gsi;
    4755              : 
    4756       137064 :       if (flag_printf_return_value
    4757       137043 :           && (!flag_rounding_math || !res.floating))
    4758       137043 :         call_removed = try_substitute_return_value (gsi, info, res);
    4759              : 
    4760       137043 :       if (!call_removed)
    4761       137051 :         try_simplify_call (&gsi_call, info, res);
    4762              :     }
    4763              : 
    4764       148895 :   return call_removed;
    4765              : }
        

Generated by: LCOV version 2.5.0-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.