OSDN Git Service

* c-decl.c (grokfield): Allow typedefs for anonymous structs and
[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
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 "gengtype.h"
24 #include "errors.h"     /* for fatal */
25 #include "double-int.h"
26 #include "hashtab.h"
27
28 /* Data types, macros, etc. used only in this file.  */
29
30 /* Kinds of types we can understand.  */
31 enum typekind {
32   TYPE_SCALAR,
33   TYPE_STRING,
34   TYPE_STRUCT,
35   TYPE_UNION,
36   TYPE_POINTER,
37   TYPE_ARRAY,
38   TYPE_LANG_STRUCT,
39   TYPE_PARAM_STRUCT
40 };
41
42 typedef unsigned lang_bitmap;
43
44 /* A way to pass data through to the output end.  */
45 struct options
46 {
47   struct options *next;
48   const char *name;
49   const char *info;
50 };
51
52 /* Option data for the 'nested_ptr' option.  */
53 struct nested_ptr_data
54 {
55   type_p type;
56   const char *convert_to;
57   const char *convert_from;
58 };
59
60 /* A name and a type.  */
61 struct pair
62 {
63   pair_p next;
64   const char *name;
65   type_p type;
66   struct fileloc line;
67   options_p opt;
68 };
69
70 #define NUM_PARAM 10
71
72 /* A description of a type.  */
73 enum gc_used_enum
74   {
75     GC_UNUSED = 0,
76     GC_USED,
77     /* Used for structures whose definitions we haven't seen so far when
78        we encounter a pointer to it that is annotated with ``maybe_undef''.
79        If after reading in everything we don't have source file
80        information for it, we assume that it never has been defined. */
81     GC_MAYBE_POINTED_TO,
82     GC_POINTED_TO
83   };
84
85 struct type
86 {
87   enum typekind kind;
88   type_p next;
89   type_p pointer_to;
90   enum gc_used_enum gc_used;
91   union {
92     type_p p;
93     struct {
94       const char *tag;
95       struct fileloc line;
96       pair_p fields;
97       options_p opt;
98       lang_bitmap bitmap;
99       type_p lang_struct;
100     } s;
101     bool scalar_is_char;
102     struct {
103       type_p p;
104       const char *len;
105     } a;
106     struct {
107       type_p stru;
108       type_p param[NUM_PARAM];
109       struct fileloc line;
110     } param_struct;
111   } u;
112 };
113
114 #define UNION_P(x)                                      \
115  ((x)->kind == TYPE_UNION ||                            \
116   ((x)->kind == TYPE_LANG_STRUCT                        \
117    && (x)->u.s.lang_struct->kind == TYPE_UNION))
118 #define UNION_OR_STRUCT_P(x)                    \
119  ((x)->kind == TYPE_UNION                       \
120   || (x)->kind == TYPE_STRUCT                   \
121   || (x)->kind == TYPE_LANG_STRUCT)
122
123 /* Structure representing an output file.  */
124 struct outf
125 {
126   struct outf *next;
127   const char *name;
128   size_t buflength;
129   size_t bufused;
130   char *buf;
131 };
132 typedef struct outf * outf_p;
133
134 /* An output file, suitable for definitions, that can see declarations
135    made in INPUT_FILE and is linked into every language that uses
136    INPUT_FILE.  May return NULL in plugin mode. */
137 extern outf_p get_output_file_with_visibility
138    (const char *input_file);
139 const char *get_output_file_name (const char *);
140
141 /* Print, like fprintf, to O.  No-op if O is NULL. */
142 static void oprintf (outf_p o, const char *S, ...)
143      ATTRIBUTE_PRINTF_2;
144
145 /* The list of output files.  */
146 static outf_p output_files;
147
148 /* The plugin input files and their number; in that case only
149    a single file is produced.  */
150 static char** plugin_files;
151 static size_t nb_plugin_files;
152 /* the generated plugin output name & file */
153 static outf_p plugin_output;
154
155 /* The output header file that is included into pretty much every
156    source file.  */
157 static outf_p header_file;
158
159 /* Source directory.  */
160 static const char *srcdir;
161
162 /* Length of srcdir name.  */
163 static size_t srcdir_len = 0;
164
165 static outf_p create_file (const char *, const char *);
166
167 static const char * get_file_basename (const char *);
168 static const char * get_file_realbasename (const char *);
169 static const char * get_file_srcdir_relative_path (const char *);
170
171 static int get_prefix_langdir_index (const char *);
172 static const char * get_file_langdir (const char *);
173
174 \f
175 /* Nonzero iff an error has occurred.  */
176 bool hit_error = false;
177
178 static void gen_rtx_next (void);
179 static void write_rtx_next (void);
180 static void open_base_files (void);
181 static void close_output_files (void);
182
183 /* Report an error at POS, printing MSG.  */
184
185 void
186 error_at_line (const struct fileloc *pos, const char *msg, ...)
187 {
188   va_list ap;
189
190   va_start (ap, msg);
191
192   fprintf (stderr, "%s:%d: ", pos->file, pos->line);
193   vfprintf (stderr, msg, ap);
194   fputc ('\n', stderr);
195   hit_error = true;
196
197   va_end (ap);
198 }
199
200 /* asprintf, but produces fatal message on out-of-memory.  */
201 char *
202 xasprintf (const char *format, ...)
203 {
204   int n;
205   char *result;
206   va_list ap;
207
208   va_start (ap, format);
209   n = vasprintf (&result, format, ap);
210   if (result == NULL || n < 0)
211     fatal ("out of memory");
212   va_end (ap);
213
214   return result;
215 }
216 \f
217 /* Input file handling. */
218
219 /* Table of all input files.  */
220 static const char **gt_files;
221 static size_t num_gt_files;
222
223 /* A number of places use the name of this file for a location for
224    things that we can't rely on the source to define.  Make sure we
225    can still use pointer comparison on filenames.  */
226 static const char this_file[] = __FILE__;
227
228 /* Vector of per-language directories.  */
229 static const char **lang_dir_names;
230 static size_t num_lang_dirs;
231
232 /* An array of output files suitable for definitions.  There is one
233    BASE_FILES entry for each language.  */
234 static outf_p *base_files;
235
236 /* Return a bitmap which has bit `1 << BASE_FILE_<lang>' set iff
237    INPUT_FILE is used by <lang>.
238
239    This function should be written to assume that a file _is_ used
240    if the situation is unclear.  If it wrongly assumes a file _is_ used,
241    a linker error will result.  If it wrongly assumes a file _is not_ used,
242    some GC roots may be missed, which is a much harder-to-debug problem.
243
244    The relevant bitmap is stored immediately before the file's name in the
245    buffer set up by read_input_list.  It may be unaligned, so we have to
246    read it byte-by-byte.  */
247
248 static lang_bitmap
249 get_lang_bitmap (const char *gtfile)
250 {
251
252   if (gtfile == this_file)
253     /* Things defined in this file are universal.  */
254     return (((lang_bitmap)1) << num_lang_dirs) - 1;
255   else
256     {
257       lang_bitmap n = 0;
258       int i;
259       for (i = -(int) sizeof (lang_bitmap); i < 0; i++)
260         n = (n << CHAR_BIT) + (unsigned char)gtfile[i];
261       return n;
262     }
263 }
264
265 /* Set the bitmap returned by get_lang_bitmap.  The only legitimate
266    caller of this function is read_input_list.  */
267 static void
268 set_lang_bitmap (char *gtfile, lang_bitmap n)
269 {
270   int i;
271   for (i = -1; i >= -(int) sizeof (lang_bitmap); i--)
272     {
273       gtfile[i] = n & ((1U << CHAR_BIT)-1);
274       n >>= CHAR_BIT;
275     }
276 }
277
278 /* Scan the input file, LIST, and determine how much space we need to
279    store strings in.  Also, count the number of language directories
280    and files.  The numbers returned are overestimates as they does not
281    consider repeated files.  */
282 static size_t
283 measure_input_list (FILE *list)
284 {
285   size_t n = 0;
286   int c;
287   bool atbol = true;
288   num_lang_dirs = 0;
289   num_gt_files = plugin_files ? nb_plugin_files : 0;
290   while ((c = getc (list)) != EOF)
291     {
292       n++;
293       if (atbol)
294         {
295           if (c == '[')
296             num_lang_dirs++;
297           else
298             {
299               /* Add space for a lang_bitmap before the input file name.  */
300               n += sizeof (lang_bitmap);
301               num_gt_files++;
302             }
303           atbol = false;
304         }
305
306       if (c == '\n')
307         atbol = true;
308     }
309
310   rewind (list);
311   return n;
312 }
313
314 /* Read one input line from LIST to HEREP (which is updated).  A
315    pointer to the string is returned via LINEP.  If it was a language
316    subdirectory in square brackets, strip off the square brackets and
317    return true.  Otherwise, leave space before the string for a
318    lang_bitmap, and return false.  At EOF, returns false, does not
319    touch *HEREP, and sets *LINEP to NULL.  POS is used for
320    diagnostics.  */
321 static bool
322 read_input_line (FILE *list, char **herep, char **linep,
323                  struct fileloc *pos)
324 {
325   char *here = *herep;
326   char *line;
327   int c = getc (list);
328
329   /* Read over whitespace.  */
330   while (c == '\n' || c == ' ')
331     c = getc (list);
332
333   if (c == EOF)
334     {
335       *linep = 0;
336       return false;
337     }
338   else if (c == '[')
339     {
340       /* No space for a lang_bitmap is necessary.  Discard the '['. */
341       c = getc (list);
342       line = here;
343       while (c != ']' && c != '\n' && c != EOF)
344         {
345           *here++ = c;
346           c = getc (list);
347         }
348       *here++ = '\0';
349
350       if (c == ']')
351         {
352           c = getc (list);  /* eat what should be a newline */
353           if (c != '\n' && c != EOF)
354             error_at_line (pos, "junk on line after language tag [%s]", line);
355         }
356       else
357         error_at_line (pos, "missing close bracket for language tag [%s", line);
358
359       *herep = here;
360       *linep = line;
361       return true;
362     }
363   else
364     {
365       /* Leave space for a lang_bitmap.  */
366       memset (here, 0, sizeof (lang_bitmap));
367       here += sizeof (lang_bitmap);
368       line = here;
369       do
370         {
371           *here++ = c;
372           c = getc (list);
373         }
374       while (c != EOF && c != '\n');
375       *here++ = '\0';
376       *herep = here;
377       *linep = line;
378       return false;
379     }
380 }
381
382 /* Read the list of input files from LIST and compute all of the
383    relevant tables.  There is one file per line of the list.  At
384    first, all the files on the list are language-generic, but
385    eventually a line will appear which is the name of a language
386    subdirectory in square brackets, like this: [cp].  All subsequent
387    files are specific to that language, until another language
388    subdirectory tag appears.  Files can appear more than once, if
389    they apply to more than one language.  */
390 static void
391 read_input_list (const char *listname)
392 {
393   FILE *list = fopen (listname, "r");
394   if (!list)
395     fatal ("cannot open %s: %s", listname, strerror (errno));
396   else
397     {
398       struct fileloc epos;
399       size_t bufsz = measure_input_list (list);
400       char *buf = XNEWVEC (char, bufsz);
401       char *here = buf;
402       char *committed = buf;
403       char *limit = buf + bufsz;
404       char *line;
405       bool is_language;
406       size_t langno = 0;
407       size_t nfiles = 0;
408       lang_bitmap curlangs = (1 << num_lang_dirs) - 1;
409
410       epos.file = listname;
411       epos.line = 0;
412
413       lang_dir_names = XNEWVEC (const char *, num_lang_dirs);
414       gt_files = XNEWVEC (const char *, num_gt_files);
415
416       for (;;)
417         {
418         next_line:
419           epos.line++;
420           committed = here;
421           is_language = read_input_line (list, &here, &line, &epos);
422           gcc_assert (here <= limit);
423           if (line == 0)
424             break;
425           else if (is_language)
426             {
427               size_t i;
428               gcc_assert (langno <= num_lang_dirs);
429               for (i = 0; i < langno; i++)
430                 if (strcmp (lang_dir_names[i], line) == 0)
431                   {
432                     error_at_line (&epos, "duplicate language tag [%s]", line);
433                     curlangs = 1 << i;
434                     here = committed;
435                     goto next_line;
436                   }
437
438               curlangs = 1 << langno;
439               lang_dir_names[langno++] = line;
440             }
441           else
442             {
443               size_t i;
444               gcc_assert (nfiles <= num_gt_files);
445               for (i = 0; i < nfiles; i++)
446                 if (strcmp (gt_files[i], line) == 0)
447                   {
448                     /* Throw away the string we just read, and add the
449                        current language to the existing string's bitmap.  */
450                     lang_bitmap bmap = get_lang_bitmap (gt_files[i]);
451                     if (bmap & curlangs)
452                       error_at_line (&epos, "file %s specified more than once "
453                                      "for language %s", line, langno == 0
454                                      ? "(all)"
455                                      : lang_dir_names[langno - 1]);
456
457                     bmap |= curlangs;
458                     set_lang_bitmap (CONST_CAST(char *, gt_files[i]), bmap);
459                     here = committed;
460                     goto next_line;
461                   }
462
463               set_lang_bitmap (line, curlangs);
464               gt_files[nfiles++] = line;
465             }
466         }
467       /* Update the global counts now that we know accurately how many
468          things there are.  (We do not bother resizing the arrays down.)  */
469       num_lang_dirs = langno;
470       /* Add the plugin files if provided.  */
471       if (plugin_files)
472         {
473           size_t i;
474           for (i = 0; i < nb_plugin_files; i++)
475             gt_files[nfiles++] = plugin_files[i];
476         }
477       num_gt_files = nfiles;
478     }
479
480   /* Sanity check: any file that resides in a language subdirectory
481      (e.g. 'cp') ought to belong to the corresponding language.
482      ??? Still true if for instance ObjC++ is enabled and C++ isn't?
483      (Can you even do that?  Should you be allowed to?)  */
484   {
485     size_t f;
486     for (f = 0; f < num_gt_files; f++)
487       {
488         lang_bitmap bitmap = get_lang_bitmap (gt_files[f]);
489         const char *basename = get_file_basename (gt_files[f]);
490         const char *slashpos = strchr (basename, '/');
491
492         if (slashpos)
493           {
494             size_t l;
495             for (l = 0; l < num_lang_dirs; l++)
496               if ((size_t)(slashpos - basename) == strlen (lang_dir_names [l])
497                   && memcmp (basename, lang_dir_names[l],
498                              strlen (lang_dir_names[l])) == 0)
499                 {
500                   if (!(bitmap & (1 << l)))
501                     error ("%s is in language directory '%s' but is not "
502                            "tagged for that language",
503                            basename, lang_dir_names[l]);
504                   break;
505                 }
506           }
507       }
508   }
509
510   if (ferror (list))
511     fatal ("error reading %s: %s", listname, strerror (errno));
512
513   fclose (list);
514 }
515
516
517 \f
518 /* The one and only TYPE_STRING.  */
519
520 static struct type string_type = {
521   TYPE_STRING, 0, 0, GC_USED, {0}
522 };
523
524 /* The two and only TYPE_SCALARs.  Their u.scalar_is_char flags are
525    set to appropriate values at the beginning of main.  */
526
527 static struct type scalar_nonchar = {
528   TYPE_SCALAR, 0, 0, GC_USED, {0}
529 };
530 static struct type scalar_char = {
531   TYPE_SCALAR, 0, 0, GC_USED, {0}
532 };
533
534 /* Lists of various things.  */
535
536 static pair_p typedefs;
537 static type_p structures;
538 static type_p param_structs;
539 static pair_p variables;
540
541 static type_p find_param_structure
542   (type_p t, type_p param[NUM_PARAM]);
543 static type_p adjust_field_tree_exp (type_p t, options_p opt);
544 static type_p adjust_field_rtx_def (type_p t, options_p opt);
545
546 /* Define S as a typedef to T at POS.  */
547
548 void
549 do_typedef (const char *s, type_p t, struct fileloc *pos)
550 {
551   pair_p p;
552
553   /* temporary kludge - gengtype doesn't handle conditionals or
554      macros.  Ignore any attempt to typedef CUMULATIVE_ARGS, unless it
555      is coming from this file (main() sets them up with safe dummy
556      definitions).  */
557   if (!strcmp (s, "CUMULATIVE_ARGS") && pos->file != this_file)
558     return;
559
560   for (p = typedefs; p != NULL; p = p->next)
561     if (strcmp (p->name, s) == 0)
562       {
563         if (p->type != t)
564           {
565             error_at_line (pos, "type `%s' previously defined", s);
566             error_at_line (&p->line, "previously defined here");
567           }
568         return;
569       }
570
571   p = XNEW (struct pair);
572   p->next = typedefs;
573   p->name = s;
574   p->type = t;
575   p->line = *pos;
576   p->opt = NULL;
577   typedefs = p;
578 }
579
580 /* Define S as a typename of a scalar.  Cannot be used to define
581    typedefs of 'char'.  Note: is also used for pointer-to-function
582    typedefs (which are therefore not treated as pointers).  */
583
584 void
585 do_scalar_typedef (const char *s, struct fileloc *pos)
586 {
587   do_typedef (s, &scalar_nonchar, pos);
588 }
589
590 /* Return the type previously defined for S.  Use POS to report errors.  */
591
592 type_p
593 resolve_typedef (const char *s, struct fileloc *pos)
594 {
595   pair_p p;
596   for (p = typedefs; p != NULL; p = p->next)
597     if (strcmp (p->name, s) == 0)
598       return p->type;
599   error_at_line (pos, "unidentified type `%s'", s);
600   return &scalar_nonchar;  /* treat as "int" */
601 }
602
603 /* Create and return a new structure with tag NAME (or a union iff
604    ISUNION is nonzero), at POS with fields FIELDS and options O.  */
605
606 type_p
607 new_structure (const char *name, int isunion, struct fileloc *pos,
608                pair_p fields, options_p o)
609 {
610   type_p si;
611   type_p s = NULL;
612   lang_bitmap bitmap = get_lang_bitmap (pos->file);
613
614   /* temporary kludge - gengtype doesn't handle conditionals or
615      macros.  Ignore any attempt to define struct location_s, unless
616      it is coming from this file (main() sets it up safely). */
617   if (!strcmp (name, "location_s") && !isunion
618       && pos->file != this_file)
619     return find_structure (name, 0);
620
621   for (si = structures; si != NULL; si = si->next)
622     if (strcmp (name, si->u.s.tag) == 0
623         && UNION_P (si) == isunion)
624       {
625         type_p ls = NULL;
626         if (si->kind == TYPE_LANG_STRUCT)
627           {
628             ls = si;
629
630             for (si = ls->u.s.lang_struct; si != NULL; si = si->next)
631               if (si->u.s.bitmap == bitmap)
632                 s = si;
633           }
634         else if (si->u.s.line.file != NULL && si->u.s.bitmap != bitmap)
635           {
636             ls = si;
637             si = XCNEW (struct type);
638             memcpy (si, ls, sizeof (struct type));
639             ls->kind = TYPE_LANG_STRUCT;
640             ls->u.s.lang_struct = si;
641             ls->u.s.fields = NULL;
642             si->next = NULL;
643             si->pointer_to = NULL;
644             si->u.s.lang_struct = ls;
645           }
646         else
647           s = si;
648
649         if (ls != NULL && s == NULL)
650           {
651             s = XCNEW (struct type);
652             s->next = ls->u.s.lang_struct;
653             ls->u.s.lang_struct = s;
654             s->u.s.lang_struct = ls;
655           }
656         break;
657       }
658
659   if (s == NULL)
660     {
661       s = XCNEW (struct type);
662       s->next = structures;
663       structures = s;
664     }
665
666   if (s->u.s.line.file != NULL
667       || (s->u.s.lang_struct && (s->u.s.lang_struct->u.s.bitmap & bitmap)))
668     {
669       error_at_line (pos, "duplicate definition of '%s %s'",
670                      isunion ? "union" : "struct", s->u.s.tag);
671       error_at_line (&s->u.s.line, "previous definition here");
672     }
673
674   s->kind = isunion ? TYPE_UNION : TYPE_STRUCT;
675   s->u.s.tag = name;
676   s->u.s.line = *pos;
677   s->u.s.fields = fields;
678   s->u.s.opt = o;
679   s->u.s.bitmap = bitmap;
680   if (s->u.s.lang_struct)
681     s->u.s.lang_struct->u.s.bitmap |= bitmap;
682
683   /* Reset location_s's location to input.h so that we know where to
684      write out its mark routine.  */
685   if (!strcmp (name, "location_s") && !isunion
686       && pos->file == this_file)
687     {
688       size_t n;
689       for (n = 0; n < num_gt_files; n++)
690         if (!strcmp (gt_files[n] + strlen (gt_files[n]) - strlen ("input.h"),
691                      "input.h"))
692           {
693             s->u.s.line.file = gt_files[n];
694             break;
695           }
696     }
697
698     return s;
699 }
700
701 /* Return the previously-defined structure with tag NAME (or a union
702    iff ISUNION is nonzero), or a new empty structure or union if none
703    was defined previously.  */
704
705 type_p
706 find_structure (const char *name, int isunion)
707 {
708   type_p s;
709
710   for (s = structures; s != NULL; s = s->next)
711     if (strcmp (name, s->u.s.tag) == 0
712         && UNION_P (s) == isunion)
713       return s;
714
715   s = XCNEW (struct type);
716   s->next = structures;
717   structures = s;
718   s->kind = isunion ? TYPE_UNION : TYPE_STRUCT;
719   s->u.s.tag = name;
720   structures = s;
721   return s;
722 }
723
724 /* Return the previously-defined parameterized structure for structure
725    T and parameters PARAM, or a new parameterized empty structure or
726    union if none was defined previously.  */
727
728 static type_p
729 find_param_structure (type_p t, type_p param[NUM_PARAM])
730 {
731   type_p res;
732
733   for (res = param_structs; res; res = res->next)
734     if (res->u.param_struct.stru == t
735         && memcmp (res->u.param_struct.param, param,
736                    sizeof (type_p) * NUM_PARAM) == 0)
737       break;
738   if (res == NULL)
739     {
740       res = XCNEW (struct type);
741       res->kind = TYPE_PARAM_STRUCT;
742       res->next = param_structs;
743       param_structs = res;
744       res->u.param_struct.stru = t;
745       memcpy (res->u.param_struct.param, param, sizeof (type_p) * NUM_PARAM);
746     }
747   return res;
748 }
749
750 /* Return a scalar type with name NAME.  */
751
752 type_p
753 create_scalar_type (const char *name)
754 {
755   if (!strcmp (name, "char") || !strcmp (name, "unsigned char"))
756     return &scalar_char;
757   else
758     return &scalar_nonchar;
759 }
760
761 /* Return a pointer to T.  */
762
763 type_p
764 create_pointer (type_p t)
765 {
766   if (! t->pointer_to)
767     {
768       type_p r = XCNEW (struct type);
769       r->kind = TYPE_POINTER;
770       r->u.p = t;
771       t->pointer_to = r;
772     }
773   return t->pointer_to;
774 }
775
776 /* Return an array of length LEN.  */
777
778 type_p
779 create_array (type_p t, const char *len)
780 {
781   type_p v;
782
783   v = XCNEW (struct type);
784   v->kind = TYPE_ARRAY;
785   v->u.a.p = t;
786   v->u.a.len = len;
787   return v;
788 }
789
790 /* Return an options structure with name NAME and info INFO.  NEXT is the
791    next option in the chain.  */
792
793 options_p
794 create_option (options_p next, const char *name, const void *info)
795 {
796   options_p o = XNEW (struct options);
797   o->next = next;
798   o->name = name;
799   o->info = (const char*) info;
800   return o;
801 }
802
803 /* Return an options structure for a "nested_ptr" option.  */
804 options_p
805 create_nested_ptr_option (options_p next, type_p t,
806                           const char *to, const char *from)
807 {
808   struct nested_ptr_data *d = XNEW (struct nested_ptr_data);
809
810   d->type = adjust_field_type (t, 0);
811   d->convert_to = to;
812   d->convert_from = from;
813   return create_option (next, "nested_ptr", d);
814 }
815
816 /* Add a variable named S of type T with options O defined at POS,
817    to `variables'.  */
818
819 void
820 note_variable (const char *s, type_p t, options_p o, struct fileloc *pos)
821 {
822   pair_p n;
823   n = XNEW (struct pair);
824   n->name = s;
825   n->type = t;
826   n->line = *pos;
827   n->opt = o;
828   n->next = variables;
829   variables = n;
830 }
831
832 /* Most-general structure field creator.  */
833 static pair_p
834 create_field_all (pair_p next, type_p type, const char *name, options_p opt,
835                   const char *file, int line)
836 {
837   pair_p field;
838
839   field = XNEW (struct pair);
840   field->next = next;
841   field->type = type;
842   field->name = name;
843   field->opt = opt;
844   field->line.file = file;
845   field->line.line = line;
846   return field;
847 }
848
849 /* Create a field that came from the source code we are scanning,
850    i.e. we have a 'struct fileloc', and possibly options; also,
851    adjust_field_type should be called.  */
852 pair_p
853 create_field_at (pair_p next, type_p type, const char *name, options_p opt,
854                  struct fileloc *pos)
855 {
856   return create_field_all (next, adjust_field_type (type, opt),
857                            name, opt, pos->file, pos->line);
858 }
859
860 /* Create a fake field with the given type and name.  NEXT is the next
861    field in the chain.  */
862 #define create_field(next,type,name) \
863     create_field_all(next,type,name, 0, this_file, __LINE__)
864
865 /* Like create_field, but the field is only valid when condition COND
866    is true.  */
867
868 static pair_p
869 create_optional_field_ (pair_p next, type_p type, const char *name,
870                         const char *cond, int line)
871 {
872   static int id = 1;
873   pair_p union_fields;
874   type_p union_type;
875
876   /* Create a fake union type with a single nameless field of type TYPE.
877      The field has a tag of "1".  This allows us to make the presence
878      of a field of type TYPE depend on some boolean "desc" being true.  */
879   union_fields = create_field (NULL, type, "");
880   union_fields->opt = create_option (union_fields->opt, "dot", "");
881   union_fields->opt = create_option (union_fields->opt, "tag", "1");
882   union_type = new_structure (xasprintf ("%s_%d", "fake_union", id++), 1,
883                               &lexer_line, union_fields, NULL);
884
885   /* Create the field and give it the new fake union type.  Add a "desc"
886      tag that specifies the condition under which the field is valid.  */
887   return create_field_all (next, union_type, name,
888                            create_option (0, "desc", cond),
889                            this_file, line);
890 }
891 #define create_optional_field(next,type,name,cond)      \
892        create_optional_field_(next,type,name,cond,__LINE__)
893
894 /* Reverse a linked list of 'struct pair's in place.  */
895 pair_p
896 nreverse_pairs (pair_p list)
897 {
898   pair_p prev = 0, p, next;
899   for (p = list; p; p = next)
900     {
901       next = p->next;
902       p->next = prev;
903       prev = p;
904     }
905   return prev;
906 }
907
908 \f
909 /* We don't care how long a CONST_DOUBLE is.  */
910 #define CONST_DOUBLE_FORMAT "ww"
911 /* We don't want to see codes that are only for generator files.  */
912 #undef GENERATOR_FILE
913
914 enum rtx_code {
915 #define DEF_RTL_EXPR(ENUM, NAME, FORMAT, CLASS) ENUM ,
916 #include "rtl.def"
917 #undef DEF_RTL_EXPR
918   NUM_RTX_CODE
919 };
920
921 static const char * const rtx_name[NUM_RTX_CODE] = {
922 #define DEF_RTL_EXPR(ENUM, NAME, FORMAT, CLASS)   NAME ,
923 #include "rtl.def"
924 #undef DEF_RTL_EXPR
925 };
926
927 static const char * const rtx_format[NUM_RTX_CODE] = {
928 #define DEF_RTL_EXPR(ENUM, NAME, FORMAT, CLASS)   FORMAT ,
929 #include "rtl.def"
930 #undef DEF_RTL_EXPR
931 };
932
933 static int rtx_next_new[NUM_RTX_CODE];
934
935 /* We also need codes and names for insn notes (not register notes).
936    Note that we do *not* bias the note values here.  */
937 enum insn_note {
938 #define DEF_INSN_NOTE(NAME) NAME,
939 #include "insn-notes.def"
940 #undef DEF_INSN_NOTE
941
942   NOTE_INSN_MAX
943 };
944
945 /* We must allocate one more entry here, as we use NOTE_INSN_MAX as the
946    default field for line number notes.  */
947 static const char *const note_insn_name[NOTE_INSN_MAX+1] = {
948 #define DEF_INSN_NOTE(NAME) #NAME,
949 #include "insn-notes.def"
950 #undef DEF_INSN_NOTE
951 };
952
953 #undef CONST_DOUBLE_FORMAT
954 #define GENERATOR_FILE
955
956 /* Generate the contents of the rtx_next array.  This really doesn't belong
957    in gengtype at all, but it's needed for adjust_field_rtx_def.  */
958
959 static void
960 gen_rtx_next (void)
961 {
962   int i;
963   for (i = 0; i < NUM_RTX_CODE; i++)
964     {
965       int k;
966
967       rtx_next_new[i] = -1;
968       if (strncmp (rtx_format[i], "iuu", 3) == 0)
969         rtx_next_new[i] = 2;
970       else if (i == COND_EXEC || i == SET || i == EXPR_LIST || i == INSN_LIST)
971         rtx_next_new[i] = 1;
972       else
973         for (k = strlen (rtx_format[i]) - 1; k >= 0; k--)
974           if (rtx_format[i][k] == 'e' || rtx_format[i][k] == 'u')
975             rtx_next_new[i] = k;
976     }
977 }
978
979 /* Write out the contents of the rtx_next array.  */
980 static void
981 write_rtx_next (void)
982 {
983   outf_p f = get_output_file_with_visibility (NULL);
984   int i;
985   if (!f)
986     return;
987
988   oprintf (f, "\n/* Used to implement the RTX_NEXT macro.  */\n");
989   oprintf (f, "EXPORTED_CONST unsigned char rtx_next[NUM_RTX_CODE] = {\n");
990   for (i = 0; i < NUM_RTX_CODE; i++)
991     if (rtx_next_new[i] == -1)
992       oprintf (f, "  0,\n");
993     else
994       oprintf (f,
995                "  RTX_HDR_SIZE + %d * sizeof (rtunion),\n",
996                rtx_next_new[i]);
997   oprintf (f, "};\n");
998 }
999
1000 /* Handle `special("rtx_def")'.  This is a special case for field
1001    `fld' of struct rtx_def, which is an array of unions whose values
1002    are based in a complex way on the type of RTL.  */
1003
1004 static type_p
1005 adjust_field_rtx_def (type_p t, options_p ARG_UNUSED (opt))
1006 {
1007   pair_p flds = NULL;
1008   options_p nodot;
1009   int i;
1010   type_p rtx_tp, rtvec_tp, tree_tp, mem_attrs_tp, note_union_tp, scalar_tp;
1011   type_p bitmap_tp, basic_block_tp, reg_attrs_tp, constant_tp, symbol_union_tp;
1012
1013   if (t->kind != TYPE_UNION)
1014     {
1015       error_at_line (&lexer_line,
1016                      "special `rtx_def' must be applied to a union");
1017       return &string_type;
1018     }
1019
1020   nodot = create_option (NULL, "dot", "");
1021
1022   rtx_tp = create_pointer (find_structure ("rtx_def", 0));
1023   rtvec_tp = create_pointer (find_structure ("rtvec_def", 0));
1024   tree_tp = create_pointer (find_structure ("tree_node", 1));
1025   mem_attrs_tp = create_pointer (find_structure ("mem_attrs", 0));
1026   reg_attrs_tp = create_pointer (find_structure ("reg_attrs", 0));
1027   bitmap_tp = create_pointer (find_structure ("bitmap_element_def", 0));
1028   basic_block_tp = create_pointer (find_structure ("basic_block_def", 0));
1029   constant_tp = create_pointer (find_structure ("constant_descriptor_rtx", 0));
1030   scalar_tp = &scalar_nonchar;  /* rtunion int */
1031
1032   {
1033     pair_p note_flds = NULL;
1034     int c;
1035
1036     for (c = 0; c <= NOTE_INSN_MAX; c++)
1037       {
1038         switch (c)
1039           {
1040           case NOTE_INSN_MAX:
1041           case NOTE_INSN_DELETED_LABEL:
1042             note_flds = create_field (note_flds, &string_type, "rt_str");
1043             break;
1044
1045           case NOTE_INSN_BLOCK_BEG:
1046           case NOTE_INSN_BLOCK_END:
1047             note_flds = create_field (note_flds, tree_tp, "rt_tree");
1048             break;
1049
1050           case NOTE_INSN_VAR_LOCATION:
1051             note_flds = create_field (note_flds, rtx_tp, "rt_rtx");
1052             break;
1053
1054           default:
1055             note_flds = create_field (note_flds, scalar_tp, "rt_int");
1056             break;
1057           }
1058         /* NOTE_INSN_MAX is used as the default field for line
1059            number notes.  */
1060         if (c == NOTE_INSN_MAX)
1061           note_flds->opt = create_option (nodot, "default", "");
1062         else
1063           note_flds->opt = create_option (nodot, "tag", note_insn_name[c]);
1064       }
1065     note_union_tp = new_structure ("rtx_def_note_subunion", 1,
1066                                    &lexer_line, note_flds, NULL);
1067   }
1068   /* Create a type to represent the various forms of SYMBOL_REF_DATA.  */
1069   {
1070     pair_p sym_flds;
1071
1072     sym_flds = create_field (NULL, tree_tp, "rt_tree");
1073     sym_flds->opt = create_option (nodot, "default", "");
1074
1075     sym_flds = create_field (sym_flds, constant_tp, "rt_constant");
1076     sym_flds->opt = create_option (nodot, "tag", "1");
1077
1078     symbol_union_tp = new_structure ("rtx_def_symbol_subunion", 1,
1079                                      &lexer_line, sym_flds, NULL);
1080   }
1081   for (i = 0; i < NUM_RTX_CODE; i++)
1082     {
1083       pair_p subfields = NULL;
1084       size_t aindex, nmindex;
1085       const char *sname;
1086       type_p substruct;
1087       char *ftag;
1088
1089       for (aindex = 0; aindex < strlen (rtx_format[i]); aindex++)
1090         {
1091           type_p t;
1092           const char *subname;
1093
1094           switch (rtx_format[i][aindex])
1095             {
1096             case '*':
1097             case 'i':
1098             case 'n':
1099             case 'w':
1100               t = scalar_tp;
1101               subname = "rt_int";
1102               break;
1103
1104             case '0':
1105               if (i == MEM && aindex == 1)
1106                 t = mem_attrs_tp, subname = "rt_mem";
1107               else if (i == JUMP_INSN && aindex == 8)
1108                 t = rtx_tp, subname = "rt_rtx";
1109               else if (i == CODE_LABEL && aindex == 4)
1110                 t = scalar_tp, subname = "rt_int";
1111               else if (i == CODE_LABEL && aindex == 5)
1112                 t = rtx_tp, subname = "rt_rtx";
1113               else if (i == LABEL_REF
1114                        && (aindex == 1 || aindex == 2))
1115                 t = rtx_tp, subname = "rt_rtx";
1116               else if (i == NOTE && aindex == 4)
1117                 t = note_union_tp, subname = "";
1118               else if (i == NOTE && aindex == 5)
1119                 t = scalar_tp, subname = "rt_int";
1120               else if (i == NOTE && aindex >= 7)
1121                 t = scalar_tp, subname = "rt_int";
1122               else if (i == ADDR_DIFF_VEC && aindex == 4)
1123                 t = scalar_tp, subname = "rt_int";
1124               else if (i == VALUE && aindex == 0)
1125                 t = scalar_tp, subname = "rt_int";
1126               else if (i == DEBUG_EXPR && aindex == 0)
1127                 t = tree_tp, subname = "rt_tree";
1128               else if (i == REG && aindex == 1)
1129                 t = scalar_tp, subname = "rt_int";
1130               else if (i == REG && aindex == 2)
1131                 t = reg_attrs_tp, subname = "rt_reg";
1132               else if (i == SCRATCH && aindex == 0)
1133                 t = scalar_tp, subname = "rt_int";
1134               else if (i == SYMBOL_REF && aindex == 1)
1135                 t = scalar_tp, subname = "rt_int";
1136               else if (i == SYMBOL_REF && aindex == 2)
1137                 t = symbol_union_tp, subname = "";
1138               else if (i == BARRIER && aindex >= 3)
1139                 t = scalar_tp, subname = "rt_int";
1140               else
1141                 {
1142                   error_at_line (&lexer_line,
1143                         "rtx type `%s' has `0' in position %lu, can't handle",
1144                                  rtx_name[i], (unsigned long) aindex);
1145                   t = &string_type;
1146                   subname = "rt_int";
1147                 }
1148               break;
1149
1150             case 's':
1151             case 'S':
1152             case 'T':
1153               t = &string_type;
1154               subname = "rt_str";
1155               break;
1156
1157             case 'e':
1158             case 'u':
1159               t = rtx_tp;
1160               subname = "rt_rtx";
1161               break;
1162
1163             case 'E':
1164             case 'V':
1165               t = rtvec_tp;
1166               subname = "rt_rtvec";
1167               break;
1168
1169             case 't':
1170               t = tree_tp;
1171               subname = "rt_tree";
1172               break;
1173
1174             case 'b':
1175               t = bitmap_tp;
1176               subname = "rt_bit";
1177               break;
1178
1179             case 'B':
1180               t = basic_block_tp;
1181               subname = "rt_bb";
1182               break;
1183
1184             default:
1185               error_at_line (&lexer_line,
1186                      "rtx type `%s' has `%c' in position %lu, can't handle",
1187                              rtx_name[i], rtx_format[i][aindex],
1188                              (unsigned long)aindex);
1189               t = &string_type;
1190               subname = "rt_int";
1191               break;
1192             }
1193
1194           subfields = create_field (subfields, t,
1195                                     xasprintf (".fld[%lu].%s",
1196                                                (unsigned long) aindex,
1197                                                subname));
1198           subfields->opt = nodot;
1199           if (t == note_union_tp)
1200             subfields->opt = create_option (subfields->opt, "desc",
1201                                             "NOTE_KIND (&%0)");
1202           if (t == symbol_union_tp)
1203             subfields->opt = create_option (subfields->opt, "desc",
1204                                             "CONSTANT_POOL_ADDRESS_P (&%0)");
1205         }
1206
1207       if (i == SYMBOL_REF)
1208         {
1209           /* Add the "block_sym" field if SYMBOL_REF_HAS_BLOCK_INFO_P holds.  */
1210           type_p field_tp = find_structure ("block_symbol", 0);
1211           subfields
1212             = create_optional_field (subfields, field_tp, "block_sym",
1213                                      "SYMBOL_REF_HAS_BLOCK_INFO_P (&%0)");
1214         }
1215
1216       sname = xasprintf ("rtx_def_%s", rtx_name[i]);
1217       substruct = new_structure (sname, 0, &lexer_line, subfields, NULL);
1218
1219       ftag = xstrdup (rtx_name[i]);
1220       for (nmindex = 0; nmindex < strlen (ftag); nmindex++)
1221         ftag[nmindex] = TOUPPER (ftag[nmindex]);
1222
1223       flds = create_field (flds, substruct, "");
1224       flds->opt = create_option (nodot, "tag", ftag);
1225     }
1226
1227   return new_structure ("rtx_def_subunion", 1, &lexer_line, flds, nodot);
1228 }
1229
1230 /* Handle `special("tree_exp")'.  This is a special case for
1231    field `operands' of struct tree_exp, which although it claims to contain
1232    pointers to trees, actually sometimes contains pointers to RTL too.
1233    Passed T, the old type of the field, and OPT its options.  Returns
1234    a new type for the field.  */
1235
1236 static type_p
1237 adjust_field_tree_exp (type_p t, options_p opt ATTRIBUTE_UNUSED)
1238 {
1239   pair_p flds;
1240   options_p nodot;
1241
1242   if (t->kind != TYPE_ARRAY)
1243     {
1244       error_at_line (&lexer_line,
1245                      "special `tree_exp' must be applied to an array");
1246       return &string_type;
1247     }
1248
1249   nodot = create_option (NULL, "dot", "");
1250
1251   flds = create_field (NULL, t, "");
1252   flds->opt = create_option (nodot, "length",
1253                              "TREE_OPERAND_LENGTH ((tree) &%0)");
1254   flds->opt = create_option (flds->opt, "default", "");
1255
1256   return new_structure ("tree_exp_subunion", 1, &lexer_line, flds, nodot);
1257 }
1258
1259 /* Perform any special processing on a type T, about to become the type
1260    of a field.  Return the appropriate type for the field.
1261    At present:
1262    - Converts pointer-to-char, with no length parameter, to TYPE_STRING;
1263    - Similarly for arrays of pointer-to-char;
1264    - Converts structures for which a parameter is provided to
1265      TYPE_PARAM_STRUCT;
1266    - Handles "special" options.
1267 */
1268
1269 type_p
1270 adjust_field_type (type_p t, options_p opt)
1271 {
1272   int length_p = 0;
1273   const int pointer_p = t->kind == TYPE_POINTER;
1274   type_p params[NUM_PARAM];
1275   int params_p = 0;
1276   int i;
1277
1278   for (i = 0; i < NUM_PARAM; i++)
1279     params[i] = NULL;
1280
1281   for (; opt; opt = opt->next)
1282     if (strcmp (opt->name, "length") == 0)
1283       length_p = 1;
1284     else if (strcmp (opt->name, "param_is") == 0
1285              || (strncmp (opt->name, "param", 5) == 0
1286                  && ISDIGIT (opt->name[5])
1287                  && strcmp (opt->name + 6, "_is") == 0))
1288       {
1289         int num = ISDIGIT (opt->name[5]) ? opt->name[5] - '0' : 0;
1290
1291         if (! UNION_OR_STRUCT_P (t)
1292             && (t->kind != TYPE_POINTER || ! UNION_OR_STRUCT_P (t->u.p)))
1293           {
1294             error_at_line (&lexer_line,
1295    "option `%s' may only be applied to structures or structure pointers",
1296                            opt->name);
1297             return t;
1298           }
1299
1300         params_p = 1;
1301         if (params[num] != NULL)
1302           error_at_line (&lexer_line, "duplicate `%s' option", opt->name);
1303         if (! ISDIGIT (opt->name[5]))
1304           params[num] = create_pointer (CONST_CAST2(type_p, const char *, opt->info));
1305         else
1306           params[num] = CONST_CAST2 (type_p, const char *, opt->info);
1307       }
1308     else if (strcmp (opt->name, "special") == 0)
1309       {
1310         const char *special_name = opt->info;
1311         if (strcmp (special_name, "tree_exp") == 0)
1312           t = adjust_field_tree_exp (t, opt);
1313         else if (strcmp (special_name, "rtx_def") == 0)
1314           t = adjust_field_rtx_def (t, opt);
1315         else
1316           error_at_line (&lexer_line, "unknown special `%s'", special_name);
1317       }
1318
1319   if (params_p)
1320     {
1321       type_p realt;
1322
1323       if (pointer_p)
1324         t = t->u.p;
1325       realt = find_param_structure (t, params);
1326       t = pointer_p ? create_pointer (realt) : realt;
1327     }
1328
1329   if (! length_p
1330       && pointer_p
1331       && t->u.p->kind == TYPE_SCALAR
1332       && t->u.p->u.scalar_is_char)
1333     return &string_type;
1334   if (t->kind == TYPE_ARRAY && t->u.a.p->kind == TYPE_POINTER
1335       && t->u.a.p->u.p->kind == TYPE_SCALAR
1336       && t->u.a.p->u.p->u.scalar_is_char)
1337     return create_array (&string_type, t->u.a.len);
1338
1339   return t;
1340 }
1341
1342 \f
1343 static void set_gc_used_type (type_p, enum gc_used_enum, type_p *);
1344 static void set_gc_used (pair_p);
1345
1346 /* Handle OPT for set_gc_used_type.  */
1347
1348 static void
1349 process_gc_options (options_p opt, enum gc_used_enum level, int *maybe_undef,
1350                     int *pass_param, int *length, int *skip, type_p *nested_ptr)
1351 {
1352   options_p o;
1353   for (o = opt; o; o = o->next)
1354     if (strcmp (o->name, "ptr_alias") == 0 && level == GC_POINTED_TO)
1355       set_gc_used_type (CONST_CAST2 (type_p, const char *, o->info),
1356                         GC_POINTED_TO, NULL);
1357     else if (strcmp (o->name, "maybe_undef") == 0)
1358       *maybe_undef = 1;
1359     else if (strcmp (o->name, "use_params") == 0)
1360       *pass_param = 1;
1361     else if (strcmp (o->name, "length") == 0)
1362       *length = 1;
1363     else if (strcmp (o->name, "skip") == 0)
1364       *skip = 1;
1365     else if (strcmp (o->name, "nested_ptr") == 0)
1366       *nested_ptr = ((const struct nested_ptr_data *) o->info)->type;
1367 }
1368
1369 /* Set the gc_used field of T to LEVEL, and handle the types it references.  */
1370
1371 static void
1372 set_gc_used_type (type_p t, enum gc_used_enum level, type_p param[NUM_PARAM])
1373 {
1374   if (t->gc_used >= level)
1375     return;
1376
1377   t->gc_used = level;
1378
1379   switch (t->kind)
1380     {
1381     case TYPE_STRUCT:
1382     case TYPE_UNION:
1383       {
1384         pair_p f;
1385         int dummy;
1386         type_p dummy2;
1387
1388         process_gc_options (t->u.s.opt, level, &dummy, &dummy, &dummy, &dummy,
1389                             &dummy2);
1390
1391         for (f = t->u.s.fields; f; f = f->next)
1392           {
1393             int maybe_undef = 0;
1394             int pass_param = 0;
1395             int length = 0;
1396             int skip = 0;
1397             type_p nested_ptr = NULL;
1398             process_gc_options (f->opt, level, &maybe_undef, &pass_param,
1399                                 &length, &skip, &nested_ptr);
1400
1401             if (nested_ptr && f->type->kind == TYPE_POINTER)
1402               set_gc_used_type (nested_ptr, GC_POINTED_TO,
1403                                 pass_param ? param : NULL);
1404             else if (length && f->type->kind == TYPE_POINTER)
1405               set_gc_used_type (f->type->u.p, GC_USED, NULL);
1406             else if (maybe_undef && f->type->kind == TYPE_POINTER)
1407               set_gc_used_type (f->type->u.p, GC_MAYBE_POINTED_TO, NULL);
1408             else if (pass_param && f->type->kind == TYPE_POINTER && param)
1409               set_gc_used_type (find_param_structure (f->type->u.p, param),
1410                                 GC_POINTED_TO, NULL);
1411             else if (skip)
1412               ; /* target type is not used through this field */
1413             else
1414               set_gc_used_type (f->type, GC_USED, pass_param ? param : NULL);
1415           }
1416         break;
1417       }
1418
1419     case TYPE_POINTER:
1420       set_gc_used_type (t->u.p, GC_POINTED_TO, NULL);
1421       break;
1422
1423     case TYPE_ARRAY:
1424       set_gc_used_type (t->u.a.p, GC_USED, param);
1425       break;
1426
1427     case TYPE_LANG_STRUCT:
1428       for (t = t->u.s.lang_struct; t; t = t->next)
1429         set_gc_used_type (t, level, param);
1430       break;
1431
1432     case TYPE_PARAM_STRUCT:
1433       {
1434         int i;
1435         for (i = 0; i < NUM_PARAM; i++)
1436           if (t->u.param_struct.param[i] != 0)
1437             set_gc_used_type (t->u.param_struct.param[i], GC_USED, NULL);
1438       }
1439       if (t->u.param_struct.stru->gc_used == GC_POINTED_TO)
1440         level = GC_POINTED_TO;
1441       else
1442         level = GC_USED;
1443       t->u.param_struct.stru->gc_used = GC_UNUSED;
1444       set_gc_used_type (t->u.param_struct.stru, level,
1445                         t->u.param_struct.param);
1446       break;
1447
1448     default:
1449       break;
1450     }
1451 }
1452
1453 /* Set the gc_used fields of all the types pointed to by VARIABLES.  */
1454
1455 static void
1456 set_gc_used (pair_p variables)
1457 {
1458   pair_p p;
1459   for (p = variables; p; p = p->next)
1460     set_gc_used_type (p->type, GC_USED, NULL);
1461 }
1462 \f
1463 /* File mapping routines.  For each input file, there is one output .c file
1464    (but some output files have many input files), and there is one .h file
1465    for the whole build.  */
1466
1467 /* Output file handling.  */
1468
1469 /* Create and return an outf_p for a new file for NAME, to be called
1470    ONAME.  */
1471
1472 static outf_p
1473 create_file (const char *name, const char *oname)
1474 {
1475   static const char *const hdr[] = {
1476     "   Copyright (C) 2004, 2007, 2009 Free Software Foundation, Inc.\n",
1477     "\n",
1478     "This file is part of GCC.\n",
1479     "\n",
1480     "GCC is free software; you can redistribute it and/or modify it under\n",
1481     "the terms of the GNU General Public License as published by the Free\n",
1482     "Software Foundation; either version 3, or (at your option) any later\n",
1483     "version.\n",
1484     "\n",
1485     "GCC is distributed in the hope that it will be useful, but WITHOUT ANY\n",
1486     "WARRANTY; without even the implied warranty of MERCHANTABILITY or\n",
1487     "FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n",
1488     "for more details.\n",
1489     "\n",
1490     "You should have received a copy of the GNU General Public License\n",
1491     "along with GCC; see the file COPYING3.  If not see\n",
1492     "<http://www.gnu.org/licenses/>.  */\n",
1493     "\n",
1494     "/* This file is machine generated.  Do not edit.  */\n"
1495   };
1496   outf_p f;
1497   size_t i;
1498
1499   gcc_assert (name != NULL);
1500   gcc_assert (oname != NULL);
1501   f = XCNEW (struct outf);
1502   f->next = output_files;
1503   f->name = oname;
1504   output_files = f;
1505
1506   oprintf (f, "/* Type information for %s.\n", name);
1507   for (i = 0; i < ARRAY_SIZE (hdr); i++)
1508     oprintf (f, "%s", hdr[i]);
1509   return f;
1510 }
1511
1512 /* Print, like fprintf, to O.
1513    N.B. You might think this could be implemented more efficiently
1514    with vsnprintf().  Unfortunately, there are C libraries that
1515    provide that function but without the C99 semantics for its return
1516    value, making it impossible to know how much space is required.  */
1517 void
1518 oprintf (outf_p o, const char *format, ...)
1519 {
1520   char *s;
1521   size_t slength;
1522   va_list ap;
1523
1524   /* In plugin mode, the O could be a NULL pointer, so avoid crashing
1525      in that case.  */
1526   if (!o)
1527     return;
1528
1529   va_start (ap, format);
1530   slength = vasprintf (&s, format, ap);
1531   if (s == NULL || (int)slength < 0)
1532     fatal ("out of memory");
1533   va_end (ap);
1534
1535   if (o->bufused + slength > o->buflength)
1536     {
1537       size_t new_len = o->buflength;
1538       if (new_len == 0)
1539         new_len = 1024;
1540       do {
1541         new_len *= 2;
1542       } while (o->bufused + slength >= new_len);
1543       o->buf = XRESIZEVEC (char, o->buf, new_len);
1544       o->buflength = new_len;
1545     }
1546   memcpy (o->buf + o->bufused, s, slength);
1547   o->bufused += slength;
1548   free (s);
1549 }
1550
1551 /* Open the global header file and the language-specific header files.  */
1552
1553 static void
1554 open_base_files (void)
1555 {
1556   size_t i;
1557
1558   if (nb_plugin_files > 0 && plugin_files)
1559     return;
1560
1561   header_file = create_file ("GCC", "gtype-desc.h");
1562
1563   base_files = XNEWVEC (outf_p, num_lang_dirs);
1564
1565   for (i = 0; i < num_lang_dirs; i++)
1566     base_files[i] = create_file (lang_dir_names[i],
1567                                  xasprintf ("gtype-%s.h", lang_dir_names[i]));
1568
1569   /* gtype-desc.c is a little special, so we create it here.  */
1570   {
1571     /* The order of files here matters very much.  */
1572     static const char *const ifiles [] = {
1573       "config.h", "system.h", "coretypes.h", "tm.h",
1574       "hashtab.h", "splay-tree.h",  "obstack.h", "bitmap.h", "input.h",
1575       "tree.h", "rtl.h", "function.h", "insn-config.h", "expr.h",
1576       "hard-reg-set.h", "basic-block.h", "cselib.h", "insn-addr.h",
1577       "optabs.h", "libfuncs.h", "debug.h", "ggc.h", "cgraph.h",
1578       "tree-flow.h", "reload.h", "cpp-id-data.h", "tree-chrec.h",
1579       "cfglayout.h", "except.h", "output.h", "gimple.h", "cfgloop.h",
1580       "target.h", "ipa-prop.h", "lto-streamer.h", NULL
1581     };
1582     const char *const *ifp;
1583     outf_p gtype_desc_c;
1584
1585     gtype_desc_c = create_file ("GCC", "gtype-desc.c");
1586     for (ifp = ifiles; *ifp; ifp++)
1587       oprintf (gtype_desc_c, "#include \"%s\"\n", *ifp);
1588
1589     /* Make sure we handle "cfun" specially.  */
1590     oprintf (gtype_desc_c, "\n/* See definition in function.h.  */\n");
1591     oprintf (gtype_desc_c, "#undef cfun\n");
1592   }
1593 }
1594
1595 /* For F a filename, return the real basename of F, with all the directory
1596    components skipped.  */
1597
1598 static const char *
1599 get_file_realbasename (const char *f)
1600 {
1601   const char * lastslash = strrchr (f, '/');
1602
1603   return (lastslash != NULL) ? lastslash + 1 : f;
1604 }
1605
1606 /* For F a filename, return the relative path to F from $(srcdir) if the
1607    latter is a prefix in F, NULL otherwise.  */
1608
1609 static const char *
1610 get_file_srcdir_relative_path (const char *f)
1611 {
1612   if (strlen (f) > srcdir_len
1613       && IS_DIR_SEPARATOR (f[srcdir_len])
1614       && memcmp (f, srcdir, srcdir_len) == 0)
1615     return f + srcdir_len + 1;
1616   else
1617     return NULL;
1618 }
1619
1620 /* For F a filename, return the relative path to F from $(srcdir) if the
1621    latter is a prefix in F, or the real basename of F otherwise.  */
1622
1623 static const char *
1624 get_file_basename (const char *f)
1625 {
1626   const char * srcdir_path = get_file_srcdir_relative_path (f);
1627
1628   return (srcdir_path != NULL) ? srcdir_path : get_file_realbasename (f);
1629 }
1630
1631 /* For F a filename, return the lang_dir_names relative index of the language
1632    directory that is a prefix in F, if any, -1 otherwise.  */
1633
1634 static int
1635 get_prefix_langdir_index (const char *f)
1636 {
1637   size_t f_len = strlen (f);
1638   size_t lang_index;
1639
1640   for (lang_index = 0; lang_index < num_lang_dirs; lang_index++)
1641     {
1642       const char * langdir = lang_dir_names [lang_index];
1643       size_t langdir_len = strlen (langdir);
1644
1645       if (f_len > langdir_len
1646           && IS_DIR_SEPARATOR (f[langdir_len])
1647           && memcmp (f, langdir, langdir_len) == 0)
1648         return lang_index;
1649     }
1650
1651   return -1;
1652 }
1653
1654 /* For F a filename, return the name of language directory where F is located,
1655    if any, NULL otherwise.  */
1656
1657 static const char *
1658 get_file_langdir (const char *f)
1659 {
1660   /* Get the relative path to F from $(srcdir) and find the language by
1661      comparing the prefix with language directory names.  If F is not even
1662      srcdir relative, no point in looking further.  */
1663
1664   int lang_index;
1665   const char * srcdir_relative_path = get_file_srcdir_relative_path (f);
1666
1667   if (!srcdir_relative_path)
1668     return NULL;
1669
1670   lang_index = get_prefix_langdir_index (srcdir_relative_path);
1671
1672   return (lang_index >= 0) ? lang_dir_names [lang_index] : NULL;
1673 }
1674
1675 /* The gt- output file name for F.  */
1676
1677 static const char *
1678 get_file_gtfilename (const char *f)
1679 {
1680   /* Cook up an initial version of the gt- file name from the file real
1681      basename and the language name, if any.  */
1682
1683   const char *basename = get_file_realbasename (f);
1684   const char *langdir = get_file_langdir (f);
1685
1686   char * result =
1687     (langdir ? xasprintf ("gt-%s-%s", langdir, basename)
1688      : xasprintf ("gt-%s", basename));
1689
1690   /* Then replace all non alphanumerics characters by '-' and change the
1691      extension to ".h".  We expect the input filename extension was at least
1692      one character long.  */
1693
1694   char *s = result;
1695
1696   for (; *s != '.'; s++)
1697     if (! ISALNUM (*s) && *s != '-')
1698       *s = '-';
1699
1700   memcpy (s, ".h", sizeof (".h"));
1701
1702   return result;
1703 }
1704
1705 /* An output file, suitable for definitions, that can see declarations
1706    made in INPUT_FILE and is linked into every language that uses
1707    INPUT_FILE.  */
1708
1709 outf_p
1710 get_output_file_with_visibility (const char *input_file)
1711 {
1712   outf_p r;
1713   size_t len;
1714   const char *basename;
1715   const char *for_name;
1716   const char *output_name;
1717
1718   /* This can happen when we need a file with visibility on a
1719      structure that we've never seen.  We have to just hope that it's
1720      globally visible.  */
1721   if (input_file == NULL)
1722     input_file = "system.h";
1723
1724   /* In plugin mode, return NULL unless the input_file is one of the
1725      plugin_files.  */
1726   if (plugin_files)
1727     {
1728       size_t i;
1729       for (i = 0; i < nb_plugin_files; i++)
1730         if (strcmp (input_file, plugin_files[i]) == 0)
1731           return plugin_output;
1732
1733       return NULL;
1734     }
1735
1736   /* Determine the output file name.  */
1737   basename = get_file_basename (input_file);
1738
1739   len = strlen (basename);
1740   if ((len > 2 && memcmp (basename+len-2, ".c", 2) == 0)
1741       || (len > 2 && memcmp (basename+len-2, ".y", 2) == 0)
1742       || (len > 3 && memcmp (basename+len-3, ".in", 3) == 0))
1743     {
1744       output_name = get_file_gtfilename (input_file);
1745       for_name = basename;
1746     }
1747   /* Some headers get used by more than one front-end; hence, it
1748      would be inappropriate to spew them out to a single gtype-<lang>.h
1749      (and gengtype doesn't know how to direct spewage into multiple
1750      gtype-<lang>.h headers at this time).  Instead, we pair up these
1751      headers with source files (and their special purpose gt-*.h headers).  */
1752   else if (strcmp (basename, "c-common.h") == 0)
1753     output_name = "gt-c-common.h", for_name = "c-common.c";
1754   else if (strcmp (basename, "c-lang.h") == 0)
1755     output_name = "gt-c-decl.h", for_name = "c-decl.c";
1756   else if (strcmp (basename, "c-tree.h") == 0)
1757     output_name = "gt-c-decl.h", for_name = "c-decl.c";
1758   else if (strncmp (basename, "cp", 2) == 0 && IS_DIR_SEPARATOR (basename[2])
1759            && strcmp (basename + 3, "cp-tree.h") == 0)
1760     output_name = "gt-cp-tree.h", for_name = "cp/tree.c";
1761   else if (strncmp (basename, "cp", 2) == 0 && IS_DIR_SEPARATOR (basename[2])
1762            && strcmp (basename + 3, "decl.h") == 0)
1763     output_name = "gt-cp-decl.h", for_name = "cp/decl.c";
1764   else if (strncmp (basename, "cp", 2) == 0 && IS_DIR_SEPARATOR (basename[2])
1765            && strcmp (basename + 3, "name-lookup.h") == 0)
1766     output_name = "gt-cp-name-lookup.h", for_name = "cp/name-lookup.c";
1767   else if (strncmp (basename, "objc", 4) == 0 && IS_DIR_SEPARATOR (basename[4])
1768            && strcmp (basename + 5, "objc-act.h") == 0)
1769     output_name = "gt-objc-objc-act.h", for_name = "objc/objc-act.c";
1770   else
1771     {
1772       int lang_index = get_prefix_langdir_index (basename);
1773
1774       if (lang_index >= 0)
1775         return base_files[lang_index];
1776
1777       output_name = "gtype-desc.c";
1778       for_name = NULL;
1779     }
1780
1781   /* Look through to see if we've ever seen this output filename before.  */
1782   for (r = output_files; r; r = r->next)
1783     if (strcmp (r->name, output_name) == 0)
1784       return r;
1785
1786   /* If not, create it.  */
1787   r = create_file (for_name, output_name);
1788
1789   gcc_assert (r && r->name);
1790   return r;
1791 }
1792
1793 /* The name of an output file, suitable for definitions, that can see
1794    declarations made in INPUT_FILE and is linked into every language
1795    that uses INPUT_FILE.  */
1796
1797 const char *
1798 get_output_file_name (const char *input_file)
1799 {
1800   outf_p o =  get_output_file_with_visibility (input_file);
1801   if (o)
1802     return o->name;
1803   return NULL;
1804 }
1805
1806 /* Check if existing file is equal to the in memory buffer. */
1807
1808 static bool
1809 is_file_equal (outf_p of)
1810 {
1811   FILE *newfile = fopen (of->name, "r");
1812   size_t i;
1813   bool equal;
1814   if (newfile == NULL)
1815     return false;
1816
1817   equal = true;
1818   for (i = 0; i < of->bufused; i++)
1819     {
1820       int ch;
1821       ch = fgetc (newfile);
1822       if (ch == EOF || ch != (unsigned char) of->buf[i])
1823         {
1824           equal = false;
1825           break;
1826         }
1827     }
1828   fclose (newfile);
1829   return equal;
1830 }
1831
1832 /* Copy the output to its final destination,
1833    but don't unnecessarily change modification times.  */
1834
1835 static void
1836 close_output_files (void)
1837 {
1838   outf_p of;
1839
1840   for (of = output_files; of; of = of->next)
1841     {
1842
1843       if (!is_file_equal(of))
1844       {
1845         FILE *newfile = fopen (of->name, "w");
1846         if (newfile == NULL)
1847           fatal ("opening output file %s: %s", of->name, strerror (errno));
1848         if (fwrite (of->buf, 1, of->bufused, newfile) != of->bufused)
1849           fatal ("writing output file %s: %s", of->name, strerror (errno));
1850         if (fclose (newfile) != 0)
1851           fatal ("closing output file %s: %s", of->name, strerror (errno));
1852       }
1853       free(of->buf);
1854       of->buf = NULL;
1855       of->bufused = of->buflength = 0;
1856     }
1857 }
1858 \f
1859 struct flist {
1860   struct flist *next;
1861   int started_p;
1862   const char *name;
1863   outf_p f;
1864 };
1865
1866 struct walk_type_data;
1867
1868 /* For scalars and strings, given the item in 'val'.
1869    For structures, given a pointer to the item in 'val'.
1870    For misc. pointers, given the item in 'val'.
1871 */
1872 typedef void (*process_field_fn)
1873      (type_p f, const struct walk_type_data *p);
1874 typedef void (*func_name_fn)
1875      (type_p s, const struct walk_type_data *p);
1876
1877 /* Parameters for write_types.  */
1878
1879 struct write_types_data
1880 {
1881   const char *prefix;
1882   const char *param_prefix;
1883   const char *subfield_marker_routine;
1884   const char *marker_routine;
1885   const char *reorder_note_routine;
1886   const char *comment;
1887   int skip_hooks;               /* skip hook generation if non zero */
1888 };
1889
1890 static void output_escaped_param (struct walk_type_data *d,
1891                                   const char *, const char *);
1892 static void output_mangled_typename (outf_p, const_type_p);
1893 static void walk_type (type_p t, struct walk_type_data *d);
1894 static void write_func_for_structure
1895      (type_p orig_s, type_p s, type_p * param,
1896       const struct write_types_data *wtd);
1897 static void write_types_process_field
1898      (type_p f, const struct walk_type_data *d);
1899 static void write_types (outf_p output_header,
1900                          type_p structures,
1901                          type_p param_structs,
1902                          const struct write_types_data *wtd);
1903 static void write_types_local_process_field
1904      (type_p f, const struct walk_type_data *d);
1905 static void write_local_func_for_structure
1906      (const_type_p orig_s, type_p s, type_p * param);
1907 static void write_local (outf_p output_header,
1908                          type_p structures,
1909                          type_p param_structs);
1910 static void write_enum_defn (type_p structures, type_p param_structs);
1911 static int contains_scalar_p (type_p t);
1912 static void put_mangled_filename (outf_p , const char *);
1913 static void finish_root_table (struct flist *flp, const char *pfx,
1914                                const char *tname, const char *lastname,
1915                                const char *name);
1916 static void write_root (outf_p , pair_p, type_p, const char *, int,
1917                         struct fileloc *, const char *, bool);
1918 static void write_array (outf_p f, pair_p v,
1919                          const struct write_types_data *wtd);
1920 static void write_roots (pair_p, bool);
1921
1922 /* Parameters for walk_type.  */
1923
1924 struct walk_type_data
1925 {
1926   process_field_fn process_field;
1927   const void *cookie;
1928   outf_p of;
1929   options_p opt;
1930   const char *val;
1931   const char *prev_val[4];
1932   int indent;
1933   int counter;
1934   const struct fileloc *line;
1935   lang_bitmap bitmap;
1936   type_p *param;
1937   int used_length;
1938   type_p orig_s;
1939   const char *reorder_fn;
1940   bool needs_cast_p;
1941   bool fn_wants_lvalue;
1942 };
1943
1944 /* Print a mangled name representing T to OF.  */
1945
1946 static void
1947 output_mangled_typename (outf_p of, const_type_p t)
1948 {
1949   if (t == NULL)
1950     oprintf (of, "Z");
1951   else switch (t->kind)
1952     {
1953     case TYPE_POINTER:
1954       oprintf (of, "P");
1955       output_mangled_typename (of, t->u.p);
1956       break;
1957     case TYPE_SCALAR:
1958       oprintf (of, "I");
1959       break;
1960     case TYPE_STRING:
1961       oprintf (of, "S");
1962       break;
1963     case TYPE_STRUCT:
1964     case TYPE_UNION:
1965     case TYPE_LANG_STRUCT:
1966       oprintf (of, "%lu%s", (unsigned long) strlen (t->u.s.tag), t->u.s.tag);
1967       break;
1968     case TYPE_PARAM_STRUCT:
1969       {
1970         int i;
1971         for (i = 0; i < NUM_PARAM; i++)
1972           if (t->u.param_struct.param[i] != NULL)
1973             output_mangled_typename (of, t->u.param_struct.param[i]);
1974         output_mangled_typename (of, t->u.param_struct.stru);
1975       }
1976       break;
1977     case TYPE_ARRAY:
1978       gcc_unreachable ();
1979     }
1980 }
1981
1982 /* Print PARAM to D->OF processing escapes.  D->VAL references the
1983    current object, D->PREV_VAL the object containing the current
1984    object, ONAME is the name of the option and D->LINE is used to
1985    print error messages.  */
1986
1987 static void
1988 output_escaped_param (struct walk_type_data *d, const char *param,
1989                       const char *oname)
1990 {
1991   const char *p;
1992
1993   for (p = param; *p; p++)
1994     if (*p != '%')
1995       oprintf (d->of, "%c", *p);
1996     else switch (*++p)
1997       {
1998       case 'h':
1999         oprintf (d->of, "(%s)", d->prev_val[2]);
2000         break;
2001       case '0':
2002         oprintf (d->of, "(%s)", d->prev_val[0]);
2003         break;
2004       case '1':
2005         oprintf (d->of, "(%s)", d->prev_val[1]);
2006         break;
2007       case 'a':
2008         {
2009           const char *pp = d->val + strlen (d->val);
2010           while (pp[-1] == ']')
2011             while (*pp != '[')
2012               pp--;
2013           oprintf (d->of, "%s", pp);
2014         }
2015         break;
2016       default:
2017         error_at_line (d->line, "`%s' option contains bad escape %c%c",
2018                        oname, '%', *p);
2019       }
2020 }
2021
2022 /* Call D->PROCESS_FIELD for every field (or subfield) of D->VAL,
2023    which is of type T.  Write code to D->OF to constrain execution (at
2024    the point that D->PROCESS_FIELD is called) to the appropriate
2025    cases.  Call D->PROCESS_FIELD on subobjects before calling it on
2026    pointers to those objects.  D->PREV_VAL lists the objects
2027    containing the current object, D->OPT is a list of options to
2028    apply, D->INDENT is the current indentation level, D->LINE is used
2029    to print error messages, D->BITMAP indicates which languages to
2030    print the structure for, and D->PARAM is the current parameter
2031    (from an enclosing param_is option).  */
2032
2033 static void
2034 walk_type (type_p t, struct walk_type_data *d)
2035 {
2036   const char *length = NULL;
2037   const char *desc = NULL;
2038   int maybe_undef_p = 0;
2039   int use_param_num = -1;
2040   int use_params_p = 0;
2041   options_p oo;
2042   const struct nested_ptr_data *nested_ptr_d = NULL;
2043
2044   d->needs_cast_p = false;
2045   for (oo = d->opt; oo; oo = oo->next)
2046     if (strcmp (oo->name, "length") == 0)
2047       length = oo->info;
2048     else if (strcmp (oo->name, "maybe_undef") == 0)
2049       maybe_undef_p = 1;
2050     else if (strncmp (oo->name, "use_param", 9) == 0
2051              && (oo->name[9] == '\0' || ISDIGIT (oo->name[9])))
2052       use_param_num = oo->name[9] == '\0' ? 0 : oo->name[9] - '0';
2053     else if (strcmp (oo->name, "use_params") == 0)
2054       use_params_p = 1;
2055     else if (strcmp (oo->name, "desc") == 0)
2056       desc = oo->info;
2057     else if (strcmp (oo->name, "mark_hook") == 0)
2058       ;
2059     else if (strcmp (oo->name, "nested_ptr") == 0)
2060       nested_ptr_d = (const struct nested_ptr_data *) oo->info;
2061     else if (strcmp (oo->name, "dot") == 0)
2062       ;
2063     else if (strcmp (oo->name, "tag") == 0)
2064       ;
2065     else if (strcmp (oo->name, "special") == 0)
2066       ;
2067     else if (strcmp (oo->name, "skip") == 0)
2068       ;
2069     else if (strcmp (oo->name, "default") == 0)
2070       ;
2071     else if (strcmp (oo->name, "descbits") == 0)
2072       ;
2073     else if (strcmp (oo->name, "param_is") == 0)
2074       ;
2075     else if (strncmp (oo->name, "param", 5) == 0
2076              && ISDIGIT (oo->name[5])
2077              && strcmp (oo->name + 6, "_is") == 0)
2078       ;
2079     else if (strcmp (oo->name, "chain_next") == 0)
2080       ;
2081     else if (strcmp (oo->name, "chain_prev") == 0)
2082       ;
2083     else if (strcmp (oo->name, "chain_circular") == 0)
2084       ;
2085     else if (strcmp (oo->name, "reorder") == 0)
2086       ;
2087     else
2088       error_at_line (d->line, "unknown option `%s'\n", oo->name);
2089
2090   if (d->used_length)
2091     length = NULL;
2092
2093   if (use_params_p)
2094     {
2095       int pointer_p = t->kind == TYPE_POINTER;
2096
2097       if (pointer_p)
2098         t = t->u.p;
2099       if (! UNION_OR_STRUCT_P (t))
2100         error_at_line (d->line, "`use_params' option on unimplemented type");
2101       else
2102         t = find_param_structure (t, d->param);
2103       if (pointer_p)
2104         t = create_pointer (t);
2105     }
2106
2107   if (use_param_num != -1)
2108     {
2109       if (d->param != NULL && d->param[use_param_num] != NULL)
2110         {
2111           type_p nt = d->param[use_param_num];
2112
2113           if (t->kind == TYPE_ARRAY)
2114             nt = create_array (nt, t->u.a.len);
2115           else if (length != NULL && t->kind == TYPE_POINTER)
2116             nt = create_pointer (nt);
2117           d->needs_cast_p = (t->kind != TYPE_POINTER
2118                              && (nt->kind == TYPE_POINTER
2119                                  || nt->kind == TYPE_STRING));
2120           t = nt;
2121         }
2122       else
2123         error_at_line (d->line, "no parameter defined for `%s'",
2124                        d->val);
2125     }
2126
2127   if (maybe_undef_p
2128       && (t->kind != TYPE_POINTER || ! UNION_OR_STRUCT_P (t->u.p)))
2129     {
2130       error_at_line (d->line,
2131                      "field `%s' has invalid option `maybe_undef_p'\n",
2132                      d->val);
2133       return;
2134     }
2135
2136   switch (t->kind)
2137     {
2138     case TYPE_SCALAR:
2139     case TYPE_STRING:
2140       d->process_field (t, d);
2141       break;
2142
2143     case TYPE_POINTER:
2144       {
2145         if (maybe_undef_p
2146             && t->u.p->u.s.line.file == NULL)
2147           {
2148             oprintf (d->of, "%*sgcc_assert (!%s);\n", d->indent, "", d->val);
2149             break;
2150           }
2151
2152         if (! length)
2153           {
2154             if (! UNION_OR_STRUCT_P (t->u.p)
2155                 && t->u.p->kind != TYPE_PARAM_STRUCT)
2156               {
2157                 error_at_line (d->line,
2158                                "field `%s' is pointer to unimplemented type",
2159                                d->val);
2160                 break;
2161               }
2162
2163             if (nested_ptr_d)
2164               {
2165                 const char *oldprevval2 = d->prev_val[2];
2166
2167                 if (! UNION_OR_STRUCT_P (nested_ptr_d->type))
2168                   {
2169                     error_at_line (d->line,
2170                                    "field `%s' has invalid "
2171                                    "option `nested_ptr'\n",
2172                                    d->val);
2173                     return;
2174                   }
2175
2176                 d->prev_val[2] = d->val;
2177                 oprintf (d->of, "%*s{\n", d->indent, "");
2178                 d->indent += 2;
2179                 d->val = xasprintf ("x%d", d->counter++);
2180                 oprintf (d->of, "%*s%s %s * %s%s =\n", d->indent, "",
2181                          (nested_ptr_d->type->kind == TYPE_UNION
2182                           ? "union" : "struct"),
2183                          nested_ptr_d->type->u.s.tag,
2184                          d->fn_wants_lvalue ? "" : "const ",
2185                          d->val);
2186                 oprintf (d->of, "%*s", d->indent + 2, "");
2187                 output_escaped_param (d, nested_ptr_d->convert_from,
2188                                       "nested_ptr");
2189                 oprintf (d->of, ";\n");
2190
2191                 d->process_field (nested_ptr_d->type, d);
2192
2193                 if (d->fn_wants_lvalue)
2194                   {
2195                     oprintf (d->of, "%*s%s = ", d->indent, "",
2196                              d->prev_val[2]);
2197                     d->prev_val[2] = d->val;
2198                     output_escaped_param (d, nested_ptr_d->convert_to,
2199                                           "nested_ptr");
2200                     oprintf (d->of, ";\n");
2201                   }
2202
2203                 d->indent -= 2;
2204                 oprintf (d->of, "%*s}\n", d->indent, "");
2205                 d->val = d->prev_val[2];
2206                 d->prev_val[2] = oldprevval2;
2207               }
2208             else
2209               d->process_field (t->u.p, d);
2210           }
2211         else
2212           {
2213             int loopcounter = d->counter++;
2214             const char *oldval = d->val;
2215             const char *oldprevval3 = d->prev_val[3];
2216             char *newval;
2217
2218             oprintf (d->of, "%*sif (%s != NULL) {\n", d->indent, "", d->val);
2219             d->indent += 2;
2220             oprintf (d->of, "%*ssize_t i%d;\n", d->indent, "", loopcounter);
2221             oprintf (d->of, "%*sfor (i%d = 0; i%d != (size_t)(", d->indent, "",
2222                      loopcounter, loopcounter);
2223             output_escaped_param (d, length, "length");
2224             oprintf (d->of, "); i%d++) {\n", loopcounter);
2225             d->indent += 2;
2226             d->val = newval = xasprintf ("%s[i%d]", oldval, loopcounter);
2227             d->used_length = 1;
2228             d->prev_val[3] = oldval;
2229             walk_type (t->u.p, d);
2230             free (newval);
2231             d->val = oldval;
2232             d->prev_val[3] = oldprevval3;
2233             d->used_length = 0;
2234             d->indent -= 2;
2235             oprintf (d->of, "%*s}\n", d->indent, "");
2236             d->process_field(t, d);
2237             d->indent -= 2;
2238             oprintf (d->of, "%*s}\n", d->indent, "");
2239           }
2240       }
2241       break;
2242
2243     case TYPE_ARRAY:
2244       {
2245         int loopcounter = d->counter++;
2246         const char *oldval = d->val;
2247         char *newval;
2248
2249         /* If it's an array of scalars, we optimize by not generating
2250            any code.  */
2251         if (t->u.a.p->kind == TYPE_SCALAR)
2252           break;
2253
2254         /* When walking an array, compute the length and store it in a
2255            local variable before walking the array elements, instead of
2256            recomputing the length expression each time through the loop.
2257            This is necessary to handle tcc_vl_exp objects like CALL_EXPR,
2258            where the length is stored in the first array element,
2259            because otherwise that operand can get overwritten on the
2260            first iteration.  */
2261         oprintf (d->of, "%*s{\n", d->indent, "");
2262         d->indent += 2;
2263         oprintf (d->of, "%*ssize_t i%d;\n", d->indent, "", loopcounter);
2264         oprintf (d->of, "%*ssize_t l%d = (size_t)(",
2265                  d->indent, "", loopcounter);
2266         if (length)
2267           output_escaped_param (d, length, "length");
2268         else
2269           oprintf (d->of, "%s", t->u.a.len);
2270         oprintf (d->of, ");\n");
2271
2272         oprintf (d->of, "%*sfor (i%d = 0; i%d != l%d; i%d++) {\n",
2273                  d->indent, "",
2274                  loopcounter, loopcounter, loopcounter, loopcounter);
2275         d->indent += 2;
2276         d->val = newval = xasprintf ("%s[i%d]", oldval, loopcounter);
2277         d->used_length = 1;
2278         walk_type (t->u.a.p, d);
2279         free (newval);
2280         d->used_length = 0;
2281         d->val = oldval;
2282         d->indent -= 2;
2283         oprintf (d->of, "%*s}\n", d->indent, "");
2284         d->indent -= 2;
2285         oprintf (d->of, "%*s}\n", d->indent, "");
2286       }
2287       break;
2288
2289     case TYPE_STRUCT:
2290     case TYPE_UNION:
2291       {
2292         pair_p f;
2293         const char *oldval = d->val;
2294         const char *oldprevval1 = d->prev_val[1];
2295         const char *oldprevval2 = d->prev_val[2];
2296         const int union_p = t->kind == TYPE_UNION;
2297         int seen_default_p = 0;
2298         options_p o;
2299
2300         if (! t->u.s.line.file)
2301           error_at_line (d->line, "incomplete structure `%s'", t->u.s.tag);
2302
2303         if ((d->bitmap & t->u.s.bitmap) != d->bitmap)
2304           {
2305             error_at_line (d->line,
2306                            "structure `%s' defined for mismatching languages",
2307                            t->u.s.tag);
2308             error_at_line (&t->u.s.line, "one structure defined here");
2309           }
2310
2311         /* Some things may also be defined in the structure's options.  */
2312         for (o = t->u.s.opt; o; o = o->next)
2313           if (! desc && strcmp (o->name, "desc") == 0)
2314             desc = o->info;
2315
2316         d->prev_val[2] = oldval;
2317         d->prev_val[1] = oldprevval2;
2318         if (union_p)
2319           {
2320             if (desc == NULL)
2321               {
2322                 error_at_line (d->line, "missing `desc' option for union `%s'",
2323                                t->u.s.tag);
2324                 desc = "1";
2325               }
2326             oprintf (d->of, "%*sswitch (", d->indent, "");
2327             output_escaped_param (d, desc, "desc");
2328             oprintf (d->of, ")\n");
2329             d->indent += 2;
2330             oprintf (d->of, "%*s{\n", d->indent, "");
2331           }
2332         for (f = t->u.s.fields; f; f = f->next)
2333           {
2334             options_p oo;
2335             const char *dot = ".";
2336             const char *tagid = NULL;
2337             int skip_p = 0;
2338             int default_p = 0;
2339             int use_param_p = 0;
2340             char *newval;
2341
2342             d->reorder_fn = NULL;
2343             for (oo = f->opt; oo; oo = oo->next)
2344               if (strcmp (oo->name, "dot") == 0)
2345                 dot = oo->info;
2346               else if (strcmp (oo->name, "tag") == 0)
2347                 tagid = oo->info;
2348               else if (strcmp (oo->name, "skip") == 0)
2349                 skip_p = 1;
2350               else if (strcmp (oo->name, "default") == 0)
2351                 default_p = 1;
2352               else if (strcmp (oo->name, "reorder") == 0)
2353                 d->reorder_fn = oo->info;
2354               else if (strncmp (oo->name, "use_param", 9) == 0
2355                        && (oo->name[9] == '\0' || ISDIGIT (oo->name[9])))
2356                 use_param_p = 1;
2357
2358             if (skip_p)
2359               continue;
2360
2361             if (union_p && tagid)
2362               {
2363                 oprintf (d->of, "%*scase %s:\n", d->indent, "", tagid);
2364                 d->indent += 2;
2365               }
2366             else if (union_p && default_p)
2367               {
2368                 oprintf (d->of, "%*sdefault:\n", d->indent, "");
2369                 d->indent += 2;
2370                 seen_default_p = 1;
2371               }
2372             else if (! union_p && (default_p || tagid))
2373               error_at_line (d->line,
2374                              "can't use `%s' outside a union on field `%s'",
2375                              default_p ? "default" : "tag", f->name);
2376             else if (union_p && ! (default_p || tagid)
2377                      && f->type->kind == TYPE_SCALAR)
2378               {
2379                 fprintf (stderr,
2380         "%s:%d: warning: field `%s' is missing `tag' or `default' option\n",
2381                          d->line->file, d->line->line, f->name);
2382                 continue;
2383               }
2384             else if (union_p && ! (default_p || tagid))
2385               error_at_line (d->line,
2386                              "field `%s' is missing `tag' or `default' option",
2387                              f->name);
2388
2389             d->line = &f->line;
2390             d->val = newval = xasprintf ("%s%s%s", oldval, dot, f->name);
2391             d->opt = f->opt;
2392             d->used_length = false;
2393
2394             if (union_p && use_param_p && d->param == NULL)
2395               oprintf (d->of, "%*sgcc_unreachable ();\n", d->indent, "");
2396             else
2397               walk_type (f->type, d);
2398
2399             free (newval);
2400
2401             if (union_p)
2402               {
2403                 oprintf (d->of, "%*sbreak;\n", d->indent, "");
2404                 d->indent -= 2;
2405               }
2406           }
2407         d->reorder_fn = NULL;
2408
2409         d->val = oldval;
2410         d->prev_val[1] = oldprevval1;
2411         d->prev_val[2] = oldprevval2;
2412
2413         if (union_p && ! seen_default_p)
2414           {
2415             oprintf (d->of, "%*sdefault:\n", d->indent, "");
2416             oprintf (d->of, "%*s  break;\n", d->indent, "");
2417           }
2418         if (union_p)
2419           {
2420             oprintf (d->of, "%*s}\n", d->indent, "");
2421             d->indent -= 2;
2422           }
2423       }
2424       break;
2425
2426     case TYPE_LANG_STRUCT:
2427       {
2428         type_p nt;
2429         for (nt = t->u.s.lang_struct; nt; nt = nt->next)
2430           if ((d->bitmap & nt->u.s.bitmap) == d->bitmap)
2431             break;
2432         if (nt == NULL)
2433           error_at_line (d->line, "structure `%s' differs between languages",
2434                          t->u.s.tag);
2435         else
2436           walk_type (nt, d);
2437       }
2438       break;
2439
2440     case TYPE_PARAM_STRUCT:
2441       {
2442         type_p *oldparam = d->param;
2443
2444         d->param = t->u.param_struct.param;
2445         walk_type (t->u.param_struct.stru, d);
2446         d->param = oldparam;
2447       }
2448       break;
2449
2450     default:
2451       gcc_unreachable ();
2452     }
2453 }
2454
2455 /* process_field routine for marking routines.  */
2456
2457 static void
2458 write_types_process_field (type_p f, const struct walk_type_data *d)
2459 {
2460   const struct write_types_data *wtd;
2461   const char *cast = d->needs_cast_p ? "(void *)" : "";
2462   wtd = (const struct write_types_data *) d->cookie;
2463
2464   switch (f->kind)
2465     {
2466     case TYPE_POINTER:
2467       oprintf (d->of, "%*s%s (%s%s", d->indent, "",
2468                wtd->subfield_marker_routine, cast, d->val);
2469       if (wtd->param_prefix)
2470         {
2471           oprintf (d->of, ", %s", d->prev_val[3]);
2472           if (d->orig_s)
2473             {
2474               oprintf (d->of, ", gt_%s_", wtd->param_prefix);
2475               output_mangled_typename (d->of, d->orig_s);
2476             }
2477           else
2478             oprintf (d->of, ", gt_%sa_%s", wtd->param_prefix, d->prev_val[0]);
2479
2480           if (f->u.p->kind == TYPE_PARAM_STRUCT
2481               && f->u.p->u.s.line.file != NULL)
2482             {
2483               oprintf (d->of, ", gt_e_");
2484               output_mangled_typename (d->of, f);
2485             }
2486           else if (UNION_OR_STRUCT_P (f)
2487                    && f->u.p->u.s.line.file != NULL)
2488             {
2489               oprintf (d->of, ", gt_ggc_e_");
2490               output_mangled_typename (d->of, f);
2491             }
2492           else
2493             oprintf (d->of, ", gt_types_enum_last");
2494         }
2495       oprintf (d->of, ");\n");
2496       if (d->reorder_fn && wtd->reorder_note_routine)
2497         oprintf (d->of, "%*s%s (%s%s, %s, %s);\n", d->indent, "",
2498                  wtd->reorder_note_routine, cast, d->val,
2499                  d->prev_val[3], d->reorder_fn);
2500       break;
2501
2502     case TYPE_STRING:
2503     case TYPE_STRUCT:
2504     case TYPE_UNION:
2505     case TYPE_LANG_STRUCT:
2506     case TYPE_PARAM_STRUCT:
2507       oprintf (d->of, "%*sgt_%s_", d->indent, "", wtd->prefix);
2508       output_mangled_typename (d->of, f);
2509       oprintf (d->of, " (%s%s);\n", cast, d->val);
2510       if (d->reorder_fn && wtd->reorder_note_routine)
2511         oprintf (d->of, "%*s%s (%s%s, %s%s, %s);\n", d->indent, "",
2512                  wtd->reorder_note_routine, cast, d->val, cast, d->val,
2513                  d->reorder_fn);
2514       break;
2515
2516     case TYPE_SCALAR:
2517       break;
2518
2519     default:
2520       gcc_unreachable ();
2521     }
2522 }
2523
2524 /* A subroutine of write_func_for_structure.  Write the enum tag for S.  */
2525
2526 static void
2527 output_type_enum (outf_p of, type_p s)
2528 {
2529   if (s->kind == TYPE_PARAM_STRUCT && s->u.s.line.file != NULL)
2530     {
2531       oprintf (of, ", gt_e_");
2532       output_mangled_typename (of, s);
2533     }
2534   else if (UNION_OR_STRUCT_P (s) && s->u.s.line.file != NULL)
2535     {
2536       oprintf (of, ", gt_ggc_e_");
2537       output_mangled_typename (of, s);
2538     }
2539   else
2540     oprintf (of, ", gt_types_enum_last");
2541 }
2542
2543 /* Return an output file that is suitable for definitions which can
2544    reference struct S */
2545
2546 static outf_p
2547 get_output_file_for_structure (const_type_p s, type_p *param)
2548 {
2549   const char * fn = s->u.s.line.file;
2550   int i;
2551
2552   /* This is a hack, and not the good kind either.  */
2553   for (i = NUM_PARAM - 1; i >= 0; i--)
2554     if (param && param[i] && param[i]->kind == TYPE_POINTER
2555         && UNION_OR_STRUCT_P (param[i]->u.p))
2556       fn = param[i]->u.p->u.s.line.file;
2557
2558   return get_output_file_with_visibility (fn);
2559 }
2560
2561 /* For S, a structure that's part of ORIG_S, and using parameters
2562    PARAM, write out a routine that:
2563    - Takes a parameter, a void * but actually of type *S
2564    - If SEEN_ROUTINE returns nonzero, calls write_types_process_field on each
2565      field of S or its substructures and (in some cases) things
2566      that are pointed to by S.
2567 */
2568
2569 static void
2570 write_func_for_structure (type_p orig_s, type_p s, type_p *param,
2571                           const struct write_types_data *wtd)
2572 {
2573   const char *chain_next = NULL;
2574   const char *chain_prev = NULL;
2575   const char *chain_circular = NULL;
2576   const char *mark_hook_name = NULL;
2577   options_p opt;
2578   struct walk_type_data d;
2579
2580   memset (&d, 0, sizeof (d));
2581   d.of = get_output_file_for_structure (s, param);
2582
2583   for (opt = s->u.s.opt; opt; opt = opt->next)
2584     if (strcmp (opt->name, "chain_next") == 0)
2585       chain_next = opt->info;
2586     else if (strcmp (opt->name, "chain_prev") == 0)
2587       chain_prev = opt->info;
2588     else if (strcmp (opt->name, "chain_circular") == 0)
2589       chain_circular = opt->info;
2590     else if (strcmp (opt->name, "mark_hook") == 0)
2591       mark_hook_name = opt->info;
2592
2593   if (chain_prev != NULL && chain_next == NULL)
2594     error_at_line (&s->u.s.line, "chain_prev without chain_next");
2595   if (chain_circular != NULL && chain_next != NULL)
2596     error_at_line (&s->u.s.line, "chain_circular with chain_next");
2597   if (chain_circular != NULL)
2598     chain_next = chain_circular;
2599
2600   d.process_field = write_types_process_field;
2601   d.cookie = wtd;
2602   d.orig_s = orig_s;
2603   d.opt = s->u.s.opt;
2604   d.line = &s->u.s.line;
2605   d.bitmap = s->u.s.bitmap;
2606   d.param = param;
2607   d.prev_val[0] = "*x";
2608   d.prev_val[1] = "not valid postage";  /* Guarantee an error.  */
2609   d.prev_val[3] = "x";
2610   d.val = "(*x)";
2611
2612   oprintf (d.of, "\n");
2613   oprintf (d.of, "void\n");
2614   if (param == NULL)
2615     oprintf (d.of, "gt_%sx_%s", wtd->prefix, orig_s->u.s.tag);
2616   else
2617     {
2618       oprintf (d.of, "gt_%s_", wtd->prefix);
2619       output_mangled_typename (d.of, orig_s);
2620     }
2621   oprintf (d.of, " (void *x_p)\n");
2622   oprintf (d.of, "{\n");
2623   oprintf (d.of, "  %s %s * %sx = (%s %s *)x_p;\n",
2624            s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag,
2625            chain_next == NULL ? "const " : "",
2626            s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag);
2627   if (chain_next != NULL)
2628     oprintf (d.of, "  %s %s * xlimit = x;\n",
2629              s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag);
2630   if (chain_next == NULL)
2631     {
2632       oprintf (d.of, "  if (%s (x", wtd->marker_routine);
2633       if (wtd->param_prefix)
2634         {
2635           oprintf (d.of, ", x, gt_%s_", wtd->param_prefix);
2636           output_mangled_typename (d.of, orig_s);
2637           output_type_enum (d.of, orig_s);
2638         }
2639       oprintf (d.of, "))\n");
2640     }
2641   else
2642     {
2643       if (chain_circular != NULL)
2644         oprintf (d.of, "  if (!%s (xlimit", wtd->marker_routine);
2645       else
2646         oprintf (d.of, "  while (%s (xlimit", wtd->marker_routine);
2647       if (wtd->param_prefix)
2648         {
2649           oprintf (d.of, ", xlimit, gt_%s_", wtd->param_prefix);
2650           output_mangled_typename (d.of, orig_s);
2651           output_type_enum (d.of, orig_s);
2652         }
2653       oprintf (d.of, "))\n");
2654       if (chain_circular != NULL)
2655         oprintf (d.of, "    return;\n  do\n");
2656       if (mark_hook_name && !wtd->skip_hooks)
2657         {
2658           oprintf (d.of, "    {\n");
2659           oprintf (d.of, "      %s (xlimit);\n   ", mark_hook_name);
2660         }
2661       oprintf (d.of, "   xlimit = (");
2662       d.prev_val[2] = "*xlimit";
2663       output_escaped_param (&d, chain_next, "chain_next");
2664       oprintf (d.of, ");\n");
2665       if (mark_hook_name && !wtd->skip_hooks)
2666         oprintf (d.of, "    }\n");
2667       if (chain_prev != NULL)
2668         {
2669           oprintf (d.of, "  if (x != xlimit)\n");
2670           oprintf (d.of, "    for (;;)\n");
2671           oprintf (d.of, "      {\n");
2672           oprintf (d.of, "        %s %s * const xprev = (",
2673                    s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag);
2674
2675           d.prev_val[2] = "*x";
2676           output_escaped_param (&d, chain_prev, "chain_prev");
2677           oprintf (d.of, ");\n");
2678           oprintf (d.of, "        if (xprev == NULL) break;\n");
2679           oprintf (d.of, "        x = xprev;\n");
2680           oprintf (d.of, "        (void) %s (xprev",
2681                    wtd->marker_routine);
2682           if (wtd->param_prefix)
2683             {
2684               oprintf (d.of, ", xprev, gt_%s_", wtd->param_prefix);
2685               output_mangled_typename (d.of, orig_s);
2686               output_type_enum (d.of, orig_s);
2687             }
2688           oprintf (d.of, ");\n");
2689           oprintf (d.of, "      }\n");
2690         }
2691       if (chain_circular != NULL)
2692         {
2693           oprintf (d.of, "  while (%s (xlimit", wtd->marker_routine);
2694           if (wtd->param_prefix)
2695             {
2696               oprintf (d.of, ", xlimit, gt_%s_", wtd->param_prefix);
2697               output_mangled_typename (d.of, orig_s);
2698               output_type_enum (d.of, orig_s);
2699             }
2700           oprintf (d.of, "));\n");
2701           if (mark_hook_name && !wtd->skip_hooks)
2702             oprintf (d.of, "  %s (xlimit);\n", mark_hook_name);
2703           oprintf (d.of, "  do\n");
2704         }
2705       else
2706         oprintf (d.of, "  while (x != xlimit)\n");
2707     }
2708   oprintf (d.of, "    {\n");
2709   if (mark_hook_name && chain_next == NULL && !wtd->skip_hooks)
2710     {
2711       oprintf (d.of, "      %s (x);\n", mark_hook_name);
2712     }
2713   d.prev_val[2] = "*x";
2714   d.indent = 6;
2715   walk_type (s, &d);
2716
2717   if (chain_next != NULL)
2718     {
2719       oprintf (d.of, "      x = (");
2720       output_escaped_param (&d, chain_next, "chain_next");
2721       oprintf (d.of, ");\n");
2722     }
2723
2724   oprintf (d.of, "    }\n");
2725   if (chain_circular != NULL)
2726     oprintf (d.of, "  while (x != xlimit);\n");
2727   oprintf (d.of, "}\n");
2728 }
2729
2730 /* Write out marker routines for STRUCTURES and PARAM_STRUCTS.  */
2731
2732 static void
2733 write_types (outf_p output_header, type_p structures, type_p param_structs,
2734              const struct write_types_data *wtd)
2735 {
2736   type_p s;
2737
2738   oprintf (output_header, "\n/* %s*/\n", wtd->comment);
2739   /* We first emit the macros and the declarations. Functions' code is
2740      emitted afterwards.  This is needed in plugin mode.  */
2741   oprintf (output_header, "/* macros and declarations */\n");
2742   for (s = structures; s; s = s->next)
2743     if (s->gc_used == GC_POINTED_TO
2744         || s->gc_used == GC_MAYBE_POINTED_TO)
2745       {
2746         options_p opt;
2747
2748         if (s->gc_used == GC_MAYBE_POINTED_TO
2749             && s->u.s.line.file == NULL)
2750           continue;
2751
2752         oprintf (output_header, "#define gt_%s_", wtd->prefix);
2753         output_mangled_typename (output_header, s);
2754         oprintf (output_header, "(X) do { \\\n");
2755         oprintf (output_header,
2756                  "  if (X != NULL) gt_%sx_%s (X);\\\n", wtd->prefix,
2757                  s->u.s.tag);
2758         oprintf (output_header,
2759                  "  } while (0)\n");
2760
2761         for (opt = s->u.s.opt; opt; opt = opt->next)
2762           if (strcmp (opt->name, "ptr_alias") == 0)
2763             {
2764               const_type_p const t = (const_type_p) opt->info;
2765               if (t->kind == TYPE_STRUCT
2766                   || t->kind == TYPE_UNION
2767                   || t->kind == TYPE_LANG_STRUCT)
2768                 oprintf (output_header,
2769                          "#define gt_%sx_%s gt_%sx_%s\n",
2770                          wtd->prefix, s->u.s.tag, wtd->prefix, t->u.s.tag);
2771               else
2772                 error_at_line (&s->u.s.line,
2773                                "structure alias is not a structure");
2774               break;
2775             }
2776         if (opt)
2777           continue;
2778
2779         /* Declare the marker procedure only once.  */
2780         oprintf (output_header,
2781                  "extern void gt_%sx_%s (void *);\n",
2782                  wtd->prefix, s->u.s.tag);
2783
2784         if (s->u.s.line.file == NULL)
2785           {
2786             fprintf (stderr, "warning: structure `%s' used but not defined\n",
2787                      s->u.s.tag);
2788             continue;
2789           }
2790       }
2791
2792   for (s = param_structs; s; s = s->next)
2793     if (s->gc_used == GC_POINTED_TO)
2794       {
2795         type_p stru = s->u.param_struct.stru;
2796
2797         /* Declare the marker procedure.  */
2798         oprintf (output_header, "extern void gt_%s_", wtd->prefix);
2799         output_mangled_typename (output_header, s);
2800         oprintf (output_header, " (void *);\n");
2801
2802         if (stru->u.s.line.file == NULL)
2803           {
2804             fprintf (stderr, "warning: structure `%s' used but not defined\n",
2805                      s->u.s.tag);
2806             continue;
2807           }
2808       }
2809
2810   /* At last we emit the functions code.  */
2811   oprintf (output_header, "\n/* functions code */\n");
2812   for (s = structures; s; s = s->next)
2813     if (s->gc_used == GC_POINTED_TO
2814         || s->gc_used == GC_MAYBE_POINTED_TO)
2815       {
2816         options_p opt;
2817
2818         if (s->gc_used == GC_MAYBE_POINTED_TO
2819             && s->u.s.line.file == NULL)
2820           continue;
2821         for (opt = s->u.s.opt; opt; opt = opt->next)
2822           if (strcmp (opt->name, "ptr_alias") == 0)
2823             break;
2824         if (opt)
2825           continue;
2826
2827         if (s->kind == TYPE_LANG_STRUCT)
2828           {
2829             type_p ss;
2830             for (ss = s->u.s.lang_struct; ss; ss = ss->next)
2831               write_func_for_structure (s, ss, NULL, wtd);
2832           }
2833         else
2834           write_func_for_structure (s, s, NULL, wtd);
2835       }
2836   for (s = param_structs; s; s = s->next)
2837     if (s->gc_used == GC_POINTED_TO)
2838       {
2839         type_p *param = s->u.param_struct.param;
2840         type_p stru = s->u.param_struct.stru;
2841         if (stru->u.s.line.file == NULL)
2842           continue;
2843         if (stru->kind == TYPE_LANG_STRUCT)
2844           {
2845             type_p ss;
2846             for (ss = stru->u.s.lang_struct; ss; ss = ss->next)
2847               write_func_for_structure (s, ss, param, wtd);
2848           }
2849         else
2850           write_func_for_structure (s, stru, param, wtd);
2851       }
2852 }
2853
2854 static const struct write_types_data ggc_wtd =
2855 {
2856   "ggc_m", NULL, "ggc_mark", "ggc_test_and_set_mark", NULL,
2857   "GC marker procedures.  ",
2858   FALSE
2859 };
2860
2861 static const struct write_types_data pch_wtd =
2862 {
2863   "pch_n", "pch_p", "gt_pch_note_object", "gt_pch_note_object",
2864   "gt_pch_note_reorder",
2865   "PCH type-walking procedures.  ",
2866   TRUE
2867 };
2868
2869 /* Write out the local pointer-walking routines.  */
2870
2871 /* process_field routine for local pointer-walking.  */
2872
2873 static void
2874 write_types_local_process_field (type_p f, const struct walk_type_data *d)
2875 {
2876   switch (f->kind)
2877     {
2878     case TYPE_POINTER:
2879     case TYPE_STRUCT:
2880     case TYPE_UNION:
2881     case TYPE_LANG_STRUCT:
2882     case TYPE_PARAM_STRUCT:
2883     case TYPE_STRING:
2884       oprintf (d->of, "%*sif ((void *)(%s) == this_obj)\n", d->indent, "",
2885                d->prev_val[3]);
2886       oprintf (d->of, "%*s  op (&(%s), cookie);\n", d->indent, "", d->val);
2887       break;
2888
2889     case TYPE_SCALAR:
2890       break;
2891
2892     default:
2893       gcc_unreachable ();
2894     }
2895 }
2896
2897 /* For S, a structure that's part of ORIG_S, and using parameters
2898    PARAM, write out a routine that:
2899    - Is of type gt_note_pointers
2900    - Calls PROCESS_FIELD on each field of S or its substructures.
2901 */
2902
2903 static void
2904 write_local_func_for_structure (const_type_p orig_s, type_p s, type_p *param)
2905 {
2906   struct walk_type_data d;
2907
2908   memset (&d, 0, sizeof (d));
2909   d.of = get_output_file_for_structure (s, param);
2910   d.process_field = write_types_local_process_field;
2911   d.opt = s->u.s.opt;
2912   d.line = &s->u.s.line;
2913   d.bitmap = s->u.s.bitmap;
2914   d.param = param;
2915   d.prev_val[0] = d.prev_val[2] = "*x";
2916   d.prev_val[1] = "not valid postage";  /* Guarantee an error.  */
2917   d.prev_val[3] = "x";
2918   d.val = "(*x)";
2919   d.fn_wants_lvalue = true;
2920
2921   oprintf (d.of, "\n");
2922   oprintf (d.of, "void\n");
2923   oprintf (d.of, "gt_pch_p_");
2924   output_mangled_typename (d.of, orig_s);
2925   oprintf (d.of, " (ATTRIBUTE_UNUSED void *this_obj,\n"
2926            "\tvoid *x_p,\n"
2927            "\tATTRIBUTE_UNUSED gt_pointer_operator op,\n"
2928            "\tATTRIBUTE_UNUSED void *cookie)\n");
2929   oprintf (d.of, "{\n");
2930   oprintf (d.of, "  %s %s * const x ATTRIBUTE_UNUSED = (%s %s *)x_p;\n",
2931            s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag,
2932            s->kind == TYPE_UNION ? "union" : "struct", s->u.s.tag);
2933   d.indent = 2;
2934   walk_type (s, &d);
2935   oprintf (d.of, "}\n");
2936 }
2937
2938 /* Write out local marker routines for STRUCTURES and PARAM_STRUCTS.  */
2939
2940 static void
2941 write_local (outf_p output_header, type_p structures, type_p param_structs)
2942 {
2943   type_p s;
2944
2945   if (!output_header)
2946     return;
2947   oprintf (output_header, "\n/* Local pointer-walking routines.  */\n");
2948   for (s = structures; s; s = s->next)
2949     if (s->gc_used == GC_POINTED_TO
2950         || s->gc_used == GC_MAYBE_POINTED_TO)
2951       {
2952         options_p opt;
2953
2954         if (s->u.s.line.file == NULL)
2955           continue;
2956
2957         for (opt = s->u.s.opt; opt; opt = opt->next)
2958           if (strcmp (opt->name, "ptr_alias") == 0)
2959             {
2960               const_type_p const t = (const_type_p) opt->info;
2961               if (t->kind == TYPE_STRUCT
2962                   || t->kind == TYPE_UNION
2963                   || t->kind == TYPE_LANG_STRUCT)
2964                 {
2965                   oprintf (output_header, "#define gt_pch_p_");
2966                   output_mangled_typename (output_header, s);
2967                   oprintf (output_header, " gt_pch_p_");
2968                   output_mangled_typename (output_header, t);
2969                   oprintf (output_header, "\n");
2970                 }
2971               else
2972                 error_at_line (&s->u.s.line,
2973                                "structure alias is not a structure");
2974               break;
2975             }
2976         if (opt)
2977           continue;
2978
2979         /* Declare the marker procedure only once.  */
2980         oprintf (output_header, "extern void gt_pch_p_");
2981         output_mangled_typename (output_header, s);
2982         oprintf (output_header,
2983          "\n    (void *, void *, gt_pointer_operator, void *);\n");
2984
2985         if (s->kind == TYPE_LANG_STRUCT)
2986           {
2987             type_p ss;
2988             for (ss = s->u.s.lang_struct; ss; ss = ss->next)
2989               write_local_func_for_structure (s, ss, NULL);
2990           }
2991         else
2992           write_local_func_for_structure (s, s, NULL);
2993       }
2994
2995   for (s = param_structs; s; s = s->next)
2996     if (s->gc_used == GC_POINTED_TO)
2997       {
2998         type_p * param = s->u.param_struct.param;
2999         type_p stru = s->u.param_struct.stru;
3000
3001         /* Declare the marker procedure.  */
3002         oprintf (output_header, "extern void gt_pch_p_");
3003         output_mangled_typename (output_header, s);
3004         oprintf (output_header,
3005          "\n    (void *, void *, gt_pointer_operator, void *);\n");
3006
3007         if (stru->u.s.line.file == NULL)
3008           {
3009             fprintf (stderr, "warning: structure `%s' used but not defined\n",
3010                      s->u.s.tag);
3011             continue;
3012           }
3013
3014         if (stru->kind == TYPE_LANG_STRUCT)
3015           {
3016             type_p ss;
3017             for (ss = stru->u.s.lang_struct; ss; ss = ss->next)
3018               write_local_func_for_structure (s, ss, param);
3019           }
3020         else
3021           write_local_func_for_structure (s, stru, param);
3022       }
3023 }
3024
3025 /* Write out the 'enum' definition for gt_types_enum.  */
3026
3027 static void
3028 write_enum_defn (type_p structures, type_p param_structs)
3029 {
3030   type_p s;
3031
3032   if (!header_file)
3033     return;
3034   oprintf (header_file, "\n/* Enumeration of types known.  */\n");
3035   oprintf (header_file, "enum gt_types_enum {\n");
3036   for (s = structures; s; s = s->next)
3037     if (s->gc_used == GC_POINTED_TO
3038         || s->gc_used == GC_MAYBE_POINTED_TO)
3039       {
3040         if (s->gc_used == GC_MAYBE_POINTED_TO
3041             && s->u.s.line.file == NULL)
3042           continue;
3043
3044         oprintf (header_file, " gt_ggc_e_");
3045         output_mangled_typename (header_file, s);
3046         oprintf (header_file, ", \n");
3047       }
3048   for (s = param_structs; s; s = s->next)
3049     if (s->gc_used == GC_POINTED_TO)
3050       {
3051         oprintf (header_file, " gt_e_");
3052         output_mangled_typename (header_file, s);
3053         oprintf (header_file, ", \n");
3054       }
3055   oprintf (header_file, " gt_types_enum_last\n");
3056   oprintf (header_file, "};\n");
3057 }
3058
3059 /* Might T contain any non-pointer elements?  */
3060
3061 static int
3062 contains_scalar_p (type_p t)
3063 {
3064   switch (t->kind)
3065     {
3066     case TYPE_STRING:
3067     case TYPE_POINTER:
3068       return 0;
3069     case TYPE_ARRAY:
3070       return contains_scalar_p (t->u.a.p);
3071     default:
3072       /* Could also check for structures that have no non-pointer
3073          fields, but there aren't enough of those to worry about.  */
3074       return 1;
3075     }
3076 }
3077
3078 /* Mangle FN and print it to F.  */
3079
3080 static void
3081 put_mangled_filename (outf_p f, const char *fn)
3082 {
3083   const char *name = get_output_file_name (fn);
3084   if (!f || !name)
3085     return;
3086   for (; *name != 0; name++)
3087     if (ISALNUM (*name))
3088       oprintf (f, "%c", *name);
3089     else
3090       oprintf (f, "%c", '_');
3091 }
3092
3093 /* Finish off the currently-created root tables in FLP.  PFX, TNAME,
3094    LASTNAME, and NAME are all strings to insert in various places in
3095    the resulting code.  */
3096
3097 static void
3098 finish_root_table (struct flist *flp, const char *pfx, const char *lastname,
3099                    const char *tname, const char *name)
3100 {
3101   struct flist *fli2;
3102
3103   for (fli2 = flp; fli2; fli2 = fli2->next)
3104     if (fli2->started_p)
3105       {
3106         oprintf (fli2->f, "  %s\n", lastname);
3107         oprintf (fli2->f, "};\n\n");
3108       }
3109
3110   for (fli2 = flp; fli2 && base_files; fli2 = fli2->next)
3111     if (fli2->started_p)
3112       {
3113         lang_bitmap bitmap = get_lang_bitmap (fli2->name);
3114         int fnum;
3115
3116         for (fnum = 0; bitmap != 0; fnum++, bitmap >>= 1)
3117           if (bitmap & 1)
3118             {
3119               oprintf (base_files[fnum],
3120                        "extern const struct %s gt_%s_",
3121                        tname, pfx);
3122               put_mangled_filename (base_files[fnum], fli2->name);
3123               oprintf (base_files[fnum], "[];\n");
3124             }
3125       }
3126
3127   {
3128     size_t fnum;
3129     for (fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
3130       oprintf (base_files [fnum],
3131                "EXPORTED_CONST struct %s * const %s[] = {\n",
3132                tname, name);
3133   }
3134
3135
3136   for (fli2 = flp; fli2; fli2 = fli2->next)
3137     if (fli2->started_p)
3138       {
3139         lang_bitmap bitmap = get_lang_bitmap (fli2->name);
3140         int fnum;
3141
3142         fli2->started_p = 0;
3143
3144         for (fnum = 0; base_files && bitmap != 0; fnum++, bitmap >>= 1)
3145           if (bitmap & 1)
3146             {
3147               oprintf (base_files[fnum], "  gt_%s_", pfx);
3148               put_mangled_filename (base_files[fnum], fli2->name);
3149               oprintf (base_files[fnum], ",\n");
3150             }
3151       }
3152
3153   {
3154     size_t fnum;
3155     for (fnum = 0; base_files && fnum < num_lang_dirs; fnum++)
3156       {
3157         oprintf (base_files[fnum], "  NULL\n");
3158         oprintf (base_files[fnum], "};\n");
3159       }
3160   }
3161 }
3162
3163 /* Write out to F the table entry and any marker routines needed to
3164    mark NAME as TYPE.  The original variable is V, at LINE.
3165    HAS_LENGTH is nonzero iff V was a variable-length array.  IF_MARKED
3166    is nonzero iff we are building the root table for hash table caches.  */
3167
3168 static void
3169 write_root (outf_p f, pair_p v, type_p type, const char *name, int has_length,
3170             struct fileloc *line, const char *if_marked, bool emit_pch)
3171 {
3172   switch (type->kind)
3173     {
3174     case TYPE_STRUCT:
3175       {
3176         pair_p fld;
3177         for (fld = type->u.s.fields; fld; fld = fld->next)
3178           {
3179             int skip_p = 0;
3180             const char *desc = NULL;
3181             options_p o;
3182
3183             for (o = fld->opt; o; o = o->next)
3184               if (strcmp (o->name, "skip") == 0)
3185                 skip_p = 1;
3186               else if (strcmp (o->name, "desc") == 0)
3187                 desc = o->info;
3188               else if (strcmp (o->name, "param_is") == 0)
3189                 ;
3190               else
3191                 error_at_line (line,
3192                        "field `%s' of global `%s' has unknown option `%s'",
3193                                fld->name, name, o->name);
3194
3195             if (skip_p)
3196               continue;
3197             else if (desc && fld->type->kind == TYPE_UNION)
3198               {
3199                 pair_p validf = NULL;
3200                 pair_p ufld;
3201
3202                 for (ufld = fld->type->u.s.fields; ufld; ufld = ufld->next)
3203                   {
3204                     const char *tag = NULL;
3205                     options_p oo;
3206
3207                     for (oo = ufld->opt; oo; oo = oo->next)
3208                       if (strcmp (oo->name, "tag") == 0)
3209                         tag = oo->info;
3210                     if (tag == NULL || strcmp (tag, desc) != 0)
3211                       continue;
3212                     if (validf != NULL)
3213                       error_at_line (line,
3214                            "both `%s.%s.%s' and `%s.%s.%s' have tag `%s'",
3215                                      name, fld->name, validf->name,
3216                                      name, fld->name, ufld->name,
3217                                      tag);
3218                     validf = ufld;
3219                   }
3220                 if (validf != NULL)
3221                   {
3222                     char *newname;
3223                     newname = xasprintf ("%s.%s.%s",
3224                                          name, fld->name, validf->name);
3225                     write_root (f, v, validf->type, newname, 0, line,
3226                                 if_marked, emit_pch);
3227                     free (newname);
3228                   }
3229               }
3230             else if (desc)
3231               error_at_line (line,
3232                      "global `%s.%s' has `desc' option but is not union",
3233                              name, fld->name);
3234             else
3235               {
3236                 char *newname;
3237                 newname = xasprintf ("%s.%s", name, fld->name);
3238                 write_root (f, v, fld->type, newname, 0, line, if_marked,
3239                             emit_pch);
3240                 free (newname);
3241               }
3242           }
3243       }
3244       break;
3245
3246     case TYPE_ARRAY:
3247       {
3248         char *newname;
3249         newname = xasprintf ("%s[0]", name);
3250         write_root (f, v, type->u.a.p, newname, has_length, line, if_marked,
3251                     emit_pch);
3252         free (newname);
3253       }
3254       break;
3255
3256     case TYPE_POINTER:
3257       {
3258         type_p ap, tp;
3259
3260         oprintf (f, "  {\n");
3261         oprintf (f, "    &%s,\n", name);
3262         oprintf (f, "    1");
3263
3264         for (ap = v->type; ap->kind == TYPE_ARRAY; ap = ap->u.a.p)
3265           if (ap->u.a.len[0])
3266             oprintf (f, " * (%s)", ap->u.a.len);
3267           else if (ap == v->type)
3268             oprintf (f, " * ARRAY_SIZE (%s)", v->name);
3269         oprintf (f, ",\n");
3270         oprintf (f, "    sizeof (%s", v->name);
3271         for (ap = v->type; ap->kind == TYPE_ARRAY; ap = ap->u.a.p)
3272           oprintf (f, "[0]");
3273         oprintf (f, "),\n");
3274
3275         tp = type->u.p;
3276
3277         if (! has_length && UNION_OR_STRUCT_P (tp))
3278           {
3279             oprintf (f, "    &gt_ggc_mx_%s,\n", tp->u.s.tag);
3280             if (emit_pch)
3281               oprintf (f, "    &gt_pch_nx_%s", tp->u.s.tag);
3282             else
3283               oprintf (f, "    NULL");
3284           }
3285         else if (! has_length && tp->kind == TYPE_PARAM_STRUCT)
3286           {
3287             oprintf (f, "    &gt_ggc_m_");
3288             output_mangled_typename (f, tp);
3289             if (emit_pch)
3290               {
3291                 oprintf (f, ",\n    &gt_pch_n_");
3292                 output_mangled_typename (f, tp);
3293               }
3294             else
3295               oprintf (f, ",\n    NULL");
3296           }
3297         else if (has_length
3298                  && (tp->kind == TYPE_POINTER || UNION_OR_STRUCT_P (tp)))
3299           {
3300             oprintf (f, "    &gt_ggc_ma_%s,\n", name);
3301             if (emit_pch)
3302               oprintf (f, "    &gt_pch_na_%s", name);
3303             else
3304               oprintf (f, "    NULL");
3305           }
3306         else
3307           {
3308             error_at_line (line,
3309                            "global `%s' is pointer to unimplemented type",
3310                            name);
3311           }
3312         if (if_marked)
3313           oprintf (f, ",\n    &%s", if_marked);
3314         oprintf (f, "\n  },\n");
3315       }
3316       break;
3317
3318     case TYPE_STRING:
3319       {
3320         oprintf (f, "  {\n");
3321         oprintf (f, "    &%s,\n", name);
3322         oprintf (f, "    1, \n");
3323         oprintf (f, "    sizeof (%s),\n", v->name);
3324         oprintf (f, "    (gt_pointer_walker) &gt_ggc_m_S,\n");
3325         oprintf (f, "    (gt_pointer_walker) &gt_pch_n_S\n");
3326         oprintf (f, "  },\n");
3327       }
3328       break;
3329
3330     case TYPE_SCALAR:
3331       break;
3332
3333     default:
3334       error_at_line (line,
3335                      "global `%s' is unimplemented type",
3336                      name);
3337     }
3338 }
3339
3340 /* This generates a routine to walk an array.  */
3341
3342 static void
3343 write_array (outf_p f, pair_p v, const struct write_types_data *wtd)
3344 {
3345   struct walk_type_data d;
3346   char *prevval3;
3347
3348   memset (&d, 0, sizeof (d));
3349   d.of = f;
3350   d.cookie = wtd;
3351   d.indent = 2;
3352   d.line = &v->line;
3353   d.opt = v->opt;
3354   d.bitmap = get_lang_bitmap (v->line.file);
3355   d.param = NULL;
3356
3357   d.prev_val[3] = prevval3 = xasprintf ("&%s", v->name);
3358
3359   if (wtd->param_prefix)
3360     {
3361       oprintf (f, "static void gt_%sa_%s\n", wtd->param_prefix, v->name);
3362       oprintf (f,
3363        "    (void *, void *, gt_pointer_operator, void *);\n");
3364       oprintf (f, "static void gt_%sa_%s (ATTRIBUTE_UNUSED void *this_obj,\n",
3365                wtd->param_prefix, v->name);
3366       oprintf (d.of,
3367                "      ATTRIBUTE_UNUSED void *x_p,\n"
3368                "      ATTRIBUTE_UNUSED gt_pointer_operator op,\n"
3369                "      ATTRIBUTE_UNUSED void * cookie)\n");
3370       oprintf (d.of, "{\n");
3371       d.prev_val[0] = d.prev_val[1] = d.prev_val[2] = d.val = v->name;
3372       d.process_field = write_types_local_process_field;
3373       walk_type (v->type, &d);
3374       oprintf (f, "}\n\n");
3375     }
3376
3377   d.opt = v->opt;
3378   oprintf (f, "static void gt_%sa_%s (void *);\n",
3379            wtd->prefix, v->name);
3380   oprintf (f, "static void\ngt_%sa_%s (ATTRIBUTE_UNUSED void *x_p)\n",
3381            wtd->prefix, v->name);
3382   oprintf (f, "{\n");
3383   d.prev_val[0] = d.prev_val[1] = d.prev_val[2] = d.val = v->name;
3384   d.process_field = write_types_process_field;
3385   walk_type (v->type, &d);
3386   free (prevval3);
3387   oprintf (f, "}\n\n");
3388 }
3389
3390 /* Output a table describing the locations and types of VARIABLES.  */
3391
3392 static void
3393 write_roots (pair_p variables, bool emit_pch)
3394 {
3395   pair_p v;
3396   struct flist *flp = NULL;
3397
3398   for (v = variables; v; v = v->next)
3399     {
3400       outf_p f = get_output_file_with_visibility (v->line.file);
3401       struct flist *fli;
3402       const char *length = NULL;
3403       int deletable_p = 0;
3404       options_p o;
3405
3406       for (o = v->opt; o; o = o->next)
3407         if (strcmp (o->name, "length") == 0)
3408           length = o->info;
3409         else if (strcmp (o->name, "deletable") == 0)
3410           deletable_p = 1;
3411         else if (strcmp (o->name, "param_is") == 0)
3412           ;
3413         else if (strncmp (o->name, "param", 5) == 0
3414                  && ISDIGIT (o->name[5])
3415                  && strcmp (o->name + 6, "_is") == 0)
3416           ;
3417         else if (strcmp (o->name, "if_marked") == 0)
3418           ;
3419         else
3420           error_at_line (&v->line,
3421                          "global `%s' has unknown option `%s'",
3422                          v->name, o->name);
3423
3424       for (fli = flp; fli; fli = fli->next)
3425         if (fli->f == f && f)
3426           break;
3427       if (fli == NULL)
3428         {
3429           fli = XNEW (struct flist);
3430           fli->f = f;
3431           fli->next = flp;
3432           fli->started_p = 0;
3433           fli->name = v->line.file;
3434           gcc_assert(fli->name);
3435           flp = fli;
3436
3437           oprintf (f, "\n/* GC roots.  */\n\n");
3438         }
3439
3440       if (! deletable_p
3441           && length
3442           && v->type->kind == TYPE_POINTER
3443           && (v->type->u.p->kind == TYPE_POINTER
3444               || v->type->u.p->kind == TYPE_STRUCT))
3445         {
3446           write_array (f, v, &ggc_wtd);
3447           write_array (f, v, &pch_wtd);
3448         }
3449     }
3450
3451   for (v = variables; v; v = v->next)
3452     {
3453       outf_p f = get_output_file_with_visibility (v->line.file);
3454       struct flist *fli;
3455       int skip_p = 0;
3456       int length_p = 0;
3457       options_p o;
3458
3459       for (o = v->opt; o; o = o->next)
3460         if (strcmp (o->name, "length") == 0)
3461           length_p = 1;
3462         else if (strcmp (o->name, "deletable") == 0
3463                  || strcmp (o->name, "if_marked") == 0)
3464           skip_p = 1;
3465
3466       if (skip_p)
3467         continue;
3468
3469       for (fli = flp; fli; fli = fli->next)
3470         if (fli->f == f)
3471           break;
3472       if (! fli->started_p)
3473         {
3474           fli->started_p = 1;
3475
3476           oprintf (f, "EXPORTED_CONST struct ggc_root_tab gt_ggc_r_");
3477           put_mangled_filename (f, v->line.file);
3478           oprintf (f, "[] = {\n");
3479         }
3480
3481       write_root (f, v, v->type, v->name, length_p, &v->line, NULL, emit_pch);
3482     }
3483
3484   finish_root_table (flp, "ggc_r", "LAST_GGC_ROOT_TAB", "ggc_root_tab",
3485                      "gt_ggc_rtab");
3486
3487   for (v = variables; v; v = v->next)
3488     {
3489       outf_p f = get_output_file_with_visibility (v->line.file);
3490       struct flist *fli;
3491       int skip_p = 1;
3492       options_p o;
3493
3494       for (o = v->opt; o; o = o->next)
3495         if (strcmp (o->name, "deletable") == 0)
3496           skip_p = 0;
3497         else if (strcmp (o->name, "if_marked") == 0)
3498           skip_p = 1;
3499
3500       if (skip_p)
3501         continue;
3502
3503       for (fli = flp; fli; fli = fli->next)
3504         if (fli->f == f)
3505           break;
3506       if (! fli->started_p)
3507         {
3508           fli->started_p = 1;
3509
3510           oprintf (f, "EXPORTED_CONST struct ggc_root_tab gt_ggc_rd_");
3511           put_mangled_filename (f, v->line.file);
3512           oprintf (f, "[] = {\n");
3513         }
3514
3515       oprintf (f, "  { &%s, 1, sizeof (%s), NULL, NULL },\n",
3516                v->name, v->name);
3517     }
3518
3519   finish_root_table (flp, "ggc_rd", "LAST_GGC_ROOT_TAB", "ggc_root_tab",
3520                      "gt_ggc_deletable_rtab");
3521
3522   for (v = variables; v; v = v->next)
3523     {
3524       outf_p f = get_output_file_with_visibility (v->line.file);
3525       struct flist *fli;
3526       const char *if_marked = NULL;
3527       int length_p = 0;
3528       options_p o;
3529
3530       for (o = v->opt; o; o = o->next)
3531         if (strcmp (o->name, "length") == 0)
3532           length_p = 1;
3533         else if (strcmp (o->name, "if_marked") == 0)
3534           if_marked = o->info;
3535
3536       if (if_marked == NULL)
3537         continue;
3538
3539       if (v->type->kind != TYPE_POINTER
3540           || v->type->u.p->kind != TYPE_PARAM_STRUCT
3541           || v->type->u.p->u.param_struct.stru != find_structure ("htab", 0))
3542         {
3543           error_at_line (&v->line, "if_marked option used but not hash table");
3544           continue;
3545         }
3546
3547       for (fli = flp; fli; fli = fli->next)
3548         if (fli->f == f)
3549           break;
3550       if (! fli->started_p)
3551         {
3552           fli->started_p = 1;
3553
3554           oprintf (f, "EXPORTED_CONST struct ggc_cache_tab gt_ggc_rc_");
3555           put_mangled_filename (f, v->line.file);
3556           oprintf (f, "[] = {\n");
3557         }
3558
3559       write_root (f, v, v->type->u.p->u.param_struct.param[0],
3560                   v->name, length_p, &v->line, if_marked, emit_pch);
3561     }
3562
3563   finish_root_table (flp, "ggc_rc", "LAST_GGC_CACHE_TAB", "ggc_cache_tab",
3564                      "gt_ggc_cache_rtab");
3565
3566   if (!emit_pch)
3567     return;
3568
3569   for (v = variables; v; v = v->next)
3570     {
3571       outf_p f = get_output_file_with_visibility (v->line.file);
3572       struct flist *fli;
3573       int length_p = 0;
3574       int if_marked_p = 0;
3575       options_p o;
3576
3577       for (o = v->opt; o; o = o->next)
3578         if (strcmp (o->name, "length") == 0)
3579           length_p = 1;
3580         else if (strcmp (o->name, "if_marked") == 0)
3581           if_marked_p = 1;
3582
3583       if (! if_marked_p)
3584         continue;
3585
3586       for (fli = flp; fli; fli = fli->next)
3587         if (fli->f == f)
3588           break;
3589       if (! fli->started_p)
3590         {
3591           fli->started_p = 1;
3592
3593           oprintf (f, "EXPORTED_CONST struct ggc_root_tab gt_pch_rc_");
3594           put_mangled_filename (f, v->line.file);
3595           oprintf (f, "[] = {\n");
3596         }
3597
3598       write_root (f, v, v->type, v->name, length_p, &v->line, NULL, emit_pch);
3599     }
3600
3601   finish_root_table (flp, "pch_rc", "LAST_GGC_ROOT_TAB", "ggc_root_tab",
3602                      "gt_pch_cache_rtab");
3603
3604   for (v = variables; v; v = v->next)
3605     {
3606       outf_p f = get_output_file_with_visibility (v->line.file);
3607       struct flist *fli;
3608       int skip_p = 0;
3609       options_p o;
3610
3611       for (o = v->opt; o; o = o->next)
3612         if (strcmp (o->name, "deletable") == 0
3613             || strcmp (o->name, "if_marked") == 0)
3614           skip_p = 1;
3615
3616       if (skip_p)
3617         continue;
3618
3619       if (! contains_scalar_p (v->type))
3620         continue;
3621
3622       for (fli = flp; fli; fli = fli->next)
3623         if (fli->f == f)
3624           break;
3625       if (! fli->started_p)
3626         {
3627           fli->started_p = 1;
3628
3629           oprintf (f, "EXPORTED_CONST struct ggc_root_tab gt_pch_rs_");
3630           put_mangled_filename (f, v->line.file);
3631           oprintf (f, "[] = {\n");
3632         }
3633
3634       oprintf (f, "  { &%s, 1, sizeof (%s), NULL, NULL },\n",
3635                v->name, v->name);
3636     }
3637
3638   finish_root_table (flp, "pch_rs", "LAST_GGC_ROOT_TAB", "ggc_root_tab",
3639                      "gt_pch_scalar_rtab");
3640 }
3641
3642 /* Record the definition of a generic VEC structure, as if we had expanded
3643    the macros in vec.h:
3644
3645    typedef struct VEC_<type>_base GTY(()) {
3646    unsigned num;
3647    unsigned alloc;
3648    <type> GTY((length ("%h.num"))) vec[1];
3649    } VEC_<type>_base
3650
3651    where the GTY(()) tags are only present if is_scalar is _false_.  */
3652
3653 void
3654 note_def_vec (const char *type_name, bool is_scalar, struct fileloc *pos)
3655 {
3656   pair_p fields;
3657   type_p t;
3658   options_p o;
3659   type_p len_ty = create_scalar_type ("unsigned");
3660   const char *name = concat ("VEC_", type_name, "_base", (char *)0);
3661
3662   if (is_scalar)
3663     {
3664       t = create_scalar_type (type_name);
3665       o = 0;
3666     }
3667   else
3668     {
3669       t = resolve_typedef (type_name, pos);
3670       o = create_option (0, "length", "%h.num");
3671     }
3672
3673   /* We assemble the field list in reverse order.  */
3674   fields = create_field_at (0, create_array (t, "1"), "vec", o, pos);
3675   fields = create_field_at (fields, len_ty, "alloc", 0, pos);
3676   fields = create_field_at (fields, len_ty, "num", 0, pos);
3677
3678   do_typedef (name, new_structure (name, 0, pos, fields, 0), pos);
3679 }
3680
3681 /* Record the definition of an allocation-specific VEC structure, as if
3682    we had expanded the macros in vec.h:
3683
3684    typedef struct VEC_<type>_<astrat> {
3685      VEC_<type>_base base;
3686    } VEC_<type>_<astrat>;
3687 */
3688 void
3689 note_def_vec_alloc (const char *type, const char *astrat, struct fileloc *pos)
3690 {
3691   const char *astratname = concat ("VEC_", type, "_", astrat, (char *)0);
3692   const char *basename = concat ("VEC_", type, "_base", (char *)0);
3693
3694   pair_p field = create_field_at (0, resolve_typedef (basename, pos),
3695                                   "base", 0, pos);
3696
3697   do_typedef (astratname, new_structure (astratname, 0, pos, field, 0), pos);
3698 }
3699
3700 static void dump_pair (int indent, pair_p p);
3701 static void dump_type (int indent, type_p p);
3702 static void dump_type_list (int indent, type_p p);
3703
3704 #define INDENT 2
3705
3706 /* Dumps the value of typekind KIND.  */
3707
3708 static void
3709 dump_typekind (int indent, enum typekind kind)
3710 {
3711   printf ("%*ckind = ", indent, ' ');
3712   switch (kind)
3713     {
3714     case TYPE_SCALAR: printf ("TYPE_SCALAR"); break;
3715     case TYPE_STRING: printf ("TYPE_STRING"); break;
3716     case TYPE_STRUCT: printf ("TYPE_STRUCT"); break;
3717     case TYPE_UNION:  printf ("TYPE_UNION"); break;
3718     case TYPE_POINTER: printf ("TYPE_POINTER"); break;
3719     case TYPE_ARRAY: printf ("TYPE_ARRAY"); break;
3720     case TYPE_LANG_STRUCT: printf ("TYPE_LANG_STRUCT"); break;
3721     case TYPE_PARAM_STRUCT: printf ("TYPE_PARAM_STRUCT"); break;
3722     default: gcc_unreachable ();
3723     }
3724   printf ("\n");
3725 }
3726
3727 /* Dumps the value of GC_USED flag.  */
3728
3729 static void
3730 dump_gc_used (int indent, enum gc_used_enum gc_used)
3731 {
3732   printf ("%*cgc_used = ", indent, ' ');
3733   switch (gc_used)
3734     {
3735     case GC_UNUSED: printf ("GC_UNUSED"); break;
3736     case GC_USED: printf ("GC_USED"); break;
3737     case GC_MAYBE_POINTED_TO: printf ("GC_MAYBE_POINTED_TO"); break;
3738     case GC_POINTED_TO: printf ("GC_POINTED_TO"); break;
3739     default: gcc_unreachable ();
3740     }
3741   printf ("\n");
3742 }
3743
3744 /* Dumps the type options OPT.  */
3745
3746 static void
3747 dump_options (int indent, options_p opt)
3748 {
3749   options_p o;
3750   printf ("%*coptions = ", indent, ' ');
3751   o = opt;
3752   while (o)
3753     {
3754        printf ("%s:%s ", o->name, o->info);
3755        o = o->next;
3756     }
3757   printf ("\n");
3758 }
3759
3760 /* Dumps the source file location in LINE.  */
3761
3762 static void
3763 dump_fileloc (int indent, struct fileloc line)
3764 {
3765   printf ("%*cfileloc: file = %s, line = %d\n", indent, ' ', line.file,
3766           line.line);
3767 }
3768
3769 /* Recursively dumps the struct, union, or a language-specific
3770    struct T.  */
3771
3772 static void
3773 dump_type_u_s (int indent, type_p t)
3774 {
3775   pair_p fields;
3776
3777   gcc_assert (t->kind == TYPE_STRUCT || t->kind == TYPE_UNION
3778               || t->kind == TYPE_LANG_STRUCT);
3779   printf ("%*cu.s.tag = %s\n", indent, ' ', t->u.s.tag);
3780   dump_fileloc (indent, t->u.s.line);
3781   printf ("%*cu.s.fields =\n", indent, ' ');
3782   fields = t->u.s.fields;
3783   while (fields)
3784     {
3785        dump_pair (indent + INDENT, fields);
3786        fields = fields->next;
3787     }
3788   printf ("%*cend of fields of type %p\n", indent, ' ', (void *) t);
3789   dump_options (indent, t->u.s.opt);
3790   printf ("%*cu.s.bitmap = %X\n", indent, ' ', t->u.s.bitmap);
3791   if (t->kind == TYPE_LANG_STRUCT)
3792     {
3793       printf ("%*cu.s.lang_struct:\n", indent, ' ');
3794       dump_type_list (indent + INDENT, t->u.s.lang_struct);
3795     }
3796 }
3797
3798 /* Recursively dumps the array T.  */
3799
3800 static void
3801 dump_type_u_a (int indent, type_p t)
3802 {
3803   gcc_assert (t->kind == TYPE_ARRAY);
3804   printf ("%*clen = %s, u.a.p:\n", indent, ' ', t->u.a.len);
3805   dump_type_list (indent + INDENT, t->u.a.p);
3806 }
3807
3808 /* Recursively dumps the parameterized struct T.  */
3809
3810 static void
3811 dump_type_u_param_struct (int indent, type_p t)
3812 {
3813   int i;
3814   gcc_assert (t->kind == TYPE_PARAM_STRUCT);
3815   printf ("%*cu.param_struct.stru:\n", indent, ' ');
3816   dump_type_list (indent, t->u.param_struct.stru);
3817   dump_fileloc (indent, t->u.param_struct.line);
3818   for (i = 0; i < NUM_PARAM; i++)
3819     {
3820       if (t->u.param_struct.param[i] == NULL)
3821         continue;
3822       printf ("%*cu.param_struct.param[%d]:\n", indent, ' ', i);
3823       dump_type (indent + INDENT, t->u.param_struct.param[i]);
3824     }
3825 }
3826
3827 /* Recursively dumps the type list T.  */
3828
3829 static void
3830 dump_type_list (int indent, type_p t)
3831 {
3832   type_p p = t;
3833   while (p)
3834     {
3835       dump_type (indent, p);
3836       p = p->next;
3837     }
3838 }
3839
3840 static htab_t seen_types;
3841
3842 /* Recursively dumps the type T if it was not dumped previously.  */
3843
3844 static void
3845 dump_type (int indent, type_p t)
3846 {
3847   PTR *slot;
3848
3849   printf ("%*cType at %p: ", indent, ' ', (void *)t);
3850   slot = htab_find_slot (seen_types, t, INSERT);
3851   if (*slot != NULL)
3852     {
3853       printf ("already seen.\n");
3854       return;
3855     }
3856   *slot = t;
3857   printf ("\n");
3858
3859   dump_typekind (indent, t->kind);
3860   printf ("%*cpointer_to = %p\n", indent + INDENT, ' ',
3861           (void *)t->pointer_to);
3862   dump_gc_used (indent + INDENT, t->gc_used);
3863   switch (t->kind)
3864     {
3865     case TYPE_SCALAR:
3866       printf ("%*cscalar_is_char = %s\n", indent + INDENT, ' ',
3867               t->u.scalar_is_char ? "true" : "false");
3868       break;
3869     case TYPE_STRING:
3870       break;
3871     case TYPE_STRUCT:
3872     case TYPE_UNION:
3873     case TYPE_LANG_STRUCT:
3874       dump_type_u_s (indent + INDENT, t);
3875       break;
3876     case TYPE_POINTER:
3877       printf ("%*cp:\n", indent + INDENT, ' ');
3878       dump_type (indent + INDENT, t->u.p);
3879       break;
3880     case TYPE_ARRAY:
3881       dump_type_u_a (indent + INDENT, t);
3882       break;
3883     case TYPE_PARAM_STRUCT:
3884       dump_type_u_param_struct (indent + INDENT, t);
3885       break;
3886     default:
3887       gcc_unreachable ();
3888     }
3889   printf ("%*cEnd of type at %p\n", indent, ' ', (void *)t);
3890 }
3891
3892 /* Dumps the pair P.  */
3893
3894 static void
3895 dump_pair (int indent, pair_p p)
3896 {
3897   printf ("%*cpair: name = %s\n", indent, ' ', p->name);
3898   dump_type (indent, p->type);
3899   dump_fileloc (indent, p->line);
3900   dump_options (indent, p->opt);
3901   printf ("%*cEnd of pair %s\n", indent, ' ', p->name);
3902 }
3903
3904 /* Dumps the list of pairs PP.  */
3905
3906 static void
3907 dump_pair_list (const char * name, pair_p pp)
3908 {
3909   pair_p p;
3910   printf ("%s:\n", name);
3911   for (p = pp; p != NULL; p = p->next)
3912     dump_pair (0, p);
3913   printf ("End of %s\n\n", name);
3914 }
3915
3916 /* Dumps the STRUCTURES.  */
3917
3918 static void
3919 dump_structures (const char * name, type_p structures)
3920 {
3921   printf ("%s:\n", name);
3922   dump_type_list (0, structures);
3923   printf ("End of %s\n\n", name);
3924 }
3925
3926 /* Dumps the internal structures of gengtype.  */
3927
3928 static void
3929 dump_everything (void)
3930 {
3931   seen_types = htab_create (100, htab_hash_pointer, htab_eq_pointer, NULL);
3932   dump_pair_list ("typedefs", typedefs);
3933   dump_structures ("structures", structures);
3934   dump_structures ("param_structs", param_structs);
3935   dump_pair_list ("variables", variables);
3936   htab_delete (seen_types);
3937 }
3938
3939 \f
3940 int
3941 main (int argc, char **argv)
3942 {
3943   size_t i;
3944   static struct fileloc pos = { this_file, 0 };
3945   char* inputlist = 0;
3946   int do_dump = 0;
3947   outf_p output_header;
3948   char* plugin_output_filename = NULL;
3949   /* fatal uses this */
3950   progname = "gengtype";
3951
3952   if (argc >= 2 && !strcmp (argv[1], "-d"))
3953     {
3954       do_dump = 1;
3955       argv = &argv[1];
3956       argc--;
3957     }
3958
3959   if (argc >= 6 && !strcmp (argv[1], "-P"))
3960     {
3961       plugin_output_filename = argv[2];
3962       plugin_output = create_file ("GCC", plugin_output_filename);
3963       srcdir = argv[3];
3964       inputlist = argv[4];
3965       nb_plugin_files = argc - 5;
3966       plugin_files = XCNEWVEC (char *, nb_plugin_files);
3967       for (i = 0; i < nb_plugin_files; i++)
3968       {
3969         /* Place an all zero lang_bitmap before the plugin file
3970            name.  */
3971         char *name = argv[i + 5];
3972         int len = strlen(name) + 1 + sizeof (lang_bitmap);
3973         plugin_files[i] = XCNEWVEC (char, len) + sizeof (lang_bitmap);
3974         strcpy (plugin_files[i], name);
3975       }
3976     }
3977   else if (argc == 3)
3978     {
3979       srcdir = argv[1];
3980       inputlist = argv[2];
3981     }
3982   else
3983     fatal ("usage: gengtype [-d] [-P pluginout.h] srcdir input-list "
3984            "[file1 file2 ... fileN]");
3985
3986   srcdir_len = strlen (srcdir);
3987
3988   read_input_list (inputlist);
3989   if (hit_error)
3990     return 1;
3991
3992   scalar_char.u.scalar_is_char = true;
3993   scalar_nonchar.u.scalar_is_char = false;
3994   gen_rtx_next ();
3995
3996   /* These types are set up with #define or else outside of where
3997      we can see them.  */
3998   pos.line = __LINE__ + 1;
3999   do_scalar_typedef ("CUMULATIVE_ARGS", &pos); pos.line++;
4000   do_scalar_typedef ("REAL_VALUE_TYPE", &pos); pos.line++;
4001   do_scalar_typedef ("FIXED_VALUE_TYPE", &pos); pos.line++;
4002   do_scalar_typedef ("double_int", &pos); pos.line++;
4003   do_scalar_typedef ("uint64_t", &pos); pos.line++;
4004   do_scalar_typedef ("uint8", &pos); pos.line++;
4005   do_scalar_typedef ("jword", &pos); pos.line++;
4006   do_scalar_typedef ("JCF_u2", &pos); pos.line++;
4007   do_scalar_typedef ("void", &pos); pos.line++;
4008   do_typedef ("PTR", create_pointer (resolve_typedef ("void", &pos)), &pos);
4009
4010   for (i = 0; i < num_gt_files; i++)
4011     parse_file (gt_files[i]);
4012
4013   if (hit_error)
4014     return 1;
4015
4016   set_gc_used (variables);
4017
4018   open_base_files ();
4019   write_enum_defn (structures, param_structs);
4020   output_header = plugin_output ? plugin_output : header_file;
4021   write_types (output_header, structures, param_structs, &ggc_wtd);
4022   if (plugin_files == NULL)
4023     {
4024       write_types (header_file, structures, param_structs, &pch_wtd);
4025       write_local (header_file, structures, param_structs);
4026     }
4027   write_roots (variables, plugin_files == NULL);
4028   write_rtx_next ();
4029   close_output_files ();
4030
4031   if (do_dump)
4032     dump_everything ();
4033
4034   if (plugin_files)
4035   {
4036     for (i = 0; i < nb_plugin_files; i++)
4037       free (plugin_files[i] - sizeof (lang_bitmap));
4038     free (plugin_files);
4039   }
4040
4041   if (hit_error)
4042     return 1;
4043   return 0;
4044 }