1 /* Copyright (C) 2016-2018 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 rathger 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 fornmat 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-fold.h"
57 #include "gimple-pretty-print.h"
58 #include "diagnostic-core.h"
59 #include "fold-const.h"
60 #include "gimple-iterator.h"
61 #include "tree-ssa.h"
62 #include "tree-object-size.h"
63 #include "params.h"
64 #include "tree-cfg.h"
65 #include "tree-ssa-propagate.h"
66 #include "calls.h"
67 #include "cfgloop.h"
68 #include "intl.h"
69 #include "langhooks.h"
70 
71 #include "builtins.h"
72 #include "stor-layout.h"
73 
74 #include "realmpfr.h"
75 #include "target.h"
76 
77 #include "cpplib.h"
78 #include "input.h"
79 #include "toplev.h"
80 #include "substring-locations.h"
81 #include "diagnostic.h"
82 #include "domwalk.h"
83 #include "alloc-pool.h"
84 #include "vr-values.h"
85 #include "gimple-ssa-evrp-analyze.h"
86 
87 /* The likely worst case value of MB_LEN_MAX for the target, large enough
88    for UTF-8.  Ideally, this would be obtained by a target hook if it were
89    to be used for optimization but it's good enough as is for warnings.  */
90 #define target_mb_len_max()   6
91 
92 /* The maximum number of bytes a single non-string directive can result
93    in.  This is the result of printf("%.*Lf", INT_MAX, -LDBL_MAX) for
94    LDBL_MAX_10_EXP of 4932.  */
95 #define IEEE_MAX_10_EXP    4932
96 #define target_dir_max()   (target_int_max () + IEEE_MAX_10_EXP + 2)
97 
98 namespace {
99 
100 const pass_data pass_data_sprintf_length = {
101   GIMPLE_PASS,             // pass type
102   "printf-return-value",   // pass name
103   OPTGROUP_NONE,           // optinfo_flags
104   TV_NONE,                 // tv_id
105   PROP_cfg,                // properties_required
106   0,	                   // properties_provided
107   0,	                   // properties_destroyed
108   0,	                   // properties_start
109   0,	                   // properties_finish
110 };
111 
112 /* Set to the warning level for the current function which is equal
113    either to warn_format_trunc for bounded functions or to
114    warn_format_overflow otherwise.  */
115 
116 static int warn_level;
117 
118 struct format_result;
119 
120 class sprintf_dom_walker : public dom_walker
121 {
122  public:
123   sprintf_dom_walker () : dom_walker (CDI_DOMINATORS) {}
124   ~sprintf_dom_walker () {}
125 
126   edge before_dom_children (basic_block) FINAL OVERRIDE;
127   void after_dom_children (basic_block) FINAL OVERRIDE;
128   bool handle_gimple_call (gimple_stmt_iterator *);
129 
130   struct call_info;
131   bool compute_format_length (call_info &, format_result *);
132   class evrp_range_analyzer evrp_range_analyzer;
133 };
134 
135 class pass_sprintf_length : public gimple_opt_pass
136 {
137   bool fold_return_value;
138 
139 public:
140   pass_sprintf_length (gcc::context *ctxt)
141     : gimple_opt_pass (pass_data_sprintf_length, ctxt),
142     fold_return_value (false)
143   { }
144 
145   opt_pass * clone () { return new pass_sprintf_length (m_ctxt); }
146 
147   virtual bool gate (function *);
148 
149   virtual unsigned int execute (function *);
150 
151   void set_pass_param (unsigned int n, bool param)
152     {
153       gcc_assert (n == 0);
154       fold_return_value = param;
155     }
156 
157 };
158 
159 bool
160 pass_sprintf_length::gate (function *)
161 {
162   /* Run the pass iff -Warn-format-overflow or -Warn-format-truncation
163      is specified and either not optimizing and the pass is being invoked
164      early, or when optimizing and the pass is being invoked during
165      optimization (i.e., "late").  */
166   return ((warn_format_overflow > 0
167 	   || warn_format_trunc > 0
168 	   || flag_printf_return_value)
169 	  && (optimize > 0) == fold_return_value);
170 }
171 
172 /* The minimum, maximum, likely, and unlikely maximum number of bytes
173    of output either a formatting function or an individual directive
174    can result in.  */
175 
176 struct result_range
177 {
178   /* The absolute minimum number of bytes.  The result of a successful
179      conversion is guaranteed to be no less than this.  (An erroneous
180      conversion can be indicated by MIN > HOST_WIDE_INT_MAX.)  */
181   unsigned HOST_WIDE_INT min;
182   /* The likely maximum result that is used in diagnostics.  In most
183      cases MAX is the same as the worst case UNLIKELY result.  */
184   unsigned HOST_WIDE_INT max;
185   /* The likely result used to trigger diagnostics.  For conversions
186      that result in a range of bytes [MIN, MAX], LIKELY is somewhere
187      in that range.  */
188   unsigned HOST_WIDE_INT likely;
189   /* In rare cases (e.g., for nultibyte characters) UNLIKELY gives
190      the worst cases maximum result of a directive.  In most cases
191      UNLIKELY == MAX.  UNLIKELY is used to control the return value
192      optimization but not in diagnostics.  */
193   unsigned HOST_WIDE_INT unlikely;
194 };
195 
196 /* The result of a call to a formatted function.  */
197 
198 struct format_result
199 {
200   /* Range of characters written by the formatted function.
201      Setting the minimum to HOST_WIDE_INT_MAX disables all
202      length tracking for the remainder of the format string.  */
203   result_range range;
204 
205   /* True when the range above is obtained from known values of
206      directive arguments, or bounds on the amount of output such
207      as width and precision, and not the result of  heuristics that
208      depend on warning levels.  It's used to issue stricter diagnostics
209      in cases where strings of unknown lengths are bounded by the arrays
210      they are determined to refer to.  KNOWNRANGE must not be used for
211      the return value optimization.  */
212   bool knownrange;
213 
214   /* True if no individual directive resulted in more than 4095 bytes
215      of output (the total NUMBER_CHARS_{MIN,MAX} might be greater).
216      Implementations are not required to handle directives that produce
217      more than 4K bytes (leading to undefined behavior) and so when one
218      is found it disables the return value optimization.  */
219   bool under4k;
220 
221   /* True when a floating point directive has been seen in the format
222      string.  */
223   bool floating;
224 
225   /* True when an intermediate result has caused a warning.  Used to
226      avoid issuing duplicate warnings while finishing the processing
227      of a call.  WARNED also disables the return value optimization.  */
228   bool warned;
229 
230   /* Preincrement the number of output characters by 1.  */
231   format_result& operator++ ()
232   {
233     return *this += 1;
234   }
235 
236   /* Postincrement the number of output characters by 1.  */
237   format_result operator++ (int)
238   {
239     format_result prev (*this);
240     *this += 1;
241     return prev;
242   }
243 
244   /* Increment the number of output characters by N.  */
245   format_result& operator+= (unsigned HOST_WIDE_INT);
246 };
247 
248 format_result&
249 format_result::operator+= (unsigned HOST_WIDE_INT n)
250 {
251   gcc_assert (n < HOST_WIDE_INT_MAX);
252 
253   if (range.min < HOST_WIDE_INT_MAX)
254     range.min += n;
255 
256   if (range.max < HOST_WIDE_INT_MAX)
257     range.max += n;
258 
259   if (range.likely < HOST_WIDE_INT_MAX)
260     range.likely += n;
261 
262   if (range.unlikely < HOST_WIDE_INT_MAX)
263     range.unlikely += n;
264 
265   return *this;
266 }
267 
268 /* Return the value of INT_MIN for the target.  */
269 
270 static inline HOST_WIDE_INT
271 target_int_min ()
272 {
273   return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node));
274 }
275 
276 /* Return the value of INT_MAX for the target.  */
277 
278 static inline unsigned HOST_WIDE_INT
279 target_int_max ()
280 {
281   return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node));
282 }
283 
284 /* Return the value of SIZE_MAX for the target.  */
285 
286 static inline unsigned HOST_WIDE_INT
287 target_size_max ()
288 {
289   return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node));
290 }
291 
292 /* A straightforward mapping from the execution character set to the host
293    character set indexed by execution character.  */
294 
295 static char target_to_host_charmap[256];
296 
297 /* Initialize a mapping from the execution character set to the host
298    character set.  */
299 
300 static bool
301 init_target_to_host_charmap ()
302 {
303   /* If the percent sign is non-zero the mapping has already been
304      initialized.  */
305   if (target_to_host_charmap['%'])
306     return true;
307 
308   /* Initialize the target_percent character (done elsewhere).  */
309   if (!init_target_chars ())
310     return false;
311 
312   /* The subset of the source character set used by printf conversion
313      specifications (strictly speaking, not all letters are used but
314      they are included here for the sake of simplicity).  The dollar
315      sign must be included even though it's not in the basic source
316      character set.  */
317   const char srcset[] = " 0123456789!\"#%&'()*+,-./:;<=>?[\\]^_{|}~$"
318     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
319 
320   /* Set the mapping for all characters to some ordinary value (i,e.,
321      not none used in printf conversion specifications) and overwrite
322      those that are used by conversion specifications with their
323      corresponding values.  */
324   memset (target_to_host_charmap + 1, '?', sizeof target_to_host_charmap - 1);
325 
326   /* Are the two sets of characters the same?  */
327   bool all_same_p = true;
328 
329   for (const char *pc = srcset; *pc; ++pc)
330     {
331       /* Slice off the high end bits in case target characters are
332 	 signed.  All values are expected to be non-nul, otherwise
333 	 there's a problem.  */
334       if (unsigned char tc = lang_hooks.to_target_charset (*pc))
335 	{
336 	  target_to_host_charmap[tc] = *pc;
337 	  if (tc != *pc)
338 	    all_same_p = false;
339 	}
340       else
341 	return false;
342 
343     }
344 
345   /* Set the first element to a non-zero value if the mapping
346      is 1-to-1, otherwise leave it clear (NUL is assumed to be
347      the same in both character sets).  */
348   target_to_host_charmap[0] = all_same_p;
349 
350   return true;
351 }
352 
353 /* Return the host source character corresponding to the character
354    CH in the execution character set if one exists, or some innocuous
355    (non-special, non-nul) source character otherwise.  */
356 
357 static inline unsigned char
358 target_to_host (unsigned char ch)
359 {
360   return target_to_host_charmap[ch];
361 }
362 
363 /* Convert an initial substring of the string TARGSTR consisting of
364    characters in the execution character set into a string in the
365    source character set on the host and store up to HOSTSZ characters
366    in the buffer pointed to by HOSTR.  Return HOSTR.  */
367 
368 static const char*
369 target_to_host (char *hostr, size_t hostsz, const char *targstr)
370 {
371   /* Make sure the buffer is reasonably big.  */
372   gcc_assert (hostsz > 4);
373 
374   /* The interesting subset of source and execution characters are
375      the same so no conversion is necessary.  However, truncate
376      overlong strings just like the translated strings are.  */
377   if (target_to_host_charmap['\0'] == 1)
378     {
379       strncpy (hostr, targstr, hostsz - 4);
380       if (strlen (targstr) >= hostsz)
381 	strcpy (hostr + hostsz - 4, "...");
382       return hostr;
383     }
384 
385   /* Convert the initial substring of TARGSTR to the corresponding
386      characters in the host set, appending "..." if TARGSTR is too
387      long to fit.  Using the static buffer assumes the function is
388      not called in between sequence points (which it isn't).  */
389   for (char *ph = hostr; ; ++targstr)
390     {
391       *ph++ = target_to_host (*targstr);
392       if (!*targstr)
393 	break;
394 
395       if (size_t (ph - hostr) == hostsz - 4)
396 	{
397 	  *ph = '\0';
398 	  strcat (ph, "...");
399 	  break;
400 	}
401     }
402 
403   return hostr;
404 }
405 
406 /* Convert the sequence of decimal digits in the execution character
407    starting at S to a long, just like strtol does.  Return the result
408    and set *END to one past the last converted character.  On range
409    error set ERANGE to the digit that caused it.  */
410 
411 static inline long
412 target_strtol10 (const char **ps, const char **erange)
413 {
414   unsigned HOST_WIDE_INT val = 0;
415   for ( ; ; ++*ps)
416     {
417       unsigned char c = target_to_host (**ps);
418       if (ISDIGIT (c))
419 	{
420 	  c -= '0';
421 
422 	  /* Check for overflow.  */
423 	  if (val > (LONG_MAX - c) / 10LU)
424 	    {
425 	      val = LONG_MAX;
426 	      *erange = *ps;
427 
428 	      /* Skip the remaining digits.  */
429 	      do
430 		c = target_to_host (*++*ps);
431 	      while (ISDIGIT (c));
432 	      break;
433 	    }
434 	  else
435 	    val = val * 10 + c;
436 	}
437       else
438 	break;
439     }
440 
441   return val;
442 }
443 
444 /* Return the constant initial value of DECL if available or DECL
445    otherwise.  Same as the synonymous function in c/c-typeck.c.  */
446 
447 static tree
448 decl_constant_value (tree decl)
449 {
450   if (/* Don't change a variable array bound or initial value to a constant
451 	 in a place where a variable is invalid.  Note that DECL_INITIAL
452 	 isn't valid for a PARM_DECL.  */
453       current_function_decl != 0
454       && TREE_CODE (decl) != PARM_DECL
455       && !TREE_THIS_VOLATILE (decl)
456       && TREE_READONLY (decl)
457       && DECL_INITIAL (decl) != 0
458       && TREE_CODE (DECL_INITIAL (decl)) != ERROR_MARK
459       /* This is invalid if initial value is not constant.
460 	 If it has either a function call, a memory reference,
461 	 or a variable, then re-evaluating it could give different results.  */
462       && TREE_CONSTANT (DECL_INITIAL (decl))
463       /* Check for cases where this is sub-optimal, even though valid.  */
464       && TREE_CODE (DECL_INITIAL (decl)) != CONSTRUCTOR)
465     return DECL_INITIAL (decl);
466   return decl;
467 }
468 
469 /* Given FORMAT, set *PLOC to the source location of the format string
470    and return the format string if it is known or null otherwise.  */
471 
472 static const char*
473 get_format_string (tree format, location_t *ploc)
474 {
475   if (VAR_P (format))
476     {
477       /* Pull out a constant value if the front end didn't.  */
478       format = decl_constant_value (format);
479       STRIP_NOPS (format);
480     }
481 
482   if (integer_zerop (format))
483     {
484       /* FIXME: Diagnose null format string if it hasn't been diagnosed
485 	 by -Wformat (the latter diagnoses only nul pointer constants,
486 	 this pass can do better).  */
487       return NULL;
488     }
489 
490   HOST_WIDE_INT offset = 0;
491 
492   if (TREE_CODE (format) == POINTER_PLUS_EXPR)
493     {
494       tree arg0 = TREE_OPERAND (format, 0);
495       tree arg1 = TREE_OPERAND (format, 1);
496       STRIP_NOPS (arg0);
497       STRIP_NOPS (arg1);
498 
499       if (TREE_CODE (arg1) != INTEGER_CST)
500 	return NULL;
501 
502       format = arg0;
503 
504       /* POINTER_PLUS_EXPR offsets are to be interpreted signed.  */
505       if (!cst_and_fits_in_hwi (arg1))
506 	return NULL;
507 
508       offset = int_cst_value (arg1);
509     }
510 
511   if (TREE_CODE (format) != ADDR_EXPR)
512     return NULL;
513 
514   *ploc = EXPR_LOC_OR_LOC (format, input_location);
515 
516   format = TREE_OPERAND (format, 0);
517 
518   if (TREE_CODE (format) == ARRAY_REF
519       && tree_fits_shwi_p (TREE_OPERAND (format, 1))
520       && (offset += tree_to_shwi (TREE_OPERAND (format, 1))) >= 0)
521     format = TREE_OPERAND (format, 0);
522 
523   if (offset < 0)
524     return NULL;
525 
526   tree array_init;
527   tree array_size = NULL_TREE;
528 
529   if (VAR_P (format)
530       && TREE_CODE (TREE_TYPE (format)) == ARRAY_TYPE
531       && (array_init = decl_constant_value (format)) != format
532       && TREE_CODE (array_init) == STRING_CST)
533     {
534       /* Extract the string constant initializer.  Note that this may
535 	 include a trailing NUL character that is not in the array (e.g.
536 	 const char a[3] = "foo";).  */
537       array_size = DECL_SIZE_UNIT (format);
538       format = array_init;
539     }
540 
541   if (TREE_CODE (format) != STRING_CST)
542     return NULL;
543 
544   tree type = TREE_TYPE (format);
545 
546   scalar_int_mode char_mode;
547   if (!is_int_mode (TYPE_MODE (TREE_TYPE (type)), &char_mode)
548       || GET_MODE_SIZE (char_mode) != 1)
549     {
550       /* Wide format string.  */
551       return NULL;
552     }
553 
554   const char *fmtstr = TREE_STRING_POINTER (format);
555   unsigned fmtlen = TREE_STRING_LENGTH (format);
556 
557   if (array_size)
558     {
559       /* Variable length arrays can't be initialized.  */
560       gcc_assert (TREE_CODE (array_size) == INTEGER_CST);
561 
562       if (tree_fits_shwi_p (array_size))
563 	{
564 	  HOST_WIDE_INT array_size_value = tree_to_shwi (array_size);
565 	  if (array_size_value > 0
566 	      && array_size_value == (int) array_size_value
567 	      && fmtlen > array_size_value)
568 	    fmtlen = array_size_value;
569 	}
570     }
571   if (offset)
572     {
573       if (offset >= fmtlen)
574 	return NULL;
575 
576       fmtstr += offset;
577       fmtlen -= offset;
578     }
579 
580   if (fmtlen < 1 || fmtstr[--fmtlen] != 0)
581     {
582       /* FIXME: Diagnose an unterminated format string if it hasn't been
583 	 diagnosed by -Wformat.  Similarly to a null format pointer,
584 	 -Wformay diagnoses only nul pointer constants, this pass can
585 	 do better).  */
586       return NULL;
587     }
588 
589   return fmtstr;
590 }
591 
592 /* For convenience and brevity, shorter named entrypoints of
593    format_warning_at_substring and format_warning_at_substring_n.
594    These have to be functions with the attribute so that exgettext
595    works properly.  */
596 
597 static bool
598 ATTRIBUTE_GCC_DIAG (5, 6)
599 fmtwarn (const substring_loc &fmt_loc, location_t param_loc,
600 	 const char *corrected_substring, int opt, const char *gmsgid, ...)
601 {
602   va_list ap;
603   va_start (ap, gmsgid);
604   bool warned = format_warning_va (fmt_loc, param_loc, corrected_substring,
605 				   opt, gmsgid, &ap);
606   va_end (ap);
607 
608   return warned;
609 }
610 
611 static bool
612 ATTRIBUTE_GCC_DIAG (6, 8) ATTRIBUTE_GCC_DIAG (7, 8)
613 fmtwarn_n (const substring_loc &fmt_loc, location_t param_loc,
614 	   const char *corrected_substring, int opt, unsigned HOST_WIDE_INT n,
615 	   const char *singular_gmsgid, const char *plural_gmsgid, ...)
616 {
617   va_list ap;
618   va_start (ap, plural_gmsgid);
619   bool warned = format_warning_n_va (fmt_loc, param_loc, corrected_substring,
620 				     opt, n, singular_gmsgid, plural_gmsgid,
621 				     &ap);
622   va_end (ap);
623 
624   return warned;
625 }
626 
627 /* Format length modifiers.  */
628 
629 enum format_lengths
630 {
631   FMT_LEN_none,
632   FMT_LEN_hh,    // char argument
633   FMT_LEN_h,     // short
634   FMT_LEN_l,     // long
635   FMT_LEN_ll,    // long long
636   FMT_LEN_L,     // long double (and GNU long long)
637   FMT_LEN_z,     // size_t
638   FMT_LEN_t,     // ptrdiff_t
639   FMT_LEN_j      // intmax_t
640 };
641 
642 
643 /* Description of the result of conversion either of a single directive
644    or the whole format string.  */
645 
646 struct fmtresult
647 {
648   /* Construct a FMTRESULT object with all counters initialized
649      to MIN.  KNOWNRANGE is set when MIN is valid.  */
650   fmtresult (unsigned HOST_WIDE_INT min = HOST_WIDE_INT_MAX)
651   : argmin (), argmax (),
652     knownrange (min < HOST_WIDE_INT_MAX),
653     nullp ()
654   {
655     range.min = min;
656     range.max = min;
657     range.likely = min;
658     range.unlikely = min;
659   }
660 
661   /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
662      KNOWNRANGE is set when both MIN and MAX are valid.   */
663   fmtresult (unsigned HOST_WIDE_INT min, unsigned HOST_WIDE_INT max,
664 	     unsigned HOST_WIDE_INT likely = HOST_WIDE_INT_MAX)
665   : argmin (), argmax (),
666     knownrange (min < HOST_WIDE_INT_MAX && max < HOST_WIDE_INT_MAX),
667     nullp ()
668   {
669     range.min = min;
670     range.max = max;
671     range.likely = max < likely ? min : likely;
672     range.unlikely = max;
673   }
674 
675   /* Adjust result upward to reflect the RANGE of values the specified
676      width or precision is known to be in.  */
677   fmtresult& adjust_for_width_or_precision (const HOST_WIDE_INT[2],
678 					    tree = NULL_TREE,
679 					    unsigned = 0, unsigned = 0);
680 
681   /* Return the maximum number of decimal digits a value of TYPE
682      formats as on output.  */
683   static unsigned type_max_digits (tree, int);
684 
685   /* The range a directive's argument is in.  */
686   tree argmin, argmax;
687 
688   /* The minimum and maximum number of bytes that a directive
689      results in on output for an argument in the range above.  */
690   result_range range;
691 
692   /* True when the range above is obtained from a known value of
693      a directive's argument or its bounds and not the result of
694      heuristics that depend on warning levels.  */
695   bool knownrange;
696 
697   /* True when the argument is a null pointer.  */
698   bool nullp;
699 };
700 
701 /* Adjust result upward to reflect the range ADJUST of values the
702    specified width or precision is known to be in.  When non-null,
703    TYPE denotes the type of the directive whose result is being
704    adjusted, BASE gives the base of the directive (octal, decimal,
705    or hex), and ADJ denotes the additional adjustment to the LIKELY
706    counter that may need to be added when ADJUST is a range.  */
707 
708 fmtresult&
709 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust[2],
710 					  tree type /* = NULL_TREE */,
711 					  unsigned base /* = 0 */,
712 					  unsigned adj /* = 0 */)
713 {
714   bool minadjusted = false;
715 
716   /* Adjust the minimum and likely counters.  */
717   if (adjust[0] >= 0)
718     {
719       if (range.min < (unsigned HOST_WIDE_INT)adjust[0])
720 	{
721 	  range.min = adjust[0];
722 	  minadjusted = true;
723 	}
724 
725       /* Adjust the likely counter.  */
726       if (range.likely < range.min)
727 	range.likely = range.min;
728     }
729   else if (adjust[0] == target_int_min ()
730 	   && (unsigned HOST_WIDE_INT)adjust[1] == target_int_max ())
731     knownrange = false;
732 
733   /* Adjust the maximum counter.  */
734   if (adjust[1] > 0)
735     {
736       if (range.max < (unsigned HOST_WIDE_INT)adjust[1])
737 	{
738 	  range.max = adjust[1];
739 
740 	  /* Set KNOWNRANGE if both the minimum and maximum have been
741 	     adjusted.  Otherwise leave it at what it was before.  */
742 	  knownrange = minadjusted;
743 	}
744     }
745 
746   if (warn_level > 1 && type)
747     {
748       /* For large non-constant width or precision whose range spans
749 	 the maximum number of digits produced by the directive for
750 	 any argument, set the likely number of bytes to be at most
751 	 the number digits plus other adjustment determined by the
752 	 caller (one for sign or two for the hexadecimal "0x"
753 	 prefix).  */
754       unsigned dirdigs = type_max_digits (type, base);
755       if (adjust[0] < dirdigs && dirdigs < adjust[1]
756 	  && range.likely < dirdigs)
757 	range.likely = dirdigs + adj;
758     }
759   else if (range.likely < (range.min ? range.min : 1))
760     {
761       /* Conservatively, set LIKELY to at least MIN but no less than
762 	 1 unless MAX is zero.  */
763       range.likely = (range.min
764 		      ? range.min
765 		      : range.max && (range.max < HOST_WIDE_INT_MAX
766 				      || warn_level > 1) ? 1 : 0);
767     }
768 
769   /* Finally adjust the unlikely counter to be at least as large as
770      the maximum.  */
771   if (range.unlikely < range.max)
772     range.unlikely = range.max;
773 
774   return *this;
775 }
776 
777 /* Return the maximum number of digits a value of TYPE formats in
778    BASE on output, not counting base prefix .  */
779 
780 unsigned
781 fmtresult::type_max_digits (tree type, int base)
782 {
783   unsigned prec = TYPE_PRECISION (type);
784   if (base == 8)
785     return (prec + 2) / 3;
786 
787   if (base == 16)
788     return prec / 4;
789 
790   /* Decimal approximation: yields 3, 5, 10, and 20 for precision
791      of 8, 16, 32, and 64 bits.  */
792   return prec * 301 / 1000 + 1;
793 }
794 
795 static bool
796 get_int_range (tree, HOST_WIDE_INT *, HOST_WIDE_INT *, bool, HOST_WIDE_INT,
797 	       class vr_values *vr_values);
798 
799 /* Description of a format directive.  A directive is either a plain
800    string or a conversion specification that starts with '%'.  */
801 
802 struct directive
803 {
804   /* The 1-based directive number (for debugging).  */
805   unsigned dirno;
806 
807   /* The first character of the directive and its length.  */
808   const char *beg;
809   size_t len;
810 
811   /* A bitmap of flags, one for each character.  */
812   unsigned flags[256 / sizeof (int)];
813 
814   /* The range of values of the specified width, or -1 if not specified.  */
815   HOST_WIDE_INT width[2];
816   /* The range of values of the specified precision, or -1 if not
817      specified.  */
818   HOST_WIDE_INT prec[2];
819 
820   /* Length modifier.  */
821   format_lengths modifier;
822 
823   /* Format specifier character.  */
824   char specifier;
825 
826   /* The argument of the directive or null when the directive doesn't
827      take one or when none is available (such as for vararg functions).  */
828   tree arg;
829 
830   /* Format conversion function that given a directive and an argument
831      returns the formatting result.  */
832   fmtresult (*fmtfunc) (const directive &, tree, vr_values *);
833 
834   /* Return True when a the format flag CHR has been used.  */
835   bool get_flag (char chr) const
836   {
837     unsigned char c = chr & 0xff;
838     return (flags[c / (CHAR_BIT * sizeof *flags)]
839 	    & (1U << (c % (CHAR_BIT * sizeof *flags))));
840   }
841 
842   /* Make a record of the format flag CHR having been used.  */
843   void set_flag (char chr)
844   {
845     unsigned char c = chr & 0xff;
846     flags[c / (CHAR_BIT * sizeof *flags)]
847       |= (1U << (c % (CHAR_BIT * sizeof *flags)));
848   }
849 
850   /* Reset the format flag CHR.  */
851   void clear_flag (char chr)
852   {
853     unsigned char c = chr & 0xff;
854     flags[c / (CHAR_BIT * sizeof *flags)]
855       &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
856   }
857 
858   /* Set both bounds of the width range to VAL.  */
859   void set_width (HOST_WIDE_INT val)
860   {
861     width[0] = width[1] = val;
862   }
863 
864   /* Set the width range according to ARG, with both bounds being
865      no less than 0.  For a constant ARG set both bounds to its value
866      or 0, whichever is greater.  For a non-constant ARG in some range
867      set width to its range adjusting each bound to -1 if it's less.
868      For an indeterminate ARG set width to [0, INT_MAX].  */
869   void set_width (tree arg, vr_values *vr_values)
870   {
871     get_int_range (arg, width, width + 1, true, 0, vr_values);
872   }
873 
874   /* Set both bounds of the precision range to VAL.  */
875   void set_precision (HOST_WIDE_INT val)
876   {
877     prec[0] = prec[1] = val;
878   }
879 
880   /* Set the precision range according to ARG, with both bounds being
881      no less than -1.  For a constant ARG set both bounds to its value
882      or -1 whichever is greater.  For a non-constant ARG in some range
883      set precision to its range adjusting each bound to -1 if it's less.
884      For an indeterminate ARG set precision to [-1, INT_MAX].  */
885   void set_precision (tree arg, vr_values *vr_values)
886   {
887     get_int_range (arg, prec, prec + 1, false, -1, vr_values);
888   }
889 
890   /* Return true if both width and precision are known to be
891      either constant or in some range, false otherwise.  */
892   bool known_width_and_precision () const
893   {
894     return ((width[1] < 0
895 	     || (unsigned HOST_WIDE_INT)width[1] <= target_int_max ())
896 	    && (prec[1] < 0
897 		|| (unsigned HOST_WIDE_INT)prec[1] < target_int_max ()));
898   }
899 };
900 
901 /* Return the logarithm of X in BASE.  */
902 
903 static int
904 ilog (unsigned HOST_WIDE_INT x, int base)
905 {
906   int res = 0;
907   do
908     {
909       ++res;
910       x /= base;
911     } while (x);
912   return res;
913 }
914 
915 /* Return the number of bytes resulting from converting into a string
916    the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
917    PLUS indicates whether 1 for a plus sign should be added for positive
918    numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
919    ('0x') prefix should be added for nonzero numbers.  Return -1 if X cannot
920    be represented.  */
921 
922 static HOST_WIDE_INT
923 tree_digits (tree x, int base, HOST_WIDE_INT prec, bool plus, bool prefix)
924 {
925   unsigned HOST_WIDE_INT absval;
926 
927   HOST_WIDE_INT res;
928 
929   if (TYPE_UNSIGNED (TREE_TYPE (x)))
930     {
931       if (tree_fits_uhwi_p (x))
932 	{
933 	  absval = tree_to_uhwi (x);
934 	  res = plus;
935 	}
936       else
937 	return -1;
938     }
939   else
940     {
941       if (tree_fits_shwi_p (x))
942 	{
943 	  HOST_WIDE_INT i = tree_to_shwi (x);
944          if (HOST_WIDE_INT_MIN == i)
945            {
946              /* Avoid undefined behavior due to negating a minimum.  */
947              absval = HOST_WIDE_INT_MAX;
948              res = 1;
949            }
950          else if (i < 0)
951 	   {
952 	     absval = -i;
953 	     res = 1;
954 	   }
955 	 else
956 	   {
957 	     absval = i;
958 	     res = plus;
959 	   }
960 	}
961       else
962 	return -1;
963     }
964 
965   int ndigs = ilog (absval, base);
966 
967   res += prec < ndigs ? ndigs : prec;
968 
969   /* Adjust a non-zero value for the base prefix, either hexadecimal,
970      or, unless precision has resulted in a leading zero, also octal.  */
971   if (prefix && absval && (base == 16 || prec <= ndigs))
972     {
973       if (base == 8)
974 	res += 1;
975       else if (base == 16)
976 	res += 2;
977     }
978 
979   return res;
980 }
981 
982 /* Given the formatting result described by RES and NAVAIL, the number
983    of available in the destination, return the range of bytes remaining
984    in the destination.  */
985 
986 static inline result_range
987 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
988 {
989   result_range range;
990 
991   if (HOST_WIDE_INT_MAX <= navail)
992     {
993       range.min = range.max = range.likely = range.unlikely = navail;
994       return range;
995     }
996 
997   /* The lower bound of the available range is the available size
998      minus the maximum output size, and the upper bound is the size
999      minus the minimum.  */
1000   range.max = res.range.min < navail ? navail - res.range.min : 0;
1001 
1002   range.likely = res.range.likely < navail ? navail - res.range.likely : 0;
1003 
1004   if (res.range.max < HOST_WIDE_INT_MAX)
1005     range.min = res.range.max < navail ? navail - res.range.max : 0;
1006   else
1007     range.min = range.likely;
1008 
1009   range.unlikely = (res.range.unlikely < navail
1010 		    ? navail - res.range.unlikely : 0);
1011 
1012   return range;
1013 }
1014 
1015 /* Description of a call to a formatted function.  */
1016 
1017 struct sprintf_dom_walker::call_info
1018 {
1019   /* Function call statement.  */
1020   gimple *callstmt;
1021 
1022   /* Function called.  */
1023   tree func;
1024 
1025   /* Called built-in function code.  */
1026   built_in_function fncode;
1027 
1028   /* Format argument and format string extracted from it.  */
1029   tree format;
1030   const char *fmtstr;
1031 
1032   /* The location of the format argument.  */
1033   location_t fmtloc;
1034 
1035   /* The destination object size for __builtin___xxx_chk functions
1036      typically determined by __builtin_object_size, or -1 if unknown.  */
1037   unsigned HOST_WIDE_INT objsize;
1038 
1039   /* Number of the first variable argument.  */
1040   unsigned HOST_WIDE_INT argidx;
1041 
1042   /* True for functions like snprintf that specify the size of
1043      the destination, false for others like sprintf that don't.  */
1044   bool bounded;
1045 
1046   /* True for bounded functions like snprintf that specify a zero-size
1047      buffer as a request to compute the size of output without actually
1048      writing any.  NOWRITE is cleared in response to the %n directive
1049      which has side-effects similar to writing output.  */
1050   bool nowrite;
1051 
1052   /* Return true if the called function's return value is used.  */
1053   bool retval_used () const
1054   {
1055     return gimple_get_lhs (callstmt);
1056   }
1057 
1058   /* Return the warning option corresponding to the called function.  */
1059   int warnopt () const
1060   {
1061     return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
1062   }
1063 };
1064 
1065 /* Return the result of formatting a no-op directive (such as '%n').  */
1066 
1067 static fmtresult
1068 format_none (const directive &, tree, vr_values *)
1069 {
1070   fmtresult res (0);
1071   return res;
1072 }
1073 
1074 /* Return the result of formatting the '%%' directive.  */
1075 
1076 static fmtresult
1077 format_percent (const directive &, tree, vr_values *)
1078 {
1079   fmtresult res (1);
1080   return res;
1081 }
1082 
1083 
1084 /* Compute intmax_type_node and uintmax_type_node similarly to how
1085    tree.c builds size_type_node.  */
1086 
1087 static void
1088 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
1089 {
1090   if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
1091     {
1092       *pintmax = integer_type_node;
1093       *puintmax = unsigned_type_node;
1094     }
1095   else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
1096     {
1097       *pintmax = long_integer_type_node;
1098       *puintmax = long_unsigned_type_node;
1099     }
1100   else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
1101     {
1102       *pintmax = long_long_integer_type_node;
1103       *puintmax = long_long_unsigned_type_node;
1104     }
1105   else
1106     {
1107       for (int i = 0; i < NUM_INT_N_ENTS; i++)
1108 	if (int_n_enabled_p[i])
1109 	  {
1110 	    char name[50];
1111 	    sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
1112 
1113 	    if (strcmp (name, UINTMAX_TYPE) == 0)
1114 	      {
1115 	        *pintmax = int_n_trees[i].signed_type;
1116 	        *puintmax = int_n_trees[i].unsigned_type;
1117 		return;
1118 	      }
1119 	  }
1120       gcc_unreachable ();
1121     }
1122 }
1123 
1124 /* Determine the range [*PMIN, *PMAX] that the expression ARG is
1125    in and that is representable in type int.
1126    Return true when the range is a subrange of that of int.
1127    When ARG is null it is as if it had the full range of int.
1128    When ABSOLUTE is true the range reflects the absolute value of
1129    the argument.  When ABSOLUTE is false, negative bounds of
1130    the determined range are replaced with NEGBOUND.  */
1131 
1132 static bool
1133 get_int_range (tree arg, HOST_WIDE_INT *pmin, HOST_WIDE_INT *pmax,
1134 	       bool absolute, HOST_WIDE_INT negbound,
1135 	       class vr_values *vr_values)
1136 {
1137   /* The type of the result.  */
1138   const_tree type = integer_type_node;
1139 
1140   bool knownrange = false;
1141 
1142   if (!arg)
1143     {
1144       *pmin = tree_to_shwi (TYPE_MIN_VALUE (type));
1145       *pmax = tree_to_shwi (TYPE_MAX_VALUE (type));
1146     }
1147   else if (TREE_CODE (arg) == INTEGER_CST
1148 	   && TYPE_PRECISION (TREE_TYPE (arg)) <= TYPE_PRECISION (type))
1149     {
1150       /* For a constant argument return its value adjusted as specified
1151 	 by NEGATIVE and NEGBOUND and return true to indicate that the
1152 	 result is known.  */
1153       *pmin = tree_fits_shwi_p (arg) ? tree_to_shwi (arg) : tree_to_uhwi (arg);
1154       *pmax = *pmin;
1155       knownrange = true;
1156     }
1157   else
1158     {
1159       /* True if the argument's range cannot be determined.  */
1160       bool unknown = true;
1161 
1162       tree argtype = TREE_TYPE (arg);
1163 
1164       /* Ignore invalid arguments with greater precision that that
1165 	 of the expected type (e.g., in sprintf("%*i", 12LL, i)).
1166 	 They will have been detected and diagnosed by -Wformat and
1167 	 so it's not important to complicate this code to try to deal
1168 	 with them again.  */
1169       if (TREE_CODE (arg) == SSA_NAME
1170 	  && INTEGRAL_TYPE_P (argtype)
1171 	  && TYPE_PRECISION (argtype) <= TYPE_PRECISION (type))
1172 	{
1173 	  /* Try to determine the range of values of the integer argument.  */
1174 	  value_range *vr = vr_values->get_value_range (arg);
1175 	  if (vr->type == VR_RANGE
1176 	      && TREE_CODE (vr->min) == INTEGER_CST
1177 	      && TREE_CODE (vr->max) == INTEGER_CST)
1178 	    {
1179 	      HOST_WIDE_INT type_min
1180 		= (TYPE_UNSIGNED (argtype)
1181 		   ? tree_to_uhwi (TYPE_MIN_VALUE (argtype))
1182 		   : tree_to_shwi (TYPE_MIN_VALUE (argtype)));
1183 
1184 	      HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (argtype));
1185 
1186 	      *pmin = TREE_INT_CST_LOW (vr->min);
1187 	      *pmax = TREE_INT_CST_LOW (vr->max);
1188 
1189 	      if (*pmin < *pmax)
1190 		{
1191 		  /* Return true if the adjusted range is a subrange of
1192 		     the full range of the argument's type.  *PMAX may
1193 		     be less than *PMIN when the argument is unsigned
1194 		     and its upper bound is in excess of TYPE_MAX.  In
1195 		     that (invalid) case disregard the range and use that
1196 		     of the expected type instead.  */
1197 		  knownrange = type_min < *pmin || *pmax < type_max;
1198 
1199 		  unknown = false;
1200 		}
1201 	    }
1202 	}
1203 
1204       /* Handle an argument with an unknown range as if none had been
1205 	 provided.  */
1206       if (unknown)
1207 	return get_int_range (NULL_TREE, pmin, pmax, absolute,
1208 			      negbound, vr_values);
1209     }
1210 
1211   /* Adjust each bound as specified by ABSOLUTE and NEGBOUND.  */
1212   if (absolute)
1213     {
1214       if (*pmin < 0)
1215 	{
1216 	  if (*pmin == *pmax)
1217 	    *pmin = *pmax = -*pmin;
1218 	  else
1219 	    {
1220 	      /* Make sure signed overlow is avoided.  */
1221 	      gcc_assert (*pmin != HOST_WIDE_INT_MIN);
1222 
1223 	      HOST_WIDE_INT tmp = -*pmin;
1224 	      *pmin = 0;
1225 	      if (*pmax < tmp)
1226 		*pmax = tmp;
1227 	    }
1228 	}
1229     }
1230   else if (*pmin < negbound)
1231     *pmin = negbound;
1232 
1233   return knownrange;
1234 }
1235 
1236 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1237    argument, due to the conversion from either *ARGMIN or *ARGMAX to
1238    the type of the directive's formal argument it's possible for both
1239    to result in the same number of bytes or a range of bytes that's
1240    less than the number of bytes that would result from formatting
1241    some other value in the range [*ARGMIN, *ARGMAX].  This can be
1242    determined by checking for the actual argument being in the range
1243    of the type of the directive.  If it isn't it must be assumed to
1244    take on the full range of the directive's type.
1245    Return true when the range has been adjusted to the full range
1246    of DIRTYPE, and false otherwise.  */
1247 
1248 static bool
1249 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
1250 {
1251   tree argtype = TREE_TYPE (*argmin);
1252   unsigned argprec = TYPE_PRECISION (argtype);
1253   unsigned dirprec = TYPE_PRECISION (dirtype);
1254 
1255   /* If the actual argument and the directive's argument have the same
1256      precision and sign there can be no overflow and so there is nothing
1257      to adjust.  */
1258   if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
1259     return false;
1260 
1261   /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1262      branch in the extract_range_from_unary_expr function in tree-vrp.c.  */
1263 
1264   if (TREE_CODE (*argmin) == INTEGER_CST
1265       && TREE_CODE (*argmax) == INTEGER_CST
1266       && (dirprec >= argprec
1267 	  || integer_zerop (int_const_binop (RSHIFT_EXPR,
1268 					     int_const_binop (MINUS_EXPR,
1269 							      *argmax,
1270 							      *argmin),
1271 					     size_int (dirprec)))))
1272     {
1273       *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
1274       *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
1275 
1276       /* If *ARGMIN is still less than *ARGMAX the conversion above
1277 	 is safe.  Otherwise, it has overflowed and would be unsafe.  */
1278       if (tree_int_cst_le (*argmin, *argmax))
1279 	return false;
1280     }
1281 
1282   *argmin = TYPE_MIN_VALUE (dirtype);
1283   *argmax = TYPE_MAX_VALUE (dirtype);
1284   return true;
1285 }
1286 
1287 /* Return a range representing the minimum and maximum number of bytes
1288    that the format directive DIR will output for any argument given
1289    the WIDTH and PRECISION (extracted from DIR).  This function is
1290    used when the directive argument or its value isn't known.  */
1291 
1292 static fmtresult
1293 format_integer (const directive &dir, tree arg, vr_values *vr_values)
1294 {
1295   tree intmax_type_node;
1296   tree uintmax_type_node;
1297 
1298   /* Base to format the number in.  */
1299   int base;
1300 
1301   /* True when a conversion is preceded by a prefix indicating the base
1302      of the argument (octal or hexadecimal).  */
1303   bool maybebase = dir.get_flag ('#');
1304 
1305   /* True when a signed conversion is preceded by a sign or space.  */
1306   bool maybesign = false;
1307 
1308   /* True for signed conversions (i.e., 'd' and 'i').  */
1309   bool sign = false;
1310 
1311   switch (dir.specifier)
1312     {
1313     case 'd':
1314     case 'i':
1315       /* Space and '+' are  only meaningful for signed conversions.  */
1316       maybesign = dir.get_flag (' ') | dir.get_flag ('+');
1317       sign = true;
1318       base = 10;
1319       break;
1320     case 'u':
1321       base = 10;
1322       break;
1323     case 'o':
1324       base = 8;
1325       break;
1326     case 'X':
1327     case 'x':
1328       base = 16;
1329       break;
1330     default:
1331       gcc_unreachable ();
1332     }
1333 
1334   /* The type of the "formal" argument expected by the directive.  */
1335   tree dirtype = NULL_TREE;
1336 
1337   /* Determine the expected type of the argument from the length
1338      modifier.  */
1339   switch (dir.modifier)
1340     {
1341     case FMT_LEN_none:
1342       if (dir.specifier == 'p')
1343 	dirtype = ptr_type_node;
1344       else
1345 	dirtype = sign ? integer_type_node : unsigned_type_node;
1346       break;
1347 
1348     case FMT_LEN_h:
1349       dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
1350       break;
1351 
1352     case FMT_LEN_hh:
1353       dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
1354       break;
1355 
1356     case FMT_LEN_l:
1357       dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
1358       break;
1359 
1360     case FMT_LEN_L:
1361     case FMT_LEN_ll:
1362       dirtype = (sign
1363 		 ? long_long_integer_type_node
1364 		 : long_long_unsigned_type_node);
1365       break;
1366 
1367     case FMT_LEN_z:
1368       dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
1369       break;
1370 
1371     case FMT_LEN_t:
1372       dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
1373       break;
1374 
1375     case FMT_LEN_j:
1376       build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
1377       dirtype = sign ? intmax_type_node : uintmax_type_node;
1378       break;
1379 
1380     default:
1381       return fmtresult ();
1382     }
1383 
1384   /* The type of the argument to the directive, either deduced from
1385      the actual non-constant argument if one is known, or from
1386      the directive itself when none has been provided because it's
1387      a va_list.  */
1388   tree argtype = NULL_TREE;
1389 
1390   if (!arg)
1391     {
1392       /* When the argument has not been provided, use the type of
1393 	 the directive's argument as an approximation.  This will
1394 	 result in false positives for directives like %i with
1395 	 arguments with smaller precision (such as short or char).  */
1396       argtype = dirtype;
1397     }
1398   else if (TREE_CODE (arg) == INTEGER_CST)
1399     {
1400       /* When a constant argument has been provided use its value
1401 	 rather than type to determine the length of the output.  */
1402       fmtresult res;
1403 
1404       if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
1405 	{
1406 	  /* As a special case, a precision of zero with a zero argument
1407 	     results in zero bytes except in base 8 when the '#' flag is
1408 	     specified, and for signed conversions in base 8 and 10 when
1409 	     either the space or '+' flag has been specified and it results
1410 	     in just one byte (with width having the normal effect).  This
1411 	     must extend to the case of a specified precision with
1412 	     an unknown value because it can be zero.  */
1413 	  res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
1414 	  if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
1415 	    {
1416 	      res.range.max = 1;
1417 	      res.range.likely = 1;
1418 	    }
1419 	  else
1420 	    {
1421 	      res.range.max = res.range.min;
1422 	      res.range.likely = res.range.min;
1423 	    }
1424 	}
1425       else
1426 	{
1427 	  /* Convert the argument to the type of the directive.  */
1428 	  arg = fold_convert (dirtype, arg);
1429 
1430 	  res.range.min = tree_digits (arg, base, dir.prec[0],
1431 				       maybesign, maybebase);
1432 	  if (dir.prec[0] == dir.prec[1])
1433 	    res.range.max = res.range.min;
1434 	  else
1435 	    res.range.max = tree_digits (arg, base, dir.prec[1],
1436 					 maybesign, maybebase);
1437 	  res.range.likely = res.range.min;
1438 	  res.knownrange = true;
1439 	}
1440 
1441       res.range.unlikely = res.range.max;
1442 
1443       /* Bump up the counters if WIDTH is greater than LEN.  */
1444       res.adjust_for_width_or_precision (dir.width, dirtype, base,
1445 					 (sign | maybebase) + (base == 16));
1446       /* Bump up the counters again if PRECision is greater still.  */
1447       res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1448 					 (sign | maybebase) + (base == 16));
1449 
1450       return res;
1451     }
1452   else if (INTEGRAL_TYPE_P (TREE_TYPE (arg))
1453 	   || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1454     /* Determine the type of the provided non-constant argument.  */
1455     argtype = TREE_TYPE (arg);
1456   else
1457     /* Don't bother with invalid arguments since they likely would
1458        have already been diagnosed, and disable any further checking
1459        of the format string by returning [-1, -1].  */
1460     return fmtresult ();
1461 
1462   fmtresult res;
1463 
1464   /* Using either the range the non-constant argument is in, or its
1465      type (either "formal" or actual), create a range of values that
1466      constrain the length of output given the warning level.  */
1467   tree argmin = NULL_TREE;
1468   tree argmax = NULL_TREE;
1469 
1470   if (arg
1471       && TREE_CODE (arg) == SSA_NAME
1472       && INTEGRAL_TYPE_P (argtype))
1473     {
1474       /* Try to determine the range of values of the integer argument
1475 	 (range information is not available for pointers).  */
1476       value_range *vr = vr_values->get_value_range (arg);
1477       if (vr->type == VR_RANGE
1478 	  && TREE_CODE (vr->min) == INTEGER_CST
1479 	  && TREE_CODE (vr->max) == INTEGER_CST)
1480 	{
1481 	  argmin = vr->min;
1482 	  argmax = vr->max;
1483 
1484 	  /* Set KNOWNRANGE if the argument is in a known subrange
1485 	     of the directive's type and neither width nor precision
1486 	     is unknown.  (KNOWNRANGE may be reset below).  */
1487 	  res.knownrange
1488 	    = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1489 		|| !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax))
1490 	       && dir.known_width_and_precision ());
1491 
1492 	  res.argmin = argmin;
1493 	  res.argmax = argmax;
1494 	}
1495       else if (vr->type == VR_ANTI_RANGE)
1496 	{
1497 	  /* Handle anti-ranges if/when bug 71690 is resolved.  */
1498 	}
1499       else if (vr->type == VR_VARYING
1500 	       || vr->type == VR_UNDEFINED)
1501 	{
1502 	  /* The argument here may be the result of promoting the actual
1503 	     argument to int.  Try to determine the type of the actual
1504 	     argument before promotion and narrow down its range that
1505 	     way.  */
1506 	  gimple *def = SSA_NAME_DEF_STMT (arg);
1507 	  if (is_gimple_assign (def))
1508 	    {
1509 	      tree_code code = gimple_assign_rhs_code (def);
1510 	      if (code == INTEGER_CST)
1511 		{
1512 		  arg = gimple_assign_rhs1 (def);
1513 		  return format_integer (dir, arg, vr_values);
1514 		}
1515 
1516 	      if (code == NOP_EXPR)
1517 		{
1518 		  tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1519 		  if (INTEGRAL_TYPE_P (type)
1520 		      || TREE_CODE (type) == POINTER_TYPE)
1521 		    argtype = type;
1522 		}
1523 	    }
1524 	}
1525     }
1526 
1527   if (!argmin)
1528     {
1529       if (TREE_CODE (argtype) == POINTER_TYPE)
1530 	{
1531 	  argmin = build_int_cst (pointer_sized_int_node, 0);
1532 	  argmax = build_all_ones_cst (pointer_sized_int_node);
1533 	}
1534       else
1535 	{
1536 	  argmin = TYPE_MIN_VALUE (argtype);
1537 	  argmax = TYPE_MAX_VALUE (argtype);
1538 	}
1539     }
1540 
1541   /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1542      of the directive.  If it has been cleared then since ARGMIN and/or
1543      ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1544      ARGMAX in the result to include in diagnostics.  */
1545   if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1546     {
1547       res.knownrange = false;
1548       res.argmin = argmin;
1549       res.argmax = argmax;
1550     }
1551 
1552   /* Recursively compute the minimum and maximum from the known range.  */
1553   if (TYPE_UNSIGNED (dirtype) || tree_int_cst_sgn (argmin) >= 0)
1554     {
1555       /* For unsigned conversions/directives or signed when
1556 	 the minimum is positive, use the minimum and maximum to compute
1557 	 the shortest and longest output, respectively.  */
1558       res.range.min = format_integer (dir, argmin, vr_values).range.min;
1559       res.range.max = format_integer (dir, argmax, vr_values).range.max;
1560     }
1561   else if (tree_int_cst_sgn (argmax) < 0)
1562     {
1563       /* For signed conversions/directives if maximum is negative,
1564 	 use the minimum as the longest output and maximum as the
1565 	 shortest output.  */
1566       res.range.min = format_integer (dir, argmax, vr_values).range.min;
1567       res.range.max = format_integer (dir, argmin, vr_values).range.max;
1568     }
1569   else
1570     {
1571       /* Otherwise, 0 is inside of the range and minimum negative.  Use 0
1572 	 as the shortest output and for the longest output compute the
1573 	 length of the output of both minimum and maximum and pick the
1574 	 longer.  */
1575       unsigned HOST_WIDE_INT max1
1576 	= format_integer (dir, argmin, vr_values).range.max;
1577       unsigned HOST_WIDE_INT max2
1578 	= format_integer (dir, argmax, vr_values).range.max;
1579       res.range.min
1580 	= format_integer (dir, integer_zero_node, vr_values).range.min;
1581       res.range.max = MAX (max1, max2);
1582     }
1583 
1584   /* If the range is known, use the maximum as the likely length.  */
1585   if (res.knownrange)
1586     res.range.likely = res.range.max;
1587   else
1588     {
1589       /* Otherwise, use the minimum.  Except for the case where for %#x or
1590          %#o the minimum is just for a single value in the range (0) and
1591          for all other values it is something longer, like 0x1 or 01.
1592 	  Use the length for value 1 in that case instead as the likely
1593 	  length.  */
1594       res.range.likely = res.range.min;
1595       if (maybebase
1596 	  && base != 10
1597 	  && (tree_int_cst_sgn (argmin) < 0 || tree_int_cst_sgn (argmax) > 0))
1598 	{
1599 	  if (res.range.min == 1)
1600 	    res.range.likely += base == 8 ? 1 : 2;
1601 	  else if (res.range.min == 2
1602 		   && base == 16
1603 		   && (dir.width[0] == 2 || dir.prec[0] == 2))
1604 	    ++res.range.likely;
1605 	}
1606     }
1607 
1608   res.range.unlikely = res.range.max;
1609   res.adjust_for_width_or_precision (dir.width, dirtype, base,
1610 				     (sign | maybebase) + (base == 16));
1611   res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1612 				     (sign | maybebase) + (base == 16));
1613 
1614   return res;
1615 }
1616 
1617 /* Return the number of bytes that a format directive consisting of FLAGS,
1618    PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1619    would result for argument X under ideal conditions (i.e., if PREC
1620    weren't excessive).  MPFR 3.1 allocates large amounts of memory for
1621    values of PREC with large magnitude and can fail (see MPFR bug #21056).
1622    This function works around those problems.  */
1623 
1624 static unsigned HOST_WIDE_INT
1625 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1626 			char spec, char rndspec)
1627 {
1628   char fmtstr[40];
1629 
1630   HOST_WIDE_INT len = strlen (flags);
1631 
1632   fmtstr[0] = '%';
1633   memcpy (fmtstr + 1, flags, len);
1634   memcpy (fmtstr + 1 + len, ".*R", 3);
1635   fmtstr[len + 4] = rndspec;
1636   fmtstr[len + 5] = spec;
1637   fmtstr[len + 6] = '\0';
1638 
1639   spec = TOUPPER (spec);
1640   if (spec == 'E' || spec == 'F')
1641     {
1642       /* For %e, specify the precision explicitly since mpfr_sprintf
1643 	 does its own thing just to be different (see MPFR bug 21088).  */
1644       if (prec < 0)
1645 	prec = 6;
1646     }
1647   else
1648     {
1649       /* Avoid passing negative precisions with larger magnitude to MPFR
1650 	 to avoid exposing its bugs.  (A negative precision is supposed
1651 	 to be ignored.)  */
1652       if (prec < 0)
1653 	prec = -1;
1654     }
1655 
1656   HOST_WIDE_INT p = prec;
1657 
1658   if (spec == 'G' && !strchr (flags, '#'))
1659     {
1660       /* For G/g without the pound flag, precision gives the maximum number
1661 	 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1662 	 a 128 bit IEEE extended precision, 4932.  Using twice as much here
1663 	 should be more than sufficient for any real format.  */
1664       if ((IEEE_MAX_10_EXP * 2) < prec)
1665 	prec = IEEE_MAX_10_EXP * 2;
1666       p = prec;
1667     }
1668   else
1669     {
1670       /* Cap precision arbitrarily at 1KB and add the difference
1671 	 (if any) to the MPFR result.  */
1672       if (prec > 1024)
1673 	p = 1024;
1674     }
1675 
1676   len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1677 
1678   /* Handle the unlikely (impossible?) error by returning more than
1679      the maximum dictated by the function's return type.  */
1680   if (len < 0)
1681     return target_dir_max () + 1;
1682 
1683   /* Adjust the return value by the difference.  */
1684   if (p < prec)
1685     len += prec - p;
1686 
1687   return len;
1688 }
1689 
1690 /* Return the number of bytes to format using the format specifier
1691    SPEC and the precision PREC the largest value in the real floating
1692    TYPE.  */
1693 
1694 static unsigned HOST_WIDE_INT
1695 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1696 {
1697   machine_mode mode = TYPE_MODE (type);
1698 
1699   /* IBM Extended mode.  */
1700   if (MODE_COMPOSITE_P (mode))
1701     mode = DFmode;
1702 
1703   /* Get the real type format desription for the target.  */
1704   const real_format *rfmt = REAL_MODE_FORMAT (mode);
1705   REAL_VALUE_TYPE rv;
1706 
1707   real_maxval (&rv, 0, mode);
1708 
1709   /* Convert the GCC real value representation with the precision
1710      of the real type to the mpfr_t format with the GCC default
1711      round-to-nearest mode.  */
1712   mpfr_t x;
1713   mpfr_init2 (x, rfmt->p);
1714   mpfr_from_real (x, &rv, GMP_RNDN);
1715 
1716   /* Return a value one greater to account for the leading minus sign.  */
1717   unsigned HOST_WIDE_INT r
1718     = 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1719   mpfr_clear (x);
1720   return r;
1721 }
1722 
1723 /* Return a range representing the minimum and maximum number of bytes
1724    that the directive DIR will output for any argument.  PREC gives
1725    the adjusted precision range to account for negative precisions
1726    meaning the default 6.  This function is used when the directive
1727    argument or its value isn't known.  */
1728 
1729 static fmtresult
1730 format_floating (const directive &dir, const HOST_WIDE_INT prec[2])
1731 {
1732   tree type;
1733 
1734   switch (dir.modifier)
1735     {
1736     case FMT_LEN_l:
1737     case FMT_LEN_none:
1738       type = double_type_node;
1739       break;
1740 
1741     case FMT_LEN_L:
1742       type = long_double_type_node;
1743       break;
1744 
1745     case FMT_LEN_ll:
1746       type = long_double_type_node;
1747       break;
1748 
1749     default:
1750       return fmtresult ();
1751     }
1752 
1753   /* The minimum and maximum number of bytes produced by the directive.  */
1754   fmtresult res;
1755 
1756   /* The minimum output as determined by flags.  It's always at least 1.
1757      When plus or space are set the output is preceded by either a sign
1758      or a space.  */
1759   unsigned flagmin = (1 /* for the first digit */
1760 		      + (dir.get_flag ('+') | dir.get_flag (' ')));
1761 
1762   /* When the pound flag is set the decimal point is included in output
1763      regardless of precision.  Whether or not a decimal point is included
1764      otherwise depends on the specification and precision.  */
1765   bool radix = dir.get_flag ('#');
1766 
1767   switch (dir.specifier)
1768     {
1769     case 'A':
1770     case 'a':
1771       {
1772 	HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1773 	if (dir.prec[0] <= 0)
1774 	  minprec = 0;
1775 	else if (dir.prec[0] > 0)
1776 	  minprec = dir.prec[0] + !radix /* decimal point */;
1777 
1778 	res.range.min = (2 /* 0x */
1779 			 + flagmin
1780 			 + radix
1781 			 + minprec
1782 			 + 3 /* p+0 */);
1783 
1784 	res.range.max = format_floating_max (type, 'a', prec[1]);
1785 	res.range.likely = res.range.min;
1786 
1787 	/* The unlikely maximum accounts for the longest multibyte
1788 	   decimal point character.  */
1789 	res.range.unlikely = res.range.max;
1790 	if (dir.prec[1] > 0)
1791 	  res.range.unlikely += target_mb_len_max () - 1;
1792 
1793 	break;
1794       }
1795 
1796     case 'E':
1797     case 'e':
1798       {
1799 	/* Minimum output attributable to precision and, when it's
1800 	   non-zero, decimal point.  */
1801 	HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1802 
1803 	/* The minimum output is "[-+]1.234567e+00" regardless
1804 	   of the value of the actual argument.  */
1805 	res.range.min = (flagmin
1806 			 + radix
1807 			 + minprec
1808 			 + 2 /* e+ */ + 2);
1809 
1810 	res.range.max = format_floating_max (type, 'e', prec[1]);
1811 	res.range.likely = res.range.min;
1812 
1813 	/* The unlikely maximum accounts for the longest multibyte
1814 	   decimal point character.  */
1815 	if (dir.prec[0] != dir.prec[1]
1816 	    || dir.prec[0] == -1 || dir.prec[0] > 0)
1817 	  res.range.unlikely = res.range.max + target_mb_len_max () -1;
1818 	else
1819 	  res.range.unlikely = res.range.max;
1820 	break;
1821       }
1822 
1823     case 'F':
1824     case 'f':
1825       {
1826 	/* Minimum output attributable to precision and, when it's non-zero,
1827 	   decimal point.  */
1828 	HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1829 
1830 	/* The lower bound when precision isn't specified is 8 bytes
1831 	   ("1.23456" since precision is taken to be 6).  When precision
1832 	   is zero, the lower bound is 1 byte (e.g., "1").  Otherwise,
1833 	   when precision is greater than zero, then the lower bound
1834 	   is 2 plus precision (plus flags).  */
1835 	res.range.min = flagmin + radix + minprec;
1836 
1837 	/* Compute the upper bound for -TYPE_MAX.  */
1838 	res.range.max = format_floating_max (type, 'f', prec[1]);
1839 
1840 	/* The minimum output with unknown precision is a single byte
1841 	   (e.g., "0") but the more likely output is 3 bytes ("0.0").  */
1842 	if (dir.prec[0] < 0 && dir.prec[1] > 0)
1843 	  res.range.likely = 3;
1844 	else
1845 	  res.range.likely = res.range.min;
1846 
1847 	/* The unlikely maximum accounts for the longest multibyte
1848 	   decimal point character.  */
1849 	if (dir.prec[0] != dir.prec[1]
1850 	    || dir.prec[0] == -1 || dir.prec[0] > 0)
1851 	  res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1852 	break;
1853       }
1854 
1855     case 'G':
1856     case 'g':
1857       {
1858 	/* The %g output depends on precision and the exponent of
1859 	   the argument.  Since the value of the argument isn't known
1860 	   the lower bound on the range of bytes (not counting flags
1861 	   or width) is 1 plus radix (i.e., either "0" or "0." for
1862 	   "%g" and "%#g", respectively, with a zero argument).  */
1863 	res.range.min = flagmin + radix;
1864 
1865 	char spec = 'g';
1866 	HOST_WIDE_INT maxprec = dir.prec[1];
1867 	if (radix && maxprec)
1868 	  {
1869 	    /* When the pound flag (radix) is set, trailing zeros aren't
1870 	       trimmed and so the longest output is the same as for %e,
1871 	       except with precision minus 1 (as specified in C11).  */
1872 	    spec = 'e';
1873 	    if (maxprec > 0)
1874 	      --maxprec;
1875 	    else if (maxprec < 0)
1876 	      maxprec = 5;
1877 	  }
1878 	else
1879 	  maxprec = prec[1];
1880 
1881 	res.range.max = format_floating_max (type, spec, maxprec);
1882 
1883 	/* The likely output is either the maximum computed above
1884 	   minus 1 (assuming the maximum is positive) when precision
1885 	   is known (or unspecified), or the same minimum as for %e
1886 	   (which is computed for a non-negative argument).  Unlike
1887 	   for the other specifiers above the likely output isn't
1888 	   the minimum because for %g that's 1 which is unlikely.  */
1889 	if (dir.prec[1] < 0
1890 	    || (unsigned HOST_WIDE_INT)dir.prec[1] < target_int_max ())
1891 	  res.range.likely = res.range.max - 1;
1892 	else
1893 	  {
1894 	    HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1895 	    res.range.likely = (flagmin
1896 				+ radix
1897 				+ minprec
1898 				+ 2 /* e+ */ + 2);
1899 	  }
1900 
1901 	/* The unlikely maximum accounts for the longest multibyte
1902 	   decimal point character.  */
1903 	res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1904 	break;
1905       }
1906 
1907     default:
1908       return fmtresult ();
1909     }
1910 
1911   /* Bump up the byte counters if WIDTH is greater.  */
1912   res.adjust_for_width_or_precision (dir.width);
1913   return res;
1914 }
1915 
1916 /* Return a range representing the minimum and maximum number of bytes
1917    that the directive DIR will write on output for the floating argument
1918    ARG.  */
1919 
1920 static fmtresult
1921 format_floating (const directive &dir, tree arg, vr_values *)
1922 {
1923   HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
1924   tree type = (dir.modifier == FMT_LEN_L || dir.modifier == FMT_LEN_ll
1925 	       ? long_double_type_node : double_type_node);
1926 
1927   /* For an indeterminate precision the lower bound must be assumed
1928      to be zero.  */
1929   if (TOUPPER (dir.specifier) == 'A')
1930     {
1931       /* Get the number of fractional decimal digits needed to represent
1932 	 the argument without a loss of accuracy.  */
1933       unsigned fmtprec
1934 	= REAL_MODE_FORMAT (TYPE_MODE (type))->p;
1935 
1936       /* The precision of the IEEE 754 double format is 53.
1937 	 The precision of all other GCC binary double formats
1938 	 is 56 or less.  */
1939       unsigned maxprec = fmtprec <= 56 ? 13 : 15;
1940 
1941       /* For %a, leave the minimum precision unspecified to let
1942 	 MFPR trim trailing zeros (as it and many other systems
1943 	 including Glibc happen to do) and set the maximum
1944 	 precision to reflect what it would be with trailing zeros
1945 	 present (as Solaris and derived systems do).  */
1946       if (dir.prec[1] < 0)
1947 	{
1948 	  /* Both bounds are negative implies that precision has
1949 	     not been specified.  */
1950 	  prec[0] = maxprec;
1951 	  prec[1] = -1;
1952 	}
1953       else if (dir.prec[0] < 0)
1954 	{
1955 	  /* With a negative lower bound and a non-negative upper
1956 	     bound set the minimum precision to zero and the maximum
1957 	     to the greater of the maximum precision (i.e., with
1958 	     trailing zeros present) and the specified upper bound.  */
1959 	  prec[0] = 0;
1960 	  prec[1] = dir.prec[1] < maxprec ? maxprec : dir.prec[1];
1961 	}
1962     }
1963   else if (dir.prec[0] < 0)
1964     {
1965       if (dir.prec[1] < 0)
1966 	{
1967 	  /* A precision in a strictly negative range is ignored and
1968 	     the default of 6 is used instead.  */
1969 	  prec[0] = prec[1] = 6;
1970 	}
1971       else
1972 	{
1973 	  /* For a precision in a partly negative range, the lower bound
1974 	     must be assumed to be zero and the new upper bound is the
1975 	     greater of 6 (the default precision used when the specified
1976 	     precision is negative) and the upper bound of the specified
1977 	     range.  */
1978 	  prec[0] = 0;
1979 	  prec[1] = dir.prec[1] < 6 ? 6 : dir.prec[1];
1980 	}
1981     }
1982 
1983   if (!arg
1984       || TREE_CODE (arg) != REAL_CST
1985       || !useless_type_conversion_p (type, TREE_TYPE (arg)))
1986     return format_floating (dir, prec);
1987 
1988   /* The minimum and maximum number of bytes produced by the directive.  */
1989   fmtresult res;
1990 
1991   /* Get the real type format desription for the target.  */
1992   const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1993   const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1994 
1995   char fmtstr [40];
1996   char *pfmt = fmtstr;
1997 
1998   /* Append flags.  */
1999   for (const char *pf = "-+ #0"; *pf; ++pf)
2000     if (dir.get_flag (*pf))
2001       *pfmt++ = *pf;
2002 
2003   *pfmt = '\0';
2004 
2005   {
2006     /* Set up an array to easily iterate over.  */
2007     unsigned HOST_WIDE_INT* const minmax[] = {
2008       &res.range.min, &res.range.max
2009     };
2010 
2011     for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
2012       {
2013 	/* Convert the GCC real value representation with the precision
2014 	   of the real type to the mpfr_t format rounding down in the
2015 	   first iteration that computes the minimm and up in the second
2016 	   that computes the maximum.  This order is arbibtrary because
2017 	   rounding in either direction can result in longer output.  */
2018 	mpfr_t mpfrval;
2019 	mpfr_init2 (mpfrval, rfmt->p);
2020 	mpfr_from_real (mpfrval, rvp, i ? GMP_RNDU : GMP_RNDD);
2021 
2022 	/* Use the MPFR rounding specifier to round down in the first
2023 	   iteration and then up.  In most but not all cases this will
2024 	   result in the same number of bytes.  */
2025 	char rndspec = "DU"[i];
2026 
2027 	/* Format it and store the result in the corresponding member
2028 	   of the result struct.  */
2029 	*minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
2030 					     dir.specifier, rndspec);
2031 	mpfr_clear (mpfrval);
2032       }
2033   }
2034 
2035   /* Make sure the minimum is less than the maximum (MPFR rounding
2036      in the call to mpfr_snprintf can result in the reverse.  */
2037   if (res.range.max < res.range.min)
2038     {
2039       unsigned HOST_WIDE_INT tmp = res.range.min;
2040       res.range.min = res.range.max;
2041       res.range.max = tmp;
2042     }
2043 
2044   /* The range is known unless either width or precision is unknown.  */
2045   res.knownrange = dir.known_width_and_precision ();
2046 
2047   /* For the same floating point constant, unless width or precision
2048      is unknown, use the longer output as the likely maximum since
2049      with round to nearest either is equally likely.  Otheriwse, when
2050      precision is unknown, use the greater of the minimum and 3 as
2051      the likely output (for "0.0" since zero precision is unlikely).  */
2052   if (res.knownrange)
2053     res.range.likely = res.range.max;
2054   else if (res.range.min < 3
2055 	   && dir.prec[0] < 0
2056 	   && (unsigned HOST_WIDE_INT)dir.prec[1] == target_int_max ())
2057     res.range.likely = 3;
2058   else
2059     res.range.likely = res.range.min;
2060 
2061   res.range.unlikely = res.range.max;
2062 
2063   if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
2064     {
2065       /* Unless the precision is zero output longer than 2 bytes may
2066 	 include the decimal point which must be a single character
2067 	 up to MB_LEN_MAX in length.  This is overly conservative
2068 	 since in some conversions some constants result in no decimal
2069 	 point (e.g., in %g).  */
2070       res.range.unlikely += target_mb_len_max () - 1;
2071     }
2072 
2073   res.adjust_for_width_or_precision (dir.width);
2074   return res;
2075 }
2076 
2077 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
2078    strings referenced by the expression STR, or (-1, -1) when not known.
2079    Used by the format_string function below.  */
2080 
2081 static fmtresult
2082 get_string_length (tree str)
2083 {
2084   if (!str)
2085     return fmtresult ();
2086 
2087   if (tree slen = c_strlen (str, 1))
2088     {
2089       /* Simply return the length of the string.  */
2090       fmtresult res (tree_to_shwi (slen));
2091       return res;
2092     }
2093 
2094   /* Determine the length of the shortest and longest string referenced
2095      by STR.  Strings of unknown lengths are bounded by the sizes of
2096      arrays that subexpressions of STR may refer to.  Pointers that
2097      aren't known to point any such arrays result in LENRANGE[1] set
2098      to SIZE_MAX.  */
2099   tree lenrange[2];
2100   bool flexarray = get_range_strlen (str, lenrange);
2101 
2102   if (lenrange [0] || lenrange [1])
2103     {
2104       HOST_WIDE_INT min
2105 	= (tree_fits_uhwi_p (lenrange[0])
2106 	   ? tree_to_uhwi (lenrange[0])
2107 	   : 0);
2108 
2109       HOST_WIDE_INT max
2110 	= (tree_fits_uhwi_p (lenrange[1])
2111 	   ? tree_to_uhwi (lenrange[1])
2112 	   : HOST_WIDE_INT_M1U);
2113 
2114       /* get_range_strlen() returns the target value of SIZE_MAX for
2115 	 strings of unknown length.  Bump it up to HOST_WIDE_INT_M1U
2116 	 which may be bigger.  */
2117       if ((unsigned HOST_WIDE_INT)min == target_size_max ())
2118 	min = HOST_WIDE_INT_M1U;
2119       if ((unsigned HOST_WIDE_INT)max == target_size_max ())
2120 	max = HOST_WIDE_INT_M1U;
2121 
2122       fmtresult res (min, max);
2123 
2124       /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2125 	 by STR are known to be bounded (though not necessarily by their
2126 	 actual length but perhaps by their maximum possible length).  */
2127       if (res.range.max < target_int_max ())
2128 	{
2129 	  res.knownrange = true;
2130 	  /* When the the length of the longest string is known and not
2131 	     excessive use it as the likely length of the string(s).  */
2132 	  res.range.likely = res.range.max;
2133 	}
2134       else
2135 	{
2136 	  /* When the upper bound is unknown (it can be zero or excessive)
2137 	     set the likely length to the greater of 1 and the length of
2138 	     the shortest string and reset the lower bound to zero.  */
2139 	  res.range.likely = res.range.min ? res.range.min : warn_level > 1;
2140 	  res.range.min = 0;
2141 	}
2142 
2143       /* If the range of string length has been estimated from the size
2144 	 of an array at the end of a struct assume that it's longer than
2145 	 the array bound says it is in case it's used as a poor man's
2146 	 flexible array member, such as in struct S { char a[4]; };  */
2147       res.range.unlikely = flexarray ? HOST_WIDE_INT_MAX : res.range.max;
2148 
2149       return res;
2150     }
2151 
2152   return get_string_length (NULL_TREE);
2153 }
2154 
2155 /* Return the minimum and maximum number of characters formatted
2156    by the '%c' format directives and its wide character form for
2157    the argument ARG.  ARG can be null (for functions such as
2158    vsprinf).  */
2159 
2160 static fmtresult
2161 format_character (const directive &dir, tree arg, vr_values *vr_values)
2162 {
2163   fmtresult res;
2164 
2165   res.knownrange = true;
2166 
2167   if (dir.modifier == FMT_LEN_l)
2168     {
2169       /* A wide character can result in as few as zero bytes.  */
2170       res.range.min = 0;
2171 
2172       HOST_WIDE_INT min, max;
2173       if (get_int_range (arg, &min, &max, false, 0, vr_values))
2174 	{
2175 	  if (min == 0 && max == 0)
2176 	    {
2177 	      /* The NUL wide character results in no bytes.  */
2178 	      res.range.max = 0;
2179 	      res.range.likely = 0;
2180 	      res.range.unlikely = 0;
2181 	    }
2182 	  else if (min > 0 && min < 128)
2183 	    {
2184 	      /* A wide character in the ASCII range most likely results
2185 		 in a single byte, and only unlikely in up to MB_LEN_MAX.  */
2186 	      res.range.max = 1;
2187 	      res.range.likely = 1;
2188 	      res.range.unlikely = target_mb_len_max ();
2189 	    }
2190 	  else
2191 	    {
2192 	      /* A wide character outside the ASCII range likely results
2193 		 in up to two bytes, and only unlikely in up to MB_LEN_MAX.  */
2194 	      res.range.max = target_mb_len_max ();
2195 	      res.range.likely = 2;
2196 	      res.range.unlikely = res.range.max;
2197 	    }
2198 	}
2199       else
2200 	{
2201 	  /* An unknown wide character is treated the same as a wide
2202 	     character outside the ASCII range.  */
2203 	  res.range.max = target_mb_len_max ();
2204 	  res.range.likely = 2;
2205 	  res.range.unlikely = res.range.max;
2206 	}
2207     }
2208   else
2209     {
2210       /* A plain '%c' directive.  Its ouput is exactly 1.  */
2211       res.range.min = res.range.max = 1;
2212       res.range.likely = res.range.unlikely = 1;
2213       res.knownrange = true;
2214     }
2215 
2216   /* Bump up the byte counters if WIDTH is greater.  */
2217   return res.adjust_for_width_or_precision (dir.width);
2218 }
2219 
2220 /* Return the minimum and maximum number of characters formatted
2221    by the '%s' format directive and its wide character form for
2222    the argument ARG.  ARG can be null (for functions such as
2223    vsprinf).  */
2224 
2225 static fmtresult
2226 format_string (const directive &dir, tree arg, vr_values *)
2227 {
2228   fmtresult res;
2229 
2230   /* Compute the range the argument's length can be in.  */
2231   fmtresult slen = get_string_length (arg);
2232   if (slen.range.min == slen.range.max
2233       && slen.range.min < HOST_WIDE_INT_MAX)
2234     {
2235       /* The argument is either a string constant or it refers
2236 	 to one of a number of strings of the same length.  */
2237 
2238       /* A '%s' directive with a string argument with constant length.  */
2239       res.range = slen.range;
2240 
2241       if (dir.modifier == FMT_LEN_l)
2242 	{
2243 	  /* In the worst case the length of output of a wide string S
2244 	     is bounded by MB_LEN_MAX * wcslen (S).  */
2245 	  res.range.max *= target_mb_len_max ();
2246 	  res.range.unlikely = res.range.max;
2247 	  /* It's likely that the the total length is not more that
2248 	     2 * wcslen (S).*/
2249 	  res.range.likely = res.range.min * 2;
2250 
2251 	  if (dir.prec[1] >= 0
2252 	      && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2253 	    {
2254 	      res.range.max = dir.prec[1];
2255 	      res.range.likely = dir.prec[1];
2256 	      res.range.unlikely = dir.prec[1];
2257 	    }
2258 
2259 	  if (dir.prec[0] < 0 && dir.prec[1] > -1)
2260 	    res.range.min = 0;
2261 	  else if (dir.prec[0] >= 0)
2262 	    res.range.likely = dir.prec[0];
2263 
2264 	  /* Even a non-empty wide character string need not convert into
2265 	     any bytes.  */
2266 	  res.range.min = 0;
2267 	}
2268       else
2269 	{
2270 	  res.knownrange = true;
2271 
2272 	  if (dir.prec[0] < 0 && dir.prec[1] > -1)
2273 	    res.range.min = 0;
2274 	  else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
2275 	    res.range.min = dir.prec[0];
2276 
2277 	  if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2278 	    {
2279 	      res.range.max = dir.prec[1];
2280 	      res.range.likely = dir.prec[1];
2281 	      res.range.unlikely = dir.prec[1];
2282 	    }
2283 	}
2284     }
2285   else if (arg && integer_zerop (arg))
2286     {
2287       /* Handle null pointer argument.  */
2288 
2289       fmtresult res (0);
2290       res.nullp = true;
2291       return res;
2292     }
2293   else
2294     {
2295       /* For a '%s' and '%ls' directive with a non-constant string (either
2296 	 one of a number of strings of known length or an unknown string)
2297 	 the minimum number of characters is lesser of PRECISION[0] and
2298 	 the length of the shortest known string or zero, and the maximum
2299 	 is the lessser of the length of the longest known string or
2300 	 PTRDIFF_MAX and PRECISION[1].  The likely length is either
2301 	 the minimum at level 1 and the greater of the minimum and 1
2302 	 at level 2.  This result is adjust upward for width (if it's
2303 	 specified).  */
2304 
2305       if (dir.modifier == FMT_LEN_l)
2306 	{
2307 	  /* A wide character converts to as few as zero bytes.  */
2308 	  slen.range.min = 0;
2309 	  if (slen.range.max < target_int_max ())
2310 	    slen.range.max *= target_mb_len_max ();
2311 
2312 	  if (slen.range.likely < target_int_max ())
2313 	    slen.range.likely *= 2;
2314 
2315 	  if (slen.range.likely < target_int_max ())
2316 	    slen.range.unlikely *= target_mb_len_max ();
2317 	}
2318 
2319       res.range = slen.range;
2320 
2321       if (dir.prec[0] >= 0)
2322 	{
2323 	  /* Adjust the minimum to zero if the string length is unknown,
2324 	     or at most the lower bound of the precision otherwise.  */
2325 	  if (slen.range.min >= target_int_max ())
2326 	    res.range.min = 0;
2327 	  else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2328 	    res.range.min = dir.prec[0];
2329 
2330 	  /* Make both maxima no greater than the upper bound of precision.  */
2331 	  if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2332 	      || slen.range.max >= target_int_max ())
2333 	    {
2334 	      res.range.max = dir.prec[1];
2335 	      res.range.unlikely = dir.prec[1];
2336 	    }
2337 
2338 	  /* If precision is constant, set the likely counter to the lesser
2339 	     of it and the maximum string length.  Otherwise, if the lower
2340 	     bound of precision is greater than zero, set the likely counter
2341 	     to the minimum.  Otherwise set it to zero or one based on
2342 	     the warning level.  */
2343 	  if (dir.prec[0] == dir.prec[1])
2344 	    res.range.likely
2345 	      = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
2346 		 ? dir.prec[0] : slen.range.max);
2347 	  else if (dir.prec[0] > 0)
2348 	    res.range.likely = res.range.min;
2349 	  else
2350 	    res.range.likely = warn_level > 1;
2351 	}
2352       else if (dir.prec[1] >= 0)
2353 	{
2354 	  res.range.min = 0;
2355 	  if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
2356 	    res.range.max = dir.prec[1];
2357 	  res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
2358 	}
2359       else if (slen.range.min >= target_int_max ())
2360 	{
2361 	  res.range.min = 0;
2362 	  res.range.max = HOST_WIDE_INT_MAX;
2363 	  /* At level 1 strings of unknown length are assumed to be
2364 	     empty, while at level 1 they are assumed to be one byte
2365 	     long.  */
2366 	  res.range.likely = warn_level > 1;
2367 	}
2368       else
2369 	{
2370 	  /* A string of unknown length unconstrained by precision is
2371 	     assumed to be empty at level 1 and just one character long
2372 	     at higher levels.  */
2373 	  if (res.range.likely >= target_int_max ())
2374 	    res.range.likely = warn_level > 1;
2375 	}
2376 
2377       res.range.unlikely = res.range.max;
2378     }
2379 
2380   /* Bump up the byte counters if WIDTH is greater.  */
2381   return res.adjust_for_width_or_precision (dir.width);
2382 }
2383 
2384 /* Format plain string (part of the format string itself).  */
2385 
2386 static fmtresult
2387 format_plain (const directive &dir, tree, vr_values *)
2388 {
2389   fmtresult res (dir.len);
2390   return res;
2391 }
2392 
2393 /* Return true if the RESULT of a directive in a call describe by INFO
2394    should be diagnosed given the AVAILable space in the destination.  */
2395 
2396 static bool
2397 should_warn_p (const sprintf_dom_walker::call_info &info,
2398 	       const result_range &avail, const result_range &result)
2399 {
2400   if (result.max <= avail.min)
2401     {
2402       /* The least amount of space remaining in the destination is big
2403 	 enough for the longest output.  */
2404       return false;
2405     }
2406 
2407   if (info.bounded)
2408     {
2409       if (warn_format_trunc == 1 && result.min <= avail.max
2410 	  && info.retval_used ())
2411 	{
2412 	  /* The likely amount of space remaining in the destination is big
2413 	     enough for the least output and the return value is used.  */
2414 	  return false;
2415 	}
2416 
2417       if (warn_format_trunc == 1 && result.likely <= avail.likely
2418 	  && !info.retval_used ())
2419 	{
2420 	  /* The likely amount of space remaining in the destination is big
2421 	     enough for the likely output and the return value is unused.  */
2422 	  return false;
2423 	}
2424 
2425       if (warn_format_trunc == 2
2426 	  && result.likely <= avail.min
2427 	  && (result.max <= avail.min
2428 	      || result.max > HOST_WIDE_INT_MAX))
2429 	{
2430 	  /* The minimum amount of space remaining in the destination is big
2431 	     enough for the longest output.  */
2432 	  return false;
2433 	}
2434     }
2435   else
2436     {
2437       if (warn_level == 1 && result.likely <= avail.likely)
2438 	{
2439 	  /* The likely amount of space remaining in the destination is big
2440 	     enough for the likely output.  */
2441 	  return false;
2442 	}
2443 
2444       if (warn_level == 2
2445 	  && result.likely <= avail.min
2446 	  && (result.max <= avail.min
2447 	      || result.max > HOST_WIDE_INT_MAX))
2448 	{
2449 	  /* The minimum amount of space remaining in the destination is big
2450 	     enough for the longest output.  */
2451 	  return false;
2452 	}
2453     }
2454 
2455   return true;
2456 }
2457 
2458 /* At format string location describe by DIRLOC in a call described
2459    by INFO, issue a warning for a directive DIR whose output may be
2460    in excess of the available space AVAIL_RANGE in the destination
2461    given the formatting result FMTRES.  This function does nothing
2462    except decide whether to issue a warning for a possible write
2463    past the end or truncation and, if so, format the warning.
2464    Return true if a warning has been issued.  */
2465 
2466 static bool
2467 maybe_warn (substring_loc &dirloc, location_t argloc,
2468 	    const sprintf_dom_walker::call_info &info,
2469 	    const result_range &avail_range, const result_range &res,
2470 	    const directive &dir)
2471 {
2472   if (!should_warn_p (info, avail_range, res))
2473     return false;
2474 
2475   /* A warning will definitely be issued below.  */
2476 
2477   /* The maximum byte count to reference in the warning.  Larger counts
2478      imply that the upper bound is unknown (and could be anywhere between
2479      RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2480      than "between N and X" where X is some huge number.  */
2481   unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2482 
2483   /* True when there is enough room in the destination for the least
2484      amount of a directive's output but not enough for its likely or
2485      maximum output.  */
2486   bool maybe = (res.min <= avail_range.max
2487 		&& (avail_range.min < res.likely
2488 		    || (res.max < HOST_WIDE_INT_MAX
2489 			&& avail_range.min < res.max)));
2490 
2491   /* Buffer for the directive in the host character set (used when
2492      the source character set is different).  */
2493   char hostdir[32];
2494 
2495   if (avail_range.min == avail_range.max)
2496     {
2497       /* The size of the destination region is exact.  */
2498       unsigned HOST_WIDE_INT navail = avail_range.max;
2499 
2500       if (target_to_host (*dir.beg) != '%')
2501 	{
2502 	  /* For plain character directives (i.e., the format string itself)
2503 	     but not others, point the caret at the first character that's
2504 	     past the end of the destination.  */
2505 	  if (navail < dir.len)
2506 	    dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2507 	}
2508 
2509       if (*dir.beg == '\0')
2510 	{
2511 	  /* This is the terminating nul.  */
2512 	  gcc_assert (res.min == 1 && res.min == res.max);
2513 
2514 	  return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2515 			  info.bounded
2516 			  ? (maybe
2517 			     ? G_("%qE output may be truncated before the "
2518 				  "last format character")
2519 			     : G_("%qE output truncated before the last "
2520 				  "format character"))
2521 			  : (maybe
2522 			     ? G_("%qE may write a terminating nul past the "
2523 				  "end of the destination")
2524 			     : G_("%qE writing a terminating nul past the "
2525 				  "end of the destination")),
2526 			  info.func);
2527 	}
2528 
2529       if (res.min == res.max)
2530 	{
2531 	  const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2532 	  if (!info.bounded)
2533 	    return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2534 			      "%<%.*s%> directive writing %wu byte into a "
2535 			      "region of size %wu",
2536 			      "%<%.*s%> directive writing %wu bytes into a "
2537 			      "region of size %wu",
2538 			      (int) dir.len, d, res.min, navail);
2539 	  else if (maybe)
2540 	    return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2541 			      "%<%.*s%> directive output may be truncated "
2542 			      "writing %wu byte into a region of size %wu",
2543 			      "%<%.*s%> directive output may be truncated "
2544 			      "writing %wu bytes into a region of size %wu",
2545 			      (int) dir.len, d, res.min, navail);
2546 	  else
2547 	    return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2548 			      "%<%.*s%> directive output truncated writing "
2549 			      "%wu byte into a region of size %wu",
2550 			      "%<%.*s%> directive output truncated writing "
2551 			      "%wu bytes into a region of size %wu",
2552 			      (int) dir.len, d, res.min, navail);
2553 	}
2554       if (res.min == 0 && res.max < maxbytes)
2555 	return fmtwarn (dirloc, argloc, NULL,
2556 			info.warnopt (),
2557 			info.bounded
2558 			? (maybe
2559 			   ? G_("%<%.*s%> directive output may be truncated "
2560 				"writing up to %wu bytes into a region of "
2561 				"size %wu")
2562 			   : G_("%<%.*s%> directive output truncated writing "
2563 				"up to %wu bytes into a region of size %wu"))
2564 			: G_("%<%.*s%> directive writing up to %wu bytes "
2565 			     "into a region of size %wu"), (int) dir.len,
2566 			target_to_host (hostdir, sizeof hostdir, dir.beg),
2567 			res.max, navail);
2568 
2569       if (res.min == 0 && maxbytes <= res.max)
2570 	/* This is a special case to avoid issuing the potentially
2571 	   confusing warning:
2572 	     writing 0 or more bytes into a region of size 0.  */
2573 	return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2574 			info.bounded
2575 			? (maybe
2576 			   ? G_("%<%.*s%> directive output may be truncated "
2577 				"writing likely %wu or more bytes into a "
2578 				"region of size %wu")
2579 			   : G_("%<%.*s%> directive output truncated writing "
2580 				"likely %wu or more bytes into a region of "
2581 				"size %wu"))
2582 			: G_("%<%.*s%> directive writing likely %wu or more "
2583 			     "bytes into a region of size %wu"), (int) dir.len,
2584 			target_to_host (hostdir, sizeof hostdir, dir.beg),
2585 			res.likely, navail);
2586 
2587       if (res.max < maxbytes)
2588 	return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2589 			info.bounded
2590 			? (maybe
2591 			   ? G_("%<%.*s%> directive output may be truncated "
2592 				"writing between %wu and %wu bytes into a "
2593 				"region of size %wu")
2594 			   : G_("%<%.*s%> directive output truncated "
2595 				"writing between %wu and %wu bytes into a "
2596 				"region of size %wu"))
2597 			: G_("%<%.*s%> directive writing between %wu and "
2598 			     "%wu bytes into a region of size %wu"),
2599 			(int) dir.len,
2600 			target_to_host (hostdir, sizeof hostdir, dir.beg),
2601 			res.min, res.max, navail);
2602 
2603       return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2604 		      info.bounded
2605 		      ? (maybe
2606 			 ? G_("%<%.*s%> directive output may be truncated "
2607 			      "writing %wu or more bytes into a region of "
2608 			      "size %wu")
2609 			 : G_("%<%.*s%> directive output truncated writing "
2610 			      "%wu or more bytes into a region of size %wu"))
2611 		      : G_("%<%.*s%> directive writing %wu or more bytes "
2612 			   "into a region of size %wu"), (int) dir.len,
2613 		      target_to_host (hostdir, sizeof hostdir, dir.beg),
2614 		      res.min, navail);
2615     }
2616 
2617   /* The size of the destination region is a range.  */
2618 
2619   if (target_to_host (*dir.beg) != '%')
2620     {
2621       unsigned HOST_WIDE_INT navail = avail_range.max;
2622 
2623       /* For plain character directives (i.e., the format string itself)
2624 	 but not others, point the caret at the first character that's
2625 	 past the end of the destination.  */
2626       if (navail < dir.len)
2627 	dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2628     }
2629 
2630   if (*dir.beg == '\0')
2631     {
2632       gcc_assert (res.min == 1 && res.min == res.max);
2633 
2634       return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2635 		      info.bounded
2636 		      ? (maybe
2637 			 ? G_("%qE output may be truncated before the last "
2638 			      "format character")
2639 			 : G_("%qE output truncated before the last format "
2640 			      "character"))
2641 		      : (maybe
2642 			 ? G_("%qE may write a terminating nul past the end "
2643 			      "of the destination")
2644 			 : G_("%qE writing a terminating nul past the end "
2645 			      "of the destination")), info.func);
2646     }
2647 
2648   if (res.min == res.max)
2649     {
2650       const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2651       if (!info.bounded)
2652 	return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2653 			  "%<%.*s%> directive writing %wu byte into a region "
2654 			  "of size between %wu and %wu",
2655 			  "%<%.*s%> directive writing %wu bytes into a region "
2656 			  "of size between %wu and %wu", (int) dir.len, d,
2657 			  res.min, avail_range.min, avail_range.max);
2658       else if (maybe)
2659 	return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2660 			  "%<%.*s%> directive output may be truncated writing "
2661 			  "%wu byte into a region of size between %wu and %wu",
2662 			  "%<%.*s%> directive output may be truncated writing "
2663 			  "%wu bytes into a region of size between %wu and "
2664 			  "%wu", (int) dir.len, d, res.min, avail_range.min,
2665 			  avail_range.max);
2666       else
2667 	return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2668 			  "%<%.*s%> directive output truncated writing %wu "
2669 			  "byte into a region of size between %wu and %wu",
2670 			  "%<%.*s%> directive output truncated writing %wu "
2671 			  "bytes into a region of size between %wu and %wu",
2672 			  (int) dir.len, d, res.min, avail_range.min,
2673 			  avail_range.max);
2674     }
2675 
2676   if (res.min == 0 && res.max < maxbytes)
2677     return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2678 		    info.bounded
2679 		    ? (maybe
2680 		       ? G_("%<%.*s%> directive output may be truncated "
2681 			    "writing up to %wu bytes into a region of size "
2682 			    "between %wu and %wu")
2683 		       : G_("%<%.*s%> directive output truncated writing "
2684 			    "up to %wu bytes into a region of size between "
2685 			    "%wu and %wu"))
2686 		    : G_("%<%.*s%> directive writing up to %wu bytes "
2687 			 "into a region of size between %wu and %wu"),
2688 		    (int) dir.len,
2689 		    target_to_host (hostdir, sizeof hostdir, dir.beg),
2690 		    res.max, avail_range.min, avail_range.max);
2691 
2692   if (res.min == 0 && maxbytes <= res.max)
2693     /* This is a special case to avoid issuing the potentially confusing
2694        warning:
2695 	 writing 0 or more bytes into a region of size between 0 and N.  */
2696     return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2697 		    info.bounded
2698 		    ? (maybe
2699 		       ? G_("%<%.*s%> directive output may be truncated "
2700 			    "writing likely %wu or more bytes into a region "
2701 			    "of size between %wu and %wu")
2702 		       : G_("%<%.*s%> directive output truncated writing "
2703 			    "likely %wu or more bytes into a region of size "
2704 			    "between %wu and %wu"))
2705 		    : G_("%<%.*s%> directive writing likely %wu or more bytes "
2706 			 "into a region of size between %wu and %wu"),
2707 		    (int) dir.len,
2708 		    target_to_host (hostdir, sizeof hostdir, dir.beg),
2709 		    res.likely, avail_range.min, avail_range.max);
2710 
2711   if (res.max < maxbytes)
2712     return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2713 		    info.bounded
2714 		    ? (maybe
2715 		       ? G_("%<%.*s%> directive output may be truncated "
2716 			    "writing between %wu and %wu bytes into a region "
2717 			    "of size between %wu and %wu")
2718 		       : G_("%<%.*s%> directive output truncated writing "
2719 			    "between %wu and %wu bytes into a region of size "
2720 			    "between %wu and %wu"))
2721 		    : G_("%<%.*s%> directive writing between %wu and "
2722 			 "%wu bytes into a region of size between %wu and "
2723 			 "%wu"), (int) dir.len,
2724 		    target_to_host (hostdir, sizeof hostdir, dir.beg),
2725 		    res.min, res.max, avail_range.min, avail_range.max);
2726 
2727   return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2728 		  info.bounded
2729 		  ? (maybe
2730 		     ? G_("%<%.*s%> directive output may be truncated writing "
2731 			  "%wu or more bytes into a region of size between "
2732 			  "%wu and %wu")
2733 		     : G_("%<%.*s%> directive output truncated writing "
2734 			  "%wu or more bytes into a region of size between "
2735 			  "%wu and %wu"))
2736 		  : G_("%<%.*s%> directive writing %wu or more bytes "
2737 		       "into a region of size between %wu and %wu"),
2738 		  (int) dir.len,
2739 		  target_to_host (hostdir, sizeof hostdir, dir.beg),
2740 		  res.min, avail_range.min, avail_range.max);
2741 }
2742 
2743 /* Compute the length of the output resulting from the directive DIR
2744    in a call described by INFO and update the overall result of the call
2745    in *RES.  Return true if the directive has been handled.  */
2746 
2747 static bool
2748 format_directive (const sprintf_dom_walker::call_info &info,
2749 		  format_result *res, const directive &dir,
2750 		  class vr_values *vr_values)
2751 {
2752   /* Offset of the beginning of the directive from the beginning
2753      of the format string.  */
2754   size_t offset = dir.beg - info.fmtstr;
2755   size_t start = offset;
2756   size_t length = offset + dir.len - !!dir.len;
2757 
2758   /* Create a location for the whole directive from the % to the format
2759      specifier.  */
2760   substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2761 			offset, start, length);
2762 
2763   /* Also get the location of the argument if possible.
2764      This doesn't work for integer literals or function calls.  */
2765   location_t argloc = UNKNOWN_LOCATION;
2766   if (dir.arg)
2767     argloc = EXPR_LOCATION (dir.arg);
2768 
2769   /* Bail when there is no function to compute the output length,
2770      or when minimum length checking has been disabled.   */
2771   if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2772     return false;
2773 
2774   /* Compute the range of lengths of the formatted output.  */
2775   fmtresult fmtres = dir.fmtfunc (dir, dir.arg, vr_values);
2776 
2777   /* Record whether the output of all directives is known to be
2778      bounded by some maximum, implying that their arguments are
2779      either known exactly or determined to be in a known range
2780      or, for strings, limited by the upper bounds of the arrays
2781      they refer to.  */
2782   res->knownrange &= fmtres.knownrange;
2783 
2784   if (!fmtres.knownrange)
2785     {
2786       /* Only when the range is known, check it against the host value
2787 	 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2788 	 INT_MAX precision, which is the longest possible output of any
2789 	 single directive).  That's the largest valid byte count (though
2790 	 not valid call to a printf-like function because it can never
2791 	 return such a count).  Otherwise, the range doesn't correspond
2792 	 to known values of the argument.  */
2793       if (fmtres.range.max > target_dir_max ())
2794 	{
2795 	  /* Normalize the MAX counter to avoid having to deal with it
2796 	     later.  The counter can be less than HOST_WIDE_INT_M1U
2797 	     when compiling for an ILP32 target on an LP64 host.  */
2798 	  fmtres.range.max = HOST_WIDE_INT_M1U;
2799 	  /* Disable exact and maximum length checking after a failure
2800 	     to determine the maximum number of characters (for example
2801 	     for wide characters or wide character strings) but continue
2802 	     tracking the minimum number of characters.  */
2803 	  res->range.max = HOST_WIDE_INT_M1U;
2804 	}
2805 
2806       if (fmtres.range.min > target_dir_max ())
2807 	{
2808 	  /* Disable exact length checking after a failure to determine
2809 	     even the minimum number of characters (it shouldn't happen
2810 	     except in an error) but keep tracking the minimum and maximum
2811 	     number of characters.  */
2812 	  return true;
2813 	}
2814     }
2815 
2816   /* Buffer for the directive in the host character set (used when
2817      the source character set is different).  */
2818   char hostdir[32];
2819 
2820   int dirlen = dir.len;
2821 
2822   if (fmtres.nullp)
2823     {
2824       fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2825 	       "%<%.*s%> directive argument is null",
2826 	       dirlen, target_to_host (hostdir, sizeof hostdir, dir.beg));
2827 
2828       /* Don't bother processing the rest of the format string.  */
2829       res->warned = true;
2830       res->range.min = HOST_WIDE_INT_M1U;
2831       res->range.max = HOST_WIDE_INT_M1U;
2832       return false;
2833     }
2834 
2835   /* Compute the number of available bytes in the destination.  There
2836      must always be at least one byte of space for the terminating
2837      NUL that's appended after the format string has been processed.  */
2838   result_range avail_range = bytes_remaining (info.objsize, *res);
2839 
2840   bool warned = res->warned;
2841 
2842   if (!warned)
2843     warned = maybe_warn (dirloc, argloc, info, avail_range,
2844 			 fmtres.range, dir);
2845 
2846   /* Bump up the total maximum if it isn't too big.  */
2847   if (res->range.max < HOST_WIDE_INT_MAX
2848       && fmtres.range.max < HOST_WIDE_INT_MAX)
2849     res->range.max += fmtres.range.max;
2850 
2851   /* Raise the total unlikely maximum by the larger of the maximum
2852      and the unlikely maximum.  */
2853   unsigned HOST_WIDE_INT save = res->range.unlikely;
2854   if (fmtres.range.max < fmtres.range.unlikely)
2855     res->range.unlikely += fmtres.range.unlikely;
2856   else
2857     res->range.unlikely += fmtres.range.max;
2858 
2859   if (res->range.unlikely < save)
2860     res->range.unlikely = HOST_WIDE_INT_M1U;
2861 
2862   res->range.min += fmtres.range.min;
2863   res->range.likely += fmtres.range.likely;
2864 
2865   /* Has the minimum directive output length exceeded the maximum
2866      of 4095 bytes required to be supported?  */
2867   bool minunder4k = fmtres.range.min < 4096;
2868   bool maxunder4k = fmtres.range.max < 4096;
2869   /* Clear UNDER4K in the overall result if the maximum has exceeded
2870      the 4k (this is necessary to avoid the return valuye optimization
2871      that may not be safe in the maximum case).  */
2872   if (!maxunder4k)
2873     res->under4k = false;
2874 
2875   if (!warned
2876       /* Only warn at level 2.  */
2877       && warn_level > 1
2878       && (!minunder4k
2879 	  || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2880     {
2881       /* The directive output may be longer than the maximum required
2882 	 to be handled by an implementation according to 7.21.6.1, p15
2883 	 of C11.  Warn on this only at level 2 but remember this and
2884 	 prevent folding the return value when done.  This allows for
2885 	 the possibility of the actual libc call failing due to ENOMEM
2886 	 (like Glibc does under some conditions).  */
2887 
2888       if (fmtres.range.min == fmtres.range.max)
2889 	warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2890 			  "%<%.*s%> directive output of %wu bytes exceeds "
2891 			  "minimum required size of 4095", dirlen,
2892 			  target_to_host (hostdir, sizeof hostdir, dir.beg),
2893 			  fmtres.range.min);
2894       else
2895 	warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2896 			  minunder4k
2897 			  ? G_("%<%.*s%> directive output between %wu and %wu "
2898 			       "bytes may exceed minimum required size of "
2899 			       "4095")
2900 			  : G_("%<%.*s%> directive output between %wu and %wu "
2901 			       "bytes exceeds minimum required size of 4095"),
2902 			  dirlen,
2903 			  target_to_host (hostdir, sizeof hostdir, dir.beg),
2904 			  fmtres.range.min, fmtres.range.max);
2905     }
2906 
2907   /* Has the likely and maximum directive output exceeded INT_MAX?  */
2908   bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2909   /* Don't consider the maximum to be in excess when it's the result
2910      of a string of unknown length (i.e., whose maximum has been set
2911      to be greater than or equal to HOST_WIDE_INT_MAX.  */
2912   bool maxximax = (*dir.beg
2913 		   && res->range.max > target_int_max ()
2914 		   && res->range.max < HOST_WIDE_INT_MAX);
2915 
2916   if (!warned
2917       /* Warn for the likely output size at level 1.  */
2918       && (likelyximax
2919 	  /* But only warn for the maximum at level 2.  */
2920 	  || (warn_level > 1
2921 	      && maxximax
2922 	      && fmtres.range.max < HOST_WIDE_INT_MAX)))
2923     {
2924       /* The directive output causes the total length of output
2925 	 to exceed INT_MAX bytes.  */
2926 
2927       if (fmtres.range.min == fmtres.range.max)
2928 	warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2929 			  "%<%.*s%> directive output of %wu bytes causes "
2930 			  "result to exceed %<INT_MAX%>", dirlen,
2931 			  target_to_host (hostdir, sizeof hostdir, dir.beg),
2932 			  fmtres.range.min);
2933       else
2934 	warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2935 			  fmtres.range.min > target_int_max ()
2936 			  ? G_ ("%<%.*s%> directive output between %wu and "
2937 				"%wu bytes causes result to exceed "
2938 				"%<INT_MAX%>")
2939 			  : G_ ("%<%.*s%> directive output between %wu and "
2940 				"%wu bytes may cause result to exceed "
2941 				"%<INT_MAX%>"), dirlen,
2942 			  target_to_host (hostdir, sizeof hostdir, dir.beg),
2943 			  fmtres.range.min, fmtres.range.max);
2944     }
2945 
2946   if (warned && fmtres.range.min < fmtres.range.likely
2947       && fmtres.range.likely < fmtres.range.max)
2948     inform_n (info.fmtloc, fmtres.range.likely,
2949 	      "assuming directive output of %wu byte",
2950 	      "assuming directive output of %wu bytes",
2951 	      fmtres.range.likely);
2952 
2953   if (warned && fmtres.argmin)
2954     {
2955       if (fmtres.argmin == fmtres.argmax)
2956 	inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2957       else if (fmtres.knownrange)
2958 	inform (info.fmtloc, "directive argument in the range [%E, %E]",
2959 		fmtres.argmin, fmtres.argmax);
2960       else
2961 	inform (info.fmtloc,
2962 		"using the range [%E, %E] for directive argument",
2963 		fmtres.argmin, fmtres.argmax);
2964     }
2965 
2966   res->warned |= warned;
2967 
2968   if (!dir.beg[0] && res->warned && info.objsize < HOST_WIDE_INT_MAX)
2969     {
2970       /* If a warning has been issued for buffer overflow or truncation
2971 	 (but not otherwise) help the user figure out how big a buffer
2972 	 they need.  */
2973 
2974       location_t callloc = gimple_location (info.callstmt);
2975 
2976       unsigned HOST_WIDE_INT min = res->range.min;
2977       unsigned HOST_WIDE_INT max = res->range.max;
2978 
2979       if (min == max)
2980 	inform (callloc,
2981 		(min == 1
2982 		 ? G_("%qE output %wu byte into a destination of size %wu")
2983 		 : G_("%qE output %wu bytes into a destination of size %wu")),
2984 		info.func, min, info.objsize);
2985       else if (max < HOST_WIDE_INT_MAX)
2986 	inform (callloc,
2987 		"%qE output between %wu and %wu bytes into "
2988 		"a destination of size %wu",
2989 		info.func, min, max, info.objsize);
2990       else if (min < res->range.likely && res->range.likely < max)
2991 	inform (callloc,
2992 		"%qE output %wu or more bytes (assuming %wu) into "
2993 		"a destination of size %wu",
2994 		info.func, min, res->range.likely, info.objsize);
2995       else
2996 	inform (callloc,
2997 		"%qE output %wu or more bytes into a destination of size %wu",
2998 		info.func, min, info.objsize);
2999     }
3000 
3001   if (dump_file && *dir.beg)
3002     {
3003       fprintf (dump_file,
3004 	       "    Result: "
3005 	       HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
3006 	       HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC " ("
3007 	       HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
3008 	       HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ")\n",
3009 	       fmtres.range.min, fmtres.range.likely,
3010 	       fmtres.range.max, fmtres.range.unlikely,
3011 	       res->range.min, res->range.likely,
3012 	       res->range.max, res->range.unlikely);
3013     }
3014 
3015   return true;
3016 }
3017 
3018 /* Parse a format directive in function call described by INFO starting
3019    at STR and populate DIR structure.  Bump up *ARGNO by the number of
3020    arguments extracted for the directive.  Return the length of
3021    the directive.  */
3022 
3023 static size_t
3024 parse_directive (sprintf_dom_walker::call_info &info,
3025 		 directive &dir, format_result *res,
3026 		 const char *str, unsigned *argno,
3027 		 vr_values *vr_values)
3028 {
3029   const char *pcnt = strchr (str, target_percent);
3030   dir.beg = str;
3031 
3032   if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
3033     {
3034       /* This directive is either a plain string or the terminating nul
3035 	 (which isn't really a directive but it simplifies things to
3036 	 handle it as if it were).  */
3037       dir.len = len;
3038       dir.fmtfunc = format_plain;
3039 
3040       if (dump_file)
3041 	{
3042 	  fprintf (dump_file, "  Directive %u at offset "
3043 		   HOST_WIDE_INT_PRINT_UNSIGNED ": \"%.*s\", "
3044 		   "length = " HOST_WIDE_INT_PRINT_UNSIGNED "\n",
3045 		   dir.dirno,
3046 		   (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3047 		   (int)dir.len, dir.beg, (unsigned HOST_WIDE_INT) dir.len);
3048 	}
3049 
3050       return len - !*str;
3051     }
3052 
3053   const char *pf = pcnt + 1;
3054 
3055     /* POSIX numbered argument index or zero when none.  */
3056   HOST_WIDE_INT dollar = 0;
3057 
3058   /* With and precision.  -1 when not specified, HOST_WIDE_INT_MIN
3059      when given by a va_list argument, and a non-negative value
3060      when specified in the format string itself.  */
3061   HOST_WIDE_INT width = -1;
3062   HOST_WIDE_INT precision = -1;
3063 
3064   /* Pointers to the beginning of the width and precision decimal
3065      string (if any) within the directive.  */
3066   const char *pwidth = 0;
3067   const char *pprec = 0;
3068 
3069   /* When the value of the decimal string that specifies width or
3070      precision is out of range, points to the digit that causes
3071      the value to exceed the limit.  */
3072   const char *werange = NULL;
3073   const char *perange = NULL;
3074 
3075   /* Width specified via the asterisk.  Need not be INTEGER_CST.
3076      For vararg functions set to void_node.  */
3077   tree star_width = NULL_TREE;
3078 
3079   /* Width specified via the asterisk.  Need not be INTEGER_CST.
3080      For vararg functions set to void_node.  */
3081   tree star_precision = NULL_TREE;
3082 
3083   if (ISDIGIT (target_to_host (*pf)))
3084     {
3085       /* This could be either a POSIX positional argument, the '0'
3086 	 flag, or a width, depending on what follows.  Store it as
3087 	 width and sort it out later after the next character has
3088 	 been seen.  */
3089       pwidth = pf;
3090       width = target_strtol10 (&pf, &werange);
3091     }
3092   else if (target_to_host (*pf) == '*')
3093     {
3094       /* Similarly to the block above, this could be either a POSIX
3095 	 positional argument or a width, depending on what follows.  */
3096       if (*argno < gimple_call_num_args (info.callstmt))
3097 	star_width = gimple_call_arg (info.callstmt, (*argno)++);
3098       else
3099 	star_width = void_node;
3100       ++pf;
3101     }
3102 
3103   if (target_to_host (*pf) == '$')
3104     {
3105       /* Handle the POSIX dollar sign which references the 1-based
3106 	 positional argument number.  */
3107       if (width != -1)
3108 	dollar = width + info.argidx;
3109       else if (star_width
3110 	       && TREE_CODE (star_width) == INTEGER_CST
3111 	       && (TYPE_PRECISION (TREE_TYPE (star_width))
3112 		   <= TYPE_PRECISION (integer_type_node)))
3113 	dollar = width + tree_to_shwi (star_width);
3114 
3115       /* Bail when the numbered argument is out of range (it will
3116 	 have already been diagnosed by -Wformat).  */
3117       if (dollar == 0
3118 	  || dollar == (int)info.argidx
3119 	  || dollar > gimple_call_num_args (info.callstmt))
3120 	return false;
3121 
3122       --dollar;
3123 
3124       star_width = NULL_TREE;
3125       width = -1;
3126       ++pf;
3127     }
3128 
3129   if (dollar || !star_width)
3130     {
3131       if (width != -1)
3132 	{
3133 	  if (width == 0)
3134 	    {
3135 	      /* The '0' that has been interpreted as a width above is
3136 		 actually a flag.  Reset HAVE_WIDTH, set the '0' flag,
3137 		 and continue processing other flags.  */
3138 	      width = -1;
3139 	      dir.set_flag ('0');
3140 	    }
3141 	  else if (!dollar)
3142 	    {
3143 	      /* (Non-zero) width has been seen.  The next character
3144 		 is either a period or a digit.  */
3145 	      goto start_precision;
3146 	    }
3147 	}
3148       /* When either '$' has been seen, or width has not been seen,
3149 	 the next field is the optional flags followed by an optional
3150 	 width.  */
3151       for ( ; ; ) {
3152 	switch (target_to_host (*pf))
3153 	  {
3154 	  case ' ':
3155 	  case '0':
3156 	  case '+':
3157 	  case '-':
3158 	  case '#':
3159 	    dir.set_flag (target_to_host (*pf++));
3160 	    break;
3161 
3162 	  default:
3163 	    goto start_width;
3164 	  }
3165       }
3166 
3167     start_width:
3168       if (ISDIGIT (target_to_host (*pf)))
3169 	{
3170 	  werange = 0;
3171 	  pwidth = pf;
3172 	  width = target_strtol10 (&pf, &werange);
3173 	}
3174       else if (target_to_host (*pf) == '*')
3175 	{
3176 	  if (*argno < gimple_call_num_args (info.callstmt))
3177 	    star_width = gimple_call_arg (info.callstmt, (*argno)++);
3178 	  else
3179 	    {
3180 	      /* This is (likely) a va_list.  It could also be an invalid
3181 		 call with insufficient arguments.  */
3182 	      star_width = void_node;
3183 	    }
3184 	  ++pf;
3185 	}
3186       else if (target_to_host (*pf) == '\'')
3187 	{
3188 	  /* The POSIX apostrophe indicating a numeric grouping
3189 	     in the current locale.  Even though it's possible to
3190 	     estimate the upper bound on the size of the output
3191 	     based on the number of digits it probably isn't worth
3192 	     continuing.  */
3193 	  return 0;
3194 	}
3195     }
3196 
3197  start_precision:
3198   if (target_to_host (*pf) == '.')
3199     {
3200       ++pf;
3201 
3202       if (ISDIGIT (target_to_host (*pf)))
3203 	{
3204 	  pprec = pf;
3205 	  precision = target_strtol10 (&pf, &perange);
3206 	}
3207       else if (target_to_host (*pf) == '*')
3208 	{
3209 	  if (*argno < gimple_call_num_args (info.callstmt))
3210 	    star_precision = gimple_call_arg (info.callstmt, (*argno)++);
3211 	  else
3212 	    {
3213 	      /* This is (likely) a va_list.  It could also be an invalid
3214 		 call with insufficient arguments.  */
3215 	      star_precision = void_node;
3216 	    }
3217 	  ++pf;
3218 	}
3219       else
3220 	{
3221 	  /* The decimal precision or the asterisk are optional.
3222 	     When neither is dirified it's taken to be zero.  */
3223 	  precision = 0;
3224 	}
3225     }
3226 
3227   switch (target_to_host (*pf))
3228     {
3229     case 'h':
3230       if (target_to_host (pf[1]) == 'h')
3231 	{
3232 	  ++pf;
3233 	  dir.modifier = FMT_LEN_hh;
3234 	}
3235       else
3236 	dir.modifier = FMT_LEN_h;
3237       ++pf;
3238       break;
3239 
3240     case 'j':
3241       dir.modifier = FMT_LEN_j;
3242       ++pf;
3243       break;
3244 
3245     case 'L':
3246       dir.modifier = FMT_LEN_L;
3247       ++pf;
3248       break;
3249 
3250     case 'l':
3251       if (target_to_host (pf[1]) == 'l')
3252 	{
3253 	  ++pf;
3254 	  dir.modifier = FMT_LEN_ll;
3255 	}
3256       else
3257 	dir.modifier = FMT_LEN_l;
3258       ++pf;
3259       break;
3260 
3261     case 't':
3262       dir.modifier = FMT_LEN_t;
3263       ++pf;
3264       break;
3265 
3266     case 'z':
3267       dir.modifier = FMT_LEN_z;
3268       ++pf;
3269       break;
3270     }
3271 
3272   switch (target_to_host (*pf))
3273     {
3274       /* Handle a sole '%' character the same as "%%" but since it's
3275 	 undefined prevent the result from being folded.  */
3276     case '\0':
3277       --pf;
3278       res->range.min = res->range.max = HOST_WIDE_INT_M1U;
3279       /* FALLTHRU */
3280     case '%':
3281       dir.fmtfunc = format_percent;
3282       break;
3283 
3284     case 'a':
3285     case 'A':
3286     case 'e':
3287     case 'E':
3288     case 'f':
3289     case 'F':
3290     case 'g':
3291     case 'G':
3292       res->floating = true;
3293       dir.fmtfunc = format_floating;
3294       break;
3295 
3296     case 'd':
3297     case 'i':
3298     case 'o':
3299     case 'u':
3300     case 'x':
3301     case 'X':
3302       dir.fmtfunc = format_integer;
3303       break;
3304 
3305     case 'p':
3306       /* The %p output is implementation-defined.  It's possible
3307 	 to determine this format but due to extensions (edirially
3308 	 those of the Linux kernel -- see bug 78512) the first %p
3309 	 in the format string disables any further processing.  */
3310       return false;
3311 
3312     case 'n':
3313       /* %n has side-effects even when nothing is actually printed to
3314 	 any buffer.  */
3315       info.nowrite = false;
3316       dir.fmtfunc = format_none;
3317       break;
3318 
3319     case 'c':
3320       dir.fmtfunc = format_character;
3321       break;
3322 
3323     case 'S':
3324     case 's':
3325       dir.fmtfunc = format_string;
3326       break;
3327 
3328     default:
3329       /* Unknown conversion specification.  */
3330       return 0;
3331     }
3332 
3333   dir.specifier = target_to_host (*pf++);
3334 
3335   /* Store the length of the format directive.  */
3336   dir.len = pf - pcnt;
3337 
3338   /* Buffer for the directive in the host character set (used when
3339      the source character set is different).  */
3340   char hostdir[32];
3341 
3342   if (star_width)
3343     {
3344       if (INTEGRAL_TYPE_P (TREE_TYPE (star_width)))
3345 	dir.set_width (star_width, vr_values);
3346       else
3347 	{
3348 	  /* Width specified by a va_list takes on the range [0, -INT_MIN]
3349 	     (width is the absolute value of that specified).  */
3350 	  dir.width[0] = 0;
3351 	  dir.width[1] = target_int_max () + 1;
3352 	}
3353     }
3354   else
3355     {
3356       if (width == LONG_MAX && werange)
3357 	{
3358 	  size_t begin = dir.beg - info.fmtstr + (pwidth - pcnt);
3359 	  size_t caret = begin + (werange - pcnt);
3360 	  size_t end = pf - info.fmtstr - 1;
3361 
3362 	  /* Create a location for the width part of the directive,
3363 	     pointing the caret at the first out-of-range digit.  */
3364 	  substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3365 				caret, begin, end);
3366 
3367 	  fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3368 		   "%<%.*s%> directive width out of range", (int) dir.len,
3369 		   target_to_host (hostdir, sizeof hostdir, dir.beg));
3370 	}
3371 
3372       dir.set_width (width);
3373     }
3374 
3375   if (star_precision)
3376     {
3377       if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision)))
3378 	dir.set_precision (star_precision, vr_values);
3379       else
3380 	{
3381 	  /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3382 	     (unlike width, negative precision is ignored).  */
3383 	  dir.prec[0] = -1;
3384 	  dir.prec[1] = target_int_max ();
3385 	}
3386     }
3387   else
3388     {
3389       if (precision == LONG_MAX && perange)
3390 	{
3391 	  size_t begin = dir.beg - info.fmtstr + (pprec - pcnt) - 1;
3392 	  size_t caret = dir.beg - info.fmtstr + (perange - pcnt) - 1;
3393 	  size_t end = pf - info.fmtstr - 2;
3394 
3395 	  /* Create a location for the precision part of the directive,
3396 	     including the leading period, pointing the caret at the first
3397 	     out-of-range digit .  */
3398 	  substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3399 				caret, begin, end);
3400 
3401 	  fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3402 		   "%<%.*s%> directive precision out of range", (int) dir.len,
3403 		   target_to_host (hostdir, sizeof hostdir, dir.beg));
3404 	}
3405 
3406       dir.set_precision (precision);
3407     }
3408 
3409   /* Extract the argument if the directive takes one and if it's
3410      available (e.g., the function doesn't take a va_list).  Treat
3411      missing arguments the same as va_list, even though they will
3412      have likely already been diagnosed by -Wformat.  */
3413   if (dir.specifier != '%'
3414       && *argno < gimple_call_num_args (info.callstmt))
3415     dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
3416 
3417   if (dump_file)
3418     {
3419       fprintf (dump_file,
3420 	       "  Directive %u at offset " HOST_WIDE_INT_PRINT_UNSIGNED
3421 	       ": \"%.*s\"",
3422 	       dir.dirno,
3423 	       (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3424 	       (int)dir.len, dir.beg);
3425       if (star_width)
3426 	{
3427 	  if (dir.width[0] == dir.width[1])
3428 	    fprintf (dump_file, ", width = " HOST_WIDE_INT_PRINT_DEC,
3429 		     dir.width[0]);
3430 	  else
3431 	    fprintf (dump_file,
3432 		     ", width in range [" HOST_WIDE_INT_PRINT_DEC
3433 		     ", " HOST_WIDE_INT_PRINT_DEC "]",
3434 		     dir.width[0], dir.width[1]);
3435 	}
3436 
3437       if (star_precision)
3438 	{
3439 	  if (dir.prec[0] == dir.prec[1])
3440 	    fprintf (dump_file, ", precision = " HOST_WIDE_INT_PRINT_DEC,
3441 		     dir.prec[0]);
3442 	  else
3443 	    fprintf (dump_file,
3444 		     ", precision in range [" HOST_WIDE_INT_PRINT_DEC
3445 		     HOST_WIDE_INT_PRINT_DEC "]",
3446 		     dir.prec[0], dir.prec[1]);
3447 	}
3448       fputc ('\n', dump_file);
3449     }
3450 
3451   return dir.len;
3452 }
3453 
3454 /* Compute the length of the output resulting from the call to a formatted
3455    output function described by INFO and store the result of the call in
3456    *RES.  Issue warnings for detected past the end writes.  Return true
3457    if the complete format string has been processed and *RES can be relied
3458    on, false otherwise (e.g., when a unknown or unhandled directive was seen
3459    that caused the processing to be terminated early).  */
3460 
3461 bool
3462 sprintf_dom_walker::compute_format_length (call_info &info,
3463 					   format_result *res)
3464 {
3465   if (dump_file)
3466     {
3467       location_t callloc = gimple_location (info.callstmt);
3468       fprintf (dump_file, "%s:%i: ",
3469 	       LOCATION_FILE (callloc), LOCATION_LINE (callloc));
3470       print_generic_expr (dump_file, info.func, dump_flags);
3471 
3472       fprintf (dump_file,
3473 	       ": objsize = " HOST_WIDE_INT_PRINT_UNSIGNED
3474 	       ", fmtstr = \"%s\"\n",
3475 	       info.objsize, info.fmtstr);
3476     }
3477 
3478   /* Reset the minimum and maximum byte counters.  */
3479   res->range.min = res->range.max = 0;
3480 
3481   /* No directive has been seen yet so the length of output is bounded
3482      by the known range [0, 0] (with no conversion producing more than
3483      4K bytes) until determined otherwise.  */
3484   res->knownrange = true;
3485   res->under4k = true;
3486   res->floating = false;
3487   res->warned = false;
3488 
3489   /* 1-based directive counter.  */
3490   unsigned dirno = 1;
3491 
3492   /* The variadic argument counter.  */
3493   unsigned argno = info.argidx;
3494 
3495   for (const char *pf = info.fmtstr; ; ++dirno)
3496     {
3497       directive dir = directive ();
3498       dir.dirno = dirno;
3499 
3500       size_t n = parse_directive (info, dir, res, pf, &argno,
3501 				  evrp_range_analyzer.get_vr_values ());
3502 
3503       /* Return failure if the format function fails.  */
3504       if (!format_directive (info, res, dir,
3505 			     evrp_range_analyzer.get_vr_values ()))
3506 	return false;
3507 
3508       /* Return success the directive is zero bytes long and it's
3509 	 the last think in the format string (i.e., it's the terminating
3510 	 nul, which isn't really a directive but handling it as one makes
3511 	 things simpler).  */
3512       if (!n)
3513 	return *pf == '\0';
3514 
3515       pf += n;
3516     }
3517 
3518   /* The complete format string was processed (with or without warnings).  */
3519   return true;
3520 }
3521 
3522 /* Return the size of the object referenced by the expression DEST if
3523    available, or -1 otherwise.  */
3524 
3525 static unsigned HOST_WIDE_INT
3526 get_destination_size (tree dest)
3527 {
3528   /* Initialize object size info before trying to compute it.  */
3529   init_object_sizes ();
3530 
3531   /* Use __builtin_object_size to determine the size of the destination
3532      object.  When optimizing, determine the smallest object (such as
3533      a member array as opposed to the whole enclosing object), otherwise
3534      use type-zero object size to determine the size of the enclosing
3535      object (the function fails without optimization in this type).  */
3536   int ost = optimize > 0;
3537   unsigned HOST_WIDE_INT size;
3538   if (compute_builtin_object_size (dest, ost, &size))
3539     return size;
3540 
3541   return HOST_WIDE_INT_M1U;
3542 }
3543 
3544 /* Return true if the call described by INFO with result RES safe to
3545    optimize (i.e., no undefined behavior), and set RETVAL to the range
3546    of its return values.  */
3547 
3548 static bool
3549 is_call_safe (const sprintf_dom_walker::call_info &info,
3550 	      const format_result &res, bool under4k,
3551 	      unsigned HOST_WIDE_INT retval[2])
3552 {
3553   if (under4k && !res.under4k)
3554     return false;
3555 
3556   /* The minimum return value.  */
3557   retval[0] = res.range.min;
3558 
3559   /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3560      but in cases involving multibyte characters could be as large as
3561      RES.RANGE.UNLIKELY.  */
3562   retval[1]
3563     = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
3564 
3565   /* Adjust the number of bytes which includes the terminating nul
3566      to reflect the return value of the function which does not.
3567      Because the valid range of the function is [INT_MIN, INT_MAX],
3568      a valid range before the adjustment below is [0, INT_MAX + 1]
3569      (the functions only return negative values on error or undefined
3570      behavior).  */
3571   if (retval[0] <= target_int_max () + 1)
3572     --retval[0];
3573   if (retval[1] <= target_int_max () + 1)
3574     --retval[1];
3575 
3576   /* Avoid the return value optimization when the behavior of the call
3577      is undefined either because any directive may have produced 4K or
3578      more of output, or the return value exceeds INT_MAX, or because
3579      the output overflows the destination object (but leave it enabled
3580      when the function is bounded because then the behavior is well-
3581      defined).  */
3582   if (retval[0] == retval[1]
3583       && (info.bounded || retval[0] < info.objsize)
3584       && retval[0] <= target_int_max ())
3585     return true;
3586 
3587   if ((info.bounded || retval[1] < info.objsize)
3588       && (retval[0] < target_int_max ()
3589 	  && retval[1] < target_int_max ()))
3590     return true;
3591 
3592   if (!under4k && (info.bounded || retval[0] < info.objsize))
3593     return true;
3594 
3595   return false;
3596 }
3597 
3598 /* Given a suitable result RES of a call to a formatted output function
3599    described by INFO, substitute the result for the return value of
3600    the call.  The result is suitable if the number of bytes it represents
3601    is known and exact.  A result that isn't suitable for substitution may
3602    have its range set to the range of return values, if that is known.
3603    Return true if the call is removed and gsi_next should not be performed
3604    in the caller.  */
3605 
3606 static bool
3607 try_substitute_return_value (gimple_stmt_iterator *gsi,
3608 			     const sprintf_dom_walker::call_info &info,
3609 			     const format_result &res)
3610 {
3611   tree lhs = gimple_get_lhs (info.callstmt);
3612 
3613   /* Set to true when the entire call has been removed.  */
3614   bool removed = false;
3615 
3616   /* The minimum and maximum return value.  */
3617   unsigned HOST_WIDE_INT retval[2];
3618   bool safe = is_call_safe (info, res, true, retval);
3619 
3620   if (safe
3621       && retval[0] == retval[1]
3622       /* Not prepared to handle possibly throwing calls here; they shouldn't
3623 	 appear in non-artificial testcases, except when the __*_chk routines
3624 	 are badly declared.  */
3625       && !stmt_ends_bb_p (info.callstmt))
3626     {
3627       tree cst = build_int_cst (integer_type_node, retval[0]);
3628 
3629       if (lhs == NULL_TREE
3630 	  && info.nowrite)
3631 	{
3632 	  /* Remove the call to the bounded function with a zero size
3633 	     (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs.  */
3634 	  unlink_stmt_vdef (info.callstmt);
3635 	  gsi_remove (gsi, true);
3636 	  removed = true;
3637 	}
3638       else if (info.nowrite)
3639 	{
3640 	  /* Replace the call to the bounded function with a zero size
3641 	     (e.g., snprintf(0, 0, "%i", 123) with the constant result
3642 	     of the function.  */
3643 	  if (!update_call_from_tree (gsi, cst))
3644 	    gimplify_and_update_call_from_tree (gsi, cst);
3645 	  gimple *callstmt = gsi_stmt (*gsi);
3646 	  update_stmt (callstmt);
3647 	}
3648       else if (lhs)
3649 	{
3650 	  /* Replace the left-hand side of the call with the constant
3651 	     result of the formatted function.  */
3652 	  gimple_call_set_lhs (info.callstmt, NULL_TREE);
3653 	  gimple *g = gimple_build_assign (lhs, cst);
3654 	  gsi_insert_after (gsi, g, GSI_NEW_STMT);
3655 	  update_stmt (info.callstmt);
3656 	}
3657 
3658       if (dump_file)
3659 	{
3660 	  if (removed)
3661 	    fprintf (dump_file, "  Removing call statement.");
3662 	  else
3663 	    {
3664 	      fprintf (dump_file, "  Substituting ");
3665 	      print_generic_expr (dump_file, cst, dump_flags);
3666 	      fprintf (dump_file, " for %s.\n",
3667 		       info.nowrite ? "statement" : "return value");
3668 	    }
3669 	}
3670     }
3671   else if (lhs)
3672     {
3673       bool setrange = false;
3674 
3675       if (safe
3676 	  && (info.bounded || retval[1] < info.objsize)
3677 	  && (retval[0] < target_int_max ()
3678 	      && retval[1] < target_int_max ()))
3679 	{
3680 	  /* If the result is in a valid range bounded by the size of
3681 	     the destination set it so that it can be used for subsequent
3682 	     optimizations.  */
3683 	  int prec = TYPE_PRECISION (integer_type_node);
3684 
3685 	  wide_int min = wi::shwi (retval[0], prec);
3686 	  wide_int max = wi::shwi (retval[1], prec);
3687 	  set_range_info (lhs, VR_RANGE, min, max);
3688 
3689 	  setrange = true;
3690 	}
3691 
3692       if (dump_file)
3693 	{
3694 	  const char *inbounds
3695 	    = (retval[0] < info.objsize
3696 	       ? (retval[1] < info.objsize
3697 		  ? "in" : "potentially out-of")
3698 	       : "out-of");
3699 
3700 	  const char *what = setrange ? "Setting" : "Discarding";
3701 	  if (retval[0] != retval[1])
3702 	    fprintf (dump_file,
3703 		     "  %s %s-bounds return value range ["
3704 		     HOST_WIDE_INT_PRINT_UNSIGNED ", "
3705 		     HOST_WIDE_INT_PRINT_UNSIGNED "].\n",
3706 		     what, inbounds, retval[0], retval[1]);
3707 	  else
3708 	    fprintf (dump_file, "  %s %s-bounds return value "
3709 		     HOST_WIDE_INT_PRINT_UNSIGNED ".\n",
3710 		     what, inbounds, retval[0]);
3711 	}
3712     }
3713 
3714   if (dump_file)
3715     fputc ('\n', dump_file);
3716 
3717   return removed;
3718 }
3719 
3720 /* Try to simplify a s{,n}printf call described by INFO with result
3721    RES by replacing it with a simpler and presumably more efficient
3722    call (such as strcpy).  */
3723 
3724 static bool
3725 try_simplify_call (gimple_stmt_iterator *gsi,
3726 		   const sprintf_dom_walker::call_info &info,
3727 		   const format_result &res)
3728 {
3729   unsigned HOST_WIDE_INT dummy[2];
3730   if (!is_call_safe (info, res, info.retval_used (), dummy))
3731     return false;
3732 
3733   switch (info.fncode)
3734     {
3735     case BUILT_IN_SNPRINTF:
3736       return gimple_fold_builtin_snprintf (gsi);
3737 
3738     case BUILT_IN_SPRINTF:
3739       return gimple_fold_builtin_sprintf (gsi);
3740 
3741     default:
3742       ;
3743     }
3744 
3745   return false;
3746 }
3747 
3748 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3749    functions and if so, handle it.  Return true if the call is removed
3750    and gsi_next should not be performed in the caller.  */
3751 
3752 bool
3753 sprintf_dom_walker::handle_gimple_call (gimple_stmt_iterator *gsi)
3754 {
3755   call_info info = call_info ();
3756 
3757   info.callstmt = gsi_stmt (*gsi);
3758   if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
3759     return false;
3760 
3761   info.func = gimple_call_fndecl (info.callstmt);
3762   info.fncode = DECL_FUNCTION_CODE (info.func);
3763 
3764   /* The size of the destination as in snprintf(dest, size, ...).  */
3765   unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
3766 
3767   /* The size of the destination determined by __builtin_object_size.  */
3768   unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
3769 
3770   /* Buffer size argument number (snprintf and vsnprintf).  */
3771   unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
3772 
3773   /* Object size argument number (snprintf_chk and vsnprintf_chk).  */
3774   unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
3775 
3776   /* Format string argument number (valid for all functions).  */
3777   unsigned idx_format;
3778 
3779   switch (info.fncode)
3780     {
3781     case BUILT_IN_SPRINTF:
3782       // Signature:
3783       //   __builtin_sprintf (dst, format, ...)
3784       idx_format = 1;
3785       info.argidx = 2;
3786       break;
3787 
3788     case BUILT_IN_SPRINTF_CHK:
3789       // Signature:
3790       //   __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3791       idx_objsize = 2;
3792       idx_format = 3;
3793       info.argidx = 4;
3794       break;
3795 
3796     case BUILT_IN_SNPRINTF:
3797       // Signature:
3798       //   __builtin_snprintf (dst, size, format, ...)
3799       idx_dstsize = 1;
3800       idx_format = 2;
3801       info.argidx = 3;
3802       info.bounded = true;
3803       break;
3804 
3805     case BUILT_IN_SNPRINTF_CHK:
3806       // Signature:
3807       //   __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3808       idx_dstsize = 1;
3809       idx_objsize = 3;
3810       idx_format = 4;
3811       info.argidx = 5;
3812       info.bounded = true;
3813       break;
3814 
3815     case BUILT_IN_VSNPRINTF:
3816       // Signature:
3817       //   __builtin_vsprintf (dst, size, format, va)
3818       idx_dstsize = 1;
3819       idx_format = 2;
3820       info.argidx = -1;
3821       info.bounded = true;
3822       break;
3823 
3824     case BUILT_IN_VSNPRINTF_CHK:
3825       // Signature:
3826       //   __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
3827       idx_dstsize = 1;
3828       idx_objsize = 3;
3829       idx_format = 4;
3830       info.argidx = -1;
3831       info.bounded = true;
3832       break;
3833 
3834     case BUILT_IN_VSPRINTF:
3835       // Signature:
3836       //   __builtin_vsprintf (dst, format, va)
3837       idx_format = 1;
3838       info.argidx = -1;
3839       break;
3840 
3841     case BUILT_IN_VSPRINTF_CHK:
3842       // Signature:
3843       //   __builtin___vsprintf_chk (dst, ost, objsize, format, va)
3844       idx_format = 3;
3845       idx_objsize = 2;
3846       info.argidx = -1;
3847       break;
3848 
3849     default:
3850       return false;
3851     }
3852 
3853   /* Set the global warning level for this function.  */
3854   warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
3855 
3856   /* The first argument is a pointer to the destination.  */
3857   tree dstptr = gimple_call_arg (info.callstmt, 0);
3858 
3859   info.format = gimple_call_arg (info.callstmt, idx_format);
3860 
3861   /* True when the destination size is constant as opposed to the lower
3862      or upper bound of a range.  */
3863   bool dstsize_cst_p = true;
3864 
3865   if (idx_dstsize == HOST_WIDE_INT_M1U)
3866     {
3867       /* For non-bounded functions like sprintf, determine the size
3868 	 of the destination from the object or pointer passed to it
3869 	 as the first argument.  */
3870       dstsize = get_destination_size (dstptr);
3871     }
3872   else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
3873     {
3874       /* For bounded functions try to get the size argument.  */
3875 
3876       if (TREE_CODE (size) == INTEGER_CST)
3877 	{
3878 	  dstsize = tree_to_uhwi (size);
3879 	  /* No object can be larger than SIZE_MAX bytes (half the address
3880 	     space) on the target.
3881 	     The functions are defined only for output of at most INT_MAX
3882 	     bytes.  Specifying a bound in excess of that limit effectively
3883 	     defeats the bounds checking (and on some implementations such
3884 	     as Solaris cause the function to fail with EINVAL).  */
3885 	  if (dstsize > target_size_max () / 2)
3886 	    {
3887 	      /* Avoid warning if -Wstringop-overflow is specified since
3888 		 it also warns for the same thing though only for the
3889 		 checking built-ins.  */
3890 	      if ((idx_objsize == HOST_WIDE_INT_M1U
3891 		   || !warn_stringop_overflow))
3892 		warning_at (gimple_location (info.callstmt), info.warnopt (),
3893 			    "specified bound %wu exceeds maximum object size "
3894 			    "%wu",
3895 			    dstsize, target_size_max () / 2);
3896 	    }
3897 	  else if (dstsize > target_int_max ())
3898 	    warning_at (gimple_location (info.callstmt), info.warnopt (),
3899 			"specified bound %wu exceeds %<INT_MAX%>",
3900 			dstsize);
3901 	}
3902       else if (TREE_CODE (size) == SSA_NAME)
3903 	{
3904 	  /* Try to determine the range of values of the argument
3905 	     and use the greater of the two at level 1 and the smaller
3906 	     of them at level 2.  */
3907 	  value_range *vr = evrp_range_analyzer.get_value_range (size);
3908 	  if (vr->type == VR_RANGE
3909 	      && TREE_CODE (vr->min) == INTEGER_CST
3910 	      && TREE_CODE (vr->max) == INTEGER_CST)
3911 	    dstsize = (warn_level < 2
3912 		       ? TREE_INT_CST_LOW (vr->max)
3913 		       : TREE_INT_CST_LOW (vr->min));
3914 
3915 	  /* The destination size is not constant.  If the function is
3916 	     bounded (e.g., snprintf) a lower bound of zero doesn't
3917 	     necessarily imply it can be eliminated.  */
3918 	  dstsize_cst_p = false;
3919 	}
3920     }
3921 
3922   if (idx_objsize != HOST_WIDE_INT_M1U)
3923     if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
3924       if (tree_fits_uhwi_p (size))
3925 	objsize = tree_to_uhwi (size);
3926 
3927   if (info.bounded && !dstsize)
3928     {
3929       /* As a special case, when the explicitly specified destination
3930 	 size argument (to a bounded function like snprintf) is zero
3931 	 it is a request to determine the number of bytes on output
3932 	 without actually producing any.  Pretend the size is
3933 	 unlimited in this case.  */
3934       info.objsize = HOST_WIDE_INT_MAX;
3935       info.nowrite = dstsize_cst_p;
3936     }
3937   else
3938     {
3939       /* For calls to non-bounded functions or to those of bounded
3940 	 functions with a non-zero size, warn if the destination
3941 	 pointer is null.  */
3942       if (integer_zerop (dstptr))
3943 	{
3944 	  /* This is diagnosed with -Wformat only when the null is a constant
3945 	     pointer.  The warning here diagnoses instances where the pointer
3946 	     is not constant.  */
3947 	  location_t loc = gimple_location (info.callstmt);
3948 	  warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
3949 		      info.warnopt (), "null destination pointer");
3950 	  return false;
3951 	}
3952 
3953       /* Set the object size to the smaller of the two arguments
3954 	 of both have been specified and they're not equal.  */
3955       info.objsize = dstsize < objsize ? dstsize : objsize;
3956 
3957       if (info.bounded
3958 	  && dstsize < target_size_max () / 2 && objsize < dstsize
3959 	  /* Avoid warning if -Wstringop-overflow is specified since
3960 	     it also warns for the same thing though only for the
3961 	     checking built-ins.  */
3962 	  && (idx_objsize == HOST_WIDE_INT_M1U
3963 	      || !warn_stringop_overflow))
3964 	{
3965 	  warning_at (gimple_location (info.callstmt), info.warnopt (),
3966 		      "specified bound %wu exceeds the size %wu "
3967 		      "of the destination object", dstsize, objsize);
3968 	}
3969     }
3970 
3971   if (integer_zerop (info.format))
3972     {
3973       /* This is diagnosed with -Wformat only when the null is a constant
3974 	 pointer.  The warning here diagnoses instances where the pointer
3975 	 is not constant.  */
3976       location_t loc = gimple_location (info.callstmt);
3977       warning_at (EXPR_LOC_OR_LOC (info.format, loc),
3978 		  info.warnopt (), "null format string");
3979       return false;
3980     }
3981 
3982   info.fmtstr = get_format_string (info.format, &info.fmtloc);
3983   if (!info.fmtstr)
3984     return false;
3985 
3986   /* The result is the number of bytes output by the formatted function,
3987      including the terminating NUL.  */
3988   format_result res = format_result ();
3989 
3990   bool success = compute_format_length (info, &res);
3991 
3992   /* When optimizing and the printf return value optimization is enabled,
3993      attempt to substitute the computed result for the return value of
3994      the call.  Avoid this optimization when -frounding-math is in effect
3995      and the format string contains a floating point directive.  */
3996   bool call_removed = false;
3997   if (success && optimize > 0)
3998     {
3999       /* Save a copy of the iterator pointing at the call.  The iterator
4000 	 may change to point past the call in try_substitute_return_value
4001 	 but the original value is needed in try_simplify_call.  */
4002       gimple_stmt_iterator gsi_call = *gsi;
4003 
4004       if (flag_printf_return_value
4005 	  && (!flag_rounding_math || !res.floating))
4006 	call_removed = try_substitute_return_value (gsi, info, res);
4007 
4008       if (!call_removed)
4009 	try_simplify_call (&gsi_call, info, res);
4010     }
4011 
4012   return call_removed;
4013 }
4014 
4015 edge
4016 sprintf_dom_walker::before_dom_children (basic_block bb)
4017 {
4018   evrp_range_analyzer.enter (bb);
4019   for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
4020     {
4021       /* Iterate over statements, looking for function calls.  */
4022       gimple *stmt = gsi_stmt (si);
4023 
4024       /* First record ranges generated by this statement.  */
4025       evrp_range_analyzer.record_ranges_from_stmt (stmt, false);
4026 
4027       if (is_gimple_call (stmt) && handle_gimple_call (&si))
4028 	/* If handle_gimple_call returns true, the iterator is
4029 	   already pointing to the next statement.  */
4030 	continue;
4031 
4032       gsi_next (&si);
4033     }
4034   return NULL;
4035 }
4036 
4037 void
4038 sprintf_dom_walker::after_dom_children (basic_block bb)
4039 {
4040   evrp_range_analyzer.leave (bb);
4041 }
4042 
4043 /* Execute the pass for function FUN.  */
4044 
4045 unsigned int
4046 pass_sprintf_length::execute (function *fun)
4047 {
4048   init_target_to_host_charmap ();
4049 
4050   calculate_dominance_info (CDI_DOMINATORS);
4051 
4052   sprintf_dom_walker sprintf_dom_walker;
4053   sprintf_dom_walker.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));
4054 
4055   /* Clean up object size info.  */
4056   fini_object_sizes ();
4057   return 0;
4058 }
4059 
4060 }   /* Unnamed namespace.  */
4061 
4062 /* Return a pointer to a pass object newly constructed from the context
4063    CTXT.  */
4064 
4065 gimple_opt_pass *
4066 make_pass_sprintf_length (gcc::context *ctxt)
4067 {
4068   return new pass_sprintf_length (ctxt);
4069 }
4070