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