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