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