aarch64 - Set the mode for the unspec in speculation_tracker insn.
[platform/upstream/linaro-gcc.git] / gcc / pretty-print.c
index 8f55df2..49e1cb9 100644 (file)
@@ -1,5 +1,5 @@
 /* Various declarations for language-independent pretty-print subroutines.
-   Copyright (C) 2003, 2004, 2005, 2007 Free Software Foundation, Inc.
+   Copyright (C) 2003-2016 Free Software Foundation, Inc.
    Contributed by Gabriel Dos Reis <gdr@integrable-solutions.net>
 
 This file is part of GCC.
@@ -19,20 +19,61 @@ along with GCC; see the file COPYING3.  If not see
 <http://www.gnu.org/licenses/>.  */
 
 #include "config.h"
-#undef FLOAT /* This is for hpux. They should change hpux.  */
-#undef FFS  /* Some systems define this in param.h.  */
 #include "system.h"
 #include "coretypes.h"
 #include "intl.h"
 #include "pretty-print.h"
-#include "tree.h"
+#include "diagnostic-color.h"
 
-#define obstack_chunk_alloc xmalloc
-#define obstack_chunk_free  free
+#if HAVE_ICONV
+#include <iconv.h>
+#endif
+
+/* Overwrite the given location/range within this text_info's rich_location.
+   For use e.g. when implementing "+" in client format decoders.  */
+
+void
+text_info::set_location (unsigned int idx, location_t loc, bool show_caret_p)
+{
+  gcc_checking_assert (m_richloc);
+  m_richloc->set_range (line_table, idx, loc, show_caret_p);
+}
+
+location_t
+text_info::get_location (unsigned int index_of_location) const
+{
+  gcc_checking_assert (m_richloc);
+
+  if (index_of_location == 0)
+    return m_richloc->get_loc ();
+  else
+    return UNKNOWN_LOCATION;
+}
+
+// Default construct an output buffer.
+
+output_buffer::output_buffer ()
+  : formatted_obstack (),
+    chunk_obstack (),
+    obstack (&formatted_obstack),
+    cur_chunk_array (),
+    stream (stderr),
+    line_length (),
+    digit_buffer (),
+    flush_p (true)
+{
+  obstack_init (&formatted_obstack);
+  obstack_init (&chunk_obstack);
+}
+
+// Release resources owned by an output buffer at the end of lifetime.
+
+output_buffer::~output_buffer ()
+{
+  obstack_free (&chunk_obstack, NULL);
+  obstack_free (&formatted_obstack, NULL);
+}
 
-/* A pointer to the formatted diagnostic message.  */
-#define pp_formatted_text_data(PP) \
-   ((const char *) obstack_base (pp_base (PP)->buffer->obstack))
 
 /* Format an integer given by va_arg (ARG, type-specifier T) where
    type-specifier is a precision modifier as indicated by PREC.  F is
@@ -50,7 +91,7 @@ along with GCC; see the file COPYING3.  If not see
         break;                                               \
                                                              \
       case 2:                                                \
-        pp_scalar (PP, "%ll" F, va_arg (ARG, long long T));  \
+        pp_scalar (PP, "%" HOST_LONG_LONG_FORMAT F, va_arg (ARG, long long T));  \
         break;                                               \
                                                              \
       default:                                               \
@@ -96,7 +137,59 @@ void
 pp_write_text_to_stream (pretty_printer *pp)
 {
   const char *text = pp_formatted_text (pp);
-  fputs (text, pp->buffer->stream);
+  fputs (text, pp_buffer (pp)->stream);
+  pp_clear_output_area (pp);
+}
+
+/* As pp_write_text_to_stream, but for GraphViz label output.
+
+   Flush the formatted text of pretty-printer PP onto the attached stream.
+   Replace characters in PPF that have special meaning in a GraphViz .dot
+   file.
+   
+   This routine is not very fast, but it doesn't have to be as this is only
+   be used by routines dumping intermediate representations in graph form.  */
+
+void
+pp_write_text_as_dot_label_to_stream (pretty_printer *pp, bool for_record)
+{
+  const char *text = pp_formatted_text (pp);
+  const char *p = text;
+  FILE *fp = pp_buffer (pp)->stream;
+
+  while (*p)
+    {
+      switch (*p)
+       {
+       /* Print newlines as a left-aligned newline.  */
+       case '\n':
+         fputs ("\\l\\\n", fp);
+         break;
+
+       /* A pipe is only special for record-shape nodes.  */
+       case '|':
+         if (for_record)
+           fputc ('\\', fp);
+         fputc (*p, fp);
+         break;
+
+       /* The following characters always have to be escaped
+          for use in labels.  */
+       case '{':
+       case '}':
+       case '<':
+       case '>':
+       case '"':
+       case ' ':
+         fputc ('\\', fp);
+         /* fall through */
+       default:
+         fputc (*p, fp);
+         break;
+       }
+      p++;
+    }
+
   pp_clear_output_area (pp);
 }
 
@@ -148,15 +241,14 @@ pp_maybe_wrap_text (pretty_printer *pp, const char *start, const char *end)
 static inline void
 pp_append_r (pretty_printer *pp, const char *start, int length)
 {
-  obstack_grow (pp->buffer->obstack, start, length);
-  pp->buffer->line_length += length;
+  output_buffer_append_r (pp_buffer (pp), start, length);
 }
 
 /* Insert enough spaces into the output area of PRETTY-PRINTER to bring
    the column position to the current indentation level, assuming that a
    newline has just been written to the buffer.  */
 void
-pp_base_indent (pretty_printer *pp)
+pp_indent (pretty_printer *pp)
 {
   int n = pp_indentation (pp);
   int i;
@@ -176,6 +268,8 @@ pp_base_indent (pretty_printer *pp)
    %c: character.
    %s: string.
    %p: pointer.
+   %r: if pp_show_color(pp), switch to color identified by const char *.
+   %R: if pp_show_color(pp), reset color.
    %m: strerror(text->err_no) - does not consume a value from args_ptr.
    %%: '%'.
    %<: opening quote.
@@ -185,8 +279,6 @@ pp_base_indent (pretty_printer *pp)
    %.*s: a substring the length of which is specified by an argument
         integer.
    %Ns: likewise, but length specified as constant in the format string.
-   %H: location_t.
-   %J: a decl tree, from which DECL_SOURCE_LOCATION will be recorded.
    Flag 'q': quote formatted text (must come immediately after '%').
 
    Arguments can be used sequentially, or through %N$ resp. *N$
@@ -200,13 +292,13 @@ pp_base_indent (pretty_printer *pp)
    A format string can have at most 30 arguments.  */
 
 /* Formatting phases 1 and 2: render TEXT->format_spec plus
-   TEXT->args_ptr into a series of chunks in PP->buffer->args[].
-   Phase 3 is in pp_base_format_text.  */
+   TEXT->args_ptr into a series of chunks in pp_buffer (PP)->args[].
+   Phase 3 is in pp_format_text.  */
 
 void
-pp_base_format (pretty_printer *pp, text_info *text)
+pp_format (pretty_printer *pp, text_info *text)
 {
-  output_buffer *buffer = pp->buffer;
+  output_buffer *buffer = pp_buffer (pp);
   const char *p;
   const char **args;
   struct chunk_info *new_chunk_array;
@@ -223,13 +315,13 @@ pp_base_format (pretty_printer *pp, text_info *text)
   args = new_chunk_array->args;
 
   /* Formatting phase 1: split up TEXT->format_spec into chunks in
-     PP->buffer->args[].  Even-numbered chunks are to be output
+     pp_buffer (PP)->args[].  Even-numbered chunks are to be output
      verbatim, odd-numbered chunks are format specifiers.
      %m, %%, %<, %>, and %' are replaced with the appropriate text at
      this point.  */
 
   memset (formatters, 0, sizeof formatters);
-  
+
   for (p = text->format_spec; *p; )
     {
       while (*p != '\0' && *p != '%')
@@ -245,25 +337,44 @@ pp_base_format (pretty_printer *pp, text_info *text)
        {
        case '\0':
          gcc_unreachable ();
-         
+
        case '%':
          obstack_1grow (&buffer->chunk_obstack, '%');
          p++;
          continue;
 
        case '<':
-         obstack_grow (&buffer->chunk_obstack,
-                       open_quote, strlen (open_quote));
-         p++;
-         continue;
+         {
+           obstack_grow (&buffer->chunk_obstack,
+                         open_quote, strlen (open_quote));
+           const char *colorstr
+             = colorize_start (pp_show_color (pp), "quote");
+           obstack_grow (&buffer->chunk_obstack, colorstr, strlen (colorstr));
+           p++;
+           continue;
+         }
 
        case '>':
+         {
+           const char *colorstr = colorize_stop (pp_show_color (pp));
+           obstack_grow (&buffer->chunk_obstack, colorstr, strlen (colorstr));
+         }
+         /* FALLTHRU */
        case '\'':
          obstack_grow (&buffer->chunk_obstack,
                        close_quote, strlen (close_quote));
          p++;
          continue;
 
+       case 'R':
+         {
+           const char *colorstr = colorize_stop (pp_show_color (pp));
+           obstack_grow (&buffer->chunk_obstack, colorstr,
+                         strlen (colorstr));
+           p++;
+           continue;
+         }
+
        case 'm':
          {
            const char *errstr = xstrerror (text->err_no);
@@ -362,7 +473,7 @@ pp_base_format (pretty_printer *pp, text_info *text)
   gcc_assert (chunk < PP_NL_ARGMAX * 2);
   args[chunk++] = XOBFINISH (&buffer->chunk_obstack, const char *);
   args[chunk] = 0;
-                 
+
   /* Set output to the argument obstack, and switch line-wrapping and
      prefixing off.  */
   buffer->obstack = &buffer->chunk_obstack;
@@ -418,10 +529,19 @@ pp_base_format (pretty_printer *pp, text_info *text)
       gcc_assert (!wide || precision == 0);
 
       if (quote)
-       pp_string (pp, open_quote);
+       {
+         pp_string (pp, open_quote);
+         pp_string (pp, colorize_start (pp_show_color (pp), "quote"));
+       }
 
       switch (*p)
        {
+       case 'r':
+         pp_string (pp, colorize_start (pp_show_color (pp),
+                                        va_arg (*text->args_ptr,
+                                                const char *)));
+         break;
+
        case 'c':
          pp_character (pp, va_arg (*text->args_ptr, int));
          break;
@@ -470,22 +590,6 @@ pp_base_format (pretty_printer *pp, text_info *text)
              (pp, *text->args_ptr, precision, unsigned, "x");
          break;
 
-       case 'H':
-         {
-           location_t *locus = va_arg (*text->args_ptr, location_t *);
-           gcc_assert (text->locus != NULL);
-           *text->locus = *locus;
-         }
-         break;
-
-       case 'J':
-         {
-           tree t = va_arg (*text->args_ptr, tree);
-           gcc_assert (text->locus != NULL);
-           *text->locus = DECL_SOURCE_LOCATION (t);
-         }
-         break;
-
        case '.':
          {
            int n;
@@ -531,16 +635,18 @@ pp_base_format (pretty_printer *pp, text_info *text)
        }
 
       if (quote)
-       pp_string (pp, close_quote);
+       {
+         pp_string (pp, colorize_stop (pp_show_color (pp)));
+         pp_string (pp, close_quote);
+       }
 
       obstack_1grow (&buffer->chunk_obstack, '\0');
       *formatters[argno] = XOBFINISH (&buffer->chunk_obstack, const char *);
     }
 
-#ifdef ENABLE_CHECKING
-  for (; argno < PP_NL_ARGMAX; argno++)
-    gcc_assert (!formatters[argno]);
-#endif
+  if (CHECKING_P)
+    for (; argno < PP_NL_ARGMAX; argno++)
+      gcc_assert (!formatters[argno]);
 
   /* Revert to normal obstack and wrapping mode.  */
   buffer->obstack = &buffer->formatted_obstack;
@@ -551,7 +657,7 @@ pp_base_format (pretty_printer *pp, text_info *text)
 
 /* Format of a message pointed to by TEXT.  */
 void
-pp_base_output_formatted_text (pretty_printer *pp)
+pp_output_formatted_text (pretty_printer *pp)
 {
   unsigned int chunk;
   output_buffer *buffer = pp_buffer (pp);
@@ -561,7 +667,7 @@ pp_base_output_formatted_text (pretty_printer *pp)
   gcc_assert (buffer->obstack == &buffer->formatted_obstack);
   gcc_assert (buffer->line_length == 0);
 
-  /* This is a third phase, first 2 phases done in pp_base_format_args.
+  /* This is a third phase, first 2 phases done in pp_format_args.
      Now we actually print it.  */
   for (chunk = 0; args[chunk]; chunk++)
     pp_string (pp, args[chunk]);
@@ -575,7 +681,7 @@ pp_base_output_formatted_text (pretty_printer *pp)
 /* Helper subroutine of output_verbatim and verbatim. Do the appropriate
    settings needed by BUFFER for a verbatim formatting.  */
 void
-pp_base_format_verbatim (pretty_printer *pp, text_info *text)
+pp_format_verbatim (pretty_printer *pp, text_info *text)
 {
   /* Set verbatim mode.  */
   pp_wrapping_mode_t oldmode = pp_set_verbatim_wrapping (pp);
@@ -588,22 +694,33 @@ pp_base_format_verbatim (pretty_printer *pp, text_info *text)
   pp_wrapping_mode (pp) = oldmode;
 }
 
-/* Flush the content of BUFFER onto the attached stream.  */
+/* Flush the content of BUFFER onto the attached stream.  This
+   function does nothing unless pp->output_buffer->flush_p.  */
 void
-pp_base_flush (pretty_printer *pp)
+pp_flush (pretty_printer *pp)
 {
+  pp_clear_state (pp);
+  if (!pp->buffer->flush_p)
+    return;
   pp_write_text_to_stream (pp);
+  fflush (pp_buffer (pp)->stream);
+}
+
+/* Flush the content of BUFFER onto the attached stream independently
+   of the value of pp->output_buffer->flush_p.  */
+void
+pp_really_flush (pretty_printer *pp)
+{
   pp_clear_state (pp);
-  fputc ('\n', pp->buffer->stream);
-  fflush (pp->buffer->stream);
-  pp_needs_newline (pp) = false;
+  pp_write_text_to_stream (pp);
+  fflush (pp_buffer (pp)->stream);
 }
 
 /* Sets the number of maximum characters per line PRETTY-PRINTER can
    output in line-wrapping mode.  A LENGTH value 0 suppresses
    line-wrapping.  */
 void
-pp_base_set_line_maximum_length (pretty_printer *pp, int length)
+pp_set_line_maximum_length (pretty_printer *pp, int length)
 {
   pp_line_cutoff (pp) = length;
   pp_set_real_maximum_length (pp);
@@ -611,15 +728,16 @@ pp_base_set_line_maximum_length (pretty_printer *pp, int length)
 
 /* Clear PRETTY-PRINTER output area text info.  */
 void
-pp_base_clear_output_area (pretty_printer *pp)
+pp_clear_output_area (pretty_printer *pp)
 {
-  obstack_free (pp->buffer->obstack, obstack_base (pp->buffer->obstack));
-  pp->buffer->line_length = 0;
+  obstack_free (pp_buffer (pp)->obstack,
+                obstack_base (pp_buffer (pp)->obstack));
+  pp_buffer (pp)->line_length = 0;
 }
 
 /* Set PREFIX for PRETTY-PRINTER.  */
 void
-pp_base_set_prefix (pretty_printer *pp, const char *prefix)
+pp_set_prefix (pretty_printer *pp, const char *prefix)
 {
   pp->prefix = prefix;
   pp_set_real_maximum_length (pp);
@@ -629,7 +747,7 @@ pp_base_set_prefix (pretty_printer *pp, const char *prefix)
 
 /* Free PRETTY-PRINTER's prefix, a previously malloc()'d string.  */
 void
-pp_base_destroy_prefix (pretty_printer *pp)
+pp_destroy_prefix (pretty_printer *pp)
 {
   if (pp->prefix != NULL)
     {
@@ -640,7 +758,7 @@ pp_base_destroy_prefix (pretty_printer *pp)
 
 /* Write out PRETTY-PRINTER's prefix.  */
 void
-pp_base_emit_prefix (pretty_printer *pp)
+pp_emit_prefix (pretty_printer *pp)
 {
   if (pp->prefix != NULL)
     {
@@ -653,7 +771,7 @@ pp_base_emit_prefix (pretty_printer *pp)
        case DIAGNOSTICS_SHOW_PREFIX_ONCE:
          if (pp->emitted_prefix)
            {
-             pp_base_indent (pp);
+             pp_indent (pp);
              break;
            }
          pp_indentation (pp) += 3;
@@ -672,18 +790,30 @@ pp_base_emit_prefix (pretty_printer *pp)
 
 /* Construct a PRETTY-PRINTER with PREFIX and of MAXIMUM_LENGTH
    characters per line.  */
-void
-pp_construct (pretty_printer *pp, const char *prefix, int maximum_length)
+
+pretty_printer::pretty_printer (const char *p, int l)
+  : buffer (new (XCNEW (output_buffer)) output_buffer ()),
+    prefix (),
+    padding (pp_none),
+    maximum_length (),
+    indent_skip (),
+    wrapping (),
+    format_decoder (),
+    emitted_prefix (),
+    need_newline (),
+    translate_identifiers (true),
+    show_color ()
+{
+  pp_line_cutoff (this) = l;
+  /* By default, we emit prefixes once per message.  */
+  pp_prefixing_rule (this) = DIAGNOSTICS_SHOW_PREFIX_ONCE;
+  pp_set_prefix (this, p);
+}
+
+pretty_printer::~pretty_printer ()
 {
-  memset (pp, 0, sizeof (pretty_printer));
-  pp->buffer = XCNEW (output_buffer);
-  obstack_init (&pp->buffer->chunk_obstack);
-  obstack_init (&pp->buffer->formatted_obstack);
-  pp->buffer->obstack = &pp->buffer->formatted_obstack;
-  pp->buffer->stream = stderr;
-  pp_line_cutoff (pp) = maximum_length;
-  pp_prefixing_rule (pp) = DIAGNOSTICS_SHOW_PREFIX_ONCE;
-  pp_set_prefix (pp, prefix);
+  buffer->~output_buffer ();
+  XDELETE (buffer);
 }
 
 /* Append a string delimited by START and END to the output area of
@@ -692,10 +822,10 @@ pp_construct (pretty_printer *pp, const char *prefix, int maximum_length)
    whitespace if appropriate.  The caller must ensure that it is
    safe to do so.  */
 void
-pp_base_append_text (pretty_printer *pp, const char *start, const char *end)
+pp_append_text (pretty_printer *pp, const char *start, const char *end)
 {
   /* Emit prefix and skip whitespace if we're starting a new line.  */
-  if (pp->buffer->line_length == 0)
+  if (pp_buffer (pp)->line_length == 0)
     {
       pp_emit_prefix (pp);
       if (pp_is_wrapping_line (pp))
@@ -708,31 +838,25 @@ pp_base_append_text (pretty_printer *pp, const char *start, const char *end)
 /* Finishes constructing a NULL-terminated character string representing
    the PRETTY-PRINTED text.  */
 const char *
-pp_base_formatted_text (pretty_printer *pp)
+pp_formatted_text (pretty_printer *pp)
 {
-  obstack_1grow (pp->buffer->obstack, '\0');
-  return pp_formatted_text_data (pp);
+  return output_buffer_formatted_text (pp_buffer (pp));
 }
 
 /*  Return a pointer to the last character emitted in PRETTY-PRINTER's
     output area.  A NULL pointer means no character available.  */
 const char *
-pp_base_last_position_in_text (const pretty_printer *pp)
+pp_last_position_in_text (const pretty_printer *pp)
 {
-  const char *p = NULL;
-  struct obstack *text = pp->buffer->obstack;
-
-  if (obstack_base (text) != obstack_next_free (text))
-    p = ((const char *) obstack_next_free (text)) - 1;
-  return p;
+  return output_buffer_last_position_in_text (pp_buffer (pp));
 }
 
 /* Return the amount of characters PRETTY-PRINTER can accept to
    make a full line.  Meaningful only in line-wrapping mode.  */
 int
-pp_base_remaining_character_count_for_line (pretty_printer *pp)
+pp_remaining_character_count_for_line (pretty_printer *pp)
 {
-  return pp->maximum_length - pp->buffer->line_length;
+  return pp->maximum_length - pp_buffer (pp)->line_length;
 }
 
 
@@ -747,7 +871,6 @@ pp_printf (pretty_printer *pp, const char *msg, ...)
   text.err_no = errno;
   text.args_ptr = &ap;
   text.format_spec = msg;
-  text.locus = NULL;
   pp_format (pp, &text);
   pp_output_formatted_text (pp);
   va_end (ap);
@@ -765,7 +888,6 @@ pp_verbatim (pretty_printer *pp, const char *msg, ...)
   text.err_no = errno;
   text.args_ptr = &ap;
   text.format_spec = msg;
-  text.locus = NULL;
   pp_format_verbatim (pp, &text);
   va_end (ap);
 }
@@ -774,15 +896,16 @@ pp_verbatim (pretty_printer *pp, const char *msg, ...)
 
 /* Have PRETTY-PRINTER start a new line.  */
 void
-pp_base_newline (pretty_printer *pp)
+pp_newline (pretty_printer *pp)
 {
-  obstack_1grow (pp->buffer->obstack, '\n');
-  pp->buffer->line_length = 0;
+  obstack_1grow (pp_buffer (pp)->obstack, '\n');
+  pp_needs_newline (pp) = false;
+  pp_buffer (pp)->line_length = 0;
 }
 
 /* Have PRETTY-PRINTER add a CHARACTER.  */
 void
-pp_base_character (pretty_printer *pp, int c)
+pp_character (pretty_printer *pp, int c)
 {
   if (pp_is_wrapping_line (pp)
       && pp_remaining_character_count_for_line (pp) <= 0)
@@ -791,26 +914,281 @@ pp_base_character (pretty_printer *pp, int c)
       if (ISSPACE (c))
         return;
     }
-  obstack_1grow (pp->buffer->obstack, c);
-  ++pp->buffer->line_length;
+  obstack_1grow (pp_buffer (pp)->obstack, c);
+  ++pp_buffer (pp)->line_length;
 }
 
 /* Append a STRING to the output area of PRETTY-PRINTER; the STRING may
    be line-wrapped if in appropriate mode.  */
 void
-pp_base_string (pretty_printer *pp, const char *str)
+pp_string (pretty_printer *pp, const char *str)
 {
-  pp_maybe_wrap_text (pp, str, str + (str ? strlen (str) : 0));
+  gcc_checking_assert (str);
+  pp_maybe_wrap_text (pp, str, str + strlen (str));
 }
 
 /* Maybe print out a whitespace if needed.  */
 
 void
-pp_base_maybe_space (pretty_printer *pp)
+pp_maybe_space (pretty_printer *pp)
 {
-  if (pp_base (pp)->padding != pp_none)
+  if (pp->padding != pp_none)
     {
       pp_space (pp);
-      pp_base (pp)->padding = pp_none;
+      pp->padding = pp_none;
+    }
+}
+
+// Add a newline to the pretty printer PP and flush formatted text.
+
+void
+pp_newline_and_flush (pretty_printer *pp)
+{
+  pp_newline (pp);
+  pp_flush (pp);
+  pp_needs_newline (pp) = false;
+}
+
+// Add a newline to the pretty printer PP, followed by indentation.
+
+void
+pp_newline_and_indent (pretty_printer *pp, int n)
+{
+  pp_indentation (pp) += n;
+  pp_newline (pp);
+  pp_indent (pp);
+  pp_needs_newline (pp) = false;
+}
+
+// Add separator C, followed by a single whitespace.
+
+void
+pp_separate_with (pretty_printer *pp, char c)
+{
+  pp_character (pp, c);
+  pp_space (pp);
+}
+
+\f
+/* The string starting at P has LEN (at least 1) bytes left; if they
+   start with a valid UTF-8 sequence, return the length of that
+   sequence and set *VALUE to the value of that sequence, and
+   otherwise return 0 and set *VALUE to (unsigned int) -1.  */
+
+static int
+decode_utf8_char (const unsigned char *p, size_t len, unsigned int *value)
+{
+  unsigned int t = *p;
+
+  if (len == 0)
+    abort ();
+  if (t & 0x80)
+    {
+      size_t utf8_len = 0;
+      unsigned int ch;
+      size_t i;
+      for (t = *p; t & 0x80; t <<= 1)
+       utf8_len++;
+
+      if (utf8_len > len || utf8_len < 2 || utf8_len > 6)
+       {
+         *value = (unsigned int) -1;
+         return 0;
+       }
+      ch = *p & ((1 << (7 - utf8_len)) - 1);
+      for (i = 1; i < utf8_len; i++)
+       {
+         unsigned int u = p[i];
+         if ((u & 0xC0) != 0x80)
+           {
+             *value = (unsigned int) -1;
+             return 0;
+           }
+         ch = (ch << 6) | (u & 0x3F);
+       }
+      if (   (ch <=      0x7F && utf8_len > 1)
+         || (ch <=     0x7FF && utf8_len > 2)
+         || (ch <=    0xFFFF && utf8_len > 3)
+         || (ch <=  0x1FFFFF && utf8_len > 4)
+         || (ch <= 0x3FFFFFF && utf8_len > 5)
+         || (ch >= 0xD800 && ch <= 0xDFFF))
+       {
+         *value = (unsigned int) -1;
+         return 0;
+       }
+      *value = ch;
+      return utf8_len;
+    }
+  else
+    {
+      *value = t;
+      return 1;
+    }
+}
+
+/* Allocator for identifier_to_locale and corresponding function to
+   free memory.  */
+
+void *(*identifier_to_locale_alloc) (size_t) = xmalloc;
+void (*identifier_to_locale_free) (void *) = free;
+
+/* Given IDENT, an identifier in the internal encoding, return a
+   version of IDENT suitable for diagnostics in the locale character
+   set: either IDENT itself, or a string, allocated using
+   identifier_to_locale_alloc, converted to the locale character set
+   and using escape sequences if not representable in the locale
+   character set or containing control characters or invalid byte
+   sequences.  Existing backslashes in IDENT are not doubled, so the
+   result may not uniquely specify the contents of an arbitrary byte
+   sequence identifier.  */
+
+const char *
+identifier_to_locale (const char *ident)
+{
+  const unsigned char *uid = (const unsigned char *) ident;
+  size_t idlen = strlen (ident);
+  bool valid_printable_utf8 = true;
+  bool all_ascii = true;
+  size_t i;
+
+  for (i = 0; i < idlen;)
+    {
+      unsigned int c;
+      size_t utf8_len = decode_utf8_char (&uid[i], idlen - i, &c);
+      if (utf8_len == 0 || c <= 0x1F || (c >= 0x7F && c <= 0x9F))
+       {
+         valid_printable_utf8 = false;
+         break;
+       }
+      if (utf8_len > 1)
+       all_ascii = false;
+      i += utf8_len;
+    }
+
+  /* If IDENT contains invalid UTF-8 sequences (which may occur with
+     attributes putting arbitrary byte sequences in identifiers), or
+     control characters, we use octal escape sequences for all bytes
+     outside printable ASCII.  */
+  if (!valid_printable_utf8)
+    {
+      char *ret = (char *) identifier_to_locale_alloc (4 * idlen + 1);
+      char *p = ret;
+      for (i = 0; i < idlen; i++)
+       {
+         if (uid[i] > 0x1F && uid[i] < 0x7F)
+           *p++ = uid[i];
+         else
+           {
+             sprintf (p, "\\%03o", uid[i]);
+             p += 4;
+           }
+       }
+      *p = 0;
+      return ret;
+    }
+
+  /* Otherwise, if it is valid printable ASCII, or printable UTF-8
+     with the locale character set being UTF-8, IDENT is used.  */
+  if (all_ascii || locale_utf8)
+    return ident;
+
+  /* Otherwise IDENT is converted to the locale character set if
+     possible.  */
+#if defined ENABLE_NLS && defined HAVE_LANGINFO_CODESET && HAVE_ICONV
+  if (locale_encoding != NULL)
+    {
+      iconv_t cd = iconv_open (locale_encoding, "UTF-8");
+      bool conversion_ok = true;
+      char *ret = NULL;
+      if (cd != (iconv_t) -1)
+       {
+         size_t ret_alloc = 4 * idlen + 1;
+         for (;;)
+           {
+             /* Repeat the whole conversion process as needed with
+                larger buffers so non-reversible transformations can
+                always be detected.  */
+             ICONV_CONST char *inbuf = CONST_CAST (char *, ident);
+             char *outbuf;
+             size_t inbytesleft = idlen;
+             size_t outbytesleft = ret_alloc - 1;
+             size_t iconv_ret;
+
+             ret = (char *) identifier_to_locale_alloc (ret_alloc);
+             outbuf = ret;
+
+             if (iconv (cd, 0, 0, 0, 0) == (size_t) -1)
+               {
+                 conversion_ok = false;
+                 break;
+               }
+
+             iconv_ret = iconv (cd, &inbuf, &inbytesleft,
+                                &outbuf, &outbytesleft);
+             if (iconv_ret == (size_t) -1 || inbytesleft != 0)
+               {
+                 if (errno == E2BIG)
+                   {
+                     ret_alloc *= 2;
+                     identifier_to_locale_free (ret);
+                     ret = NULL;
+                     continue;
+                   }
+                 else
+                   {
+                     conversion_ok = false;
+                     break;
+                   }
+               }
+             else if (iconv_ret != 0)
+               {
+                 conversion_ok = false;
+                 break;
+               }
+             /* Return to initial shift state.  */
+             if (iconv (cd, 0, 0, &outbuf, &outbytesleft) == (size_t) -1)
+               {
+                 if (errno == E2BIG)
+                   {
+                     ret_alloc *= 2;
+                     identifier_to_locale_free (ret);
+                     ret = NULL;
+                     continue;
+                   }
+                 else
+                   {
+                     conversion_ok = false;
+                     break;
+                   }
+               }
+             *outbuf = 0;
+             break;
+           }
+         iconv_close (cd);
+         if (conversion_ok)
+           return ret;
+       }
     }
+#endif
+
+  /* Otherwise, convert non-ASCII characters in IDENT to UCNs.  */
+  {
+    char *ret = (char *) identifier_to_locale_alloc (10 * idlen + 1);
+    char *p = ret;
+    for (i = 0; i < idlen;)
+      {
+       unsigned int c;
+       size_t utf8_len = decode_utf8_char (&uid[i], idlen - i, &c);
+       if (utf8_len == 1)
+         *p++ = uid[i];
+       else
+         {
+           sprintf (p, "\\U%08x", c);
+           p += 10;
+         }
+       i += utf8_len;
+      }
+    *p = 0;
+    return ret;
+  }
 }