Home | History | Annotate | Line # | Download | only in gcc
      1 /* Process source files and output type information.
      2    Copyright (C) 2002-2022 Free Software Foundation, Inc.
      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 #ifdef HOST_GENERATOR_FILE
     21 #include "config.h"
     22 #define GENERATOR_FILE 1
     23 #else
     24 #include "bconfig.h"
     25 #endif
     26 #include "system.h"
     27 #include "errors.h"		/* for fatal */
     28 #include "getopt.h"
     29 #include "version.h"		/* for version_string & pkgversion_string.  */
     30 #include "xregex.h"
     31 #include "obstack.h"
     32 #include "gengtype.h"
     33 #include "filenames.h"
     34 
     35 /* Data types, macros, etc. used only in this file.  */
     36 
     37 
     38 /* The list of output files.  */
     39 outf_p output_files;
     40 
     41 /* The output header file that is included into pretty much every
     42    source file.  */
     43 outf_p header_file;
     44 
     45 
     46 /* The name of the file containing the list of input files.  */
     47 static char *inputlist;
     48 
     49 /* The plugin input files and their number; in that case only
     50    a single file is produced.  */
     51 static input_file **plugin_files;
     52 static size_t nb_plugin_files;
     53 
     54 /* The generated plugin output file and name.  */
     55 static outf_p plugin_output;
     56 static char *plugin_output_filename;
     57 
     58 /* Our source directory and its length.  */
     59 const char *srcdir;
     60 size_t srcdir_len;
     61 
     62 /* Variables used for reading and writing the state.  */
     63 const char *read_state_filename;
     64 const char *write_state_filename;
     65 
     66 /* Variables to help debugging.  */
     67 int do_dump;
     68 int do_debug;
     69 
     70 /* Level for verbose messages.  */
     71 int verbosity_level;
     72 
     73 /* We have a type count and use it to set the state_number of newly
     74    allocated types to some unique negative number.  */
     75 static int type_count;
     76 
     77 /* The backup directory should be in the same file system as the
     78    generated files, otherwise the rename(2) system call would fail.
     79    If NULL, no backup is made when overwriting a generated file.  */
     80 static const char* backup_dir;	/* (-B) program option.  */
     81 
     82 
     83 static outf_p create_file (const char *, const char *);
     84 
     85 static const char *get_file_basename (const input_file *);
     86 static const char *get_file_realbasename (const input_file *);
     87 
     88 static int get_prefix_langdir_index (const char *);
     89 static const char *get_file_langdir (const input_file *);
     90 
     91 static void dump_pair (int indent, pair_p p);
     92 static void dump_type (int indent, type_p p);
     93 static void dump_type_list (int indent, type_p p);
     94 
     95 
     97 /* Nonzero iff an error has occurred.  */
     98 bool hit_error = false;
     99 
    100 static void gen_rtx_next (void);
    101 static void write_rtx_next (void);
    102 static void open_base_files (void);
    103 static void close_output_files (void);
    104 
    105 /* Report an error at POS, printing MSG.  */
    106 
    107 void
    108 error_at_line (const struct fileloc *pos, const char *msg, ...)
    109 {
    110   va_list ap;
    111 
    112   gcc_assert (pos != NULL && pos->file != NULL);
    113   va_start (ap, msg);
    114 
    115   fprintf (stderr, "%s:%d: ", get_input_file_name (pos->file), pos->line);
    116   vfprintf (stderr, msg, ap);
    117   fputc ('\n', stderr);
    118   hit_error = true;
    119 
    120   va_end (ap);
    121 }
    122 
    123 /* Locate the ultimate base class of struct S.  */
    125 
    126 static const_type_p
    127 get_ultimate_base_class (const_type_p s)
    128 {
    129   while (s->u.s.base_class)
    130     s = s->u.s.base_class;
    131   return s;
    132 }
    133 
    134 static type_p
    135 get_ultimate_base_class (type_p s)
    136 {
    137   while (s->u.s.base_class)
    138     s = s->u.s.base_class;
    139   return s;
    140 }
    141 
    142 /* Input file handling. */
    144 
    145 /* Table of all input files.  */
    146 const input_file **gt_files;
    147 size_t num_gt_files;
    148 
    149 /* Table of headers to be included in gtype-desc.cc that are generated
    150    during the build.  These are identified as "./<filename>.h".  */
    151 const char **build_headers;
    152 size_t num_build_headers;
    153 
    154 /* A number of places use the name of this "gengtype.cc" file for a
    155    location for things that we can't rely on the source to define.
    156    Make sure we can still use pointer comparison on filenames.  */
    157 input_file* this_file;
    158 /* The "system.h" file is likewise specially useful.  */
    159 input_file* system_h_file;
    160 
    161 /* Vector of per-language directories.  */
    162 const char **lang_dir_names;
    163 size_t num_lang_dirs;
    164 
    165 /* An array of output files suitable for definitions.  There is one
    166    BASE_FILES entry for each language.  */
    167 static outf_p *base_files;
    168 
    169 /* Utility debugging function, printing the various type counts within
    170    a list of types.  Called through the DBGPRINT_COUNT_TYPE macro.  */
    171 void
    172 dbgprint_count_type_at (const char *fil, int lin, const char *msg, type_p t)
    173 {
    174   int nb_types = 0, nb_scalar = 0, nb_string = 0;
    175   int nb_struct = 0, nb_union = 0, nb_array = 0, nb_pointer = 0;
    176   int nb_lang_struct = 0;
    177   int nb_user_struct = 0, nb_undefined = 0;
    178   int nb_callback = 0;
    179   type_p p = NULL;
    180   for (p = t; p; p = p->next)
    181     {
    182       nb_types++;
    183       switch (p->kind)
    184 	{
    185 	case TYPE_UNDEFINED:
    186 	  nb_undefined++;
    187 	  break;
    188 	case TYPE_SCALAR:
    189 	  nb_scalar++;
    190 	  break;
    191 	case TYPE_STRING:
    192 	  nb_string++;
    193 	  break;
    194 	case TYPE_STRUCT:
    195 	  nb_struct++;
    196 	  break;
    197 	case TYPE_USER_STRUCT:
    198 	  nb_user_struct++;
    199 	  break;
    200 	case TYPE_UNION:
    201 	  nb_union++;
    202 	  break;
    203 	case TYPE_POINTER:
    204 	  nb_pointer++;
    205 	  break;
    206 	case TYPE_ARRAY:
    207 	  nb_array++;
    208 	  break;
    209 	case TYPE_CALLBACK:
    210 	  nb_callback++;
    211 	  break;
    212 	case TYPE_LANG_STRUCT:
    213 	  nb_lang_struct++;
    214 	  break;
    215 	case TYPE_NONE:
    216 	  gcc_unreachable ();
    217 	}
    218     }
    219   fprintf (stderr, "\n" "%s:%d: %s: @@%%@@ %d types ::\n",
    220 	   lbasename (fil), lin, msg, nb_types);
    221   if (nb_scalar > 0 || nb_string > 0)
    222     fprintf (stderr, "@@%%@@ %d scalars, %d strings\n", nb_scalar, nb_string);
    223   if (nb_struct > 0 || nb_union > 0)
    224     fprintf (stderr, "@@%%@@ %d structs, %d unions\n", nb_struct, nb_union);
    225   if (nb_pointer > 0 || nb_array > 0)
    226     fprintf (stderr, "@@%%@@ %d pointers, %d arrays\n", nb_pointer, nb_array);
    227   if (nb_callback > 0)
    228     fprintf (stderr, "@@%%@@ %d callbacks\n", nb_callback);
    229   if (nb_lang_struct > 0)
    230     fprintf (stderr, "@@%%@@ %d lang_structs\n", nb_lang_struct);
    231   if (nb_user_struct > 0)
    232     fprintf (stderr, "@@%%@@ %d user_structs\n", nb_user_struct);
    233   if (nb_undefined > 0)
    234     fprintf (stderr, "@@%%@@ %d undefined types\n", nb_undefined);
    235   fprintf (stderr, "\n");
    236 }
    237 
    238 /* Scan the input file, LIST, and determine how much space we need to
    239    store strings in.  Also, count the number of language directories
    240    and files.  The numbers returned are overestimates as they does not
    241    consider repeated files.  */
    242 static size_t
    243 measure_input_list (FILE *list)
    244 {
    245   size_t n = 0;
    246   int c;
    247   bool atbol = true;
    248   num_lang_dirs = 0;
    249   num_gt_files = plugin_files ? nb_plugin_files : 0;
    250   while ((c = getc (list)) != EOF)
    251     {
    252       n++;
    253       if (atbol)
    254 	{
    255 	  if (c == '[')
    256 	    num_lang_dirs++;
    257 	  else
    258 	    {
    259 	      /* Add space for a lang_bitmap before the input file name.  */
    260 	      n += sizeof (lang_bitmap);
    261 	      num_gt_files++;
    262 	    }
    263 	  atbol = false;
    264 	}
    265 
    266       if (c == '\n')
    267 	atbol = true;
    268     }
    269 
    270   rewind (list);
    271   return n;
    272 }
    273 
    274 /* Read one input line from LIST to HEREP (which is updated).  A
    275    pointer to the string is returned via LINEP.  If it was a language
    276    subdirectory in square brackets, strip off the square brackets and
    277    return true.  Otherwise, leave space before the string for a
    278    lang_bitmap, and return false.  At EOF, returns false, does not
    279    touch *HEREP, and sets *LINEP to NULL.  POS is used for
    280    diagnostics.  */
    281 static bool
    282 read_input_line (FILE *list, char **herep, char **linep, struct fileloc *pos)
    283 {
    284   char *here = *herep;
    285   char *line;
    286   int c = getc (list);
    287 
    288   /* Read over whitespace.  */
    289   while (c == '\n' || c == ' ')
    290     c = getc (list);
    291 
    292   if (c == EOF)
    293     {
    294       *linep = 0;
    295       return false;
    296     }
    297   else if (c == '[')
    298     {
    299       /* No space for a lang_bitmap is necessary.  Discard the '['. */
    300       c = getc (list);
    301       line = here;
    302       while (c != ']' && c != '\n' && c != EOF)
    303 	{
    304 	  *here++ = c;
    305 	  c = getc (list);
    306 	}
    307       *here++ = '\0';
    308 
    309       if (c == ']')
    310 	{
    311 	  c = getc (list);	/* eat what should be a newline */
    312 	  if (c != '\n' && c != EOF)
    313 	    error_at_line (pos, "junk on line after language tag [%s]", line);
    314 	}
    315       else
    316 	error_at_line (pos, "missing close bracket for language tag [%s",
    317 		       line);
    318 
    319       *herep = here;
    320       *linep = line;
    321       return true;
    322     }
    323   else
    324     {
    325       /* Leave space for a lang_bitmap.  */
    326       memset (here, 0, sizeof (lang_bitmap));
    327       here += sizeof (lang_bitmap);
    328       line = here;
    329       do
    330 	{
    331 	  *here++ = c;
    332 	  c = getc (list);
    333 	}
    334       while (c != EOF && c != '\n');
    335       *here++ = '\0';
    336       *herep = here;
    337       *linep = line;
    338       return false;
    339     }
    340 }
    341 
    342 /* Read the list of input files from LIST and compute all of the
    343    relevant tables.  There is one file per line of the list.  At
    344    first, all the files on the list are language-generic, but
    345    eventually a line will appear which is the name of a language
    346    subdirectory in square brackets, like this: [cp].  All subsequent
    347    files are specific to that language, until another language
    348    subdirectory tag appears.  Files can appear more than once, if
    349    they apply to more than one language.  */
    350 static void
    351 read_input_list (const char *listname)
    352 {
    353   FILE *list = fopen (listname, "r");
    354   if (!list)
    355     fatal ("cannot open %s: %s", listname, xstrerror (errno));
    356   else
    357     {
    358       struct fileloc epos;
    359       size_t bufsz = measure_input_list (list);
    360       char *buf = XNEWVEC (char, bufsz);
    361       char *here = buf;
    362       char *committed = buf;
    363       char *limit = buf + bufsz;
    364       char *line;
    365       bool is_language;
    366       size_t langno = 0;
    367       size_t nfiles = 0;
    368       lang_bitmap curlangs = (1 << num_lang_dirs) - 1;
    369 
    370       epos.file = input_file_by_name (listname);
    371       epos.line = 0;
    372 
    373       lang_dir_names = XNEWVEC (const char *, num_lang_dirs);
    374       gt_files = XNEWVEC (const input_file *, num_gt_files);
    375 
    376       for (;;)
    377 	{
    378 	next_line:
    379 	  epos.line++;
    380 	  committed = here;
    381 	  is_language = read_input_line (list, &here, &line, &epos);
    382 	  gcc_assert (here <= limit);
    383 	  if (line == 0)
    384 	    break;
    385 	  else if (is_language)
    386 	    {
    387 	      size_t i;
    388 	      gcc_assert (langno <= num_lang_dirs);
    389 	      for (i = 0; i < langno; i++)
    390 		if (strcmp (lang_dir_names[i], line) == 0)
    391 		  {
    392 		    error_at_line (&epos, "duplicate language tag [%s]",
    393 				   line);
    394 		    curlangs = 1 << i;
    395 		    here = committed;
    396 		    goto next_line;
    397 		  }
    398 
    399 	      curlangs = 1 << langno;
    400 	      lang_dir_names[langno++] = line;
    401 	    }
    402 	  else
    403 	    {
    404 	      size_t i;
    405 	      input_file *inpf = input_file_by_name (line);
    406 	      gcc_assert (nfiles <= num_gt_files);
    407 	      for (i = 0; i < nfiles; i++)
    408 		/* Since the input_file-s are uniquely hash-consed, we
    409 		   can just compare pointers! */
    410 		if (gt_files[i] == inpf)
    411 		  {
    412 		    /* Throw away the string we just read, and add the
    413 		       current language to the existing string's bitmap.  */
    414 		    lang_bitmap bmap = get_lang_bitmap (inpf);
    415 		    if (bmap & curlangs)
    416 		      error_at_line (&epos,
    417 				     "file %s specified more than once "
    418 				     "for language %s", line,
    419 				     langno ==
    420 				     0 ? "(all)" : lang_dir_names[langno -
    421 								  1]);
    422 
    423 		    bmap |= curlangs;
    424 		    set_lang_bitmap (inpf, bmap);
    425 		    here = committed;
    426 		    goto next_line;
    427 		  }
    428 
    429 	      set_lang_bitmap (inpf, curlangs);
    430 	      gt_files[nfiles++] = inpf;
    431 	    }
    432 	}
    433       /* Update the global counts now that we know accurately how many
    434          things there are.  (We do not bother resizing the arrays down.)  */
    435       num_lang_dirs = langno;
    436       /* Add the plugin files if provided.  */
    437       if (plugin_files)
    438 	{
    439 	  size_t i;
    440 	  for (i = 0; i < nb_plugin_files; i++)
    441 	    gt_files[nfiles++] = plugin_files[i];
    442 	}
    443       num_gt_files = nfiles;
    444     }
    445 
    446   /* Sanity check: any file that resides in a language subdirectory
    447      (e.g. 'cp') ought to belong to the corresponding language.
    448      ??? Still true if for instance ObjC++ is enabled and C++ isn't?
    449      (Can you even do that?  Should you be allowed to?)  */
    450   {
    451     size_t f;
    452     for (f = 0; f < num_gt_files; f++)
    453       {
    454 	lang_bitmap bitmap = get_lang_bitmap (gt_files[f]);
    455 	const char *basename = get_file_basename (gt_files[f]);
    456 	const char *slashpos = strchr (basename, '/');
    457 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
    458 	const char *slashpos2 = strchr (basename, '\\');
    459 
    460 	if (!slashpos || (slashpos2 && slashpos2 < slashpos))
    461 	  slashpos = slashpos2;
    462 #endif
    463 
    464 	if (slashpos)
    465 	  {
    466 	    size_t l;
    467 	    for (l = 0; l < num_lang_dirs; l++)
    468 	      if ((size_t) (slashpos - basename) == strlen (lang_dir_names[l])
    469 		  && memcmp (basename, lang_dir_names[l],
    470 			     strlen (lang_dir_names[l])) == 0)
    471 		{
    472 		  if (!(bitmap & (1 << l)))
    473 		    error ("%s is in language directory '%s' but is not "
    474 			   "tagged for that language",
    475 			   basename, lang_dir_names[l]);
    476 		  break;
    477 		}
    478 	  }
    479       }
    480   }
    481 
    482   if (ferror (list))
    483     fatal ("error reading %s: %s", listname, xstrerror (errno));
    484 
    485   fclose (list);
    486 }
    487 
    488 
    490 
    491 /* The one and only TYPE_STRING.  */
    492 
    493 struct type string_type = {
    494   TYPE_STRING, 0, 0, 0, GC_USED, {0}
    495 };
    496 
    497 /* The two and only TYPE_SCALARs.  Their u.scalar_is_char flags are
    498    set early in main.  */
    499 
    500 struct type scalar_nonchar = {
    501   TYPE_SCALAR, 0, 0, 0, GC_USED, {0}
    502 };
    503 
    504 struct type scalar_char = {
    505   TYPE_SCALAR, 0, 0, 0, GC_USED, {0}
    506 };
    507 
    508 struct type callback_type = {
    509   TYPE_CALLBACK, 0, 0, 0, GC_USED, {0}
    510 };
    511 
    512 /* Lists of various things.  */
    513 
    514 pair_p typedefs = NULL;
    515 type_p structures = NULL;
    516 pair_p variables = NULL;
    517 
    518 static type_p adjust_field_tree_exp (type_p t, options_p opt);
    519 static type_p adjust_field_rtx_def (type_p t, options_p opt);
    520 
    521 /* Define S as a typedef to T at POS.  */
    522 
    523 void
    524 do_typedef (const char *s, type_p t, struct fileloc *pos)
    525 {
    526   pair_p p;
    527 
    528   /* temporary kludge - gengtype doesn't handle conditionals or
    529      macros.  Ignore any attempt to typedef CUMULATIVE_ARGS, unless it
    530      is coming from this file (main() sets them up with safe dummy
    531      definitions).  */
    532   if (!strcmp (s, "CUMULATIVE_ARGS") && pos->file != this_file)
    533     return;
    534 
    535   for (p = typedefs; p != NULL; p = p->next)
    536     if (strcmp (p->name, s) == 0)
    537       {
    538 	if (p->type != t && strcmp (s, "result_type") != 0)
    539 	  {
    540 	    error_at_line (pos, "type `%s' previously defined", s);
    541 	    error_at_line (&p->line, "previously defined here");
    542 	  }
    543 	return;
    544       }
    545 
    546   p = XNEW (struct pair);
    547   p->next = typedefs;
    548   p->name = s;
    549   p->type = t;
    550   p->line = *pos;
    551   p->opt = NULL;
    552   typedefs = p;
    553 }
    554 
    555 /* Define S as a typename of a scalar.  Cannot be used to define
    556    typedefs of 'char'.  Note: is also used for pointer-to-function
    557    typedefs (which are therefore not treated as pointers).  */
    558 
    559 void
    560 do_scalar_typedef (const char *s, struct fileloc *pos)
    561 {
    562   do_typedef (s, &scalar_nonchar, pos);
    563 }
    564 
    565 /* Similar to strtok_r.  */
    566 
    567 static char *
    568 strtoken (char *str, const char *delim, char **next)
    569 {
    570   char *p;
    571 
    572   if (str == NULL)
    573     str = *next;
    574 
    575   /* Skip the leading delimiters.  */
    576   str += strspn (str, delim);
    577   if (*str == '\0')
    578     /* This is an empty token.  */
    579     return NULL;
    580 
    581   /* The current token.  */
    582   p = str;
    583 
    584   /* Find the next delimiter.  */
    585   str += strcspn (str, delim);
    586   if (*str == '\0')
    587     /* This is the last token.  */
    588     *next = str;
    589   else
    590     {
    591       /* Terminate the current token.  */
    592       *str = '\0';
    593       /* Advance to the next token.  */
    594       *next = str + 1;
    595     }
    596 
    597   return p;
    598 }
    599 
    600 /* Define TYPE_NAME to be a user defined type at location POS.  */
    601 
    602 type_p
    603 create_user_defined_type (const char *type_name, struct fileloc *pos)
    604 {
    605   type_p ty = find_structure (type_name, TYPE_USER_STRUCT);
    606 
    607   /* We might have already seen an incomplete decl of the given type,
    608      in which case we won't have yet seen a GTY((user)), and the type will
    609      only have kind "TYPE_STRUCT".  Mark it as a user struct.  */
    610   ty->kind = TYPE_USER_STRUCT;
    611 
    612   ty->u.s.line = *pos;
    613   ty->u.s.bitmap = get_lang_bitmap (pos->file);
    614   do_typedef (type_name, ty, pos);
    615 
    616   /* If TYPE_NAME specifies a template, create references to the types
    617      in the template by pretending that each type is a field of TY.
    618      This is needed to make sure that the types referenced by the
    619      template are marked as used.  */
    620   char *str = xstrdup (type_name);
    621   char *open_bracket = strchr (str, '<');
    622   if (open_bracket)
    623     {
    624       /* We only accept simple template declarations (see
    625 	 require_template_declaration), so we only need to parse a
    626 	 comma-separated list of strings, implicitly assumed to
    627 	 be type names, potentially with "*" characters.  */
    628       char *arg = open_bracket + 1;
    629       /* Workaround -Wmaybe-uninitialized false positive during
    630 	 profiledbootstrap by initializing it.  */
    631       char *next = NULL;
    632       char *type_id = strtoken (arg, ",>", &next);
    633       pair_p fields = 0;
    634       while (type_id)
    635 	{
    636 	  /* Create a new field for every type found inside the template
    637 	     parameter list.  */
    638 
    639 	  /* Support a single trailing "*" character.  */
    640 	  const char *star = strchr (type_id, '*');
    641 	  int is_ptr = (star != NULL);
    642 	  size_t offset_to_star = star - type_id;
    643 	  if (is_ptr)
    644 	    offset_to_star = star - type_id;
    645 
    646 	  if (strstr (type_id, "char*"))
    647 	    {
    648 	  type_id = strtoken (0, ",>", &next);
    649 	  continue;
    650 	    }
    651 
    652 	  char *field_name = xstrdup (type_id);
    653 
    654 	  type_p arg_type;
    655 	  if (is_ptr)
    656 	    {
    657 	      /* Strip off the first '*' character (and any subsequent text). */
    658 	      *(field_name + offset_to_star) = '\0';
    659 
    660 	      arg_type = find_structure (field_name, TYPE_STRUCT);
    661 	      arg_type = create_pointer (arg_type);
    662 	    }
    663 	  else
    664 	    arg_type = resolve_typedef (field_name, pos);
    665 
    666 	  fields = create_field_at (fields, arg_type, field_name, 0, pos);
    667 	  type_id = strtoken (0, ",>", &next);
    668 	}
    669 
    670       /* Associate the field list to TY.  */
    671       ty->u.s.fields = fields;
    672     }
    673   free (str);
    674 
    675   return ty;
    676 }
    677 
    678 
    679 /* Given a typedef name S, return its associated type.  Return NULL if
    680    S is not a registered type name.  */
    681 
    682 static type_p
    683 type_for_name (const char *s)
    684 {
    685   pair_p p;
    686 
    687   /* Special-case support for types within a "gcc::" namespace.  Rather
    688      than fully-supporting namespaces, simply strip off the "gcc::" prefix
    689      where present.  This allows us to have GTY roots of this form:
    690          extern GTY(()) gcc::some_type *some_ptr;
    691      where the autogenerated functions will refer to simply "some_type",
    692      where they can be resolved into their namespace.  */
    693   if (startswith (s, "gcc::"))
    694     s += 5;
    695 
    696   for (p = typedefs; p != NULL; p = p->next)
    697     if (strcmp (p->name, s) == 0)
    698       return p->type;
    699   return NULL;
    700 }
    701 
    702 
    703 /* Create an undefined type with name S and location POS.  Return the
    704    newly created type.  */
    705 
    706 static type_p
    707 create_undefined_type (const char *s, struct fileloc *pos)
    708 {
    709   type_p ty = find_structure (s, TYPE_UNDEFINED);
    710   ty->u.s.line = *pos;
    711   ty->u.s.bitmap = get_lang_bitmap (pos->file);
    712   do_typedef (s, ty, pos);
    713   return ty;
    714 }
    715 
    716 
    717 /* Return the type previously defined for S.  Use POS to report errors.  */
    718 
    719 type_p
    720 resolve_typedef (const char *s, struct fileloc *pos)
    721 {
    722   bool is_template_instance = (strchr (s, '<') != NULL);
    723   type_p p = type_for_name (s);
    724 
    725   /* If we did not find a typedef registered, generate a TYPE_UNDEFINED
    726      type for regular type identifiers.  If the type identifier S is a
    727      template instantiation, however, we treat it as a user defined
    728      type.
    729 
    730      FIXME, this is actually a limitation in gengtype.  Supporting
    731      template types and their instances would require keeping separate
    732      track of the basic types definition and its instances.  This
    733      essentially forces all template classes in GC to be marked
    734      GTY((user)).  */
    735   if (!p)
    736     p = (is_template_instance)
    737 	? create_user_defined_type (s, pos)
    738 	: create_undefined_type (s, pos);
    739 
    740   return p;
    741 }
    742 
    743 /* Add SUBCLASS to head of linked list of BASE's subclasses.  */
    744 
    745 void add_subclass (type_p base, type_p subclass)
    746 {
    747   gcc_assert (union_or_struct_p (base));
    748   gcc_assert (union_or_struct_p (subclass));
    749 
    750   subclass->u.s.next_sibling_class = base->u.s.first_subclass;
    751   base->u.s.first_subclass = subclass;
    752 }
    753 
    754 /* Create and return a new structure with tag NAME at POS with fields
    755    FIELDS and options O.  The KIND of structure must be one of
    756    TYPE_STRUCT, TYPE_UNION or TYPE_USER_STRUCT.  */
    757 
    758 type_p
    759 new_structure (const char *name, enum typekind kind, struct fileloc *pos,
    760 	       pair_p fields, options_p o, type_p base_class)
    761 {
    762   type_p si;
    763   type_p s = NULL;
    764   lang_bitmap bitmap = get_lang_bitmap (pos->file);
    765   bool isunion = (kind == TYPE_UNION);
    766   type_p *p = &structures;
    767 
    768   gcc_assert (union_or_struct_p (kind));
    769 
    770   for (si = structures; si != NULL; p = &si->next, si = *p)
    771     if (strcmp (name, si->u.s.tag) == 0 && UNION_P (si) == isunion)
    772       {
    773 	type_p ls = NULL;
    774 	if (si->kind == TYPE_LANG_STRUCT)
    775 	  {
    776 	    ls = si;
    777 
    778 	    for (si = ls->u.s.lang_struct; si != NULL; si = si->next)
    779 	      if (si->u.s.bitmap == bitmap)
    780 		s = si;
    781 	  }
    782 	else if (si->u.s.line.file != NULL && si->u.s.bitmap != bitmap)
    783 	  {
    784 	    ls = si;
    785 	    type_count++;
    786 	    si = XCNEW (struct type);
    787 	    memcpy (si, ls, sizeof (struct type));
    788 	    ls->kind = TYPE_LANG_STRUCT;
    789 	    ls->u.s.lang_struct = si;
    790 	    ls->u.s.fields = NULL;
    791 	    si->next = NULL;
    792 	    si->state_number = -type_count;
    793 	    si->pointer_to = NULL;
    794 	    si->u.s.lang_struct = ls;
    795 	  }
    796 	else
    797 	  s = si;
    798 
    799 	if (ls != NULL && s == NULL)
    800 	  {
    801 	    type_count++;
    802 	    s = XCNEW (struct type);
    803 	    s->state_number = -type_count;
    804 	    s->next = ls->u.s.lang_struct;
    805 	    ls->u.s.lang_struct = s;
    806 	    s->u.s.lang_struct = ls;
    807 	  }
    808 	break;
    809       }
    810 
    811   if (s == NULL)
    812     {
    813       type_count++;
    814       s = XCNEW (struct type);
    815       s->state_number = -type_count;
    816       *p = s;
    817     }
    818 
    819   if (s->u.s.lang_struct && (s->u.s.lang_struct->u.s.bitmap & bitmap))
    820     {
    821       error_at_line (pos, "duplicate definition of '%s %s'",
    822 		     isunion ? "union" : "struct", s->u.s.tag);
    823       error_at_line (&s->u.s.line, "previous definition here");
    824     }
    825 
    826   s->kind = kind;
    827   s->u.s.tag = name;
    828   s->u.s.line = *pos;
    829   s->u.s.fields = fields;
    830   s->u.s.opt = o;
    831   s->u.s.bitmap = bitmap;
    832   if (s->u.s.lang_struct)
    833     s->u.s.lang_struct->u.s.bitmap |= bitmap;
    834   s->u.s.base_class = base_class;
    835   if (base_class)
    836     add_subclass (base_class, s);
    837 
    838   return s;
    839 }
    840 
    841 /* Return the previously-defined structure or union with tag NAME,
    842    or a new empty structure or union if none was defined previously.
    843    The KIND of structure must be one of TYPE_STRUCT, TYPE_UNION or
    844    TYPE_USER_STRUCT.  */
    845 
    846 type_p
    847 find_structure (const char *name, enum typekind kind)
    848 {
    849   type_p s;
    850   bool isunion = (kind == TYPE_UNION);
    851   type_p *p = &structures;
    852 
    853   gcc_assert (kind == TYPE_UNDEFINED || union_or_struct_p (kind));
    854 
    855   for (s = structures; s != NULL; p = &s->next, s = *p)
    856     if (strcmp (name, s->u.s.tag) == 0 && UNION_P (s) == isunion)
    857       return s;
    858 
    859   type_count++;
    860   s = XCNEW (struct type);
    861   s->state_number = -type_count;
    862   s->kind = kind;
    863   s->u.s.tag = name;
    864   *p = s;
    865   return s;
    866 }
    867 
    868 /* Return a scalar type with name NAME.  */
    869 
    870 type_p
    871 create_scalar_type (const char *name)
    872 {
    873   if (!strcmp (name, "char") || !strcmp (name, "unsigned char"))
    874     return &scalar_char;
    875   else
    876     return &scalar_nonchar;
    877 }
    878 
    879 
    880 /* Return a pointer to T.  */
    881 
    882 type_p
    883 create_pointer (type_p t)
    884 {
    885   if (!t->pointer_to)
    886     {
    887       type_p r = XCNEW (struct type);
    888       type_count++;
    889       r->state_number = -type_count;
    890       r->kind = TYPE_POINTER;
    891       r->u.p = t;
    892       t->pointer_to = r;
    893     }
    894   return t->pointer_to;
    895 }
    896 
    897 /* Return an array of length LEN.  */
    898 
    899 type_p
    900 create_array (type_p t, const char *len)
    901 {
    902   type_p v;
    903 
    904   type_count++;
    905   v = XCNEW (struct type);
    906   v->kind = TYPE_ARRAY;
    907   v->state_number = -type_count;
    908   v->u.a.p = t;
    909   v->u.a.len = len;
    910   return v;
    911 }
    912 
    913 /* Return a string options structure with name NAME and info INFO.
    914    NEXT is the next option in the chain.  */
    915 options_p
    916 create_string_option (options_p next, const char *name, const char *info)
    917 {
    918   options_p o = XNEW (struct options);
    919   o->kind = OPTION_STRING;
    920   o->next = next;
    921   o->name = name;
    922   o->info.string = info;
    923   return o;
    924 }
    925 
    926 /* Create a type options structure with name NAME and info INFO.  NEXT
    927    is the next option in the chain.  */
    928 options_p
    929 create_type_option (options_p next, const char* name, type_p info)
    930 {
    931   options_p o = XNEW (struct options);
    932   o->next = next;
    933   o->name = name;
    934   o->kind = OPTION_TYPE;
    935   o->info.type = info;
    936   return o;
    937 }
    938 
    939 /* Create a nested pointer options structure with name NAME and info
    940    INFO.  NEXT is the next option in the chain.  */
    941 options_p
    942 create_nested_option (options_p next, const char* name,
    943                       struct nested_ptr_data* info)
    944 {
    945   options_p o;
    946   o = XNEW (struct options);
    947   o->next = next;
    948   o->name = name;
    949   o->kind = OPTION_NESTED;
    950   o->info.nested = info;
    951   return o;
    952 }
    953 
    954 /* Return an options structure for a "nested_ptr" option.  */
    955 options_p
    956 create_nested_ptr_option (options_p next, type_p t,
    957 			  const char *to, const char *from)
    958 {
    959   struct nested_ptr_data *d = XNEW (struct nested_ptr_data);
    960 
    961   d->type = adjust_field_type (t, 0);
    962   d->convert_to = to;
    963   d->convert_from = from;
    964   return create_nested_option (next, "nested_ptr", d);
    965 }
    966 
    967 /* Add a variable named S of type T with options O defined at POS,
    968    to `variables'.  */
    969 void
    970 note_variable (const char *s, type_p t, options_p o, struct fileloc *pos)
    971 {
    972   pair_p n;
    973   n = XNEW (struct pair);
    974   n->name = s;
    975   n->type = t;
    976   n->line = *pos;
    977   n->opt = o;
    978   n->next = variables;
    979   variables = n;
    980 }
    981 
    982 /* Most-general structure field creator.  */
    983 static pair_p
    984 create_field_all (pair_p next, type_p type, const char *name, options_p opt,
    985 		  const input_file *inpf, int line)
    986 {
    987   pair_p field;
    988 
    989   field = XNEW (struct pair);
    990   field->next = next;
    991   field->type = type;
    992   field->name = name;
    993   field->opt = opt;
    994   field->line.file = inpf;
    995   field->line.line = line;
    996   return field;
    997 }
    998 
    999 /* Create a field that came from the source code we are scanning,
   1000    i.e. we have a 'struct fileloc', and possibly options; also,
   1001    adjust_field_type should be called.  */
   1002 pair_p
   1003 create_field_at (pair_p next, type_p type, const char *name, options_p opt,
   1004 		 struct fileloc *pos)
   1005 {
   1006   return create_field_all (next, adjust_field_type (type, opt),
   1007 			   name, opt, pos->file, pos->line);
   1008 }
   1009 
   1010 /* Create a fake field with the given type and name.  NEXT is the next
   1011    field in the chain.  */
   1012 #define create_field(next,type,name) \
   1013     create_field_all (next,type,name, 0, this_file, __LINE__)
   1014 
   1015 /* Like create_field, but the field is only valid when condition COND
   1016    is true.  */
   1017 
   1018 static pair_p
   1019 create_optional_field_ (pair_p next, type_p type, const char *name,
   1020 			const char *cond, int line)
   1021 {
   1022   static int id = 1;
   1023   pair_p union_fields;
   1024   type_p union_type;
   1025 
   1026   /* Create a fake union type with a single nameless field of type TYPE.
   1027      The field has a tag of "1".  This allows us to make the presence
   1028      of a field of type TYPE depend on some boolean "desc" being true.  */
   1029   union_fields = create_field (NULL, type, "");
   1030   union_fields->opt =
   1031     create_string_option (union_fields->opt, "dot", "");
   1032   union_fields->opt =
   1033     create_string_option (union_fields->opt, "tag", "1");
   1034   union_type =
   1035     new_structure (xasprintf ("%s_%d", "fake_union", id++), TYPE_UNION,
   1036                    &lexer_line, union_fields, NULL, NULL);
   1037 
   1038   /* Create the field and give it the new fake union type.  Add a "desc"
   1039      tag that specifies the condition under which the field is valid.  */
   1040   return create_field_all (next, union_type, name,
   1041 			   create_string_option (0, "desc", cond),
   1042 			   this_file, line);
   1043 }
   1044 
   1045 #define create_optional_field(next,type,name,cond)	\
   1046        create_optional_field_(next,type,name,cond,__LINE__)
   1047 
   1048 /* Reverse a linked list of 'struct pair's in place.  */
   1049 pair_p
   1050 nreverse_pairs (pair_p list)
   1051 {
   1052   pair_p prev = 0, p, next;
   1053   for (p = list; p; p = next)
   1054     {
   1055       next = p->next;
   1056       p->next = prev;
   1057       prev = p;
   1058     }
   1059   return prev;
   1060 }
   1061 
   1062 
   1064 /* We don't care how long a CONST_DOUBLE is.  */
   1065 #define CONST_DOUBLE_FORMAT "ww"
   1066 /* We don't want to see codes that are only for generator files.  */
   1067 #undef GENERATOR_FILE
   1068 
   1069 enum rtx_code
   1070 {
   1071 #define DEF_RTL_EXPR(ENUM, NAME, FORMAT, CLASS) ENUM ,
   1072 #include "rtl.def"
   1073 #undef DEF_RTL_EXPR
   1074   NUM_RTX_CODE
   1075 };
   1076 
   1077 static const char *const rtx_name[NUM_RTX_CODE] = {
   1078 #define DEF_RTL_EXPR(ENUM, NAME, FORMAT, CLASS)   NAME ,
   1079 #include "rtl.def"
   1080 #undef DEF_RTL_EXPR
   1081 };
   1082 
   1083 static const char *const rtx_format[NUM_RTX_CODE] = {
   1084 #define DEF_RTL_EXPR(ENUM, NAME, FORMAT, CLASS)   FORMAT ,
   1085 #include "rtl.def"
   1086 #undef DEF_RTL_EXPR
   1087 };
   1088 
   1089 static int rtx_next_new[NUM_RTX_CODE];
   1090 
   1091 /* We also need codes and names for insn notes (not register notes).
   1092    Note that we do *not* bias the note values here.  */
   1093 enum insn_note
   1094 {
   1095 #define DEF_INSN_NOTE(NAME) NAME,
   1096 #include "insn-notes.def"
   1097 #undef DEF_INSN_NOTE
   1098 
   1099   NOTE_INSN_MAX
   1100 };
   1101 
   1102 /* We must allocate one more entry here, as we use NOTE_INSN_MAX as the
   1103    default field for line number notes.  */
   1104 static const char *const note_insn_name[NOTE_INSN_MAX + 1] = {
   1105 #define DEF_INSN_NOTE(NAME) #NAME,
   1106 #include "insn-notes.def"
   1107 #undef DEF_INSN_NOTE
   1108 };
   1109 
   1110 #undef CONST_DOUBLE_FORMAT
   1111 #define GENERATOR_FILE
   1112 
   1113 /* Generate the contents of the rtx_next array.  This really doesn't belong
   1114    in gengtype at all, but it's needed for adjust_field_rtx_def.  */
   1115 
   1116 static void
   1117 gen_rtx_next (void)
   1118 {
   1119   int i;
   1120   for (i = 0; i < NUM_RTX_CODE; i++)
   1121     {
   1122       int k;
   1123 
   1124       rtx_next_new[i] = -1;
   1125       if (startswith (rtx_format[i], "uu"))
   1126 	rtx_next_new[i] = 1;
   1127       else if (i == COND_EXEC || i == SET || i == EXPR_LIST || i == INSN_LIST)
   1128 	rtx_next_new[i] = 1;
   1129       else
   1130 	for (k = strlen (rtx_format[i]) - 1; k >= 0; k--)
   1131 	  if (rtx_format[i][k] == 'e' || rtx_format[i][k] == 'u')
   1132 	    rtx_next_new[i] = k;
   1133     }
   1134 }
   1135 
   1136 /* Write out the contents of the rtx_next array.  */
   1137 static void
   1138 write_rtx_next (void)
   1139 {
   1140   outf_p f = get_output_file_with_visibility (NULL);
   1141   int i;
   1142   if (!f)
   1143     return;
   1144 
   1145   oprintf (f, "\n/* Used to implement the RTX_NEXT macro.  */\n");
   1146   oprintf (f, "EXPORTED_CONST unsigned char rtx_next[NUM_RTX_CODE] = {\n");
   1147   for (i = 0; i < NUM_RTX_CODE; i++)
   1148     if (rtx_next_new[i] == -1)
   1149       oprintf (f, "  0,\n");
   1150     else
   1151       oprintf (f,
   1152 	       "  RTX_HDR_SIZE + %d * sizeof (rtunion),\n", rtx_next_new[i]);
   1153   oprintf (f, "};\n");
   1154 }
   1155 
   1156 /* Handle `special("rtx_def")'.  This is a special case for field
   1157    `fld' of struct rtx_def, which is an array of unions whose values
   1158    are based in a complex way on the type of RTL.  */
   1159 
   1160 static type_p
   1161 adjust_field_rtx_def (type_p t, options_p ARG_UNUSED (opt))
   1162 {
   1163   pair_p flds = NULL;
   1164   options_p nodot;
   1165   int i;
   1166   type_p rtx_tp, rtvec_tp, tree_tp, mem_attrs_tp, note_union_tp, scalar_tp;
   1167   type_p basic_block_tp, reg_attrs_tp, constant_tp, symbol_union_tp;
   1168 
   1169   if (t->kind != TYPE_UNION)
   1170     {
   1171       error_at_line (&lexer_line,
   1172 		     "special `rtx_def' must be applied to a union");
   1173       return &string_type;
   1174     }
   1175 
   1176   nodot = create_string_option (NULL, "dot", "");
   1177 
   1178   rtx_tp = create_pointer (find_structure ("rtx_def", TYPE_STRUCT));
   1179   rtvec_tp = create_pointer (find_structure ("rtvec_def", TYPE_STRUCT));
   1180   tree_tp = create_pointer (find_structure ("tree_node", TYPE_UNION));
   1181   mem_attrs_tp = create_pointer (find_structure ("mem_attrs", TYPE_STRUCT));
   1182   reg_attrs_tp =
   1183     create_pointer (find_structure ("reg_attrs", TYPE_STRUCT));
   1184   basic_block_tp =
   1185     create_pointer (find_structure ("basic_block_def", TYPE_STRUCT));
   1186   constant_tp =
   1187     create_pointer (find_structure ("constant_descriptor_rtx", TYPE_STRUCT));
   1188   scalar_tp = &scalar_nonchar;	/* rtunion int */
   1189 
   1190   {
   1191     pair_p note_flds = NULL;
   1192     int c;
   1193 
   1194     for (c = 0; c <= NOTE_INSN_MAX; c++)
   1195       {
   1196 	switch (c)
   1197 	  {
   1198 	  case NOTE_INSN_MAX:
   1199 	  case NOTE_INSN_DELETED_LABEL:
   1200 	  case NOTE_INSN_DELETED_DEBUG_LABEL:
   1201 	    note_flds = create_field (note_flds, &string_type, "rt_str");
   1202 	    break;
   1203 
   1204 	  case NOTE_INSN_BLOCK_BEG:
   1205 	  case NOTE_INSN_BLOCK_END:
   1206 	    note_flds = create_field (note_flds, tree_tp, "rt_tree");
   1207 	    break;
   1208 
   1209 	  case NOTE_INSN_VAR_LOCATION:
   1210 	    note_flds = create_field (note_flds, rtx_tp, "rt_rtx");
   1211 	    break;
   1212 
   1213 	  default:
   1214 	    note_flds = create_field (note_flds, scalar_tp, "rt_int");
   1215 	    break;
   1216 	  }
   1217 	/* NOTE_INSN_MAX is used as the default field for line
   1218 	   number notes.  */
   1219 	if (c == NOTE_INSN_MAX)
   1220 	  note_flds->opt =
   1221 	    create_string_option (nodot, "default", "");
   1222 	else
   1223 	  note_flds->opt =
   1224 	    create_string_option (nodot, "tag", note_insn_name[c]);
   1225       }
   1226     note_union_tp = new_structure ("rtx_def_note_subunion", TYPE_UNION,
   1227 				   &lexer_line, note_flds, NULL, NULL);
   1228   }
   1229   /* Create a type to represent the various forms of SYMBOL_REF_DATA.  */
   1230   {
   1231     pair_p sym_flds;
   1232     sym_flds = create_field (NULL, tree_tp, "rt_tree");
   1233     sym_flds->opt = create_string_option (nodot, "default", "");
   1234     sym_flds = create_field (sym_flds, constant_tp, "rt_constant");
   1235     sym_flds->opt = create_string_option (nodot, "tag", "1");
   1236     symbol_union_tp = new_structure ("rtx_def_symbol_subunion", TYPE_UNION,
   1237 				     &lexer_line, sym_flds, NULL, NULL);
   1238   }
   1239   for (i = 0; i < NUM_RTX_CODE; i++)
   1240     {
   1241       pair_p subfields = NULL;
   1242       size_t aindex, nmindex;
   1243       const char *sname;
   1244       type_p substruct;
   1245       char *ftag;
   1246 
   1247       for (aindex = 0; aindex < strlen (rtx_format[i]); aindex++)
   1248 	{
   1249 	  type_p t;
   1250 	  const char *subname;
   1251 
   1252 	  switch (rtx_format[i][aindex])
   1253 	    {
   1254 	    case '*':
   1255 	    case 'i':
   1256 	    case 'n':
   1257 	    case 'w':
   1258 	    case 'r':
   1259 	      t = scalar_tp;
   1260 	      subname = "rt_int";
   1261 	      break;
   1262 
   1263 	    case 'p':
   1264 	      t = scalar_tp;
   1265 	      subname = "rt_subreg";
   1266 	      break;
   1267 
   1268 	    case '0':
   1269 	      if (i == MEM && aindex == 1)
   1270 		t = mem_attrs_tp, subname = "rt_mem";
   1271 	      else if (i == JUMP_INSN && aindex == 7)
   1272 		t = rtx_tp, subname = "rt_rtx";
   1273 	      else if (i == CODE_LABEL && aindex == 4)
   1274 		t = scalar_tp, subname = "rt_int";
   1275 	      else if (i == CODE_LABEL && aindex == 3)
   1276 		t = rtx_tp, subname = "rt_rtx";
   1277 	      else if (i == LABEL_REF && (aindex == 1 || aindex == 2))
   1278 		t = rtx_tp, subname = "rt_rtx";
   1279 	      else if (i == NOTE && aindex == 3)
   1280 		t = note_union_tp, subname = "";
   1281 	      else if (i == NOTE && aindex == 4)
   1282 		t = scalar_tp, subname = "rt_int";
   1283 	      else if (i == NOTE && aindex >= 6)
   1284 		t = scalar_tp, subname = "rt_int";
   1285 	      else if (i == ADDR_DIFF_VEC && aindex == 4)
   1286 		t = scalar_tp, subname = "rt_int";
   1287 	      else if (i == VALUE && aindex == 0)
   1288 		t = scalar_tp, subname = "rt_int";
   1289 	      else if (i == DEBUG_EXPR && aindex == 0)
   1290 		t = tree_tp, subname = "rt_tree";
   1291 	      else if (i == SYMBOL_REF && aindex == 1)
   1292 		t = symbol_union_tp, subname = "";
   1293 	      else if (i == JUMP_TABLE_DATA && aindex >= 4)
   1294 		t = scalar_tp, subname = "rt_int";
   1295 	      else if (i == BARRIER && aindex >= 2)
   1296 		t = scalar_tp, subname = "rt_int";
   1297 	      else if (i == ENTRY_VALUE && aindex == 0)
   1298 		t = rtx_tp, subname = "rt_rtx";
   1299 	      else
   1300 		{
   1301 		  error_at_line
   1302 		    (&lexer_line,
   1303 		     "rtx type `%s' has `0' in position %lu, can't handle",
   1304 		     rtx_name[i], (unsigned long) aindex);
   1305 		  t = &string_type;
   1306 		  subname = "rt_int";
   1307 		}
   1308 	      break;
   1309 
   1310 	    case 's':
   1311 	    case 'S':
   1312 	    case 'T':
   1313 	      t = &string_type;
   1314 	      subname = "rt_str";
   1315 	      break;
   1316 
   1317 	    case 'e':
   1318 	    case 'u':
   1319 	      t = rtx_tp;
   1320 	      subname = "rt_rtx";
   1321 	      break;
   1322 
   1323 	    case 'E':
   1324 	    case 'V':
   1325 	      t = rtvec_tp;
   1326 	      subname = "rt_rtvec";
   1327 	      break;
   1328 
   1329 	    case 't':
   1330 	      t = tree_tp;
   1331 	      subname = "rt_tree";
   1332 	      break;
   1333 
   1334 	    case 'B':
   1335 	      t = basic_block_tp;
   1336 	      subname = "rt_bb";
   1337 	      break;
   1338 
   1339 	    default:
   1340 	      error_at_line
   1341 		(&lexer_line,
   1342 		 "rtx type `%s' has `%c' in position %lu, can't handle",
   1343 		 rtx_name[i], rtx_format[i][aindex],
   1344 		 (unsigned long) aindex);
   1345 	      t = &string_type;
   1346 	      subname = "rt_int";
   1347 	      break;
   1348 	    }
   1349 
   1350 	  subfields = create_field (subfields, t,
   1351 				    xasprintf (".fld[%lu].%s",
   1352 					       (unsigned long) aindex,
   1353 					       subname));
   1354 	  subfields->opt = nodot;
   1355 	  if (t == note_union_tp)
   1356 	    subfields->opt =
   1357 	      create_string_option (subfields->opt, "desc",
   1358 				    "NOTE_KIND (&%0)");
   1359 	  if (t == symbol_union_tp)
   1360 	    subfields->opt =
   1361 	      create_string_option (subfields->opt, "desc",
   1362 				    "CONSTANT_POOL_ADDRESS_P (&%0)");
   1363 	}
   1364 
   1365       if (i == REG)
   1366 	subfields = create_field (subfields, reg_attrs_tp, "reg.attrs");
   1367 
   1368       if (i == SYMBOL_REF)
   1369 	{
   1370 	  /* Add the "block_sym" field if SYMBOL_REF_HAS_BLOCK_INFO_P
   1371 	     holds.  */
   1372 	  type_p field_tp = find_structure ("block_symbol", TYPE_STRUCT);
   1373 	  subfields
   1374 	    = create_optional_field (subfields, field_tp, "block_sym",
   1375 				     "SYMBOL_REF_HAS_BLOCK_INFO_P (&%0)");
   1376 	}
   1377 
   1378       sname = xasprintf ("rtx_def_%s", rtx_name[i]);
   1379       substruct = new_structure (sname, TYPE_STRUCT, &lexer_line, subfields,
   1380 				 NULL, NULL);
   1381 
   1382       ftag = xstrdup (rtx_name[i]);
   1383       for (nmindex = 0; nmindex < strlen (ftag); nmindex++)
   1384 	ftag[nmindex] = TOUPPER (ftag[nmindex]);
   1385       flds = create_field (flds, substruct, "");
   1386       flds->opt = create_string_option (nodot, "tag", ftag);
   1387     }
   1388   return new_structure ("rtx_def_subunion", TYPE_UNION, &lexer_line, flds,
   1389 			nodot, NULL);
   1390 }
   1391 
   1392 /* Handle `special("tree_exp")'.  This is a special case for
   1393    field `operands' of struct tree_exp, which although it claims to contain
   1394    pointers to trees, actually sometimes contains pointers to RTL too.
   1395    Passed T, the old type of the field, and OPT its options.  Returns
   1396    a new type for the field.  */
   1397 
   1398 static type_p
   1399 adjust_field_tree_exp (type_p t, options_p opt ATTRIBUTE_UNUSED)
   1400 {
   1401   pair_p flds;
   1402   options_p nodot;
   1403 
   1404   if (t->kind != TYPE_ARRAY)
   1405     {
   1406       error_at_line (&lexer_line,
   1407 		     "special `tree_exp' must be applied to an array");
   1408       return &string_type;
   1409     }
   1410 
   1411   nodot = create_string_option (NULL, "dot", "");
   1412 
   1413   flds = create_field (NULL, t, "");
   1414   flds->opt = create_string_option (nodot, "length",
   1415 				    "TREE_OPERAND_LENGTH ((tree) &%0)");
   1416   flds->opt = create_string_option (flds->opt, "default", "");
   1417 
   1418   return new_structure ("tree_exp_subunion", TYPE_UNION, &lexer_line, flds,
   1419 			nodot, NULL);
   1420 }
   1421 
   1422 /* Perform any special processing on a type T, about to become the type
   1423    of a field.  Return the appropriate type for the field.
   1424    At present:
   1425    - Converts pointer-to-char, with no length parameter, to TYPE_STRING;
   1426    - Similarly for arrays of pointer-to-char;
   1427    - Converts structures for which a parameter is provided to
   1428      TYPE_PARAM_STRUCT;
   1429    - Handles "special" options.
   1430 */
   1431 
   1432 type_p
   1433 adjust_field_type (type_p t, options_p opt)
   1434 {
   1435   int length_p = 0;
   1436   const int pointer_p = t->kind == TYPE_POINTER;
   1437 
   1438   for (; opt; opt = opt->next)
   1439     if (strcmp (opt->name, "length") == 0)
   1440       {
   1441 	if (length_p)
   1442 	  error_at_line (&lexer_line, "duplicate `%s' option", opt->name);
   1443 	if (t->u.p->kind == TYPE_SCALAR || t->u.p->kind == TYPE_STRING)
   1444 	  {
   1445 	    error_at_line (&lexer_line,
   1446 			   "option `%s' may not be applied to "
   1447 			   "arrays of atomic types", opt->name);
   1448 	  }
   1449 	length_p = 1;
   1450       }
   1451     else if (strcmp (opt->name, "special") == 0
   1452 	     && opt->kind == OPTION_STRING)
   1453       {
   1454 	const char *special_name = opt->info.string;
   1455 	if (strcmp (special_name, "tree_exp") == 0)
   1456 	  t = adjust_field_tree_exp (t, opt);
   1457 	else if (strcmp (special_name, "rtx_def") == 0)
   1458 	  t = adjust_field_rtx_def (t, opt);
   1459 	else
   1460 	  error_at_line (&lexer_line, "unknown special `%s'", special_name);
   1461       }
   1462 
   1463   if (!length_p
   1464       && pointer_p && t->u.p->kind == TYPE_SCALAR && t->u.p->u.scalar_is_char)
   1465     return &string_type;
   1466   if (t->kind == TYPE_ARRAY && t->u.a.p->kind == TYPE_POINTER
   1467       && t->u.a.p->u.p->kind == TYPE_SCALAR
   1468       && t->u.a.p->u.p->u.scalar_is_char)
   1469     return create_array (&string_type, t->u.a.len);
   1470 
   1471   return t;
   1472 }
   1473 
   1474 
   1476 static void set_gc_used_type (type_p, enum gc_used_enum, bool = false);
   1477 static void set_gc_used (pair_p);
   1478 
   1479 /* Handle OPT for set_gc_used_type.  */
   1480 
   1481 static void
   1482 process_gc_options (options_p opt, enum gc_used_enum level, int *maybe_undef,
   1483 		    int *length, int *skip, int *callback, type_p *nested_ptr)
   1484 {
   1485   options_p o;
   1486   for (o = opt; o; o = o->next)
   1487     if (strcmp (o->name, "ptr_alias") == 0 && level == GC_POINTED_TO
   1488 	&& o->kind == OPTION_TYPE)
   1489       set_gc_used_type (o->info.type,
   1490 			GC_POINTED_TO);
   1491     else if (strcmp (o->name, "maybe_undef") == 0)
   1492       *maybe_undef = 1;
   1493     else if (strcmp (o->name, "length") == 0)
   1494       *length = 1;
   1495     else if (strcmp (o->name, "skip") == 0)
   1496       *skip = 1;
   1497     else if (strcmp (o->name, "callback") == 0)
   1498       *callback = 1;
   1499     else if (strcmp (o->name, "nested_ptr") == 0
   1500 	     && o->kind == OPTION_NESTED)
   1501       *nested_ptr = ((const struct nested_ptr_data *) o->info.nested)->type;
   1502 }
   1503 
   1504 
   1505 /* Set the gc_used field of T to LEVEL, and handle the types it references.
   1506 
   1507    If ALLOWED_UNDEFINED_TYPES is true, types of kind TYPE_UNDEFINED
   1508    are set to GC_UNUSED.  Otherwise, an error is emitted for
   1509    TYPE_UNDEFINED types.  This is used to support user-defined
   1510    template types with non-type arguments.
   1511 
   1512    For instance, when we parse a template type with enum arguments
   1513    (e.g. MyType<AnotherType, EnumValue>), the parser created two
   1514    artificial fields for 'MyType', one for 'AnotherType', the other
   1515    one for 'EnumValue'.
   1516 
   1517    At the time that we parse this type we don't know that 'EnumValue'
   1518    is really an enum value, so the parser creates a TYPE_UNDEFINED
   1519    type for it.  Since 'EnumValue' is never resolved to a known
   1520    structure, it will stay with TYPE_UNDEFINED.
   1521 
   1522    Since 'MyType' is a TYPE_USER_STRUCT, we can simply ignore
   1523    'EnumValue'.  Generating marking code for it would cause
   1524    compilation failures since the marking routines assumes that
   1525    'EnumValue' is a type.  */
   1526 
   1527 static void
   1528 set_gc_used_type (type_p t, enum gc_used_enum level,
   1529 		  bool allow_undefined_types)
   1530 {
   1531   if (t->gc_used >= level)
   1532     return;
   1533 
   1534   t->gc_used = level;
   1535 
   1536   switch (t->kind)
   1537     {
   1538     case TYPE_STRUCT:
   1539     case TYPE_UNION:
   1540     case TYPE_USER_STRUCT:
   1541       {
   1542 	pair_p f;
   1543 	int dummy;
   1544 	type_p dummy2;
   1545 	bool allow_undefined_field_types = (t->kind == TYPE_USER_STRUCT);
   1546 
   1547 	process_gc_options (t->u.s.opt, level, &dummy, &dummy, &dummy, &dummy,
   1548 			    &dummy2);
   1549 
   1550 	if (t->u.s.base_class)
   1551 	  set_gc_used_type (t->u.s.base_class, level, allow_undefined_types);
   1552 	/* Anything pointing to a base class might actually be pointing
   1553 	   to a subclass.  */
   1554 	for (type_p subclass = t->u.s.first_subclass; subclass;
   1555 	     subclass = subclass->u.s.next_sibling_class)
   1556 	  set_gc_used_type (subclass, level, allow_undefined_types);
   1557 
   1558 	FOR_ALL_INHERITED_FIELDS(t, f)
   1559 	  {
   1560 	    int maybe_undef = 0;
   1561 	    int length = 0;
   1562 	    int skip = 0;
   1563 	    int callback = 0;
   1564 	    type_p nested_ptr = NULL;
   1565 	    process_gc_options (f->opt, level, &maybe_undef, &length, &skip,
   1566 				&callback, &nested_ptr);
   1567 
   1568 	    if (nested_ptr && f->type->kind == TYPE_POINTER)
   1569 	      set_gc_used_type (nested_ptr, GC_POINTED_TO);
   1570 	    else if (length && f->type->kind == TYPE_POINTER)
   1571 	      set_gc_used_type (f->type->u.p, GC_USED);
   1572 	    else if (maybe_undef && f->type->kind == TYPE_POINTER)
   1573 	      set_gc_used_type (f->type->u.p, GC_MAYBE_POINTED_TO);
   1574 	    else if (skip)
   1575 	      ;			/* target type is not used through this field */
   1576 	    else if (callback)
   1577 	      f->type = &callback_type;
   1578 	    else
   1579 	      set_gc_used_type (f->type, GC_USED, allow_undefined_field_types);
   1580 	  }
   1581 	break;
   1582       }
   1583 
   1584     case TYPE_UNDEFINED:
   1585       if (level > GC_UNUSED)
   1586 	{
   1587 	  if (!allow_undefined_types)
   1588 	    error_at_line (&t->u.s.line, "undefined type `%s'", t->u.s.tag);
   1589 	  t->gc_used = GC_UNUSED;
   1590 	}
   1591       break;
   1592 
   1593     case TYPE_POINTER:
   1594       set_gc_used_type (t->u.p, GC_POINTED_TO);
   1595       break;
   1596 
   1597     case TYPE_ARRAY:
   1598       set_gc_used_type (t->u.a.p, GC_USED);
   1599       break;
   1600 
   1601     case TYPE_LANG_STRUCT:
   1602       for (t = t->u.s.lang_struct; t; t = t->next)
   1603 	set_gc_used_type (t, level);
   1604       break;
   1605 
   1606     default:
   1607       break;
   1608     }
   1609 }
   1610 
   1611 /* Set the gc_used fields of all the types pointed to by VARIABLES.  */
   1612 
   1613 static void
   1614 set_gc_used (pair_p variables)
   1615 {
   1616   int nbvars = 0;
   1617   pair_p p;
   1618   for (p = variables; p; p = p->next)
   1619     {
   1620       set_gc_used_type (p->type, GC_USED);
   1621       nbvars++;
   1622     };
   1623   if (verbosity_level >= 2)
   1624     printf ("%s used %d GTY-ed variables\n", progname, nbvars);
   1625 }
   1626 
   1627 /* File mapping routines.  For each input file, there is one output .cc file
   1629    (but some output files have many input files), and there is one .h file
   1630    for the whole build.  */
   1631 
   1632 /* Output file handling.  */
   1633 
   1634 /* Create and return an outf_p for a new file for NAME, to be called
   1635    ONAME.  */
   1636 
   1637 static outf_p
   1638 create_file (const char *name, const char *oname)
   1639 {
   1640   static const char *const hdr[] = {
   1641     "   Copyright (C) 2004-2022 Free Software Foundation, Inc.\n",
   1642     "\n",
   1643     "This file is part of GCC.\n",
   1644     "\n",
   1645     "GCC is free software; you can redistribute it and/or modify it under\n",
   1646     "the terms of the GNU General Public License as published by the Free\n",
   1647     "Software Foundation; either version 3, or (at your option) any later\n",
   1648     "version.\n",
   1649     "\n",
   1650     "GCC is distributed in the hope that it will be useful, but WITHOUT ANY\n",
   1651     "WARRANTY; without even the implied warranty of MERCHANTABILITY or\n",
   1652     "FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n",
   1653     "for more details.\n",
   1654     "\n",
   1655     "You should have received a copy of the GNU General Public License\n",
   1656     "along with GCC; see the file COPYING3.  If not see\n",
   1657     "<http://www.gnu.org/licenses/>.  */\n",
   1658     "\n",
   1659     "/* This file is machine generated.  Do not edit.  */\n"
   1660   };
   1661   outf_p f;
   1662   size_t i;
   1663 
   1664   gcc_assert (name != NULL);
   1665   gcc_assert (oname != NULL);
   1666   f = XCNEW (struct outf);
   1667   f->next = output_files;
   1668   f->name = oname;
   1669   output_files = f;
   1670 
   1671   oprintf (f, "/* Type information for %s.\n", name);
   1672   for (i = 0; i < ARRAY_SIZE (hdr); i++)
   1673     oprintf (f, "%s", hdr[i]);
   1674   return f;
   1675 }
   1676 
   1677 /* Print, like fprintf, to O.
   1678    N.B. You might think this could be implemented more efficiently
   1679    with vsnprintf().  Unfortunately, there are C libraries that
   1680    provide that function but without the C99 semantics for its return
   1681    value, making it impossible to know how much space is required.  */
   1682 void
   1683 oprintf (outf_p o, const char *format, ...)
   1684 {
   1685   char *s;
   1686   size_t slength;
   1687   va_list ap;
   1688 
   1689   /* In plugin mode, the O could be a NULL pointer, so avoid crashing
   1690      in that case.  */
   1691   if (!o)
   1692     return;
   1693 
   1694   va_start (ap, format);
   1695   slength = vasprintf (&s, format, ap);
   1696   if (s == NULL || (int) slength < 0)
   1697     fatal ("out of memory");
   1698   va_end (ap);
   1699 
   1700   if (o->bufused + slength > o->buflength)
   1701     {
   1702       size_t new_len = o->buflength;
   1703       if (new_len == 0)
   1704 	new_len = 1024;
   1705       do
   1706 	{
   1707 	  new_len *= 2;
   1708 	}
   1709       while (o->bufused + slength >= new_len);
   1710       o->buf = XRESIZEVEC (char, o->buf, new_len);
   1711       o->buflength = new_len;
   1712     }
   1713   memcpy (o->buf + o->bufused, s, slength);
   1714   o->bufused += slength;
   1715   free (s);
   1716 }
   1717 
   1718 /* Open the global header file and the language-specific header files.  */
   1719 
   1720 static void
   1721 open_base_files (void)
   1722 {
   1723   size_t i;
   1724 
   1725   if (nb_plugin_files > 0 && plugin_files)
   1726     return;
   1727 
   1728   header_file = create_file ("GCC", "gtype-desc.h");
   1729 
   1730   base_files = XNEWVEC (outf_p, num_lang_dirs);
   1731 
   1732   for (i = 0; i < num_lang_dirs; i++)
   1733     base_files[i] = create_file (lang_dir_names[i],
   1734 				 xasprintf ("gtype-%s.h", lang_dir_names[i]));
   1735 
   1736   /* gtype-desc.cc is a little special, so we create it here.  */
   1737   {
   1738     /* The order of files here matters very much.  */
   1739     static const char *const ifiles[] = {
   1740       "config.h", "system.h", "coretypes.h",
   1741       "backend.h", "predict.h", "tree.h",
   1742       "rtl.h", "gimple.h", "fold-const.h", "insn-codes.h", "splay-tree.h",
   1743       "alias.h", "insn-config.h", "flags.h", "expmed.h", "dojump.h",
   1744       "explow.h", "calls.h", "memmodel.h", "emit-rtl.h", "varasm.h",
   1745       "stmt.h", "expr.h", "alloc-pool.h", "cselib.h", "insn-addr.h",
   1746       "optabs.h", "libfuncs.h", "debug.h", "internal-fn.h", "gimple-fold.h",
   1747       "value-range.h",
   1748       "tree-eh.h", "gimple-iterator.h", "gimple-ssa.h", "tree-cfg.h",
   1749       "tree-vrp.h", "tree-phinodes.h", "ssa-iterators.h", "stringpool.h",
   1750       "tree-ssanames.h", "tree-ssa-loop.h", "tree-ssa-loop-ivopts.h",
   1751       "tree-ssa-loop-manip.h", "tree-ssa-loop-niter.h", "tree-into-ssa.h",
   1752       "tree-dfa.h", "tree-ssa.h", "reload.h", "cpplib.h", "tree-chrec.h",
   1753       "except.h", "output.h",  "cfgloop.h", "target.h", "lto-streamer.h",
   1754       "target-globals.h", "ipa-ref.h", "cgraph.h", "symbol-summary.h",
   1755       "ipa-prop.h", "ipa-fnsummary.h", "dwarf2out.h", "omp-general.h",
   1756       "omp-offload.h", "ipa-modref-tree.h", "ipa-modref.h", "symtab-thunks.h",
   1757       "symtab-clones.h", "diagnostic-spec.h", "ctfc.h",
   1758       NULL
   1759     };
   1760     const char *const *ifp;
   1761     outf_p gtype_desc_c;
   1762 
   1763     gtype_desc_c = create_file ("GCC", "gtype-desc.cc");
   1764     for (ifp = ifiles; *ifp; ifp++)
   1765       oprintf (gtype_desc_c, "#include \"%s\"\n", *ifp);
   1766     for (int j = 0; j < (int) num_build_headers; j++)
   1767       oprintf (gtype_desc_c, "#include \"%s\"\n", build_headers[j]);
   1768 
   1769     /* Make sure we handle "cfun" specially.  */
   1770     oprintf (gtype_desc_c, "\n/* See definition in function.h.  */\n");
   1771     oprintf (gtype_desc_c, "#undef cfun\n");
   1772 
   1773     oprintf (gtype_desc_c,
   1774 	     "\n"
   1775 	     "/* Types with a \"gcc::\" namespace have it stripped\n"
   1776 	     "   during gengtype parsing.  Provide a \"using\" directive\n"
   1777 	     "   to ensure that the fully-qualified types are found.  */\n"
   1778 	     "using namespace gcc;\n");
   1779   }
   1780 }
   1781 
   1782 /* For INPF an input file, return the real basename of INPF, with all
   1783    the directory components skipped.  */
   1784 
   1785 static const char *
   1786 get_file_realbasename (const input_file *inpf)
   1787 {
   1788   return lbasename (get_input_file_name (inpf));
   1789 }
   1790 
   1791 /* For INPF a filename, return the relative path to INPF from
   1792    $(srcdir) if the latter is a prefix in INPF, NULL otherwise.  */
   1793 
   1794 const char *
   1795 get_file_srcdir_relative_path (const input_file *inpf)
   1796 {
   1797   const char *f = get_input_file_name (inpf);
   1798   if (strlen (f) > srcdir_len
   1799       && IS_DIR_SEPARATOR (f[srcdir_len])
   1800       && strncmp (f, srcdir, srcdir_len) == 0)
   1801     return f + srcdir_len + 1;
   1802   else
   1803     return NULL;
   1804 }
   1805 
   1806 /*  For INPF an input_file, return the relative path to INPF from
   1807     $(srcdir) if the latter is a prefix in INPF, or the real basename
   1808     of INPF otherwise. */
   1809 
   1810 static const char *
   1811 get_file_basename (const input_file *inpf)
   1812 {
   1813   const char *srcdir_path = get_file_srcdir_relative_path (inpf);
   1814 
   1815   return (srcdir_path != NULL) ? srcdir_path : get_file_realbasename (inpf);
   1816 }
   1817 
   1818 /* For F a filename, return the lang_dir_names relative index of the language
   1819    directory that is a prefix in F, if any, -1 otherwise.  */
   1820 
   1821 static int
   1822 get_prefix_langdir_index (const char *f)
   1823 {
   1824   size_t f_len = strlen (f);
   1825   size_t lang_index;
   1826 
   1827   for (lang_index = 0; lang_index < num_lang_dirs; lang_index++)
   1828     {
   1829       const char *langdir = lang_dir_names[lang_index];
   1830       size_t langdir_len = strlen (langdir);
   1831 
   1832       if (f_len > langdir_len
   1833 	  && IS_DIR_SEPARATOR (f[langdir_len])
   1834 	  && memcmp (f, langdir, langdir_len) == 0)
   1835 	return lang_index;
   1836     }
   1837 
   1838   return -1;
   1839 }
   1840 
   1841 /* For INPF an input file, return the name of language directory where
   1842    F is located, if any, NULL otherwise.  */
   1843 
   1844 static const char *
   1845 get_file_langdir (const input_file *inpf)
   1846 {
   1847   /* Get the relative path to INPF from $(srcdir) and find the
   1848      language by comparing the prefix with language directory names.
   1849      If INPF is not even srcdir relative, no point in looking
   1850      further.  */
   1851 
   1852   int lang_index;
   1853   const char *srcdir_relative_path = get_file_srcdir_relative_path (inpf);
   1854   const char *r;
   1855 
   1856   if (!srcdir_relative_path)
   1857     return NULL;
   1858 
   1859   lang_index = get_prefix_langdir_index (srcdir_relative_path);
   1860   if (lang_index < 0 && startswith (srcdir_relative_path, "c-family"))
   1861     r = "c-family";
   1862   else if (lang_index >= 0)
   1863     r = lang_dir_names[lang_index];
   1864   else
   1865     r = NULL;
   1866 
   1867   return r;
   1868 }
   1869 
   1870 /* The gt- output file name for INPF.  */
   1871 
   1872 static const char *
   1873 get_file_gtfilename (const input_file *inpf)
   1874 {
   1875   /* Cook up an initial version of the gt- file name from the file real
   1876      basename and the language name, if any.  */
   1877 
   1878   const char *basename = get_file_realbasename (inpf);
   1879   const char *langdir = get_file_langdir (inpf);
   1880 
   1881   char *result =
   1882     (langdir ? xasprintf ("gt-%s-%s", langdir, basename)
   1883      : xasprintf ("gt-%s", basename));
   1884 
   1885   /* Then replace all non alphanumerics characters by '-' and change the
   1886      extension to ".h".  We expect the input filename extension was at least
   1887      one character long.  */
   1888 
   1889   char *s = result;
   1890 
   1891   for (; *s != '.'; s++)
   1892     if (!ISALNUM (*s) && *s != '-')
   1893       *s = '-';
   1894 
   1895   memcpy (s, ".h", sizeof (".h"));
   1896 
   1897   return result;
   1898 }
   1899 
   1900 /* Each input_file has its associated output file outf_p.  The
   1901    association is computed by the function
   1902    get_output_file_with_visibility.  The associated file is cached
   1903    inside input_file in its inpoutf field, so is really computed only
   1904    once.  Associated output file paths (i.e. output_name-s) are
   1905    computed by a rule based regexp machinery, using the files_rules
   1906    array of struct file_rule_st.  A for_name is also computed, giving
   1907    the source file name for which the output_file is generated; it is
   1908    often the last component of the input_file path.  */
   1909 
   1910 
   1911 /*
   1912  Regexpr machinery to compute the output_name and for_name-s of each
   1913  input_file.  We have a sequence of file rules which gives the POSIX
   1914  extended regular expression to match an input file path, and two
   1915  transformed strings for the corresponding output_name and the
   1916  corresponding for_name.  The transformed string contain dollars: $0
   1917  is replaced by the entire match, $1 is replaced by the substring
   1918  matching the first parenthesis in the regexp, etc.  And $$ is replaced
   1919  by a single verbatim dollar.  The rule order is important.  The
   1920  general case is last, and the particular cases should come before.
   1921  An action routine can, when needed, update the out_name & for_name
   1922  and/or return the appropriate output file.  It is invoked only when a
   1923  rule is triggered.  When a rule is triggered, the output_name and
   1924  for_name are computed using their transform string in while $$, $0,
   1925  $1, ... are suitably replaced.  If there is an action, it is called.
   1926  In some few cases, the action can directly return the outf_p, but
   1927  usually it just updates the output_name and for_name so should free
   1928  them before replacing them.  The get_output_file_with_visibility
   1929  function creates an outf_p only once per each output_name, so it
   1930  scans the output_files list for previously seen output file names.
   1931  */
   1932 
   1933 /* Signature of actions in file rules.  */
   1934 typedef outf_p (frul_actionrout_t) (input_file*, char**, char**);
   1935 
   1936 
   1937 struct file_rule_st {
   1938   const char* frul_srcexpr;	/* Source string for regexp.  */
   1939   int frul_rflags;		/* Flags passed to regcomp, usually
   1940 				 * REG_EXTENDED.  */
   1941   regex_t* frul_re;		/* Compiled regular expression
   1942 				   obtained by regcomp.  */
   1943   const char* frul_tr_out;	/* Transformation string for making
   1944 				 * the output_name, with $1 ... $9 for
   1945 				 * subpatterns and $0 for the whole
   1946 				 * matched filename.  */
   1947   const char* frul_tr_for;	/* Tranformation string for making the
   1948 				   for_name.  */
   1949   frul_actionrout_t* frul_action; /* The action, if non null, is
   1950 				   * called once the rule matches, on
   1951 				   * the transformed out_name &
   1952 				   * for_name.  It could change them
   1953 				   * and/or give the output file.  */
   1954 };
   1955 
   1956 /* File rule action handling *.h files.  */
   1957 static outf_p header_dot_h_frul (input_file*, char**, char**);
   1958 
   1959 /* File rule action handling *.cc files.  */
   1960 static outf_p source_dot_cc_frul (input_file*, char**, char**);
   1961 
   1962 #define NULL_REGEX (regex_t*)0
   1963 
   1964 /* The prefix in our regexp-s matching the directory.  */
   1965 #define DIR_PREFIX_REGEX "^(([^/]*/)*)"
   1966 
   1967 #define NULL_FRULACT (frul_actionrout_t*)0
   1968 
   1969 /* The array of our rules governing file name generation.  Rules order
   1970    matters, so change with extreme care!  */
   1971 
   1972 struct file_rule_st files_rules[] = {
   1973   /* The general rule assumes that files in subdirectories belong to a
   1974      particular front-end, and files not in subdirectories are shared.
   1975      The following rules deal with exceptions - files that are in
   1976      subdirectories and yet are shared, and files that are top-level,
   1977      but are not shared.  */
   1978 
   1979   /* the c-family/ source directory is special.  */
   1980   { DIR_PREFIX_REGEX "c-family/([[:alnum:]_-]*)\\.cc$",
   1981     REG_EXTENDED, NULL_REGEX,
   1982     "gt-c-family-$3.h", "c-family/$3.cc", NULL_FRULACT},
   1983 
   1984   { DIR_PREFIX_REGEX "c-family/([[:alnum:]_-]*)\\.h$",
   1985     REG_EXTENDED, NULL_REGEX,
   1986     "gt-c-family-$3.h", "c-family/$3.h", NULL_FRULACT},
   1987 
   1988   /* Both c-lang.h & c-tree.h gives gt-c-c-decl.h for c-decl.cc !  */
   1989   { DIR_PREFIX_REGEX "c/c-lang\\.h$",
   1990     REG_EXTENDED, NULL_REGEX, "gt-c-c-decl.h", "c/c-decl.cc", NULL_FRULACT},
   1991 
   1992   { DIR_PREFIX_REGEX "c/c-tree\\.h$",
   1993     REG_EXTENDED, NULL_REGEX, "gt-c-c-decl.h", "c/c-decl.cc", NULL_FRULACT},
   1994 
   1995   /* cp/cp-tree.h gives gt-cp-tree.h for cp/tree.cc !  */
   1996   { DIR_PREFIX_REGEX "cp/cp-tree\\.h$",
   1997     REG_EXTENDED, NULL_REGEX,
   1998     "gt-cp-tree.h", "cp/tree.cc", NULL_FRULACT },
   1999 
   2000   /* cp/decl.h & cp/decl.cc gives gt-cp-decl.h for cp/decl.cc !  */
   2001   { DIR_PREFIX_REGEX "cp/decl\\.[ch]$",
   2002     REG_EXTENDED, NULL_REGEX,
   2003     "gt-cp-decl.h", "cp/decl.cc", NULL_FRULACT },
   2004 
   2005   /* cp/name-lookup.h gives gt-cp-name-lookup.h for cp/name-lookup.cc !  */
   2006   { DIR_PREFIX_REGEX "cp/name-lookup\\.h$",
   2007     REG_EXTENDED, NULL_REGEX,
   2008     "gt-cp-name-lookup.h", "cp/name-lookup.cc", NULL_FRULACT },
   2009 
   2010   /* cp/parser.h gives gt-cp-parser.h for cp/parser.cc !  */
   2011   { DIR_PREFIX_REGEX "cp/parser\\.h$",
   2012     REG_EXTENDED, NULL_REGEX,
   2013     "gt-cp-parser.h", "cp/parser.cc", NULL_FRULACT },
   2014 
   2015   /* objc/objc-act.h gives gt-objc-objc-act.h for objc/objc-act.cc !  */
   2016   { DIR_PREFIX_REGEX "objc/objc-act\\.h$",
   2017     REG_EXTENDED, NULL_REGEX,
   2018     "gt-objc-objc-act.h", "objc/objc-act.cc", NULL_FRULACT },
   2019 
   2020   /* objc/objc-map.h gives gt-objc-objc-map.h for objc/objc-map.cc !  */
   2021   { DIR_PREFIX_REGEX "objc/objc-map\\.h$",
   2022     REG_EXTENDED, NULL_REGEX,
   2023     "gt-objc-objc-map.h", "objc/objc-map.cc", NULL_FRULACT },
   2024 
   2025   /* General cases.  For header *.h and *.cc files, we
   2026    * need special actions to handle the language.  */
   2027 
   2028   /* Source *.cc files are using get_file_gtfilename to compute their
   2029      output_name and get_file_basename to compute their for_name
   2030      through the source_dot_cc_frul action.  */
   2031   { DIR_PREFIX_REGEX "([[:alnum:]_-]*)\\.cc$",
   2032     REG_EXTENDED, NULL_REGEX, "gt-$3.h", "$3.cc", source_dot_cc_frul},
   2033 
   2034   /* Common header files get "gtype-desc.cc" as their output_name,
   2035    * while language specific header files are handled specially.  So
   2036    * we need the header_dot_h_frul action.  */
   2037   { DIR_PREFIX_REGEX "([[:alnum:]_-]*)\\.h$",
   2038     REG_EXTENDED, NULL_REGEX, "gt-$3.h", "$3.h", header_dot_h_frul},
   2039 
   2040   { DIR_PREFIX_REGEX "([[:alnum:]_-]*)\\.in$",
   2041     REG_EXTENDED, NULL_REGEX, "gt-$3.h", "$3.in", NULL_FRULACT},
   2042 
   2043   /* Mandatory null last entry signaling end of rules.  */
   2044   {NULL, 0, NULL_REGEX, NULL, NULL, NULL_FRULACT}
   2045 };
   2046 
   2047 /* Special file rules action for handling *.h header files.  It gives
   2048    "gtype-desc.cc" for common headers and corresponding output
   2049    files for language-specific header files.  */
   2050 static outf_p
   2051 header_dot_h_frul (input_file* inpf, char**poutname,
   2052 		   char**pforname ATTRIBUTE_UNUSED)
   2053 {
   2054   const char *basename = 0;
   2055   int lang_index = 0;
   2056   DBGPRINTF ("inpf %p inpname %s outname %s forname %s",
   2057 	     (void*) inpf, get_input_file_name (inpf),
   2058 	     *poutname, *pforname);
   2059   basename = get_file_basename (inpf);
   2060   lang_index = get_prefix_langdir_index (basename);
   2061   DBGPRINTF ("basename %s lang_index %d", basename, lang_index);
   2062 
   2063   if (lang_index >= 0)
   2064     {
   2065       /* The header is language specific.  Given output_name &
   2066 	 for_name remains unchanged.  The base_files array gives the
   2067 	 outf_p.  */
   2068       DBGPRINTF ("header_dot_h found language specific @ %p '%s'",
   2069 		 (void*) base_files[lang_index],
   2070 		 (base_files[lang_index])->name);
   2071       return base_files[lang_index];
   2072     }
   2073   else
   2074     {
   2075       /* The header is common to all front-end languages.  So
   2076 	 output_name is "gtype-desc.cc" file.  The calling function
   2077 	 get_output_file_with_visibility will find its outf_p.  */
   2078       free (*poutname);
   2079       *poutname = xstrdup ("gtype-desc.cc");
   2080       DBGPRINTF ("special 'gtype-desc.cc' for inpname %s",
   2081 		 get_input_file_name (inpf));
   2082       return NULL;
   2083     }
   2084 }
   2085 
   2086 
   2087 /* Special file rules action for handling *.cc source files using
   2088  * get_file_gtfilename to compute their output_name and
   2089  * get_file_basename to compute their for_name.  The output_name is
   2090  * gt-<LANG>-<BASE>.h for language specific source files, and
   2091  * gt-<BASE>.h for common source files.  */
   2092 static outf_p
   2093 source_dot_cc_frul (input_file* inpf, char**poutname, char**pforname)
   2094 {
   2095   char *newbasename = CONST_CAST (char*, get_file_basename (inpf));
   2096   char *newoutname = CONST_CAST (char*, get_file_gtfilename (inpf));
   2097   DBGPRINTF ("inpf %p inpname %s original outname %s forname %s",
   2098 	     (void*) inpf, get_input_file_name (inpf),
   2099 	     *poutname, *pforname);
   2100   DBGPRINTF ("newoutname %s", newoutname);
   2101   DBGPRINTF ("newbasename %s", newbasename);
   2102   free (*poutname);
   2103   free (*pforname);
   2104   *poutname = newoutname;
   2105   *pforname = newbasename;
   2106   return NULL;
   2107 }
   2108 
   2109 /* Utility function for get_output_file_with_visibility which returns
   2110  * a malloc-ed substituted string using TRS on matching of the FILNAM
   2111  * file name, using the PMATCH array.  */
   2112 static char*
   2113 matching_file_name_substitute (const char *filnam, regmatch_t pmatch[10],
   2114 			       const char *trs)
   2115 {
   2116   struct obstack str_obstack;
   2117   char *str = NULL;
   2118   char *rawstr = NULL;
   2119   const char *pt = NULL;
   2120   DBGPRINTF ("filnam %s", filnam);
   2121   obstack_init (&str_obstack);
   2122   for (pt = trs; *pt; pt++) {
   2123     char c = *pt;
   2124     if (c == '$')
   2125       {
   2126 	if (pt[1] == '$')
   2127 	  {
   2128 	    /* A double dollar $$ is substituted by a single verbatim
   2129 	       dollar, but who really uses dollar signs in file
   2130 	       paths? */
   2131 	    obstack_1grow (&str_obstack, '$');
   2132 	  }
   2133 	else if (ISDIGIT (pt[1]))
   2134 	  {
   2135 	    /* Handle $0 $1 ... $9 by appropriate substitution.  */
   2136 	    int dolnum = pt[1] - '0';
   2137 	    int so = pmatch[dolnum].rm_so;
   2138 	    int eo = pmatch[dolnum].rm_eo;
   2139 	    DBGPRINTF ("so=%d eo=%d dolnum=%d", so, eo, dolnum);
   2140 	    if (so>=0 && eo>=so)
   2141 	      obstack_grow (&str_obstack, filnam + so, eo - so);
   2142 	  }
   2143 	else
   2144 	  {
   2145 	    /* This can happen only when files_rules is buggy! */
   2146 	    gcc_unreachable ();
   2147 	  }
   2148 	/* Always skip the character after the dollar.  */
   2149 	pt++;
   2150       }
   2151     else
   2152       obstack_1grow (&str_obstack, c);
   2153   }
   2154   obstack_1grow (&str_obstack, '\0');
   2155   rawstr = XOBFINISH (&str_obstack, char *);
   2156   str = xstrdup (rawstr);
   2157   obstack_free (&str_obstack, NULL);
   2158   DBGPRINTF ("matched replacement %s", str);
   2159   rawstr = NULL;
   2160   return str;
   2161 }
   2162 
   2163 
   2164 /* An output file, suitable for definitions, that can see declarations
   2165    made in INPF and is linked into every language that uses INPF.
   2166    Since the result is cached inside INPF, that argument cannot be
   2167    declared constant, but is "almost" constant. */
   2168 
   2169 outf_p
   2170 get_output_file_with_visibility (input_file *inpf)
   2171 {
   2172   outf_p r;
   2173   char *for_name = NULL;
   2174   char *output_name = NULL;
   2175   const char* inpfname;
   2176 
   2177   /* This can happen when we need a file with visibility on a
   2178      structure that we've never seen.  We have to just hope that it's
   2179      globally visible.  */
   2180   if (inpf == NULL)
   2181     inpf = system_h_file;
   2182 
   2183   /* The result is cached in INPF, so return it if already known.  */
   2184   if (inpf->inpoutf)
   2185     return inpf->inpoutf;
   2186 
   2187   /* In plugin mode, return NULL unless the input_file is one of the
   2188      plugin_files.  */
   2189   if (plugin_files)
   2190     {
   2191       size_t i;
   2192       for (i = 0; i < nb_plugin_files; i++)
   2193 	if (inpf == plugin_files[i])
   2194 	  {
   2195 	    inpf->inpoutf = plugin_output;
   2196 	    return plugin_output;
   2197 	  }
   2198 
   2199       return NULL;
   2200     }
   2201 
   2202   inpfname = get_input_file_name (inpf);
   2203 
   2204   /* Try each rule in sequence in files_rules until one is triggered. */
   2205   {
   2206     int rulix = 0;
   2207     DBGPRINTF ("passing input file @ %p named %s through the files_rules",
   2208 	       (void*) inpf, inpfname);
   2209 
   2210     for (; files_rules[rulix].frul_srcexpr != NULL; rulix++)
   2211       {
   2212 	DBGPRINTF ("rulix#%d srcexpr %s",
   2213 		   rulix, files_rules[rulix].frul_srcexpr);
   2214 
   2215 	if (!files_rules[rulix].frul_re)
   2216 	  {
   2217 	    /* Compile the regexpr lazily.  */
   2218 	    int err = 0;
   2219 	    files_rules[rulix].frul_re = XCNEW (regex_t);
   2220 	    err = regcomp (files_rules[rulix].frul_re,
   2221 			   files_rules[rulix].frul_srcexpr,
   2222 			   files_rules[rulix].frul_rflags);
   2223 	    if (err)
   2224 	      {
   2225 		/* The regular expression compilation fails only when
   2226 		   file_rules is buggy.  */
   2227 		gcc_unreachable ();
   2228 	      }
   2229 	  }
   2230 
   2231 	output_name = NULL;
   2232 	for_name = NULL;
   2233 
   2234 	/* Match the regexpr and trigger the rule if matched.  */
   2235 	{
   2236 	  /* We have exactly ten pmatch-s, one for each $0, $1, $2,
   2237 	     $3, ... $9.  */
   2238 	  regmatch_t pmatch[10];
   2239 	  memset (pmatch, 0, sizeof (pmatch));
   2240 	  if (!regexec (files_rules[rulix].frul_re,
   2241 			inpfname, 10, pmatch, 0))
   2242 	    {
   2243 	      DBGPRINTF ("input @ %p filename %s matched rulix#%d pattern %s",
   2244 			 (void*) inpf, inpfname, rulix,
   2245 			 files_rules[rulix].frul_srcexpr);
   2246 	      for_name =
   2247 		matching_file_name_substitute (inpfname, pmatch,
   2248 					       files_rules[rulix].frul_tr_for);
   2249 	      DBGPRINTF ("for_name %s", for_name);
   2250 	      output_name =
   2251 		matching_file_name_substitute (inpfname, pmatch,
   2252 					       files_rules[rulix].frul_tr_out);
   2253 	      DBGPRINTF ("output_name %s", output_name);
   2254 	      if (files_rules[rulix].frul_action)
   2255 		{
   2256 		  /* Invoke our action routine.  */
   2257 		  outf_p of = NULL;
   2258 		  DBGPRINTF ("before action rulix#%d output_name %s for_name %s",
   2259 			     rulix, output_name, for_name);
   2260 		  of =
   2261 		    (files_rules[rulix].frul_action) (inpf,
   2262 						      &output_name, &for_name);
   2263 		  DBGPRINTF ("after action rulix#%d of=%p output_name %s for_name %s",
   2264 			     rulix, (void*)of, output_name, for_name);
   2265 		  /* If the action routine returned something, give it back
   2266 		     immediately and cache it in inpf.  */
   2267 		  if (of)
   2268 		    {
   2269 		      inpf->inpoutf = of;
   2270 		      return of;
   2271 		    }
   2272 		}
   2273 	      /* The rule matched, and had no action, or that action did
   2274 		 not return any output file but could have changed the
   2275 		 output_name or for_name.  We break out of the loop on the
   2276 		 files_rules.  */
   2277 	      break;
   2278 	    }
   2279 	  else
   2280 	    {
   2281 	      /* The regexpr did not match.  */
   2282 	      DBGPRINTF ("rulix#%d did not match %s pattern %s",
   2283 			 rulix, inpfname, files_rules[rulix].frul_srcexpr);
   2284 	      continue;
   2285 	    }
   2286 	}
   2287       }
   2288   }
   2289   if (!output_name || !for_name)
   2290     {
   2291       /* This should not be possible, and could only happen if the
   2292 	 files_rules is incomplete or buggy.  */
   2293       fatal ("failed to compute output name for %s", inpfname);
   2294     }
   2295 
   2296   /* Look through to see if we've ever seen this output filename
   2297      before.  If found, cache the result in inpf.  */
   2298   for (r = output_files; r; r = r->next)
   2299     if (filename_cmp (r->name, output_name) == 0)
   2300       {
   2301 	inpf->inpoutf = r;
   2302 	DBGPRINTF ("found r @ %p for output_name %s for_name %s", (void*)r,
   2303 		   output_name, for_name);
   2304 	return r;
   2305       }
   2306 
   2307   /* If not found, create it, and cache it in inpf.  */
   2308   r = create_file (for_name, output_name);
   2309 
   2310   gcc_assert (r && r->name);
   2311   DBGPRINTF ("created r @ %p for output_name %s for_name %s", (void*) r,
   2312 	     output_name, for_name);
   2313   inpf->inpoutf = r;
   2314   return r;
   2315 
   2316 
   2317 }
   2318 
   2319 /* The name of an output file, suitable for definitions, that can see
   2320    declarations made in INPF and is linked into every language that
   2321    uses INPF.  */
   2322 
   2323 const char *
   2324 get_output_file_name (input_file* inpf)
   2325 {
   2326   outf_p o = get_output_file_with_visibility (inpf);
   2327   if (o)
   2328     return o->name;
   2329   return NULL;
   2330 }
   2331 
   2332 /* Check if existing file is equal to the in memory buffer. */
   2333 
   2334 static bool
   2335 is_file_equal (outf_p of)
   2336 {
   2337   FILE *newfile = fopen (of->name, "r");
   2338   size_t i;
   2339   bool equal;
   2340   if (newfile == NULL)
   2341     return false;
   2342 
   2343   equal = true;
   2344   for (i = 0; i < of->bufused; i++)
   2345     {
   2346       int ch;
   2347       ch = fgetc (newfile);
   2348       if (ch == EOF || ch != (unsigned char) of->buf[i])
   2349 	{
   2350 	  equal = false;
   2351 	  break;
   2352 	}
   2353     }
   2354   if (equal && EOF != fgetc (newfile))
   2355     equal = false;
   2356   fclose (newfile);
   2357   return equal;
   2358 }
   2359 
   2360 /* Copy the output to its final destination,
   2361    but don't unnecessarily change modification times.  */
   2362 
   2363 static void
   2364 close_output_files (void)
   2365 {
   2366   int nbwrittenfiles = 0;
   2367   outf_p of;
   2368 
   2369   for (of = output_files; of; of = of->next)
   2370     {
   2371       if (!is_file_equal (of))
   2372 	{
   2373 	  FILE *newfile = NULL;
   2374 	  char *backupname = NULL;
   2375 	  /* Back up the old version of the output file gt-FOO.cc as
   2376 	     BACKUPDIR/gt-FOO.cc~ if we have a backup directory.  */
   2377 	  if (backup_dir)
   2378 	    {
   2379 	      backupname = concat (backup_dir, "/",
   2380 				   lbasename (of->name), "~", NULL);
   2381 	      if (!access (of->name, F_OK) && rename (of->name, backupname))
   2382 		fatal ("failed to back up %s as %s: %s",
   2383 		       of->name, backupname, xstrerror (errno));
   2384 	    }
   2385 
   2386 	  newfile = fopen (of->name, "w");
   2387 	  if (newfile == NULL)
   2388 	    fatal ("opening output file %s: %s", of->name, xstrerror (errno));
   2389 	  if (fwrite (of->buf, 1, of->bufused, newfile) != of->bufused)
   2390 	    fatal ("writing output file %s: %s", of->name, xstrerror (errno));
   2391 	  if (fclose (newfile) != 0)
   2392 	    fatal ("closing output file %s: %s", of->name, xstrerror (errno));
   2393 	  nbwrittenfiles++;
   2394 	  if (verbosity_level >= 2 && backupname)
   2395 	    printf ("%s wrote #%-3d %s backed-up in %s\n",
   2396 		    progname, nbwrittenfiles, of->name, backupname);
   2397 	  else if (verbosity_level >= 1)
   2398 	    printf ("%s write #%-3d %s\n", progname, nbwrittenfiles, of->name);
   2399 	  free (backupname);
   2400 	}
   2401       else
   2402 	{
   2403 	  /* output file remains unchanged. */
   2404 	  if (verbosity_level >= 2)
   2405 	    printf ("%s keep %s\n", progname, of->name);
   2406 	}
   2407       free (of->buf);
   2408       of->buf = NULL;
   2409       of->bufused = of->buflength = 0;
   2410     }
   2411   if (verbosity_level >= 1)
   2412     printf ("%s wrote %d files.\n", progname, nbwrittenfiles);
   2413 }
   2414 
   2415 struct flist
   2417 {
   2418   struct flist *next;
   2419   int started_p;
   2420   const input_file* file;
   2421   outf_p f;
   2422 };
   2423 
   2424 struct walk_type_data;
   2425 
   2426 /* For scalars and strings, given the item in 'val'.
   2427    For structures, given a pointer to the item in 'val'.
   2428    For misc. pointers, given the item in 'val'.
   2429 */
   2430 typedef void (*process_field_fn) (type_p f, const struct walk_type_data * p);
   2431 typedef void (*func_name_fn) (type_p s, const struct walk_type_data * p);
   2432 
   2433 /* Parameters for write_types.  */
   2434 
   2435 struct write_types_data
   2436 {
   2437   const char *prefix;
   2438   const char *param_prefix;
   2439   const char *subfield_marker_routine;
   2440   const char *marker_routine;
   2441   const char *reorder_note_routine;
   2442   const char *comment;
   2443   enum write_types_kinds kind;
   2444 };
   2445 
   2446 static void output_escaped_param (struct walk_type_data *d,
   2447 				  const char *, const char *);
   2448 static void output_mangled_typename (outf_p, const_type_p);
   2449 static void walk_type (type_p t, struct walk_type_data *d);
   2450 static void write_func_for_structure (type_p orig_s, type_p s,
   2451 				      const struct write_types_data *wtd);
   2452 static void write_types_process_field
   2453   (type_p f, const struct walk_type_data *d);
   2454 static void write_types (outf_p output_header,
   2455 			 type_p structures,
   2456 			 const struct write_types_data *wtd);
   2457 static void write_types_local_process_field
   2458   (type_p f, const struct walk_type_data *d);
   2459 static void write_local_func_for_structure (const_type_p orig_s, type_p s);
   2460 static void write_local (outf_p output_header,
   2461 			 type_p structures);
   2462 static int contains_scalar_p (type_p t);
   2463 static void put_mangled_filename (outf_p, const input_file *);
   2464 static void finish_root_table (struct flist *flp, const char *pfx,
   2465 			       const char *lastname,
   2466 			       const char *tname, const char *name);
   2467 static void write_root (outf_p, pair_p, type_p, const char *, int,
   2468 			struct fileloc *, bool);
   2469 static void write_array (outf_p f, pair_p v,
   2470 			 const struct write_types_data *wtd);
   2471 static void write_roots (pair_p, bool);
   2472 
   2473 /* Parameters for walk_type.  */
   2474 
   2475 struct walk_type_data
   2476 {
   2477   process_field_fn process_field;
   2478   const void *cookie;
   2479   outf_p of;
   2480   options_p opt;
   2481   const char *val;
   2482   const char *prev_val[4];
   2483   int indent;
   2484   int counter;
   2485   const struct fileloc *line;
   2486   lang_bitmap bitmap;
   2487   int used_length;
   2488   type_p orig_s;
   2489   const char *reorder_fn;
   2490   bool needs_cast_p;
   2491   bool fn_wants_lvalue;
   2492   bool in_record_p;
   2493   int loopcounter;
   2494   bool in_ptr_field;
   2495   bool have_this_obj;
   2496   bool in_nested_ptr;
   2497 };
   2498 
   2499 
   2500 /* Given a string TYPE_NAME, representing a C++ typename, return a valid
   2501    pre-processor identifier to use in a #define directive.  This replaces
   2502    special characters used in C++ identifiers like '>', '<' and ':' with
   2503    '_'.
   2504 
   2505    If no C++ special characters are found in TYPE_NAME, return
   2506    TYPE_NAME.  Otherwise, return a copy of TYPE_NAME with the special
   2507    characters replaced with '_'.  In this case, the caller is
   2508    responsible for freeing the allocated string.  */
   2509 
   2510 static const char *
   2511 filter_type_name (const char *type_name)
   2512 {
   2513   if (strchr (type_name, '<') || strchr (type_name, ':'))
   2514     {
   2515       size_t i;
   2516       char *s = xstrdup (type_name);
   2517       for (i = 0; i < strlen (s); i++)
   2518 	if (s[i] == '<' || s[i] == '>' || s[i] == ':' || s[i] == ','
   2519 	    || s[i] == '*')
   2520 	  s[i] = '_';
   2521       return s;
   2522     }
   2523   else
   2524     return type_name;
   2525 }
   2526 
   2527 
   2528 /* Print a mangled name representing T to OF.  */
   2529 
   2530 static void
   2531 output_mangled_typename (outf_p of, const_type_p t)
   2532 {
   2533   if (t == NULL)
   2534     oprintf (of, "Z");
   2535   else
   2536     switch (t->kind)
   2537       {
   2538       case TYPE_NONE:
   2539       case TYPE_UNDEFINED:
   2540       case TYPE_CALLBACK:
   2541 	gcc_unreachable ();
   2542 	break;
   2543       case TYPE_POINTER:
   2544 	oprintf (of, "P");
   2545 	output_mangled_typename (of, t->u.p);
   2546 	break;
   2547       case TYPE_SCALAR:
   2548 	oprintf (of, "I");
   2549 	break;
   2550       case TYPE_STRING:
   2551 	oprintf (of, "S");
   2552 	break;
   2553       case TYPE_STRUCT:
   2554       case TYPE_UNION:
   2555       case TYPE_LANG_STRUCT:
   2556       case TYPE_USER_STRUCT:
   2557 	{
   2558 	  /* For references to classes within an inheritance hierarchy,
   2559 	     only ever reference the ultimate base class, since only
   2560 	     it will have gt_ functions.  */
   2561 	  t = get_ultimate_base_class (t);
   2562 	  const char *id_for_tag = filter_type_name (t->u.s.tag);
   2563 	  oprintf (of, "%lu%s", (unsigned long) strlen (id_for_tag),
   2564 		   id_for_tag);
   2565 	  if (id_for_tag != t->u.s.tag)
   2566 	    free (CONST_CAST (char *, id_for_tag));
   2567 	}
   2568 	break;
   2569       case TYPE_ARRAY:
   2570 	gcc_unreachable ();
   2571       }
   2572 }
   2573 
   2574 /* Print PARAM to D->OF processing escapes.  D->VAL references the
   2575    current object, D->PREV_VAL the object containing the current
   2576    object, ONAME is the name of the option and D->LINE is used to
   2577    print error messages.  */
   2578 
   2579 static void
   2580 output_escaped_param (struct walk_type_data *d, const char *param,
   2581 		      const char *oname)
   2582 {
   2583   const char *p;
   2584 
   2585   for (p = param; *p; p++)
   2586     if (*p != '%')
   2587       oprintf (d->of, "%c", *p);
   2588     else
   2589       switch (*++p)
   2590 	{
   2591 	case 'h':
   2592 	  oprintf (d->of, "(%s)", d->prev_val[2]);
   2593 	  break;
   2594 	case '0':
   2595 	  oprintf (d->of, "(%s)", d->prev_val[0]);
   2596 	  break;
   2597 	case '1':
   2598 	  oprintf (d->of, "(%s)", d->prev_val[1]);
   2599 	  break;
   2600 	case 'a':
   2601 	  {
   2602 	    const char *pp = d->val + strlen (d->val);
   2603 	    while (pp[-1] == ']')
   2604 	      while (*pp != '[')
   2605 		pp--;
   2606 	    oprintf (d->of, "%s", pp);
   2607 	  }
   2608 	  break;
   2609 	default:
   2610 	  error_at_line (d->line, "`%s' option contains bad escape %c%c",
   2611 			 oname, '%', *p);
   2612 	}
   2613 }
   2614 
   2615 const char *
   2616 get_string_option (options_p opt, const char *key)
   2617 {
   2618   for (; opt; opt = opt->next)
   2619     if (strcmp (opt->name, key) == 0)
   2620       return opt->info.string;
   2621   return NULL;
   2622 }
   2623 
   2624 /* Machinery for avoiding duplicate tags within switch statements.  */
   2625 struct seen_tag
   2626 {
   2627   const char *tag;
   2628   struct seen_tag *next;
   2629 };
   2630 
   2631 int
   2632 already_seen_tag (struct seen_tag *seen_tags, const char *tag)
   2633 {
   2634   /* Linear search, so O(n^2), but n is currently small.  */
   2635   while (seen_tags)
   2636     {
   2637       if (!strcmp (seen_tags->tag, tag))
   2638 	return 1;
   2639       seen_tags = seen_tags->next;
   2640     }
   2641   /* Not yet seen this tag. */
   2642   return 0;
   2643 }
   2644 
   2645 void
   2646 mark_tag_as_seen (struct seen_tag **seen_tags, const char *tag)
   2647 {
   2648   /* Add to front of linked list. */
   2649   struct seen_tag *new_node = XCNEW (struct seen_tag);
   2650   new_node->tag = tag;
   2651   new_node->next = *seen_tags;
   2652   *seen_tags = new_node;
   2653 }
   2654 
   2655 static void
   2656 walk_subclasses (type_p base, struct walk_type_data *d,
   2657 		 struct seen_tag **seen_tags)
   2658 {
   2659   for (type_p sub = base->u.s.first_subclass; sub != NULL;
   2660        sub = sub->u.s.next_sibling_class)
   2661     {
   2662       const char *type_tag = get_string_option (sub->u.s.opt, "tag");
   2663       if (type_tag && !already_seen_tag (*seen_tags, type_tag))
   2664 	{
   2665 	  mark_tag_as_seen (seen_tags, type_tag);
   2666 	  oprintf (d->of, "%*scase %s:\n", d->indent, "", type_tag);
   2667 	  d->indent += 2;
   2668 	  oprintf (d->of, "%*s{\n", d->indent, "");
   2669 	  d->indent += 2;
   2670 	  oprintf (d->of, "%*s%s *sub = static_cast <%s *> (x);\n",
   2671 		   d->indent, "", sub->u.s.tag, sub->u.s.tag);
   2672 	  const char *old_val = d->val;
   2673 	  d->val = "(*sub)";
   2674 	  walk_type (sub, d);
   2675 	  d->val = old_val;
   2676 	  d->indent -= 2;
   2677 	  oprintf (d->of, "%*s}\n", d->indent, "");
   2678 	  oprintf (d->of, "%*sbreak;\n", d->indent, "");
   2679 	  d->indent -= 2;
   2680 	}
   2681       walk_subclasses (sub, d, seen_tags);
   2682     }
   2683 }
   2684 
   2685 /* Call D->PROCESS_FIELD for every field (or subfield) of D->VAL,
   2686    which is of type T.  Write code to D->OF to constrain execution (at
   2687    the point that D->PROCESS_FIELD is called) to the appropriate
   2688    cases.  Call D->PROCESS_FIELD on subobjects before calling it on
   2689    pointers to those objects.  D->PREV_VAL lists the objects
   2690    containing the current object, D->OPT is a list of options to
   2691    apply, D->INDENT is the current indentation level, D->LINE is used
   2692    to print error messages, D->BITMAP indicates which languages to
   2693    print the structure for.  */
   2694 
   2695 static void
   2696 walk_type (type_p t, struct walk_type_data *d)
   2697 {
   2698   const char *length = NULL;
   2699   const char *desc = NULL;
   2700   const char *type_tag = NULL;
   2701   int maybe_undef_p = 0;
   2702   int atomic_p = 0;
   2703   options_p oo;
   2704   const struct nested_ptr_data *nested_ptr_d = NULL;
   2705 
   2706   d->needs_cast_p = false;
   2707   for (oo = d->opt; oo; oo = oo->next)
   2708     if (strcmp (oo->name, "length") == 0 && oo->kind == OPTION_STRING)
   2709       length = oo->info.string;
   2710     else if (strcmp (oo->name, "maybe_undef") == 0)
   2711       maybe_undef_p = 1;
   2712     else if (strcmp (oo->name, "desc") == 0 && oo->kind == OPTION_STRING)
   2713       desc = oo->info.string;
   2714     else if (strcmp (oo->name, "nested_ptr") == 0
   2715 	     && oo->kind == OPTION_NESTED)
   2716       nested_ptr_d = (const struct nested_ptr_data *) oo->info.nested;
   2717     else if (strcmp (oo->name, "dot") == 0)
   2718       ;
   2719     else if (strcmp (oo->name, "tag") == 0)
   2720       type_tag = oo->info.string;
   2721     else if (strcmp (oo->name, "special") == 0)
   2722       ;
   2723     else if (strcmp (oo->name, "skip") == 0)
   2724       ;
   2725     else if (strcmp (oo->name, "atomic") == 0)
   2726       atomic_p = 1;
   2727     else if (strcmp (oo->name, "default") == 0)
   2728       ;
   2729     else if (strcmp (oo->name, "chain_next") == 0)
   2730       ;
   2731     else if (strcmp (oo->name, "chain_prev") == 0)
   2732       ;
   2733     else if (strcmp (oo->name, "chain_circular") == 0)
   2734       ;
   2735     else if (strcmp (oo->name, "reorder") == 0)
   2736       ;
   2737     else if (strcmp (oo->name, "variable_size") == 0)
   2738       ;
   2739     else if (strcmp (oo->name, "for_user") == 0)
   2740       ;
   2741     else if (strcmp (oo->name, "callback") == 0)
   2742       ;
   2743     else
   2744       error_at_line (d->line, "unknown option `%s'\n", oo->name);
   2745 
   2746   if (d->used_length)
   2747     length = NULL;
   2748 
   2749   if (maybe_undef_p
   2750       && (t->kind != TYPE_POINTER || !union_or_struct_p (t->u.p)))
   2751     {
   2752       error_at_line (d->line,
   2753 		     "field `%s' has invalid option `maybe_undef_p'\n",
   2754 		     d->val);
   2755       return;
   2756     }
   2757 
   2758   if (atomic_p && (t->kind != TYPE_POINTER) && (t->kind != TYPE_STRING))
   2759     {
   2760       error_at_line (d->line, "field `%s' has invalid option `atomic'\n", d->val);
   2761       return;
   2762     }
   2763 
   2764   switch (t->kind)
   2765     {
   2766     case TYPE_SCALAR:
   2767     case TYPE_STRING:
   2768     case TYPE_CALLBACK:
   2769       d->process_field (t, d);
   2770       break;
   2771 
   2772     case TYPE_POINTER:
   2773       {
   2774 	d->in_ptr_field = true;
   2775 	if (maybe_undef_p && t->u.p->u.s.line.file == NULL)
   2776 	  {
   2777 	    oprintf (d->of, "%*sgcc_assert (!%s);\n", d->indent, "", d->val);
   2778 	    break;
   2779 	  }
   2780 
   2781 	/* If a pointer type is marked as "atomic", we process the
   2782 	   field itself, but we don't walk the data that they point to.
   2783 
   2784 	   There are two main cases where we walk types: to mark
   2785 	   pointers that are reachable, and to relocate pointers when
   2786 	   writing a PCH file.  In both cases, an atomic pointer is
   2787 	   itself marked or relocated, but the memory that it points
   2788 	   to is left untouched.  In the case of PCH, that memory will
   2789 	   be read/written unchanged to the PCH file.  */
   2790 	if (atomic_p)
   2791 	  {
   2792 	    oprintf (d->of, "%*sif (%s != NULL) {\n", d->indent, "", d->val);
   2793 	    d->indent += 2;
   2794 	    d->process_field (t, d);
   2795 	    d->indent -= 2;
   2796 	    oprintf (d->of, "%*s}\n", d->indent, "");
   2797 	    break;
   2798 	  }
   2799 
   2800 	if (!length)
   2801 	  {
   2802 	    if (!union_or_struct_p (t->u.p))
   2803 	      {
   2804 		error_at_line (d->line,
   2805 			       "field `%s' is pointer to unimplemented type",
   2806 			       d->val);
   2807 		break;
   2808 	      }
   2809 
   2810 	    if (nested_ptr_d)
   2811 	      {
   2812 		const char *oldprevval2 = d->prev_val[2];
   2813 		bool old_in_nested_ptr = d->in_nested_ptr;
   2814 
   2815 		if (!union_or_struct_p (nested_ptr_d->type))
   2816 		  {
   2817 		    error_at_line (d->line,
   2818 				   "field `%s' has invalid "
   2819 				   "option `nested_ptr'\n", d->val);
   2820 		    return;
   2821 		  }
   2822 
   2823 		d->prev_val[2] = d->val;
   2824 		d->in_nested_ptr = true;
   2825 		oprintf (d->of, "%*s{\n", d->indent, "");
   2826 		d->indent += 2;
   2827 		d->val = xasprintf ("x%d", d->counter++);
   2828 		oprintf (d->of, "%*s%s %s * %s%s =\n", d->indent, "",
   2829 			 (nested_ptr_d->type->kind == TYPE_UNION
   2830 			  ? "union" : "struct"),
   2831 			 nested_ptr_d->type->u.s.tag,
   2832 			 d->fn_wants_lvalue ? "" : "const ", d->val);
   2833 		oprintf (d->of, "%*s", d->indent + 2, "");
   2834 		output_escaped_param (d, nested_ptr_d->convert_from,
   2835 				      "nested_ptr");
   2836 		oprintf (d->of, ";\n");
   2837 
   2838 		d->process_field (nested_ptr_d->type, d);
   2839 
   2840 		if (d->fn_wants_lvalue)
   2841 		  {
   2842 		    oprintf (d->of, "%*s%s = ", d->indent, "",
   2843 			     d->prev_val[2]);
   2844 		    d->prev_val[2] = d->val;
   2845 		    output_escaped_param (d, nested_ptr_d->convert_to,
   2846 					  "nested_ptr");
   2847 		    oprintf (d->of, ";\n");
   2848 		  }
   2849 
   2850 		d->indent -= 2;
   2851 		oprintf (d->of, "%*s}\n", d->indent, "");
   2852 		d->val = d->prev_val[2];
   2853 		d->prev_val[2] = oldprevval2;
   2854 		d->in_nested_ptr = old_in_nested_ptr;
   2855 	      }
   2856 	    else
   2857 	      d->process_field (t->u.p, d);
   2858 	  }
   2859 	else
   2860 	  {
   2861 	    int loopcounter = d->loopcounter;
   2862 	    const char *oldval = d->val;
   2863 	    const char *oldprevval3 = d->prev_val[3];
   2864 	    char *newval;
   2865 
   2866 	    oprintf (d->of, "%*sif (%s != NULL) {\n", d->indent, "", d->val);
   2867 	    d->indent += 2;
   2868 	    oprintf (d->of, "%*ssize_t i%d;\n", d->indent, "", loopcounter);
   2869 	    oprintf (d->of, "%*sfor (i%d = 0; i%d != (size_t)(", d->indent,
   2870 		     "", loopcounter, loopcounter);
   2871 	    if (!d->in_record_p)
   2872 	      output_escaped_param (d, length, "length");
   2873 	    else
   2874 	      oprintf (d->of, "l%d", loopcounter);
   2875 	    if (d->have_this_obj)
   2876 	      /* Try to unswitch loops (see PR53880).  */
   2877 	      oprintf (d->of, ") && ((void *)%s == this_obj", oldval);
   2878 	    oprintf (d->of, "); i%d++) {\n", loopcounter);
   2879 	    d->indent += 2;
   2880 	    d->val = newval = xasprintf ("%s[i%d]", oldval, loopcounter);
   2881 	    d->used_length = 1;
   2882 	    d->prev_val[3] = oldval;
   2883 	    walk_type (t->u.p, d);
   2884 	    free (newval);
   2885 	    d->val = oldval;
   2886 	    d->prev_val[3] = oldprevval3;
   2887 	    d->used_length = 0;
   2888 	    d->indent -= 2;
   2889 	    oprintf (d->of, "%*s}\n", d->indent, "");
   2890 	    d->process_field (t, d);
   2891 	    d->indent -= 2;
   2892 	    oprintf (d->of, "%*s}\n", d->indent, "");
   2893 	  }
   2894 	d->in_ptr_field = false;
   2895       }
   2896       break;
   2897 
   2898     case TYPE_ARRAY:
   2899       {
   2900 	int loopcounter;
   2901 	const char *oldval = d->val;
   2902 	char *newval;
   2903 
   2904 	/* If it's an array of scalars, we optimize by not generating
   2905 	   any code.  */
   2906 	if (t->u.a.p->kind == TYPE_SCALAR)
   2907 	  break;
   2908 
   2909 	if (length)
   2910 	  loopcounter = d->loopcounter;
   2911 	else
   2912 	  loopcounter = d->counter++;
   2913 
   2914 	/* When walking an array, compute the length and store it in a
   2915 	   local variable before walking the array elements, instead of
   2916 	   recomputing the length expression each time through the loop.
   2917 	   This is necessary to handle tcc_vl_exp objects like CALL_EXPR,
   2918 	   where the length is stored in the first array element,
   2919 	   because otherwise that operand can get overwritten on the
   2920 	   first iteration.  */
   2921 	oprintf (d->of, "%*s{\n", d->indent, "");
   2922 	d->indent += 2;
   2923 	oprintf (d->of, "%*ssize_t i%d;\n", d->indent, "", loopcounter);
   2924 	if (!d->in_record_p || !length)
   2925 	  {
   2926 	    oprintf (d->of, "%*ssize_t l%d = (size_t)(",
   2927 		     d->indent, "", loopcounter);
   2928 	    if (length)
   2929 	      output_escaped_param (d, length, "length");
   2930 	    else
   2931 	      oprintf (d->of, "%s", t->u.a.len);
   2932 	    oprintf (d->of, ");\n");
   2933 	  }
   2934 
   2935 	oprintf (d->of, "%*sfor (i%d = 0; i%d != l%d; i%d++) {\n",
   2936 		 d->indent, "",
   2937 		 loopcounter, loopcounter, loopcounter, loopcounter);
   2938 	d->indent += 2;
   2939 	d->val = newval = xasprintf ("%s[i%d]", oldval, loopcounter);
   2940 	d->used_length = 1;
   2941 	walk_type (t->u.a.p, d);
   2942 	free (newval);
   2943 	d->used_length = 0;
   2944 	d->val = oldval;
   2945 	d->indent -= 2;
   2946 	oprintf (d->of, "%*s}\n", d->indent, "");
   2947 	d->indent -= 2;
   2948 	oprintf (d->of, "%*s}\n", d->indent, "");
   2949       }
   2950       break;
   2951 
   2952     case TYPE_STRUCT:
   2953     case TYPE_UNION:
   2954       {
   2955 	pair_p f;
   2956 	const char *oldval = d->val;
   2957 	const char *oldprevval1 = d->prev_val[1];
   2958 	const char *oldprevval2 = d->prev_val[2];
   2959 	const int union_p = t->kind == TYPE_UNION;
   2960 	int seen_default_p = 0;
   2961 	options_p o;
   2962 	int lengths_seen = 0;
   2963 	int endcounter;
   2964 	bool any_length_seen = false;
   2965 
   2966 	if (!t->u.s.line.file)
   2967 	  error_at_line (d->line, "incomplete structure `%s'", t->u.s.tag);
   2968 
   2969 	if ((d->bitmap & t->u.s.bitmap) != d->bitmap)
   2970 	  {
   2971 	    error_at_line (d->line,
   2972 			   "structure `%s' defined for mismatching languages",
   2973 			   t->u.s.tag);
   2974 	    error_at_line (&t->u.s.line, "one structure defined here");
   2975 	  }
   2976 
   2977 	/* Some things may also be defined in the structure's options.  */
   2978 	for (o = t->u.s.opt; o; o = o->next)
   2979 	  if (!desc && strcmp (o->name, "desc") == 0
   2980 	      && o->kind == OPTION_STRING)
   2981 	    desc = o->info.string;
   2982 
   2983 	d->prev_val[2] = oldval;
   2984 	d->prev_val[1] = oldprevval2;
   2985 	if (union_p)
   2986 	  {
   2987 	    if (desc == NULL)
   2988 	      {
   2989 		error_at_line (d->line,
   2990 			       "missing `desc' option for union `%s'",
   2991 			       t->u.s.tag);
   2992 		desc = "1";
   2993 	      }
   2994 	    oprintf (d->of, "%*sswitch ((int) (", d->indent, "");
   2995 	    output_escaped_param (d, desc, "desc");
   2996 	    oprintf (d->of, "))\n");
   2997 	    d->indent += 2;
   2998 	    oprintf (d->of, "%*s{\n", d->indent, "");
   2999 	  }
   3000 	else if (desc)
   3001 	  {
   3002 	    /* We have a "desc" option on a struct, signifying the
   3003 	       base class within a GC-managed inheritance hierarchy.
   3004 	       The current code specialcases the base class, then walks
   3005 	       into subclasses, recursing into this routine to handle them.
   3006 	       This organization requires the base class to have a case in
   3007 	       the switch statement, and hence a tag value is mandatory
   3008 	       for the base class.   This restriction could be removed, but
   3009 	       it would require some restructing of this code.  */
   3010 	    if (!type_tag)
   3011 	      {
   3012 		error_at_line (d->line,
   3013 			       "missing `tag' option for type `%s'",
   3014 			       t->u.s.tag);
   3015 	      }
   3016 	    oprintf (d->of, "%*sswitch ((int) (", d->indent, "");
   3017 	    output_escaped_param (d, desc, "desc");
   3018 	    oprintf (d->of, "))\n");
   3019 	    d->indent += 2;
   3020 	    oprintf (d->of, "%*s{\n", d->indent, "");
   3021 	    oprintf (d->of, "%*scase %s:\n", d->indent, "", type_tag);
   3022 	    d->indent += 2;
   3023 	  }
   3024 
   3025 	FOR_ALL_INHERITED_FIELDS (t, f)
   3026 	  {
   3027 	    options_p oo;
   3028 	    int skip_p = 0;
   3029 	    const char *fieldlength = NULL;
   3030 
   3031 	    d->reorder_fn = NULL;
   3032 	    for (oo = f->opt; oo; oo = oo->next)
   3033 	      if (strcmp (oo->name, "skip") == 0)
   3034 		skip_p = 1;
   3035 	      else if (strcmp (oo->name, "length") == 0
   3036 		       && oo->kind == OPTION_STRING)
   3037 		fieldlength = oo->info.string;
   3038 
   3039 	    if (skip_p)
   3040 	      continue;
   3041 	    if (fieldlength)
   3042 	      {
   3043 	        lengths_seen++;
   3044 		d->counter++;
   3045 		if (!union_p)
   3046 		  {
   3047 		    if (!any_length_seen)
   3048 		      {
   3049 			oprintf (d->of, "%*s{\n", d->indent, "");
   3050 			d->indent += 2;
   3051 		      }
   3052 		    any_length_seen = true;
   3053 
   3054 		    oprintf (d->of, "%*ssize_t l%d = (size_t)(",
   3055 			     d->indent, "", d->counter - 1);
   3056 		    output_escaped_param (d, fieldlength, "length");
   3057 		    oprintf (d->of, ");\n");
   3058 		  }
   3059 	      }
   3060 	  }
   3061 	endcounter = d->counter;
   3062 
   3063 	FOR_ALL_INHERITED_FIELDS (t, f)
   3064 	  {
   3065 	    options_p oo;
   3066 	    const char *dot = ".";
   3067 	    const char *tagid = NULL;
   3068 	    int skip_p = 0;
   3069 	    int default_p = 0;
   3070 	    const char *fieldlength = NULL;
   3071 	    char *newval;
   3072 
   3073 	    d->reorder_fn = NULL;
   3074 	    for (oo = f->opt; oo; oo = oo->next)
   3075 	      if (strcmp (oo->name, "dot") == 0
   3076 		  && oo->kind == OPTION_STRING)
   3077 		dot = oo->info.string;
   3078 	      else if (strcmp (oo->name, "tag") == 0
   3079 		       && oo->kind == OPTION_STRING)
   3080 		tagid = oo->info.string;
   3081 	      else if (strcmp (oo->name, "skip") == 0)
   3082 		skip_p = 1;
   3083 	      else if (strcmp (oo->name, "default") == 0)
   3084 		default_p = 1;
   3085 	      else if (strcmp (oo->name, "reorder") == 0
   3086 		  && oo->kind == OPTION_STRING)
   3087 		d->reorder_fn = oo->info.string;
   3088 	      else if (strcmp (oo->name, "length") == 0
   3089 		       && oo->kind == OPTION_STRING)
   3090 		fieldlength = oo->info.string;
   3091 
   3092 	    if (skip_p)
   3093 	      continue;
   3094 
   3095 	    if (union_p && tagid)
   3096 	      {
   3097 		oprintf (d->of, "%*scase %s:\n", d->indent, "", tagid);
   3098 		d->indent += 2;
   3099 	      }
   3100 	    else if (union_p && default_p)
   3101 	      {
   3102 		oprintf (d->of, "%*sdefault:\n", d->indent, "");
   3103 		d->indent += 2;
   3104 		seen_default_p = 1;
   3105 	      }
   3106 	    else if (!union_p && (default_p || tagid))
   3107 	      error_at_line (d->line,
   3108 			     "can't use `%s' outside a union on field `%s'",
   3109 			     default_p ? "default" : "tag", f->name);
   3110 	    else if (union_p && !(default_p || tagid)
   3111 		     && f->type->kind == TYPE_SCALAR)
   3112 	      {
   3113 		fprintf (stderr,
   3114 			 "%s:%d: warning: field `%s' is missing `tag' or `default' option\n",
   3115 			 get_input_file_name (d->line->file), d->line->line,
   3116 			 f->name);
   3117 		continue;
   3118 	      }
   3119 	    else if (union_p && !(default_p || tagid))
   3120 	      error_at_line (d->line,
   3121 			     "field `%s' is missing `tag' or `default' option",
   3122 			     f->name);
   3123 
   3124 	    if (fieldlength)
   3125 	      {
   3126 		d->loopcounter = endcounter - lengths_seen--;
   3127 	      }
   3128 
   3129 	    d->line = &f->line;
   3130 	    d->val = newval = xasprintf ("%s%s%s", oldval, dot, f->name);
   3131 	    d->opt = f->opt;
   3132 	    d->used_length = false;
   3133 	    d->in_record_p = !union_p;
   3134 
   3135 	    walk_type (f->type, d);
   3136 
   3137 	    d->in_record_p = false;
   3138 
   3139 	    free (newval);
   3140 
   3141 	    if (union_p)
   3142 	      {
   3143 		oprintf (d->of, "%*sbreak;\n", d->indent, "");
   3144 		d->indent -= 2;
   3145 	      }
   3146 	  }
   3147 	d->reorder_fn = NULL;
   3148 
   3149 	d->val = oldval;
   3150 	d->prev_val[1] = oldprevval1;
   3151 	d->prev_val[2] = oldprevval2;
   3152 
   3153 	if (union_p && !seen_default_p)
   3154 	  {
   3155 	    oprintf (d->of, "%*sdefault:\n", d->indent, "");
   3156 	    oprintf (d->of, "%*s  break;\n", d->indent, "");
   3157 	  }
   3158 
   3159 	if (desc && !union_p)
   3160 	  {
   3161 		oprintf (d->of, "%*sbreak;\n", d->indent, "");
   3162 		d->indent -= 2;
   3163           }
   3164 	if (union_p)
   3165 	  {
   3166 	    oprintf (d->of, "%*s}\n", d->indent, "");
   3167 	    d->indent -= 2;
   3168 	  }
   3169 	else if (desc)
   3170 	  {
   3171 	    /* Add cases to handle subclasses.  */
   3172 	    struct seen_tag *tags = NULL;
   3173 	    walk_subclasses (t, d, &tags);
   3174 
   3175 	    /* Ensure that if someone forgets a "tag" option that we don't
   3176 	       silent fail to traverse that subclass's fields.  */
   3177 	    if (!seen_default_p)
   3178 	      {
   3179 		oprintf (d->of, "%*s/* Unrecognized tag value.  */\n",
   3180 			 d->indent, "");
   3181 		oprintf (d->of, "%*sdefault: gcc_unreachable (); \n",
   3182 			 d->indent, "");
   3183 	      }
   3184 
   3185 	    /* End of the switch statement */
   3186 	    oprintf (d->of, "%*s}\n", d->indent, "");
   3187 	    d->indent -= 2;
   3188 	  }
   3189 	if (any_length_seen)
   3190 	  {
   3191 	    d->indent -= 2;
   3192 	    oprintf (d->of, "%*s}\n", d->indent, "");
   3193 	  }
   3194       }
   3195       break;
   3196 
   3197     case TYPE_LANG_STRUCT:
   3198       {
   3199 	type_p nt;
   3200 	for (nt = t->u.s.lang_struct; nt; nt = nt->next)
   3201 	  if ((d->bitmap & nt->u.s.bitmap) == d->bitmap)
   3202 	    break;
   3203 	if (nt == NULL)
   3204 	  error_at_line (d->line, "structure `%s' differs between languages",
   3205 			 t->u.s.tag);
   3206 	else
   3207 	  walk_type (nt, d);
   3208       }
   3209       break;
   3210 
   3211     case TYPE_USER_STRUCT:
   3212       d->process_field (t, d);
   3213       break;
   3214 
   3215     case TYPE_NONE:
   3216     case TYPE_UNDEFINED:
   3217       gcc_unreachable ();
   3218     }
   3219 }
   3220 
   3221 /* process_field routine for marking routines.  */
   3222 
   3223 static void
   3224 write_types_process_field (type_p f, const struct walk_type_data *d)
   3225 {
   3226   const struct write_types_data *wtd;
   3227   const char *cast = d->needs_cast_p ? "(void *)" : "";
   3228   wtd = (const struct write_types_data *) d->cookie;
   3229 
   3230   switch (f->kind)
   3231     {
   3232     case TYPE_NONE:
   3233     case TYPE_UNDEFINED:
   3234       gcc_unreachable ();
   3235     case TYPE_POINTER:
   3236       oprintf (d->of, "%*s%s (%s%s", d->indent, "",
   3237 	       wtd->subfield_marker_routine, cast, d->val);
   3238       if (wtd->param_prefix)
   3239 	{
   3240 	  if (f->u.p->kind == TYPE_SCALAR)
   3241 	    /* The current type is a pointer to a scalar (so not
   3242 	       considered like a pointer to instances of user defined
   3243 	       types) and we are seeing it; it means we must be even
   3244 	       more careful about the second argument of the
   3245 	       SUBFIELD_MARKER_ROUTINE call.  That argument must
   3246 	       always be the instance of the type for which
   3247 	       write_func_for_structure was called - this really is
   3248 	       what the function SUBFIELD_MARKER_ROUTINE expects.
   3249 	       That is, it must be an instance of the ORIG_S type
   3250 	       parameter of write_func_for_structure.  The convention
   3251 	       is that that argument must be "x" in that case (as set
   3252 	       by write_func_for_structure).  The problem is, we can't
   3253 	       count on d->prev_val[3] to be always set to "x" in that
   3254 	       case.  Sometimes walk_type can set it to something else
   3255 	       (to e.g cooperate with write_array when called from
   3256 	       write_roots).  So let's set it to "x" here then.  */
   3257 	    oprintf (d->of, ", x");
   3258 	  else
   3259 	    oprintf (d->of, ", %s", d->prev_val[3]);
   3260 	  if (d->orig_s)
   3261 	    {
   3262 	      oprintf (d->of, ", gt_%s_", wtd->param_prefix);
   3263 	      output_mangled_typename (d->of, d->orig_s);
   3264 	    }
   3265 	  else
   3266 	    oprintf (d->of, ", gt_%sa_%s", wtd->param_prefix, d->prev_val[0]);
   3267 	}
   3268       oprintf (d->of, ");\n");
   3269       if (d->reorder_fn && wtd->reorder_note_routine)
   3270 	oprintf (d->of, "%*s%s (%s%s, %s, %s);\n", d->indent, "",
   3271 		 wtd->reorder_note_routine, cast, d->val,
   3272 		 d->prev_val[3], d->reorder_fn);
   3273       break;
   3274 
   3275     case TYPE_STRING:
   3276     case TYPE_STRUCT:
   3277     case TYPE_UNION:
   3278     case TYPE_LANG_STRUCT:
   3279     case TYPE_USER_STRUCT:
   3280       if (f->kind == TYPE_USER_STRUCT && !d->in_ptr_field)
   3281 	{
   3282 	  /* If F is a user-defined type and the field is not a
   3283 	     pointer to the type, then we should not generate the
   3284 	     standard pointer-marking code.  All we need to do is call
   3285 	     the user-provided marking function to process the fields
   3286 	     of F.  */
   3287 	  oprintf (d->of, "%*sgt_%sx (&(%s));\n", d->indent, "", wtd->prefix,
   3288 		   d->val);
   3289 	}
   3290       else
   3291 	{
   3292 	  oprintf (d->of, "%*sgt_%s_", d->indent, "", wtd->prefix);
   3293 	  output_mangled_typename (d->of, f);
   3294 	  oprintf (d->of, " (%s%s);\n", cast, d->val);
   3295 	  if (d->reorder_fn && wtd->reorder_note_routine)
   3296 	    oprintf (d->of, "%*s%s (%s%s, %s%s, %s);\n", d->indent, "",
   3297 		     wtd->reorder_note_routine, cast, d->val, cast, d->val,
   3298 		     d->reorder_fn);
   3299 	}
   3300       break;
   3301 
   3302     case TYPE_SCALAR:
   3303     case TYPE_CALLBACK:
   3304       break;
   3305 
   3306     case TYPE_ARRAY:
   3307       gcc_unreachable ();
   3308     }
   3309 }
   3310 
   3311 /* Return an output file that is suitable for definitions which can
   3312    reference struct S */
   3313 
   3314 static outf_p
   3315 get_output_file_for_structure (const_type_p s)
   3316 {
   3317   const input_file *fn;
   3318 
   3319   gcc_assert (union_or_struct_p (s));
   3320   fn = s->u.s.line.file;
   3321 
   3322   /* The call to get_output_file_with_visibility may update fn by
   3323      caching its result inside, so we need the CONST_CAST.  */
   3324   return get_output_file_with_visibility (CONST_CAST (input_file*, fn));
   3325 }
   3326 
   3327 
   3328 /* Returns the specifier keyword for a string or union type S, empty string
   3329    otherwise.  */
   3330 
   3331 static const char *
   3332 get_type_specifier (const type_p s)
   3333 {
   3334   if (s->kind == TYPE_STRUCT)
   3335     return "struct ";
   3336   else if (s->kind == TYPE_LANG_STRUCT)
   3337     return get_type_specifier (s->u.s.lang_struct);
   3338   else if (s->kind == TYPE_UNION)
   3339     return "union ";
   3340   return "";
   3341 }
   3342 
   3343 
   3344 /* Emits a declaration for type TY (assumed to be a union or a
   3345    structure) on stream OUT.  */
   3346 
   3347 static void
   3348 write_type_decl (outf_p out, type_p ty)
   3349 {
   3350   if (union_or_struct_p (ty))
   3351     oprintf (out, "%s%s", get_type_specifier (ty), ty->u.s.tag);
   3352   else if (ty->kind == TYPE_SCALAR)
   3353     {
   3354       if (ty->u.scalar_is_char)
   3355 	oprintf (out, "const char");
   3356       else
   3357 	oprintf (out, "void");
   3358     }
   3359   else if (ty->kind == TYPE_POINTER)
   3360     {
   3361       write_type_decl (out, ty->u.p);
   3362       oprintf (out, " *");
   3363     }
   3364   else if (ty->kind == TYPE_ARRAY)
   3365     {
   3366       write_type_decl (out, ty->u.a.p);
   3367       oprintf (out, " *");
   3368     }
   3369   else if (ty->kind == TYPE_STRING)
   3370     {
   3371       oprintf (out, "const char *");
   3372     }
   3373   else
   3374     gcc_unreachable ();
   3375 }
   3376 
   3377 
   3378 /* Write on OF the name of the marker function for structure S. PREFIX
   3379    is the prefix to use (to distinguish ggc from pch markers).  */
   3380 
   3381 static void
   3382 write_marker_function_name (outf_p of, type_p s, const char *prefix)
   3383 {
   3384   if (union_or_struct_p (s))
   3385     {
   3386       const char *id_for_tag = filter_type_name (s->u.s.tag);
   3387       oprintf (of, "gt_%sx_%s", prefix, id_for_tag);
   3388       if (id_for_tag != s->u.s.tag)
   3389 	free (CONST_CAST (char *, id_for_tag));
   3390     }
   3391   else
   3392     gcc_unreachable ();
   3393 }
   3394 
   3395 /* Write on OF a user-callable routine to act as an entry point for
   3396    the marking routine for S, generated by write_func_for_structure.
   3397    WTD distinguishes between ggc and pch markers.  */
   3398 
   3399 static void
   3400 write_user_func_for_structure_ptr (outf_p of, type_p s, const write_types_data *wtd)
   3401 {
   3402   gcc_assert (union_or_struct_p (s));
   3403 
   3404   type_p alias_of = NULL;
   3405   for (options_p opt = s->u.s.opt; opt; opt = opt->next)
   3406     if (strcmp (opt->name, "ptr_alias") == 0)
   3407       {
   3408 	/* ALIAS_OF is set if ORIG_S is marked "ptr_alias". This means that
   3409 	   we do not generate marking code for ORIG_S here. Instead, a
   3410 	   forwarder #define in gtype-desc.h will cause every call to its
   3411 	   marker to call the target of this alias.
   3412 
   3413 	   However, we still want to create a user entry code for the
   3414 	   aliased type. So, if ALIAS_OF is set, we only generate the
   3415 	   user-callable marker function.  */
   3416 	alias_of = opt->info.type;
   3417 	break;
   3418       }
   3419 
   3420   DBGPRINTF ("write_user_func_for_structure_ptr: %s %s", s->u.s.tag,
   3421 	     wtd->prefix);
   3422 
   3423   /* Only write the function once. */
   3424   if (s->u.s.wrote_user_func_for_ptr[wtd->kind])
   3425     return;
   3426   s->u.s.wrote_user_func_for_ptr[wtd->kind] = true;
   3427 
   3428   oprintf (of, "\nvoid\n");
   3429   oprintf (of, "gt_%sx (", wtd->prefix);
   3430   write_type_decl (of, s);
   3431   oprintf (of, " *& x)\n");
   3432   oprintf (of, "{\n");
   3433   oprintf (of, "  if (x)\n    ");
   3434   write_marker_function_name (of,
   3435 			      alias_of ? alias_of : get_ultimate_base_class (s),
   3436 			      wtd->prefix);
   3437   oprintf (of, " ((void *) x);\n");
   3438   oprintf (of, "}\n");
   3439 }
   3440 
   3441 
   3442 /* Write a function to mark all the fields of type S on OF.  PREFIX
   3443    and D are as in write_user_marking_functions.  */
   3444 
   3445 static void
   3446 write_user_func_for_structure_body (type_p s, const char *prefix,
   3447 				    struct walk_type_data *d)
   3448 {
   3449   oprintf (d->of, "\nvoid\n");
   3450   oprintf (d->of, "gt_%sx (", prefix);
   3451   write_type_decl (d->of, s);
   3452   oprintf (d->of, "& x_r ATTRIBUTE_UNUSED)\n");
   3453   oprintf (d->of, "{\n");
   3454   oprintf (d->of, "  ");
   3455   write_type_decl (d->of, s);
   3456   oprintf (d->of, " * ATTRIBUTE_UNUSED x = &x_r;\n");
   3457   d->val = "(*x)";
   3458   d->indent = 2;
   3459   walk_type (s, d);
   3460   oprintf (d->of, "}\n");
   3461 }
   3462 
   3463 /* Emit the user-callable functions needed to mark all the types used
   3464    by the user structure S.  PREFIX is the prefix to use to
   3465    distinguish ggc and pch markers.  D contains data needed to pass to
   3466    walk_type when traversing the fields of a type.
   3467 
   3468    For every type T referenced by S, two routines are generated: one
   3469    that takes 'T *', marks the pointer and calls the second routine,
   3470    which just marks the fields of T.  */
   3471 
   3472 static void
   3473 write_user_marking_functions (type_p s,
   3474 			      const write_types_data *w,
   3475 			      struct walk_type_data *d)
   3476 {
   3477   gcc_assert (s->kind == TYPE_USER_STRUCT);
   3478 
   3479   for (pair_p fld = s->u.s.fields; fld; fld = fld->next)
   3480     {
   3481       type_p fld_type = fld->type;
   3482       if (fld_type->kind == TYPE_POINTER)
   3483 	{
   3484 	  type_p pointed_to_type = fld_type->u.p;
   3485 	  if (union_or_struct_p (pointed_to_type))
   3486 	    write_user_func_for_structure_ptr (d->of, pointed_to_type, w);
   3487 	}
   3488       else if (union_or_struct_p (fld_type))
   3489 	write_user_func_for_structure_body (fld_type, w->prefix, d);
   3490     }
   3491 }
   3492 
   3493 
   3494 /* For S, a structure that's part of ORIG_S write out a routine that:
   3495    - Takes a parameter, a void * but actually of type *S
   3496    - If SEEN_ROUTINE returns nonzero, calls write_types_process_field on each
   3497    field of S or its substructures and (in some cases) things
   3498    that are pointed to by S.  */
   3499 
   3500 static void
   3501 write_func_for_structure (type_p orig_s, type_p s,
   3502 			  const struct write_types_data *wtd)
   3503 {
   3504   const char *chain_next = NULL;
   3505   const char *chain_prev = NULL;
   3506   const char *chain_circular = NULL;
   3507   options_p opt;
   3508   struct walk_type_data d;
   3509 
   3510   if (s->u.s.base_class)
   3511     {
   3512       /* Verify that the base class has a "desc", since otherwise
   3513 	 the traversal hooks there won't attempt to visit fields of
   3514 	 subclasses such as this one.  */
   3515       const_type_p ubc = get_ultimate_base_class (s);
   3516       if ((!opts_have (ubc->u.s.opt, "user")
   3517 	   && !opts_have (ubc->u.s.opt, "desc")))
   3518 	error_at_line (&s->u.s.line,
   3519 		       ("'%s' is a subclass of non-GTY(user) GTY class '%s'"
   3520 			", but '%s' lacks a discriminator 'desc' option"),
   3521 		       s->u.s.tag, ubc->u.s.tag, ubc->u.s.tag);
   3522 
   3523       /* Don't write fns for subclasses, only for the ultimate base class
   3524 	 within an inheritance hierarchy.  */
   3525       return;
   3526     }
   3527 
   3528   memset (&d, 0, sizeof (d));
   3529   d.of = get_output_file_for_structure (s);
   3530 
   3531   bool for_user = false;
   3532   for (opt = s->u.s.opt; opt; opt = opt->next)
   3533     if (strcmp (opt->name, "chain_next") == 0
   3534 	&& opt->kind == OPTION_STRING)
   3535       chain_next = opt->info.string;
   3536     else if (strcmp (opt->name, "chain_prev") == 0
   3537 	     && opt->kind == OPTION_STRING)
   3538       chain_prev = opt->info.string;
   3539     else if (strcmp (opt->name, "chain_circular") == 0
   3540 	     && opt->kind == OPTION_STRING)
   3541       chain_circular = opt->info.string;
   3542     else if (strcmp (opt->name, "for_user") == 0)
   3543       for_user = true;
   3544   if (chain_prev != NULL && chain_next == NULL)
   3545     error_at_line (&s->u.s.line, "chain_prev without chain_next");
   3546   if (chain_circular != NULL && chain_next != NULL)
   3547     error_at_line (&s->u.s.line, "chain_circular with chain_next");
   3548   if (chain_circular != NULL)
   3549     chain_next = chain_circular;
   3550 
   3551   d.process_field = write_types_process_field;
   3552   d.cookie = wtd;
   3553   d.orig_s = orig_s;
   3554   d.opt = s->u.s.opt;
   3555   d.line = &s->u.s.line;
   3556   d.bitmap = s->u.s.bitmap;
   3557   d.prev_val[0] = "*x";
   3558   d.prev_val[1] = "not valid postage";	/* Guarantee an error.  */
   3559   d.prev_val[3] = "x";
   3560   d.val = "(*x)";
   3561   d.have_this_obj = false;
   3562 
   3563   oprintf (d.of, "\n");
   3564   oprintf (d.of, "void\n");
   3565   write_marker_function_name (d.of, orig_s, wtd->prefix);
   3566   oprintf (d.of, " (void *x_p)\n");
   3567   oprintf (d.of, "{\n  ");
   3568   write_type_decl (d.of, s);
   3569   oprintf (d.of, " * %sx = (", chain_next == NULL ? "const " : "");
   3570   write_type_decl (d.of, s);
   3571   oprintf (d.of, " *)x_p;\n");
   3572   if (chain_next != NULL)
   3573     {
   3574       /* TYPE_USER_STRUCTs should not occur here.  These structures
   3575 	 are completely handled by user code.  */
   3576       gcc_assert (orig_s->kind != TYPE_USER_STRUCT);
   3577 
   3578       oprintf (d.of, "  ");
   3579       write_type_decl (d.of, s);
   3580       oprintf (d.of, " * xlimit = x;\n");
   3581     }
   3582   if (chain_next == NULL)
   3583     {
   3584       oprintf (d.of, "  if (%s (x", wtd->marker_routine);
   3585       if (wtd->param_prefix)
   3586 	{
   3587 	  oprintf (d.of, ", x, gt_%s_", wtd->param_prefix);
   3588 	  output_mangled_typename (d.of, orig_s);
   3589 	}
   3590       oprintf (d.of, "))\n");
   3591     }
   3592   else
   3593     {
   3594       if (chain_circular != NULL)
   3595 	oprintf (d.of, "  if (!%s (xlimit", wtd->marker_routine);
   3596       else
   3597 	oprintf (d.of, "  while (%s (xlimit", wtd->marker_routine);
   3598       if (wtd->param_prefix)
   3599 	{
   3600 	  oprintf (d.of, ", xlimit, gt_%s_", wtd->param_prefix);
   3601 	  output_mangled_typename (d.of, orig_s);
   3602 	}
   3603       oprintf (d.of, "))\n");
   3604       if (chain_circular != NULL)
   3605 	oprintf (d.of, "    return;\n  do\n");
   3606 
   3607       oprintf (d.of, "   xlimit = (");
   3608       d.prev_val[2] = "*xlimit";
   3609       output_escaped_param (&d, chain_next, "chain_next");
   3610       oprintf (d.of, ");\n");
   3611       if (chain_prev != NULL)
   3612 	{
   3613 	  oprintf (d.of, "  if (x != xlimit)\n");
   3614 	  oprintf (d.of, "    for (;;)\n");
   3615 	  oprintf (d.of, "      {\n");
   3616 	  oprintf (d.of, "        %s %s * const xprev = (",
   3617 		   s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag);
   3618 
   3619 	  d.prev_val[2] = "*x";
   3620 	  output_escaped_param (&d, chain_prev, "chain_prev");
   3621 	  oprintf (d.of, ");\n");
   3622 	  oprintf (d.of, "        if (xprev == NULL) break;\n");
   3623 	  oprintf (d.of, "        x = xprev;\n");
   3624 	  oprintf (d.of, "        (void) %s (xprev", wtd->marker_routine);
   3625 	  if (wtd->param_prefix)
   3626 	    {
   3627 	      oprintf (d.of, ", xprev, gt_%s_", wtd->param_prefix);
   3628 	      output_mangled_typename (d.of, orig_s);
   3629 	    }
   3630 	  oprintf (d.of, ");\n");
   3631 	  oprintf (d.of, "      }\n");
   3632 	}
   3633       if (chain_circular != NULL)
   3634 	{
   3635 	  oprintf (d.of, "  while (%s (xlimit", wtd->marker_routine);
   3636 	  if (wtd->param_prefix)
   3637 	    {
   3638 	      oprintf (d.of, ", xlimit, gt_%s_", wtd->param_prefix);
   3639 	      output_mangled_typename (d.of, orig_s);
   3640 	    }
   3641 	  oprintf (d.of, "));\n");
   3642 	  oprintf (d.of, "  do\n");
   3643 	}
   3644       else
   3645 	oprintf (d.of, "  while (x != xlimit)\n");
   3646     }
   3647   oprintf (d.of, "    {\n");
   3648 
   3649   d.prev_val[2] = "*x";
   3650   d.indent = 6;
   3651   if (orig_s->kind != TYPE_USER_STRUCT)
   3652     walk_type (s, &d);
   3653   else
   3654     {
   3655       /* User structures have no fields to walk. Simply generate a call
   3656 	 to the user-provided structure marker.  */
   3657       oprintf (d.of, "%*sgt_%sx (x);\n", d.indent, "", wtd->prefix);
   3658     }
   3659 
   3660   if (chain_next != NULL)
   3661     {
   3662       oprintf (d.of, "      x = (");
   3663       output_escaped_param (&d, chain_next, "chain_next");
   3664       oprintf (d.of, ");\n");
   3665     }
   3666 
   3667   oprintf (d.of, "    }\n");
   3668   if (chain_circular != NULL)
   3669     oprintf (d.of, "  while (x != xlimit);\n");
   3670   oprintf (d.of, "}\n");
   3671 
   3672   if (orig_s->kind == TYPE_USER_STRUCT)
   3673     write_user_marking_functions (orig_s, wtd, &d);
   3674 
   3675   if (for_user)
   3676     {
   3677       write_user_func_for_structure_body (orig_s, wtd->prefix, &d);
   3678       write_user_func_for_structure_ptr (d.of, orig_s, wtd);
   3679     }
   3680 }
   3681 
   3682 
   3683 /* Write out marker routines for STRUCTURES and PARAM_STRUCTS.  */
   3684 
   3685 static void
   3686 write_types (outf_p output_header, type_p structures,
   3687 	     const struct write_types_data *wtd)
   3688 {
   3689   int nbfun = 0;		/* Count the emitted functions.  */
   3690   type_p s;
   3691 
   3692   oprintf (output_header, "\n/* %s*/\n", wtd->comment);
   3693 
   3694   /* We first emit the macros and the declarations. Functions' code is
   3695      emitted afterwards.  This is needed in plugin mode.  */
   3696   oprintf (output_header, "/* Macros and declarations.  */\n");
   3697   for (s = structures; s; s = s->next)
   3698     /* Do not emit handlers for derived classes; we only ever deal with
   3699        the ultimate base class within an inheritance hierarchy.  */
   3700     if ((s->gc_used == GC_POINTED_TO || s->gc_used == GC_MAYBE_POINTED_TO)
   3701         && !s->u.s.base_class)
   3702       {
   3703 	options_p opt;
   3704 
   3705 	if (s->gc_used == GC_MAYBE_POINTED_TO && s->u.s.line.file == NULL)
   3706 	  continue;
   3707 
   3708 	const char *s_id_for_tag = filter_type_name (s->u.s.tag);
   3709 
   3710 	oprintf (output_header, "#define gt_%s_", wtd->prefix);
   3711 	output_mangled_typename (output_header, s);
   3712 	oprintf (output_header, "(X) do { \\\n");
   3713 	oprintf (output_header,
   3714 		 "  if ((intptr_t)(X) != 0) gt_%sx_%s (X);\\\n",
   3715 		 wtd->prefix, s_id_for_tag);
   3716 	oprintf (output_header, "  } while (0)\n");
   3717 
   3718 	for (opt = s->u.s.opt; opt; opt = opt->next)
   3719 	  if (strcmp (opt->name, "ptr_alias") == 0
   3720 	      && opt->kind == OPTION_TYPE)
   3721 	    {
   3722 	      const_type_p const t = (const_type_p) opt->info.type;
   3723 	      if (t->kind == TYPE_STRUCT
   3724 		  || t->kind == TYPE_UNION || t->kind == TYPE_LANG_STRUCT)
   3725 		{
   3726 		  const char *t_id_for_tag = filter_type_name (t->u.s.tag);
   3727 		  oprintf (output_header,
   3728 			   "#define gt_%sx_%s gt_%sx_%s\n",
   3729 			   wtd->prefix, s->u.s.tag, wtd->prefix, t_id_for_tag);
   3730 		  if (t_id_for_tag != t->u.s.tag)
   3731 		    free (CONST_CAST (char *, t_id_for_tag));
   3732 		}
   3733 	      else
   3734 		error_at_line (&s->u.s.line,
   3735 			       "structure alias is not a structure");
   3736 	      break;
   3737 	    }
   3738 	if (opt)
   3739 	  continue;
   3740 
   3741 	/* Declare the marker procedure only once.  */
   3742 	oprintf (output_header,
   3743 		 "extern void gt_%sx_%s (void *);\n",
   3744 		 wtd->prefix, s_id_for_tag);
   3745 
   3746 	if (s_id_for_tag != s->u.s.tag)
   3747 	  free (CONST_CAST (char *, s_id_for_tag));
   3748 
   3749 	if (s->u.s.line.file == NULL)
   3750 	  {
   3751 	    fprintf (stderr, "warning: structure `%s' used but not defined\n",
   3752 		     s->u.s.tag);
   3753 	    continue;
   3754 	  }
   3755       }
   3756 
   3757   /* At last we emit the functions code.  */
   3758   oprintf (output_header, "\n/* functions code */\n");
   3759   for (s = structures; s; s = s->next)
   3760     if (s->gc_used == GC_POINTED_TO || s->gc_used == GC_MAYBE_POINTED_TO)
   3761       {
   3762 	options_p opt;
   3763 
   3764 	if (s->gc_used == GC_MAYBE_POINTED_TO && s->u.s.line.file == NULL)
   3765 	  continue;
   3766 	for (opt = s->u.s.opt; opt; opt = opt->next)
   3767 	  if (strcmp (opt->name, "ptr_alias") == 0)
   3768 	    break;
   3769 	if (opt)
   3770 	  continue;
   3771 
   3772 	if (s->kind == TYPE_LANG_STRUCT)
   3773 	  {
   3774 	    type_p ss;
   3775 	    for (ss = s->u.s.lang_struct; ss; ss = ss->next)
   3776 	      {
   3777 		nbfun++;
   3778 		DBGPRINTF ("writing func #%d lang_struct ss @ %p '%s'",
   3779 			   nbfun, (void*) ss, ss->u.s.tag);
   3780 		write_func_for_structure (s, ss, wtd);
   3781 	      }
   3782 	  }
   3783 	else
   3784 	  {
   3785 	    nbfun++;
   3786 	    DBGPRINTF ("writing func #%d struct s @ %p '%s'",
   3787 		       nbfun, (void*) s, s->u.s.tag);
   3788 	    write_func_for_structure (s, s, wtd);
   3789 	  }
   3790       }
   3791     else
   3792       {
   3793 	/* Structure s is not possibly pointed to, so can be ignored.  */
   3794 	DBGPRINTF ("ignored s @ %p  '%s' gc_used#%d",
   3795 		   (void*)s,  s->u.s.tag,
   3796 		   (int) s->gc_used);
   3797       }
   3798 
   3799   if (verbosity_level >= 2)
   3800     printf ("%s emitted %d routines for %s\n",
   3801 	    progname, nbfun, wtd->comment);
   3802 }
   3803 
   3804 static const struct write_types_data ggc_wtd = {
   3805   "ggc_m", NULL, "ggc_mark", "ggc_test_and_set_mark", NULL,
   3806   "GC marker procedures.  ",
   3807   WTK_GGC
   3808 };
   3809 
   3810 static const struct write_types_data pch_wtd = {
   3811   "pch_n", "pch_p", "gt_pch_note_object", "gt_pch_note_object",
   3812   "gt_pch_note_reorder",
   3813   "PCH type-walking procedures.  ",
   3814   WTK_PCH
   3815 };
   3816 
   3817 /* Write out the local pointer-walking routines.  */
   3818 
   3819 /* process_field routine for local pointer-walking for user-callable
   3820    routines.  The difference between this and
   3821    write_types_local_process_field is that, in this case, we do not
   3822    need to check whether the given pointer matches the address of the
   3823    parent structure.  This check was already generated by the call
   3824    to gt_pch_nx in the main gt_pch_p_*() function that is calling
   3825    this code.  */
   3826 
   3827 static void
   3828 write_types_local_user_process_field (type_p f, const struct walk_type_data *d)
   3829 {
   3830   switch (f->kind)
   3831     {
   3832     case TYPE_POINTER:
   3833     case TYPE_STRUCT:
   3834     case TYPE_UNION:
   3835     case TYPE_LANG_STRUCT:
   3836     case TYPE_STRING:
   3837       if (d->in_nested_ptr)
   3838 	oprintf (d->of, "%*s  op (&(%s), &(%s), cookie);\n",
   3839 		 d->indent, "", d->val, d->prev_val[2]);
   3840       oprintf (d->of, "%*s  op (&(%s), NULL, cookie);\n",
   3841 	       d->indent, "", d->val);
   3842       break;
   3843 
   3844     case TYPE_USER_STRUCT:
   3845       if (d->in_ptr_field)
   3846 	oprintf (d->of, "%*s  op (&(%s), NULL, cookie);\n",
   3847 		 d->indent, "", d->val);
   3848       else
   3849 	oprintf (d->of, "%*s  gt_pch_nx (&(%s), op, cookie);\n",
   3850 		 d->indent, "", d->val);
   3851       break;
   3852 
   3853     case TYPE_SCALAR:
   3854     case TYPE_CALLBACK:
   3855       break;
   3856 
   3857     case TYPE_ARRAY:
   3858     case TYPE_NONE:
   3859     case TYPE_UNDEFINED:
   3860       gcc_unreachable ();
   3861     }
   3862 }
   3863 
   3864 
   3865 /* Write a function to PCH walk all the fields of type S on OF.
   3866    D contains data needed by walk_type to recurse into the fields of S.  */
   3867 
   3868 static void
   3869 write_pch_user_walking_for_structure_body (type_p s, struct walk_type_data *d)
   3870 {
   3871   oprintf (d->of, "\nvoid\n");
   3872   oprintf (d->of, "gt_pch_nx (");
   3873   write_type_decl (d->of, s);
   3874   oprintf (d->of, "* x ATTRIBUTE_UNUSED,\n"
   3875 	   "\tATTRIBUTE_UNUSED gt_pointer_operator op,\n"
   3876 	   "\tATTRIBUTE_UNUSED void *cookie)\n");
   3877   oprintf (d->of, "{\n");
   3878   d->val = "(*x)";
   3879   d->indent = 2;
   3880   d->process_field = write_types_local_user_process_field;
   3881   walk_type (s, d);
   3882   oprintf (d->of, "}\n");
   3883 }
   3884 
   3885 
   3886 /* Emit the user-callable functions needed to mark all the types used
   3887    by the user structure S.  PREFIX is the prefix to use to
   3888    distinguish ggc and pch markers. CHAIN_NEXT is set if S has the
   3889    chain_next option defined.  D contains data needed to pass to
   3890    walk_type when traversing the fields of a type.
   3891 
   3892    For every type T referenced by S, two routines are generated: one
   3893    that takes 'T *', marks the pointer and calls the second routine,
   3894    which just marks the fields of T.  */
   3895 
   3896 static void
   3897 write_pch_user_walking_functions (type_p s, struct walk_type_data *d)
   3898 {
   3899   gcc_assert (s->kind == TYPE_USER_STRUCT);
   3900 
   3901   for (pair_p fld = s->u.s.fields; fld; fld = fld->next)
   3902     {
   3903       type_p fld_type = fld->type;
   3904       if (union_or_struct_p (fld_type))
   3905 	write_pch_user_walking_for_structure_body (fld_type, d);
   3906     }
   3907 }
   3908 
   3909 
   3910 /* process_field routine for local pointer-walking.  */
   3911 
   3912 static void
   3913 write_types_local_process_field (type_p f, const struct walk_type_data *d)
   3914 {
   3915   gcc_assert (d->have_this_obj);
   3916   switch (f->kind)
   3917     {
   3918     case TYPE_POINTER:
   3919     case TYPE_STRUCT:
   3920     case TYPE_UNION:
   3921     case TYPE_LANG_STRUCT:
   3922     case TYPE_STRING:
   3923       oprintf (d->of, "%*sif ((void *)(%s) == this_obj)\n", d->indent, "",
   3924 	       d->prev_val[3]);
   3925       if (d->in_nested_ptr)
   3926 	oprintf (d->of, "%*s  op (&(%s), &(%s), cookie);\n",
   3927 		 d->indent, "", d->val, d->prev_val[2]);
   3928       else
   3929 	oprintf (d->of, "%*s  op (&(%s), NULL, cookie);\n",
   3930 		 d->indent, "", d->val);
   3931       break;
   3932 
   3933     case TYPE_USER_STRUCT:
   3934       oprintf (d->of, "%*sif ((void *)(%s) == this_obj)\n", d->indent, "",
   3935 	       d->prev_val[3]);
   3936       if (d->in_ptr_field)
   3937 	oprintf (d->of, "%*s  op (&(%s), NULL, cookie);\n",
   3938 		 d->indent, "", d->val);
   3939       else
   3940 	oprintf (d->of, "%*s  gt_pch_nx (&(%s), op, cookie);\n",
   3941 		 d->indent, "", d->val);
   3942       break;
   3943 
   3944     case TYPE_SCALAR:
   3945       break;
   3946 
   3947     case TYPE_CALLBACK:
   3948       oprintf (d->of, "%*sif ((void *)(%s) == this_obj)\n", d->indent, "",
   3949 	       d->prev_val[3]);
   3950       oprintf (d->of, "%*s  gt_pch_note_callback (&(%s), this_obj);\n",
   3951 	       d->indent, "", d->val);
   3952       break;
   3953 
   3954     case TYPE_ARRAY:
   3955     case TYPE_NONE:
   3956     case TYPE_UNDEFINED:
   3957       gcc_unreachable ();
   3958     }
   3959 }
   3960 
   3961 
   3962 /* For S, a structure that's part of ORIG_S, and using parameters
   3963    PARAM, write out a routine that:
   3964    - Is of type gt_note_pointers
   3965    - Calls PROCESS_FIELD on each field of S or its substructures.
   3966 */
   3967 
   3968 static void
   3969 write_local_func_for_structure (const_type_p orig_s, type_p s)
   3970 {
   3971   struct walk_type_data d;
   3972 
   3973   /* Don't write fns for subclasses, only for the ultimate base class
   3974      within an inheritance hierarchy.  */
   3975   if (s->u.s.base_class)
   3976     return;
   3977 
   3978   memset (&d, 0, sizeof (d));
   3979   d.of = get_output_file_for_structure (s);
   3980   d.process_field = write_types_local_process_field;
   3981   d.opt = s->u.s.opt;
   3982   d.line = &s->u.s.line;
   3983   d.bitmap = s->u.s.bitmap;
   3984   d.prev_val[0] = d.prev_val[2] = "*x";
   3985   d.prev_val[1] = "not valid postage";	/* Guarantee an error.  */
   3986   d.prev_val[3] = "x";
   3987   d.val = "(*x)";
   3988   d.fn_wants_lvalue = true;
   3989 
   3990   oprintf (d.of, "\n");
   3991   oprintf (d.of, "void\n");
   3992   oprintf (d.of, "gt_pch_p_");
   3993   output_mangled_typename (d.of, orig_s);
   3994   oprintf (d.of, " (ATTRIBUTE_UNUSED void *this_obj,\n"
   3995 	   "\tvoid *x_p,\n"
   3996 	   "\tATTRIBUTE_UNUSED gt_pointer_operator op,\n"
   3997 	   "\tATTRIBUTE_UNUSED void *cookie)\n");
   3998   oprintf (d.of, "{\n");
   3999   oprintf (d.of, "  %s %s * x ATTRIBUTE_UNUSED = (%s %s *)x_p;\n",
   4000 	   s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag,
   4001 	   s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag);
   4002   d.indent = 2;
   4003   d.have_this_obj = true;
   4004 
   4005   if (s->kind != TYPE_USER_STRUCT)
   4006     walk_type (s, &d);
   4007   else
   4008     {
   4009       /* User structures have no fields to walk. Simply generate a
   4010 	 call to the user-provided PCH walker.  */
   4011       oprintf (d.of, "%*sif ((void *)(%s) == this_obj)\n", d.indent, "",
   4012 	       d.prev_val[3]);
   4013       oprintf (d.of, "%*s  gt_pch_nx (&(%s), op, cookie);\n",
   4014 	       d.indent, "", d.val);
   4015     }
   4016 
   4017   oprintf (d.of, "}\n");
   4018 
   4019   /* Write user-callable entry points for the PCH walking routines.  */
   4020   if (orig_s->kind == TYPE_USER_STRUCT)
   4021     write_pch_user_walking_functions (s, &d);
   4022 
   4023   for (options_p o = s->u.s.opt; o; o = o->next)
   4024     if (strcmp (o->name, "for_user") == 0)
   4025       {
   4026 	write_pch_user_walking_for_structure_body (s, &d);
   4027 	break;
   4028       }
   4029 }
   4030 
   4031 /* Write out local marker routines for STRUCTURES and PARAM_STRUCTS.  */
   4032 
   4033 static void
   4034 write_local (outf_p output_header, type_p structures)
   4035 {
   4036   type_p s;
   4037 
   4038   if (!output_header)
   4039     return;
   4040 
   4041   oprintf (output_header, "\n/* Local pointer-walking routines.  */\n");
   4042   for (s = structures; s; s = s->next)
   4043     if (s->gc_used == GC_POINTED_TO || s->gc_used == GC_MAYBE_POINTED_TO)
   4044       {
   4045 	options_p opt;
   4046 
   4047 	if (s->u.s.line.file == NULL)
   4048 	  continue;
   4049  	for (opt = s->u.s.opt; opt; opt = opt->next)
   4050 	  if (strcmp (opt->name, "ptr_alias") == 0
   4051 	      && opt->kind == OPTION_TYPE)
   4052 	    {
   4053 	      const_type_p const t = (const_type_p) opt->info.type;
   4054 	      if (t->kind == TYPE_STRUCT
   4055 		  || t->kind == TYPE_UNION || t->kind == TYPE_LANG_STRUCT)
   4056 		{
   4057 		  oprintf (output_header, "#define gt_pch_p_");
   4058 		  output_mangled_typename (output_header, s);
   4059 		  oprintf (output_header, " gt_pch_p_");
   4060 		  output_mangled_typename (output_header, t);
   4061 		  oprintf (output_header, "\n");
   4062 		}
   4063 	      else
   4064 		error_at_line (&s->u.s.line,
   4065 			       "structure alias is not a structure");
   4066 	      break;
   4067 	    }
   4068 	if (opt)
   4069 	  continue;
   4070 
   4071 	/* Declare the marker procedure only once.  */
   4072 	oprintf (output_header, "extern void gt_pch_p_");
   4073 	output_mangled_typename (output_header, s);
   4074 	oprintf (output_header,
   4075 		 "\n    (void *, void *, gt_pointer_operator, void *);\n");
   4076 
   4077 	if (s->kind == TYPE_LANG_STRUCT)
   4078 	  {
   4079 	    type_p ss;
   4080 	    for (ss = s->u.s.lang_struct; ss; ss = ss->next)
   4081 	      write_local_func_for_structure (s, ss);
   4082 	  }
   4083 	else
   4084 	  write_local_func_for_structure (s, s);
   4085       }
   4086 }
   4087 
   4088 /* Nonzero if S is a type for which typed GC allocators should be output.  */
   4089 
   4090 #define USED_BY_TYPED_GC_P(s)						\
   4091   ((s->kind == TYPE_POINTER						\
   4092     && (s->u.p->gc_used == GC_POINTED_TO				\
   4093 	|| s->u.p->gc_used == GC_USED))					\
   4094    || (union_or_struct_p (s)   						\
   4095        && ((s)->gc_used == GC_POINTED_TO				\
   4096 	   || ((s)->gc_used == GC_MAYBE_POINTED_TO			\
   4097 	       && s->u.s.line.file != NULL)				\
   4098 	   || ((s)->gc_used == GC_USED					\
   4099 	       && !startswith (s->u.s.tag, "anonymous"))		\
   4100 	   || (s->u.s.base_class && opts_have (s->u.s.opt, "tag")))))
   4101 
   4102 
   4103 
   4104 /* Might T contain any non-pointer elements?  */
   4105 
   4106 static int
   4107 contains_scalar_p (type_p t)
   4108 {
   4109   switch (t->kind)
   4110     {
   4111     case TYPE_STRING:
   4112     case TYPE_POINTER:
   4113       return 0;
   4114     case TYPE_ARRAY:
   4115       return contains_scalar_p (t->u.a.p);
   4116     case TYPE_USER_STRUCT:
   4117       /* User-marked structures will typically contain pointers.  */
   4118       return 0;
   4119     default:
   4120       /* Could also check for structures that have no non-pointer
   4121          fields, but there aren't enough of those to worry about.  */
   4122       return 1;
   4123     }
   4124 }
   4125 
   4126 /* Mangle INPF and print it to F.  */
   4127 
   4128 static void
   4129 put_mangled_filename (outf_p f, const input_file *inpf)
   4130 {
   4131   /* The call to get_output_file_name may indirectly update fn since
   4132      get_output_file_with_visibility caches its result inside, so we
   4133      need the CONST_CAST.  */
   4134   const char *name = get_output_file_name (CONST_CAST (input_file*, inpf));
   4135   if (!f || !name)
   4136     return;
   4137   for (; *name != 0; name++)
   4138     if (ISALNUM (*name))
   4139       oprintf (f, "%c", *name);
   4140     else
   4141       oprintf (f, "%c", '_');
   4142 }
   4143 
   4144 /* Finish off the currently-created root tables in FLP.  PFX, TNAME,
   4145    LASTNAME, and NAME are all strings to insert in various places in
   4146    the resulting code.  */
   4147 
   4148 static void
   4149 finish_root_table (struct flist *flp, const char *pfx, const char *lastname,
   4150 		   const char *tname, const char *name)
   4151 {
   4152   struct flist *fli2;
   4153 
   4154   for (fli2 = flp; fli2; fli2 = fli2->next)
   4155     if (fli2->started_p)
   4156       {
   4157 	oprintf (fli2->f, "  %s\n", lastname);
   4158 	oprintf (fli2->f, "};\n\n");
   4159       }
   4160 
   4161   for (fli2 = flp; fli2 && base_files; fli2 = fli2->next)
   4162     if (fli2->started_p)
   4163       {
   4164 	lang_bitmap bitmap = get_lang_bitmap (fli2->file);
   4165 	int fnum;
   4166 
   4167 	for (fnum = 0; bitmap != 0; fnum++, bitmap >>= 1)
   4168 	  if (bitmap & 1)
   4169 	    {
   4170 	      oprintf (base_files[fnum],
   4171 		       "extern const struct %s gt_%s_", tname, pfx);
   4172 	      put_mangled_filename (base_files[fnum], fli2->file);
   4173 	      oprintf (base_files[fnum], "[];\n");
   4174 	    }
   4175       }
   4176 
   4177   {
   4178     size_t fnum;
   4179     for (fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
   4180       oprintf (base_files[fnum],
   4181 	       "EXPORTED_CONST struct %s * const %s[] = {\n", tname, name);
   4182   }
   4183 
   4184 
   4185   for (fli2 = flp; fli2; fli2 = fli2->next)
   4186     if (fli2->started_p)
   4187       {
   4188 	lang_bitmap bitmap = get_lang_bitmap (fli2->file);
   4189 	int fnum;
   4190 
   4191 	fli2->started_p = 0;
   4192 
   4193 	for (fnum = 0; base_files && bitmap != 0; fnum++, bitmap >>= 1)
   4194 	  if (bitmap & 1)
   4195 	    {
   4196 	      oprintf (base_files[fnum], "  gt_%s_", pfx);
   4197 	      put_mangled_filename (base_files[fnum], fli2->file);
   4198 	      oprintf (base_files[fnum], ",\n");
   4199 	    }
   4200       }
   4201 
   4202   {
   4203     size_t fnum;
   4204     for (fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
   4205       {
   4206 	oprintf (base_files[fnum], "  NULL\n");
   4207 	oprintf (base_files[fnum], "};\n");
   4208       }
   4209   }
   4210 }
   4211 
   4212 /* Finish off the created gt_clear_caches_file_c functions.  */
   4213 
   4214 static void
   4215 finish_cache_funcs (flist *flp)
   4216 {
   4217   struct flist *fli2;
   4218 
   4219   for (fli2 = flp; fli2; fli2 = fli2->next)
   4220     if (fli2->started_p)
   4221       {
   4222 	oprintf (fli2->f, "}\n\n");
   4223       }
   4224 
   4225   for (fli2 = flp; fli2 && base_files; fli2 = fli2->next)
   4226     if (fli2->started_p)
   4227       {
   4228 	lang_bitmap bitmap = get_lang_bitmap (fli2->file);
   4229 	int fnum;
   4230 
   4231 	for (fnum = 0; bitmap != 0; fnum++, bitmap >>= 1)
   4232 	  if (bitmap & 1)
   4233 	    {
   4234 	      oprintf (base_files[fnum], "extern void gt_clear_caches_");
   4235 	      put_mangled_filename (base_files[fnum], fli2->file);
   4236 	      oprintf (base_files[fnum], " ();\n");
   4237 	    }
   4238       }
   4239 
   4240   for (size_t fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
   4241     oprintf (base_files[fnum], "void\ngt_clear_caches ()\n{\n");
   4242 
   4243   for (fli2 = flp; fli2; fli2 = fli2->next)
   4244     if (fli2->started_p)
   4245       {
   4246 	lang_bitmap bitmap = get_lang_bitmap (fli2->file);
   4247 	int fnum;
   4248 
   4249 	fli2->started_p = 0;
   4250 
   4251 	for (fnum = 0; base_files && bitmap != 0; fnum++, bitmap >>= 1)
   4252 	  if (bitmap & 1)
   4253 	    {
   4254 	      oprintf (base_files[fnum], "  gt_clear_caches_");
   4255 	      put_mangled_filename (base_files[fnum], fli2->file);
   4256 	      oprintf (base_files[fnum], " ();\n");
   4257 	    }
   4258       }
   4259 
   4260   for (size_t fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
   4261     {
   4262       oprintf (base_files[fnum], "}\n");
   4263     }
   4264 }
   4265 
   4266 /* Write the first three fields (pointer, count and stride) for
   4267    root NAME to F.  V and LINE are as for write_root.
   4268 
   4269    Return true if the entry could be written; return false on error.  */
   4270 
   4271 static bool
   4272 start_root_entry (outf_p f, pair_p v, const char *name, struct fileloc *line)
   4273 {
   4274   type_p ap;
   4275 
   4276   if (!v)
   4277     {
   4278       error_at_line (line, "`%s' is too complex to be a root", name);
   4279       return false;
   4280     }
   4281 
   4282   oprintf (f, "  {\n");
   4283   oprintf (f, "    &%s,\n", name);
   4284   oprintf (f, "    1");
   4285 
   4286   for (ap = v->type; ap->kind == TYPE_ARRAY; ap = ap->u.a.p)
   4287     if (ap->u.a.len[0])
   4288       oprintf (f, " * (%s)", ap->u.a.len);
   4289     else if (ap == v->type)
   4290       oprintf (f, " * ARRAY_SIZE (%s)", v->name);
   4291   oprintf (f, ",\n");
   4292   oprintf (f, "    sizeof (%s", v->name);
   4293   for (ap = v->type; ap->kind == TYPE_ARRAY; ap = ap->u.a.p)
   4294     oprintf (f, "[0]");
   4295   oprintf (f, "),\n");
   4296   return true;
   4297 }
   4298 
   4299 /* A subroutine of write_root for writing the roots for field FIELD_NAME,
   4300    which has type FIELD_TYPE.  Parameters F to EMIT_PCH are the parameters
   4301    of the caller.  */
   4302 
   4303 static void
   4304 write_field_root (outf_p f, pair_p v, type_p type, const char *name,
   4305 		  int has_length, struct fileloc *line,
   4306 		  bool emit_pch, type_p field_type, const char *field_name)
   4307 {
   4308   struct pair newv;
   4309   /* If the field reference is relative to V, rather than to some
   4310      subcomponent of V, we can mark any subarrays with a single stride.
   4311      We're effectively treating the field as a global variable in its
   4312      own right.  */
   4313   if (v && type == v->type)
   4314     {
   4315       newv = *v;
   4316       newv.type = field_type;
   4317       newv.name = ACONCAT ((v->name, ".", field_name, NULL));
   4318       v = &newv;
   4319     }
   4320   /* Otherwise, any arrays nested in the structure are too complex to
   4321      handle.  */
   4322   else if (field_type->kind == TYPE_ARRAY)
   4323     v = NULL;
   4324   write_root (f, v, field_type, ACONCAT ((name, ".", field_name, NULL)),
   4325 	      has_length, line, emit_pch);
   4326 }
   4327 
   4328 /* Write out to F the table entry and any marker routines needed to
   4329    mark NAME as TYPE.  V can be one of three values:
   4330 
   4331      - null, if NAME is too complex to represent using a single
   4332        count and stride.  In this case, it is an error for NAME to
   4333        contain any gc-ed data.
   4334 
   4335      - the outermost array that contains NAME, if NAME is part of an array.
   4336 
   4337      - the C variable that contains NAME, if NAME is not part of an array.
   4338 
   4339    LINE is the line of the C source that declares the root variable.
   4340    HAS_LENGTH is nonzero iff V was a variable-length array.  */
   4341 
   4342 static void
   4343 write_root (outf_p f, pair_p v, type_p type, const char *name, int has_length,
   4344 	    struct fileloc *line, bool emit_pch)
   4345 {
   4346   switch (type->kind)
   4347     {
   4348     case TYPE_STRUCT:
   4349       {
   4350 	pair_p fld;
   4351 	for (fld = type->u.s.fields; fld; fld = fld->next)
   4352 	  {
   4353 	    int skip_p = 0;
   4354 	    const char *desc = NULL;
   4355 	    options_p o;
   4356 
   4357 	    for (o = fld->opt; o; o = o->next)
   4358 	      if (strcmp (o->name, "skip") == 0)
   4359 		skip_p = 1;
   4360 	      else if (strcmp (o->name, "desc") == 0
   4361 		       && o->kind == OPTION_STRING)
   4362 		desc = o->info.string;
   4363 	      else
   4364 		error_at_line (line,
   4365 			       "field `%s' of global `%s' has unknown option `%s'",
   4366 			       fld->name, name, o->name);
   4367 
   4368 	    if (skip_p)
   4369 	      continue;
   4370 	    else if (desc && fld->type->kind == TYPE_UNION)
   4371 	      {
   4372 		pair_p validf = NULL;
   4373 		pair_p ufld;
   4374 
   4375 		for (ufld = fld->type->u.s.fields; ufld; ufld = ufld->next)
   4376 		  {
   4377 		    const char *tag = NULL;
   4378 		    options_p oo;
   4379  		    for (oo = ufld->opt; oo; oo = oo->next)
   4380 		      if (strcmp (oo->name, "tag") == 0
   4381 			  && oo->kind == OPTION_STRING)
   4382 			tag = oo->info.string;
   4383 		    if (tag == NULL || strcmp (tag, desc) != 0)
   4384 		      continue;
   4385 		    if (validf != NULL)
   4386 		      error_at_line (line,
   4387 				     "both `%s.%s.%s' and `%s.%s.%s' have tag `%s'",
   4388 				     name, fld->name, validf->name,
   4389 				     name, fld->name, ufld->name, tag);
   4390 		    validf = ufld;
   4391 		  }
   4392 		if (validf != NULL)
   4393 		  write_field_root (f, v, type, name, 0, line, emit_pch,
   4394 				    validf->type,
   4395 				    ACONCAT ((fld->name, ".",
   4396 					      validf->name, NULL)));
   4397 	      }
   4398 	    else if (desc)
   4399 	      error_at_line (line,
   4400 			     "global `%s.%s' has `desc' option but is not union",
   4401 			     name, fld->name);
   4402 	    else
   4403 	      write_field_root (f, v, type, name, 0, line, emit_pch, fld->type,
   4404 				fld->name);
   4405 	  }
   4406       }
   4407       break;
   4408 
   4409     case TYPE_ARRAY:
   4410       {
   4411 	char *newname;
   4412 	newname = xasprintf ("%s[0]", name);
   4413 	write_root (f, v, type->u.a.p, newname, has_length, line, emit_pch);
   4414 	free (newname);
   4415       }
   4416       break;
   4417 
   4418     case TYPE_USER_STRUCT:
   4419       error_at_line (line, "`%s' must be a pointer type, because it is "
   4420 	             "a GC root and its type is marked with GTY((user))",
   4421 		     v->name);
   4422       break;
   4423 
   4424     case TYPE_POINTER:
   4425       {
   4426 	const_type_p tp;
   4427 
   4428 	if (!start_root_entry (f, v, name, line))
   4429 	  return;
   4430 
   4431 	tp = type->u.p;
   4432 
   4433 	if (!has_length && union_or_struct_p (tp))
   4434 	  {
   4435 	    tp = get_ultimate_base_class (tp);
   4436 	    const char *id_for_tag = filter_type_name (tp->u.s.tag);
   4437 	    oprintf (f, "    &gt_ggc_mx_%s,\n", id_for_tag);
   4438 	    if (emit_pch)
   4439 	      oprintf (f, "    &gt_pch_nx_%s", id_for_tag);
   4440 	    else
   4441 	      oprintf (f, "    NULL");
   4442 	    if (id_for_tag != tp->u.s.tag)
   4443 	      free (CONST_CAST (char *, id_for_tag));
   4444 	  }
   4445 	else if (has_length
   4446 		 && (tp->kind == TYPE_POINTER || union_or_struct_p (tp)))
   4447 	  {
   4448 	    oprintf (f, "    &gt_ggc_ma_%s,\n", name);
   4449 	    if (emit_pch)
   4450 	      oprintf (f, "    &gt_pch_na_%s", name);
   4451 	    else
   4452 	      oprintf (f, "    NULL");
   4453 	  }
   4454 	else
   4455 	  {
   4456 	    error_at_line (line,
   4457 			   "global `%s' is pointer to unimplemented type",
   4458 			   name);
   4459 	  }
   4460 	oprintf (f, "\n  },\n");
   4461       }
   4462       break;
   4463 
   4464     case TYPE_STRING:
   4465       {
   4466 	if (!start_root_entry (f, v, name, line))
   4467 	  return;
   4468 
   4469 	oprintf (f, "    (gt_pointer_walker) &gt_ggc_m_S,\n");
   4470 	oprintf (f, "    (gt_pointer_walker) &gt_pch_n_S\n");
   4471 	oprintf (f, "  },\n");
   4472       }
   4473       break;
   4474 
   4475     case TYPE_SCALAR:
   4476       break;
   4477 
   4478     case TYPE_NONE:
   4479     case TYPE_UNDEFINED:
   4480     case TYPE_UNION:
   4481     case TYPE_LANG_STRUCT:
   4482     case TYPE_CALLBACK:
   4483       error_at_line (line, "global `%s' is unimplemented type", name);
   4484     }
   4485 }
   4486 
   4487 /* This generates a routine to walk an array.  */
   4488 
   4489 static void
   4490 write_array (outf_p f, pair_p v, const struct write_types_data *wtd)
   4491 {
   4492   struct walk_type_data d;
   4493   char *prevval3;
   4494 
   4495   memset (&d, 0, sizeof (d));
   4496   d.of = f;
   4497   d.cookie = wtd;
   4498   d.indent = 2;
   4499   d.line = &v->line;
   4500   d.opt = v->opt;
   4501   d.bitmap = get_lang_bitmap (v->line.file);
   4502 
   4503   d.prev_val[3] = prevval3 = xasprintf ("&%s", v->name);
   4504 
   4505   if (wtd->param_prefix)
   4506     {
   4507       oprintf (f, "static void gt_%sa_%s\n", wtd->param_prefix, v->name);
   4508       oprintf (f, "    (void *, void *, gt_pointer_operator, void *);\n");
   4509       oprintf (f, "static void gt_%sa_%s (ATTRIBUTE_UNUSED void *this_obj,\n",
   4510 	       wtd->param_prefix, v->name);
   4511       oprintf (d.of,
   4512 	       "      ATTRIBUTE_UNUSED void *x_p,\n"
   4513 	       "      ATTRIBUTE_UNUSED gt_pointer_operator op,\n"
   4514 	       "      ATTRIBUTE_UNUSED void * cookie)\n");
   4515       oprintf (d.of, "{\n");
   4516       d.prev_val[0] = d.prev_val[1] = d.prev_val[2] = d.val = v->name;
   4517       d.process_field = write_types_local_process_field;
   4518       d.have_this_obj = true;
   4519       walk_type (v->type, &d);
   4520       oprintf (f, "}\n\n");
   4521     }
   4522 
   4523   d.opt = v->opt;
   4524   oprintf (f, "static void gt_%sa_%s (void *);\n", wtd->prefix, v->name);
   4525   oprintf (f, "static void\ngt_%sa_%s (ATTRIBUTE_UNUSED void *x_p)\n",
   4526 	   wtd->prefix, v->name);
   4527   oprintf (f, "{\n");
   4528   d.prev_val[0] = d.prev_val[1] = d.prev_val[2] = d.val = v->name;
   4529   d.process_field = write_types_process_field;
   4530   d.have_this_obj = false;
   4531   walk_type (v->type, &d);
   4532   free (prevval3);
   4533   oprintf (f, "}\n\n");
   4534 }
   4535 
   4536 /* Output a table describing the locations and types of VARIABLES.  */
   4537 
   4538 static void
   4539 write_roots (pair_p variables, bool emit_pch)
   4540 {
   4541   pair_p v;
   4542   struct flist *flp = NULL;
   4543 
   4544   for (v = variables; v; v = v->next)
   4545     {
   4546       outf_p f =
   4547 	get_output_file_with_visibility (CONST_CAST (input_file*,
   4548 						     v->line.file));
   4549       struct flist *fli;
   4550       const char *length = NULL;
   4551       int deletable_p = 0;
   4552       options_p o;
   4553       for (o = v->opt; o; o = o->next)
   4554 	if (strcmp (o->name, "length") == 0
   4555 	    && o->kind == OPTION_STRING)
   4556 	  length = o->info.string;
   4557 	else if (strcmp (o->name, "deletable") == 0)
   4558 	  deletable_p = 1;
   4559 	else if (strcmp (o->name, "cache") == 0)
   4560 	  ;
   4561 	else
   4562 	  error_at_line (&v->line,
   4563 			 "global `%s' has unknown option `%s'",
   4564 			 v->name, o->name);
   4565 
   4566       for (fli = flp; fli; fli = fli->next)
   4567 	if (fli->f == f && f)
   4568 	  break;
   4569       if (fli == NULL)
   4570 	{
   4571 	  fli = XNEW (struct flist);
   4572 	  fli->f = f;
   4573 	  fli->next = flp;
   4574 	  fli->started_p = 0;
   4575 	  fli->file = v->line.file;
   4576 	  gcc_assert (fli->file);
   4577 	  flp = fli;
   4578 
   4579 	  oprintf (f, "\n/* GC roots.  */\n\n");
   4580 	}
   4581 
   4582       if (!deletable_p
   4583 	  && length
   4584 	  && v->type->kind == TYPE_POINTER
   4585 	  && (v->type->u.p->kind == TYPE_POINTER
   4586 	      || v->type->u.p->kind == TYPE_STRUCT))
   4587 	{
   4588 	  write_array (f, v, &ggc_wtd);
   4589 	  write_array (f, v, &pch_wtd);
   4590 	}
   4591     }
   4592 
   4593   for (v = variables; v; v = v->next)
   4594     {
   4595       outf_p f = get_output_file_with_visibility (CONST_CAST (input_file*,
   4596 							      v->line.file));
   4597       struct flist *fli;
   4598       int skip_p = 0;
   4599       int length_p = 0;
   4600       options_p o;
   4601 
   4602       for (o = v->opt; o; o = o->next)
   4603 	if (strcmp (o->name, "length") == 0)
   4604 	  length_p = 1;
   4605 	else if (strcmp (o->name, "deletable") == 0)
   4606 	  skip_p = 1;
   4607 
   4608       if (skip_p)
   4609 	continue;
   4610 
   4611       for (fli = flp; fli; fli = fli->next)
   4612 	if (fli->f == f)
   4613 	  break;
   4614       if (!fli->started_p)
   4615 	{
   4616 	  fli->started_p = 1;
   4617 
   4618 	  oprintf (f, "EXPORTED_CONST struct ggc_root_tab gt_ggc_r_");
   4619 	  put_mangled_filename (f, v->line.file);
   4620 	  oprintf (f, "[] = {\n");
   4621 	}
   4622 
   4623       write_root (f, v, v->type, v->name, length_p, &v->line, emit_pch);
   4624     }
   4625 
   4626   finish_root_table (flp, "ggc_r", "LAST_GGC_ROOT_TAB", "ggc_root_tab",
   4627 		     "gt_ggc_rtab");
   4628 
   4629   for (v = variables; v; v = v->next)
   4630     {
   4631       outf_p f = get_output_file_with_visibility (CONST_CAST (input_file*,
   4632 							      v->line.file));
   4633       struct flist *fli;
   4634       int skip_p = 1;
   4635       options_p o;
   4636 
   4637       for (o = v->opt; o; o = o->next)
   4638 	if (strcmp (o->name, "deletable") == 0)
   4639 	  skip_p = 0;
   4640 
   4641       if (skip_p)
   4642 	continue;
   4643 
   4644       for (fli = flp; fli; fli = fli->next)
   4645 	if (fli->f == f)
   4646 	  break;
   4647       if (!fli->started_p)
   4648 	{
   4649 	  fli->started_p = 1;
   4650 
   4651 	  oprintf (f, "EXPORTED_CONST struct ggc_root_tab gt_ggc_rd_");
   4652 	  put_mangled_filename (f, v->line.file);
   4653 	  oprintf (f, "[] = {\n");
   4654 	}
   4655 
   4656       oprintf (f, "  { &%s, 1, sizeof (%s), NULL, NULL },\n",
   4657 	       v->name, v->name);
   4658     }
   4659 
   4660   finish_root_table (flp, "ggc_rd", "LAST_GGC_ROOT_TAB", "ggc_root_tab",
   4661 		     "gt_ggc_deletable_rtab");
   4662 
   4663   for (v = variables; v; v = v->next)
   4664     {
   4665       outf_p f = get_output_file_with_visibility (CONST_CAST (input_file*,
   4666 							      v->line.file));
   4667       struct flist *fli;
   4668       bool cache = false;
   4669       options_p o;
   4670 
   4671       for (o = v->opt; o; o = o->next)
   4672 	if (strcmp (o->name, "cache") == 0)
   4673 	  cache = true;
   4674        if (!cache)
   4675 	continue;
   4676 
   4677       for (fli = flp; fli; fli = fli->next)
   4678 	if (fli->f == f)
   4679 	  break;
   4680       if (!fli->started_p)
   4681 	{
   4682 	  fli->started_p = 1;
   4683 
   4684 	  oprintf (f, "void\ngt_clear_caches_");
   4685 	  put_mangled_filename (f, v->line.file);
   4686 	  oprintf (f, " ()\n{\n");
   4687 	}
   4688 
   4689       oprintf (f, "  gt_cleare_cache (%s);\n", v->name);
   4690     }
   4691 
   4692   finish_cache_funcs (flp);
   4693 
   4694   if (!emit_pch)
   4695     return;
   4696 
   4697   for (v = variables; v; v = v->next)
   4698     {
   4699       outf_p f = get_output_file_with_visibility (CONST_CAST (input_file*,
   4700 							      v->line.file));
   4701       struct flist *fli;
   4702       int skip_p = 0;
   4703       options_p o;
   4704 
   4705       for (o = v->opt; o; o = o->next)
   4706 	if (strcmp (o->name, "deletable") == 0)
   4707 	  {
   4708 	    skip_p = 1;
   4709 	    break;
   4710 	  }
   4711 
   4712       if (skip_p)
   4713 	continue;
   4714 
   4715       if (!contains_scalar_p (v->type))
   4716 	continue;
   4717 
   4718       for (fli = flp; fli; fli = fli->next)
   4719 	if (fli->f == f)
   4720 	  break;
   4721       if (!fli->started_p)
   4722 	{
   4723 	  fli->started_p = 1;
   4724 
   4725 	  oprintf (f, "EXPORTED_CONST struct ggc_root_tab gt_pch_rs_");
   4726 	  put_mangled_filename (f, v->line.file);
   4727 	  oprintf (f, "[] = {\n");
   4728 	}
   4729 
   4730       oprintf (f, "  { &%s, 1, sizeof (%s), NULL, NULL },\n",
   4731 	       v->name, v->name);
   4732     }
   4733 
   4734   finish_root_table (flp, "pch_rs", "LAST_GGC_ROOT_TAB", "ggc_root_tab",
   4735 		     "gt_pch_scalar_rtab");
   4736 }
   4737 
   4738 /* Prints not-as-ugly version of a typename of T to OF.  Trades the uniquness
   4739    guaranteee for somewhat increased readability.  If name conflicts do happen,
   4740    this funcion will have to be adjusted to be more like
   4741    output_mangled_typename.  */
   4742 
   4743 #define INDENT 2
   4744 
   4745 /* Dumps the value of typekind KIND.  */
   4746 
   4747 static void
   4748 dump_typekind (int indent, enum typekind kind)
   4749 {
   4750   printf ("%*ckind = ", indent, ' ');
   4751   switch (kind)
   4752     {
   4753     case TYPE_SCALAR:
   4754       printf ("TYPE_SCALAR");
   4755       break;
   4756     case TYPE_STRING:
   4757       printf ("TYPE_STRING");
   4758       break;
   4759     case TYPE_STRUCT:
   4760       printf ("TYPE_STRUCT");
   4761       break;
   4762     case TYPE_UNDEFINED:
   4763       printf ("TYPE_UNDEFINED");
   4764       break;
   4765     case TYPE_USER_STRUCT:
   4766       printf ("TYPE_USER_STRUCT");
   4767       break;
   4768     case TYPE_UNION:
   4769       printf ("TYPE_UNION");
   4770       break;
   4771     case TYPE_POINTER:
   4772       printf ("TYPE_POINTER");
   4773       break;
   4774     case TYPE_ARRAY:
   4775       printf ("TYPE_ARRAY");
   4776       break;
   4777     case TYPE_CALLBACK:
   4778       printf ("TYPE_CALLBACK");
   4779       break;
   4780     case TYPE_LANG_STRUCT:
   4781       printf ("TYPE_LANG_STRUCT");
   4782       break;
   4783     default:
   4784       gcc_unreachable ();
   4785     }
   4786   printf ("\n");
   4787 }
   4788 
   4789 /* Dumps the value of GC_USED flag.  */
   4790 
   4791 static void
   4792 dump_gc_used (int indent, enum gc_used_enum gc_used)
   4793 {
   4794   printf ("%*cgc_used = ", indent, ' ');
   4795   switch (gc_used)
   4796     {
   4797     case GC_UNUSED:
   4798       printf ("GC_UNUSED");
   4799       break;
   4800     case GC_USED:
   4801       printf ("GC_USED");
   4802       break;
   4803     case GC_MAYBE_POINTED_TO:
   4804       printf ("GC_MAYBE_POINTED_TO");
   4805       break;
   4806     case GC_POINTED_TO:
   4807       printf ("GC_POINTED_TO");
   4808       break;
   4809     default:
   4810       gcc_unreachable ();
   4811     }
   4812   printf ("\n");
   4813 }
   4814 
   4815 /* Dumps the type options OPT.  */
   4816 
   4817 static void
   4818 dump_options (int indent, options_p opt)
   4819 {
   4820   options_p o;
   4821   printf ("%*coptions = ", indent, ' ');
   4822   o = opt;
   4823   while (o)
   4824     {
   4825       switch (o->kind)
   4826 	{
   4827 	case OPTION_STRING:
   4828 	  printf ("%s:string %s ", o->name, o->info.string);
   4829 	  break;
   4830 	case OPTION_TYPE:
   4831 	  printf ("%s:type ", o->name);
   4832 	  dump_type (indent+1, o->info.type);
   4833 	  break;
   4834 	case OPTION_NESTED:
   4835 	  printf ("%s:nested ", o->name);
   4836 	  break;
   4837 	case OPTION_NONE:
   4838 	  gcc_unreachable ();
   4839 	}
   4840       o = o->next;
   4841     }
   4842   printf ("\n");
   4843 }
   4844 
   4845 /* Dumps the source file location in LINE.  */
   4846 
   4847 static void
   4848 dump_fileloc (int indent, struct fileloc line)
   4849 {
   4850   printf ("%*cfileloc: file = %s, line = %d\n", indent, ' ',
   4851 	  get_input_file_name (line.file),
   4852 	  line.line);
   4853 }
   4854 
   4855 /* Recursively dumps the struct, union, or a language-specific
   4856    struct T.  */
   4857 
   4858 static void
   4859 dump_type_u_s (int indent, type_p t)
   4860 {
   4861   pair_p fields;
   4862 
   4863   gcc_assert (union_or_struct_p (t));
   4864   printf ("%*cu.s.tag = %s\n", indent, ' ', t->u.s.tag);
   4865   dump_fileloc (indent, t->u.s.line);
   4866   printf ("%*cu.s.fields =\n", indent, ' ');
   4867   fields = t->u.s.fields;
   4868   while (fields)
   4869     {
   4870       dump_pair (indent + INDENT, fields);
   4871       fields = fields->next;
   4872     }
   4873   printf ("%*cend of fields of type %p\n", indent, ' ', (void *) t);
   4874   dump_options (indent, t->u.s.opt);
   4875   printf ("%*cu.s.bitmap = %X\n", indent, ' ', t->u.s.bitmap);
   4876   if (t->kind == TYPE_LANG_STRUCT)
   4877     {
   4878       printf ("%*cu.s.lang_struct:\n", indent, ' ');
   4879       dump_type_list (indent + INDENT, t->u.s.lang_struct);
   4880     }
   4881 }
   4882 
   4883 /* Recursively dumps the array T.  */
   4884 
   4885 static void
   4886 dump_type_u_a (int indent, type_p t)
   4887 {
   4888   gcc_assert (t->kind == TYPE_ARRAY);
   4889   printf ("%*clen = %s, u.a.p:\n", indent, ' ', t->u.a.len);
   4890   dump_type_list (indent + INDENT, t->u.a.p);
   4891 }
   4892 
   4893 /* Recursively dumps the type list T.  */
   4894 
   4895 static void
   4896 dump_type_list (int indent, type_p t)
   4897 {
   4898   type_p p = t;
   4899   while (p)
   4900     {
   4901       dump_type (indent, p);
   4902       p = p->next;
   4903     }
   4904 }
   4905 
   4906 static htab_t seen_types;
   4907 
   4908 /* Recursively dumps the type T if it was not dumped previously.  */
   4909 
   4910 static void
   4911 dump_type (int indent, type_p t)
   4912 {
   4913   PTR *slot;
   4914 
   4915   printf ("%*cType at %p: ", indent, ' ', (void *) t);
   4916   if (t->kind == TYPE_UNDEFINED)
   4917     {
   4918       gcc_assert (t->gc_used == GC_UNUSED);
   4919       printf ("undefined.\n");
   4920       return;
   4921     }
   4922 
   4923   if (seen_types == NULL)
   4924     seen_types = htab_create (100, htab_hash_pointer, htab_eq_pointer, NULL);
   4925 
   4926   slot = htab_find_slot (seen_types, t, INSERT);
   4927   if (*slot != NULL)
   4928     {
   4929       printf ("already seen.\n");
   4930       return;
   4931     }
   4932   *slot = t;
   4933   printf ("\n");
   4934 
   4935   dump_typekind (indent, t->kind);
   4936   printf ("%*cpointer_to = %p\n", indent + INDENT, ' ',
   4937 	  (void *) t->pointer_to);
   4938   dump_gc_used (indent + INDENT, t->gc_used);
   4939   switch (t->kind)
   4940     {
   4941     case TYPE_SCALAR:
   4942       printf ("%*cscalar_is_char = %s\n", indent + INDENT, ' ',
   4943 	      t->u.scalar_is_char ? "true" : "false");
   4944       break;
   4945     case TYPE_STRING:
   4946     case TYPE_CALLBACK:
   4947       break;
   4948     case TYPE_STRUCT:
   4949     case TYPE_UNION:
   4950     case TYPE_LANG_STRUCT:
   4951     case TYPE_USER_STRUCT:
   4952       dump_type_u_s (indent + INDENT, t);
   4953       break;
   4954     case TYPE_POINTER:
   4955       printf ("%*cp:\n", indent + INDENT, ' ');
   4956       dump_type (indent + INDENT, t->u.p);
   4957       break;
   4958     case TYPE_ARRAY:
   4959       dump_type_u_a (indent + INDENT, t);
   4960       break;
   4961     default:
   4962       gcc_unreachable ();
   4963     }
   4964   printf ("%*cEnd of type at %p\n", indent, ' ', (void *) t);
   4965 }
   4966 
   4967 /* Dumps the pair P.  */
   4968 
   4969 static void
   4970 dump_pair (int indent, pair_p p)
   4971 {
   4972   printf ("%*cpair: name = %s\n", indent, ' ', p->name);
   4973   dump_type (indent, p->type);
   4974   dump_fileloc (indent, p->line);
   4975   dump_options (indent, p->opt);
   4976   printf ("%*cEnd of pair %s\n", indent, ' ', p->name);
   4977 }
   4978 
   4979 /* Dumps the list of pairs PP.  */
   4980 
   4981 static void
   4982 dump_pair_list (const char *name, pair_p pp)
   4983 {
   4984   pair_p p;
   4985   printf ("%s:\n", name);
   4986   for (p = pp; p != NULL; p = p->next)
   4987     dump_pair (0, p);
   4988   printf ("End of %s\n\n", name);
   4989 }
   4990 
   4991 /* Dumps the STRUCTURES.  */
   4992 
   4993 static void
   4994 dump_structures (const char *name, type_p structures)
   4995 {
   4996   printf ("%s:\n", name);
   4997   dump_type_list (0, structures);
   4998   printf ("End of %s\n\n", name);
   4999 }
   5000 
   5001 /* Dumps the internal structures of gengtype.  This is useful to debug
   5002    gengtype itself, or to understand what it does, e.g. for plugin
   5003    developers.  */
   5004 
   5005 static void
   5006 dump_everything (void)
   5007 {
   5008   dump_pair_list ("typedefs", typedefs);
   5009   dump_structures ("structures", structures);
   5010   dump_pair_list ("variables", variables);
   5011 
   5012   /* Allocated with the first call to dump_type.  */
   5013   htab_delete (seen_types);
   5014 }
   5015 
   5016 
   5018 
   5019 /* Option specification for getopt_long.  */
   5020 static const struct option gengtype_long_options[] = {
   5021   {"help", no_argument, NULL, 'h'},
   5022   {"version", no_argument, NULL, 'V'},
   5023   {"verbose", no_argument, NULL, 'v'},
   5024   {"dump", no_argument, NULL, 'd'},
   5025   {"debug", no_argument, NULL, 'D'},
   5026   {"plugin", required_argument, NULL, 'P'},
   5027   {"srcdir", required_argument, NULL, 'S'},
   5028   {"backupdir", required_argument, NULL, 'B'},
   5029   {"inputs", required_argument, NULL, 'I'},
   5030   {"read-state", required_argument, NULL, 'r'},
   5031   {"write-state", required_argument, NULL, 'w'},
   5032   /* Terminating NULL placeholder.  */
   5033   {NULL, no_argument, NULL, 0},
   5034 };
   5035 
   5036 
   5037 static void
   5038 print_usage (void)
   5039 {
   5040   printf ("Usage: %s\n", progname);
   5041   printf ("\t -h | --help " " \t# Give this help.\n");
   5042   printf ("\t -D | --debug "
   5043 	  " \t# Give debug output to debug %s itself.\n", progname);
   5044   printf ("\t -V | --version " " \t# Give version information.\n");
   5045   printf ("\t -v | --verbose  \t# Increase verbosity.  Can be given several times.\n");
   5046   printf ("\t -d | --dump " " \t# Dump state for debugging.\n");
   5047   printf ("\t -P | --plugin <output-file> <plugin-src> ... "
   5048 	  " \t# Generate for plugin.\n");
   5049   printf ("\t -S | --srcdir <GCC-directory> "
   5050 	  " \t# Specify the GCC source directory.\n");
   5051   printf ("\t -B | --backupdir <directory> "
   5052 	  " \t# Specify the backup directory for updated files.\n");
   5053   printf ("\t -I | --inputs <input-list> "
   5054 	  " \t# Specify the file with source files list.\n");
   5055   printf ("\t -w | --write-state <state-file> " " \t# Write a state file.\n");
   5056   printf ("\t -r | --read-state <state-file> " " \t# Read a state file.\n");
   5057 }
   5058 
   5059 static void
   5060 print_version (void)
   5061 {
   5062   printf ("%s %s%s\n", progname, pkgversion_string, version_string);
   5063   printf ("Report bugs: %s\n", bug_report_url);
   5064 }
   5065 
   5066 /* Parse the program options using getopt_long... */
   5067 static void
   5068 parse_program_options (int argc, char **argv)
   5069 {
   5070   int opt = -1;
   5071   while ((opt = getopt_long (argc, argv, "hVvdP:S:B:I:w:r:D",
   5072 			     gengtype_long_options, NULL)) >= 0)
   5073     {
   5074       switch (opt)
   5075 	{
   5076 	case 'h':		/* --help */
   5077 	  print_usage ();
   5078 	  break;
   5079 	case 'V':		/* --version */
   5080 	  print_version ();
   5081 	  break;
   5082 	case 'd':		/* --dump */
   5083 	  do_dump = 1;
   5084 	  break;
   5085 	case 'D':		/* --debug */
   5086 	  do_debug = 1;
   5087 	  break;
   5088 	case 'v':		/* --verbose */
   5089 	  verbosity_level++;
   5090 	  break;
   5091 	case 'P':		/* --plugin */
   5092 	  if (optarg)
   5093 	    plugin_output_filename = optarg;
   5094 	  else
   5095 	    fatal ("missing plugin output file name");
   5096 	  break;
   5097 	case 'S':		/* --srcdir */
   5098 	  if (optarg)
   5099 	    srcdir = optarg;
   5100 	  else
   5101 	    fatal ("missing source directory");
   5102 	  srcdir_len = strlen (srcdir);
   5103 	  break;
   5104 	case 'B':		/* --backupdir */
   5105 	  if (optarg)
   5106 	    backup_dir = optarg;
   5107 	  else
   5108 	    fatal ("missing backup directory");
   5109 	  break;
   5110 	case 'I':		/* --inputs */
   5111 	  if (optarg)
   5112 	    inputlist = optarg;
   5113 	  else
   5114 	    fatal ("missing input list");
   5115 	  break;
   5116 	case 'r':		/* --read-state */
   5117 	  if (optarg)
   5118 	    read_state_filename = optarg;
   5119 	  else
   5120 	    fatal ("missing read state file");
   5121 	  DBGPRINTF ("read state %s\n", optarg);
   5122 	  break;
   5123 	case 'w':		/* --write-state */
   5124 	  DBGPRINTF ("write state %s\n", optarg);
   5125 	  if (optarg)
   5126 	    write_state_filename = optarg;
   5127 	  else
   5128 	    fatal ("missing write state file");
   5129 	  break;
   5130 	default:
   5131 	  fprintf (stderr, "%s: unknown flag '%c'\n", progname, opt);
   5132 	  print_usage ();
   5133 	  fatal ("unexpected flag");
   5134 	}
   5135     };
   5136   if (plugin_output_filename)
   5137     {
   5138       /* In plugin mode we require some input files.  */
   5139       int i = 0;
   5140       if (optind >= argc)
   5141 	fatal ("no source files given in plugin mode");
   5142       nb_plugin_files = argc - optind;
   5143       plugin_files = XNEWVEC (input_file*, nb_plugin_files);
   5144       for (i = 0; i < (int) nb_plugin_files; i++)
   5145 	{
   5146 	  char *name = argv[i + optind];
   5147 	  plugin_files[i] = input_file_by_name (name);
   5148 	}
   5149     }
   5150 }
   5151 
   5152 
   5153 
   5154 /******* Manage input files.  ******/
   5156 
   5157 /* Hash table of unique input file names.  */
   5158 static htab_t input_file_htab;
   5159 
   5160 /* Find or allocate a new input_file by hash-consing it.  */
   5161 input_file*
   5162 input_file_by_name (const char* name)
   5163 {
   5164   PTR* slot;
   5165   input_file* f = NULL;
   5166   int namlen = 0;
   5167   if (!name)
   5168     return NULL;
   5169   namlen = strlen (name);
   5170   f = XCNEWVAR (input_file, sizeof (input_file)+namlen+2);
   5171   f->inpbitmap = 0;
   5172   f->inpoutf = NULL;
   5173   f->inpisplugin = false;
   5174   strcpy (f->inpname, name);
   5175   slot = htab_find_slot (input_file_htab, f, INSERT);
   5176   gcc_assert (slot != NULL);
   5177   if (*slot)
   5178     {
   5179       /* Already known input file.  */
   5180       free (f);
   5181       return (input_file*)(*slot);
   5182     }
   5183   /* New input file.  */
   5184   *slot = f;
   5185   return f;
   5186     }
   5187 
   5188 /* Hash table support routines for input_file-s.  */
   5189 static hashval_t
   5190 htab_hash_inputfile (const void *p)
   5191 {
   5192   const input_file *inpf = (const input_file *) p;
   5193   gcc_assert (inpf);
   5194   return htab_hash_string (get_input_file_name (inpf));
   5195 }
   5196 
   5197 static int
   5198 htab_eq_inputfile (const void *x, const void *y)
   5199 {
   5200   const input_file *inpfx = (const input_file *) x;
   5201   const input_file *inpfy = (const input_file *) y;
   5202   gcc_assert (inpfx != NULL && inpfy != NULL);
   5203   return !filename_cmp (get_input_file_name (inpfx), get_input_file_name (inpfy));
   5204 }
   5205 
   5206 
   5207 int
   5208 main (int argc, char **argv)
   5209 {
   5210   size_t i;
   5211   static struct fileloc pos = { NULL, 0 };
   5212   outf_p output_header;
   5213 
   5214   /* Mandatory common initializations.  */
   5215   progname = "gengtype";	/* For fatal and messages.  */
   5216   /* Create the hash-table used to hash-cons input files.  */
   5217   input_file_htab =
   5218     htab_create (800, htab_hash_inputfile, htab_eq_inputfile, NULL);
   5219   /* Initialize our special input files.  */
   5220   this_file = input_file_by_name (__FILE__);
   5221   system_h_file = input_file_by_name ("system.h");
   5222   /* Set the scalar_is_char union number for predefined scalar types.  */
   5223   scalar_nonchar.u.scalar_is_char = FALSE;
   5224   scalar_char.u.scalar_is_char = TRUE;
   5225 
   5226   parse_program_options (argc, argv);
   5227 
   5228   if (do_debug)
   5229     {
   5230       time_t now = (time_t) 0;
   5231       time (&now);
   5232       DBGPRINTF ("gengtype started pid %d at %s",
   5233 		 (int) getpid (), ctime (&now));
   5234     }
   5235 
   5236   /* Parse the input list and the input files.  */
   5237   DBGPRINTF ("inputlist %s", inputlist);
   5238   if (read_state_filename)
   5239     {
   5240       if (inputlist)
   5241 	fatal ("input list %s cannot be given with a read state file %s",
   5242 	       inputlist, read_state_filename);
   5243       read_state (read_state_filename);
   5244       DBGPRINT_COUNT_TYPE ("structures after read_state", structures);
   5245     }
   5246   else if (inputlist)
   5247     {
   5248       /* These types are set up with #define or else outside of where
   5249          we can see them.  We should initialize them before calling
   5250          read_input_list.  */
   5251 #define POS_HERE(Call) do { pos.file = this_file; pos.line = __LINE__; \
   5252 	Call;} while (0)
   5253       POS_HERE (do_scalar_typedef ("CUMULATIVE_ARGS", &pos));
   5254       POS_HERE (do_scalar_typedef ("REAL_VALUE_TYPE", &pos));
   5255       POS_HERE (do_scalar_typedef ("FIXED_VALUE_TYPE", &pos));
   5256       POS_HERE (do_scalar_typedef ("double_int", &pos));
   5257       POS_HERE (do_scalar_typedef ("poly_int64_pod", &pos));
   5258       POS_HERE (do_scalar_typedef ("offset_int", &pos));
   5259       POS_HERE (do_scalar_typedef ("widest_int", &pos));
   5260       POS_HERE (do_scalar_typedef ("int64_t", &pos));
   5261       POS_HERE (do_scalar_typedef ("poly_int64", &pos));
   5262       POS_HERE (do_scalar_typedef ("poly_uint64", &pos));
   5263       POS_HERE (do_scalar_typedef ("uint64_t", &pos));
   5264       POS_HERE (do_scalar_typedef ("uint32_t", &pos));
   5265       POS_HERE (do_scalar_typedef ("uint8", &pos));
   5266       POS_HERE (do_scalar_typedef ("uintptr_t", &pos));
   5267       POS_HERE (do_scalar_typedef ("jword", &pos));
   5268       POS_HERE (do_scalar_typedef ("JCF_u2", &pos));
   5269       POS_HERE (do_scalar_typedef ("void", &pos));
   5270       POS_HERE (do_scalar_typedef ("machine_mode", &pos));
   5271       POS_HERE (do_scalar_typedef ("fixed_size_mode", &pos));
   5272       POS_HERE (do_scalar_typedef ("CONSTEXPR", &pos));
   5273       POS_HERE (do_typedef ("PTR",
   5274 			    create_pointer (resolve_typedef ("void", &pos)),
   5275 			    &pos));
   5276 #undef POS_HERE
   5277       read_input_list (inputlist);
   5278       num_build_headers = 0;
   5279       for (i = 0; i < num_gt_files; i++)
   5280 	{
   5281 	  const char *fname = get_input_file_name (gt_files[i]);
   5282 	  parse_file (fname);
   5283 	  DBGPRINTF ("parsed file #%d %s", (int) i, fname);
   5284 	  /* Check if this is a header file generated during the build.  */
   5285 	  int len = strlen (fname);
   5286 	  if (len >= 5
   5287 	      && fname[0] == '.'
   5288 	      && IS_DIR_SEPARATOR (fname[1])
   5289 	      && fname[len-2] == '.'
   5290 	      && fname[len-1] == 'h')
   5291 	    num_build_headers++;
   5292 	}
   5293       if (verbosity_level >= 1)
   5294 	printf ("%s parsed %d files with %d GTY types\n",
   5295 		progname, (int) num_gt_files, type_count);
   5296 
   5297       DBGPRINT_COUNT_TYPE ("structures after parsing", structures);
   5298     }
   5299   else
   5300     fatal ("either an input list or a read state file should be given");
   5301   if (hit_error)
   5302     return 1;
   5303 
   5304 
   5305   if (plugin_output_filename)
   5306     {
   5307       size_t ix = 0;
   5308       /* In plugin mode, we should have read a state file, and have
   5309 	 given at least one plugin file.  */
   5310       if (!read_state_filename)
   5311 	fatal ("No read state given in plugin mode for %s",
   5312 	       plugin_output_filename);
   5313 
   5314       if (nb_plugin_files == 0 || !plugin_files)
   5315 	fatal ("No plugin files given in plugin mode for %s",
   5316 	       plugin_output_filename);
   5317 
   5318       /* Parse our plugin files and augment the state.  */
   5319       for (ix = 0; ix < nb_plugin_files; ix++)
   5320 	{
   5321 	  input_file* pluginput = plugin_files [ix];
   5322 	  pluginput->inpisplugin = true;
   5323 	  parse_file (get_input_file_name (pluginput));
   5324 	}
   5325       if (hit_error)
   5326 	return 1;
   5327 
   5328       plugin_output = create_file ("GCC", plugin_output_filename);
   5329       DBGPRINTF ("created plugin_output %p named %s",
   5330 		 (void *) plugin_output, plugin_output->name);
   5331     }
   5332   else
   5333     {				/* No plugin files, we are in normal mode.  */
   5334       if (!srcdir)
   5335 	fatal ("gengtype needs a source directory in normal mode");
   5336     }
   5337   if (hit_error)
   5338     return 1;
   5339 
   5340   gen_rtx_next ();
   5341 
   5342   set_gc_used (variables);
   5343 
   5344   for (type_p t = structures; t; t = t->next)
   5345     {
   5346       bool for_user = false;
   5347       for (options_p o = t->u.s.opt; o; o = o->next)
   5348 	if (strcmp (o->name, "for_user") == 0)
   5349 	  {
   5350 	    for_user = true;
   5351 	    break;
   5352 	  }
   5353 
   5354       if (for_user)
   5355 	set_gc_used_type (t, GC_POINTED_TO);
   5356     }
   5357  /* The state at this point is read from the state input file or by
   5358     parsing source files and optionally augmented by parsing plugin
   5359     source files.  Write it now.  */
   5360   if (write_state_filename)
   5361     {
   5362       DBGPRINT_COUNT_TYPE ("structures before write_state", structures);
   5363 
   5364       if (hit_error)
   5365 	fatal ("didn't write state file %s after errors",
   5366 	       write_state_filename);
   5367 
   5368       DBGPRINTF ("before write_state %s", write_state_filename);
   5369       write_state (write_state_filename);
   5370 
   5371       if (do_dump)
   5372 	dump_everything ();
   5373 
   5374       /* After having written the state file we return immediately to
   5375 	 avoid generating any output file.  */
   5376       if (hit_error)
   5377 	return 1;
   5378       else
   5379 	return 0;
   5380     }
   5381 
   5382 
   5383   open_base_files ();
   5384 
   5385   output_header = plugin_output ? plugin_output : header_file;
   5386   DBGPRINT_COUNT_TYPE ("structures before write_types outputheader",
   5387 		       structures);
   5388 
   5389   write_types (output_header, structures, &ggc_wtd);
   5390   if (plugin_files == NULL)
   5391     {
   5392       DBGPRINT_COUNT_TYPE ("structures before write_types headerfil",
   5393 			   structures);
   5394       write_types (header_file, structures, &pch_wtd);
   5395       write_local (header_file, structures);
   5396     }
   5397   write_roots (variables, plugin_files == NULL);
   5398   write_rtx_next ();
   5399   close_output_files ();
   5400 
   5401   if (do_dump)
   5402     dump_everything ();
   5403 
   5404   /* Don't bother about free-ing any input or plugin file, etc.  */
   5405 
   5406   if (hit_error)
   5407     return 1;
   5408   return 0;
   5409 }
   5410