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