OSDN Git Service

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