cleanup reading/writing of long/int/unsigned values
[libfirm] / ir / ir / irio.c
1 /*
2  * Copyright (C) 1995-2009 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief   Write textual representation of firm to file.
23  * @author  Moritz Kroll
24  * @version $Id$
25  */
26 #include "config.h"
27
28 #include <string.h>
29 #include <ctype.h>
30 #include <stdbool.h>
31 #include <stdarg.h>
32
33 #include "irio.h"
34
35 #include "irnode_t.h"
36 #include "irprog.h"
37 #include "irgraph_t.h"
38 #include "ircons.h"
39 #include "irgmod.h"
40 #include "irflag_t.h"
41 #include "irgwalk.h"
42 #include "tv.h"
43 #include "array.h"
44 #include "error.h"
45 #include "typerep.h"
46 #include "adt/set.h"
47 #include "adt/obst.h"
48
49 #define SYMERROR ((unsigned) ~0)
50
51 typedef struct io_env_t
52 {
53         int c;                /**< currently read char */
54         FILE *file;
55         set *idset;           /**< id_entry set, which maps from file ids to new Firm elements */
56         int ignoreblocks;
57         const char *inputname;
58         int line;
59         ir_type **fixedtypes;
60         struct obstack obst;
61         ir_graph *irg;
62 } io_env_t;
63
64 typedef enum typetag_t
65 {
66         tt_align,
67         tt_allocation,
68         tt_builtin,
69         tt_cond_jmp_predicate,
70         tt_initializer,
71         tt_iro,
72         tt_keyword,
73         tt_mode_sort,
74         tt_mode_arithmetic,
75         tt_pin_state,
76         tt_tpo,
77         tt_type_state,
78         tt_volatility,
79         tt_linkage,
80         tt_segment,
81         tt_visibility
82 } typetag_t;
83
84 typedef enum keyword_t
85 {
86         kw_constirg,
87         kw_entity,
88         kw_irg,
89         kw_mode,
90         kw_modes,
91         kw_type,
92         kw_typegraph,
93         kw_program,
94         kw_segment_type
95 } keyword_t;
96
97 typedef struct symbol_t
98 {
99         const char *str;      /**< The name of this symbol. */
100         typetag_t   typetag;  /**< The type tag of this symbol. */
101         unsigned    code;     /**< The value of this symbol. */
102 } symbol_t;
103
104 typedef struct id_entry
105 {
106         long id;
107         void *elem;
108 } id_entry;
109
110 /** The symbol table, a set of symbol_t elements. */
111 static set *symtbl;
112
113 /**
114  * Compare two symbol table entries.
115  */
116 static int symbol_cmp(const void *elt, const void *key, size_t size)
117 {
118         int res;
119         const symbol_t *entry = (const symbol_t *) elt;
120         const symbol_t *keyentry = (const symbol_t *) key;
121         (void) size;
122         res = entry->typetag - keyentry->typetag;
123         if (res) return res;
124         return strcmp(entry->str, keyentry->str);
125 }
126
127 static int id_cmp(const void *elt, const void *key, size_t size)
128 {
129         const id_entry *entry = (const id_entry *) elt;
130         const id_entry *keyentry = (const id_entry *) key;
131         (void) size;
132         return entry->id - keyentry->id;
133 }
134
135 static void __attribute__((format(printf, 2, 3)))
136 parse_error(io_env_t *env, const char *fmt, ...)
137 {
138         va_list ap;
139         int     line = env->line;
140
141         /* workaround read_c "feature" that a '\n' triggers the line++
142          * instead of the character after the '\n' */
143         if (env->c == '\n') {
144                 line--;
145         }
146
147         fprintf(stderr, "%s:%d: error ", env->inputname, line);
148
149         va_start(ap, fmt);
150         vfprintf(stderr, fmt, ap);
151         va_end(ap);
152 }
153
154 /** Initializes the symbol table. May be called more than once without problems. */
155 static void symtbl_init(void)
156 {
157         symbol_t key;
158
159         /* Only initialize once */
160         if (symtbl != NULL)
161                 return;
162
163         symtbl = new_set(symbol_cmp, 256);
164
165 #define INSERT(tt, s, cod)                                       \
166         key.str = (s);                                               \
167         key.typetag = (tt);                                          \
168         key.code = (cod);                                            \
169         set_insert(symtbl, &key, sizeof(key), firm_fnv_hash_str(s) + tt * 17)
170
171 #define INSERTENUM(tt, e) INSERT(tt, #e, e)
172 #define INSERTKEYWORD(k) INSERT(tt_keyword, #k, kw_##k)
173
174         INSERT(tt_tpo, "array", tpo_array);
175         INSERT(tt_tpo, "class", tpo_class);
176         INSERT(tt_tpo, "method", tpo_method);
177         INSERT(tt_tpo, "pointer", tpo_pointer);
178         INSERT(tt_tpo, "primitive", tpo_primitive);
179         INSERT(tt_tpo, "struct", tpo_struct);
180         INSERT(tt_tpo, "union", tpo_union);
181         INSERT(tt_tpo, "Unknown", tpo_unknown);
182
183         INSERT(tt_mode_sort, "auxiliary", irms_auxiliary);
184         INSERT(tt_mode_sort, "control_flow", irms_control_flow);
185         INSERT(tt_mode_sort, "memory", irms_memory);
186         INSERT(tt_mode_sort, "internal_boolean", irms_internal_boolean);
187         INSERT(tt_mode_sort, "reference", irms_reference);
188         INSERT(tt_mode_sort, "int_number", irms_int_number);
189         INSERT(tt_mode_sort, "float_number", irms_float_number);
190
191         INSERT(tt_segment, "global", IR_SEGMENT_GLOBAL);
192         INSERT(tt_segment, "thread_local", IR_SEGMENT_THREAD_LOCAL);
193         INSERT(tt_segment, "constructors", IR_SEGMENT_CONSTRUCTORS);
194         INSERT(tt_segment, "destructors", IR_SEGMENT_DESTRUCTORS);
195
196         INSERT(tt_linkage, "constant", IR_LINKAGE_CONSTANT);
197         INSERT(tt_linkage, "weak", IR_LINKAGE_WEAK);
198         INSERT(tt_linkage, "garbage_collect", IR_LINKAGE_GARBAGE_COLLECT);
199         INSERT(tt_linkage, "merge", IR_LINKAGE_MERGE);
200         INSERT(tt_linkage, "hidden_user", IR_LINKAGE_HIDDEN_USER);
201
202         INSERT(tt_visibility, "local", ir_visibility_local);
203         INSERT(tt_visibility, "external", ir_visibility_external);
204         INSERT(tt_visibility, "default", ir_visibility_default);
205         INSERT(tt_visibility, "private", ir_visibility_private);
206
207         INSERTKEYWORD(constirg);
208         INSERTKEYWORD(entity);
209         INSERTKEYWORD(irg);
210         INSERTKEYWORD(mode);
211         INSERTKEYWORD(modes);
212         INSERTKEYWORD(type);
213         INSERTKEYWORD(typegraph);
214         INSERTKEYWORD(program);
215         INSERTKEYWORD(segment_type);
216
217 #include "gen_irio_lex.inl"
218
219         INSERTENUM(tt_align, align_non_aligned);
220         INSERTENUM(tt_align, align_is_aligned);
221
222         INSERTENUM(tt_builtin, ir_bk_trap);
223         INSERTENUM(tt_builtin, ir_bk_debugbreak);
224         INSERTENUM(tt_builtin, ir_bk_return_address);
225         INSERTENUM(tt_builtin, ir_bk_frame_address);
226         INSERTENUM(tt_builtin, ir_bk_prefetch);
227         INSERTENUM(tt_builtin, ir_bk_ffs);
228         INSERTENUM(tt_builtin, ir_bk_clz);
229         INSERTENUM(tt_builtin, ir_bk_ctz);
230         INSERTENUM(tt_builtin, ir_bk_popcount);
231         INSERTENUM(tt_builtin, ir_bk_parity);
232         INSERTENUM(tt_builtin, ir_bk_bswap);
233         INSERTENUM(tt_builtin, ir_bk_inport);
234         INSERTENUM(tt_builtin, ir_bk_outport);
235         INSERTENUM(tt_builtin, ir_bk_inner_trampoline);
236
237         INSERTENUM(tt_cond_jmp_predicate, COND_JMP_PRED_NONE);
238         INSERTENUM(tt_cond_jmp_predicate, COND_JMP_PRED_TRUE);
239         INSERTENUM(tt_cond_jmp_predicate, COND_JMP_PRED_FALSE);
240
241         INSERTENUM(tt_initializer, IR_INITIALIZER_CONST);
242         INSERTENUM(tt_initializer, IR_INITIALIZER_TARVAL);
243         INSERTENUM(tt_initializer, IR_INITIALIZER_NULL);
244         INSERTENUM(tt_initializer, IR_INITIALIZER_COMPOUND);
245
246         INSERTENUM(tt_mode_arithmetic, irma_uninitialized);
247         INSERTENUM(tt_mode_arithmetic, irma_none);
248         INSERTENUM(tt_mode_arithmetic, irma_twos_complement);
249         INSERTENUM(tt_mode_arithmetic, irma_ones_complement);
250         INSERTENUM(tt_mode_arithmetic, irma_int_BCD);
251         INSERTENUM(tt_mode_arithmetic, irma_ieee754);
252         INSERTENUM(tt_mode_arithmetic, irma_float_BCD);
253
254         INSERTENUM(tt_pin_state, op_pin_state_floats);
255         INSERTENUM(tt_pin_state, op_pin_state_pinned);
256         INSERTENUM(tt_pin_state, op_pin_state_exc_pinned);
257         INSERTENUM(tt_pin_state, op_pin_state_mem_pinned);
258
259         INSERTENUM(tt_type_state, layout_undefined);
260         INSERTENUM(tt_type_state, layout_fixed);
261
262         INSERTENUM(tt_volatility, volatility_non_volatile);
263         INSERTENUM(tt_volatility, volatility_is_volatile);
264
265 #undef INSERTKEYWORD
266 #undef INSERTENUM
267 #undef INSERT
268 }
269
270 static const char *get_segment_name(ir_segment_t segment)
271 {
272         switch (segment) {
273         case IR_SEGMENT_GLOBAL:       return "global";
274         case IR_SEGMENT_THREAD_LOCAL: return "thread_local";
275         case IR_SEGMENT_CONSTRUCTORS: return "constructors";
276         case IR_SEGMENT_DESTRUCTORS:  return "destructors";
277         }
278         return "INVALID_SEGMENT";
279 }
280
281 static const char *get_visibility_name(ir_visibility visibility)
282 {
283         switch (visibility) {
284         case ir_visibility_local:    return "local";
285         case ir_visibility_external: return "external";
286         case ir_visibility_default:  return "default";
287         case ir_visibility_private:  return "private";
288         }
289         return "INVALID_VISIBILITY";
290 }
291
292 /** Returns the according symbol value for the given string and tag, or SYMERROR if none was found. */
293 static unsigned symbol(const char *str, typetag_t typetag)
294 {
295         symbol_t key, *entry;
296
297         key.str = str;
298         key.typetag = typetag;
299
300         entry = (symbol_t*)set_find(symtbl, &key, sizeof(key), firm_fnv_hash_str(str) + typetag * 17);
301         return entry ? entry->code : SYMERROR;
302 }
303
304 static void *get_id(io_env_t *env, long id)
305 {
306         id_entry key, *entry;
307         key.id = id;
308
309         entry = (id_entry*)set_find(env->idset, &key, sizeof(key), (unsigned) id);
310         return entry ? entry->elem : NULL;
311 }
312
313 static void set_id(io_env_t *env, long id, void *elem)
314 {
315         id_entry key;
316         key.id = id;
317         key.elem = elem;
318         set_insert(env->idset, &key, sizeof(key), (unsigned) id);
319 }
320
321 static void write_long(io_env_t *env, long value)
322 {
323         fprintf(env->file, "%ld ", value);
324 }
325
326 static void write_int(io_env_t *env, int value)
327 {
328         fprintf(env->file, "%d ", value);
329 }
330
331 static void write_unsigned(io_env_t *env, unsigned value)
332 {
333         fprintf(env->file, "%u ", value);
334 }
335
336 static void write_entity_ref(io_env_t *env, ir_entity *entity)
337 {
338         write_long(env, get_entity_nr(entity));
339 }
340
341 static void write_type_ref(io_env_t *env, ir_type *type)
342 {
343         write_long(env, get_type_nr(type));
344 }
345
346 static void write_mode(io_env_t *env, ir_mode *mode)
347 {
348         fputs(get_mode_name(mode), env->file);
349         fputc(' ', env->file);
350 }
351
352 static void write_tarval(io_env_t *env, ir_tarval *tv)
353 {
354         char buf[1024];
355         write_mode(env, get_tarval_mode(tv));
356         tarval_snprintf(buf, sizeof(buf), tv);
357         fputs(buf, env->file);
358         fputc(' ', env->file);
359 }
360
361 static void write_align(io_env_t *env, ir_node *irn)
362 {
363         ir_align align;
364
365         if (is_Load(irn))
366                 align = get_Load_align(irn);
367         else if (is_Store(irn))
368                 align = get_Store_align(irn);
369         else
370                 panic("Invalid optype for write_align");
371
372         fputs(get_align_name(align), env->file);
373         fputc(' ', env->file);
374 }
375
376 static void write_builtin_kind(io_env_t *env, ir_node *irn)
377 {
378         fputs(get_builtin_kind_name(get_Builtin_kind(irn)), env->file);
379         fputc(' ', env->file);
380 }
381
382 static void write_cond_jmp_predicate(io_env_t *env, ir_node *irn)
383 {
384         fputs(get_cond_jmp_predicate_name(get_Cond_jmp_pred(irn)), env->file);
385         fputc(' ', env->file);
386 }
387
388 static void write_initializer(io_env_t *env, ir_initializer_t *ini)
389 {
390         FILE *f = env->file;
391         ir_initializer_kind_t ini_kind = get_initializer_kind(ini);
392
393         fputs(get_initializer_kind_name(ini_kind), f);
394         fputc(' ', f);
395
396         switch (ini_kind) {
397         case IR_INITIALIZER_CONST:
398                 write_long(env, get_irn_node_nr(get_initializer_const_value(ini)));
399                 break;
400
401         case IR_INITIALIZER_TARVAL:
402                 write_tarval(env, get_initializer_tarval_value(ini));
403                 break;
404
405         case IR_INITIALIZER_NULL:
406                 break;
407
408         case IR_INITIALIZER_COMPOUND: {
409                 unsigned i, n = get_initializer_compound_n_entries(ini);
410                 fprintf(f, "%u ", n);
411                 for (i = 0; i < n; i++)
412                         write_initializer(env, get_initializer_compound_value(ini, i));
413                 break;
414         }
415
416         default:
417                 panic("Unknown initializer kind");
418         }
419 }
420
421 static void write_pin_state(io_env_t *env, ir_node *irn)
422 {
423         fputs(get_op_pin_state_name(get_irn_pinned(irn)), env->file);
424         fputc(' ', env->file);
425 }
426
427 static void write_volatility(io_env_t *env, ir_node *irn)
428 {
429         ir_volatility vol;
430
431         if (is_Load(irn))
432                 vol = get_Load_volatility(irn);
433         else if (is_Store(irn))
434                 vol = get_Store_volatility(irn);
435         else
436                 panic("Invalid optype for write_volatility");
437
438         fputs(get_volatility_name(vol), env->file);
439         fputc(' ', env->file);
440 }
441
442 static void export_type_common(io_env_t *env, ir_type *tp)
443 {
444         fprintf(env->file, "\ttype %ld %s %u %u %s %u ",
445                 get_type_nr(tp),
446                 get_type_tpop_name(tp),
447                 get_type_size_bytes(tp),
448                 get_type_alignment_bytes(tp),
449                 get_type_state_name(get_type_state(tp)),
450                 tp->flags);
451 }
452
453 static void export_compound_name(FILE *f, const ir_type *tp)
454 {
455         ident *name = get_compound_ident(tp);
456         if (name == NULL) {
457                 fputs("NULL ", f);
458         } else {
459                 fprintf(f, "\"%s\" ", get_id_str(name));
460         }
461 }
462
463 static void export_type_pre(io_env_t *env, ir_type *tp)
464 {
465         FILE *f = env->file;
466
467         /* skip types to be handled by post walker */
468         switch (get_type_tpop_code(tp)) {
469         case tpo_array:
470         case tpo_method:
471         case tpo_pointer:
472                 return;
473         default:
474                 break;
475         }
476
477         export_type_common(env, tp);
478
479         switch (get_type_tpop_code(tp)) {
480         case tpo_uninitialized:
481                 panic("invalid type found");
482
483         case tpo_class:
484                 export_compound_name(f, tp);
485                 break;
486
487         case tpo_primitive:
488                 write_mode(env, get_type_mode(tp));
489                 break;
490
491         case tpo_union:
492         case tpo_struct:
493         case tpo_enumeration:
494                 export_compound_name(f, tp);
495                 break;
496
497         case tpo_array:
498         case tpo_method:
499         case tpo_pointer:
500         case tpo_code:
501         case tpo_none:
502         case tpo_unknown:
503                 break;
504         }
505         fputc('\n', f);
506 }
507
508 static void export_type_post(io_env_t *env, ir_type *tp)
509 {
510         FILE *f = env->file;
511         int i;
512
513         /* skip types already handled by pre walker */
514         switch (get_type_tpop_code(tp)) {
515         case tpo_class:
516         case tpo_primitive:
517         case tpo_struct:
518         case tpo_union:
519         case tpo_unknown:
520         case tpo_uninitialized:
521         case tpo_code:
522         case tpo_none:
523                 return;
524         case tpo_array:
525         case tpo_method:
526         case tpo_pointer:
527         case tpo_enumeration:
528                 break;
529         }
530
531         export_type_common(env, tp);
532
533         switch (get_type_tpop_code(tp)) {
534         case tpo_array: {
535                 int n = get_array_n_dimensions(tp);
536                 fprintf(f, "%d %ld ", n, get_type_nr(get_array_element_type(tp)));
537                 for (i = 0; i < n; i++) {
538                         ir_node *lower = get_array_lower_bound(tp, i);
539                         ir_node *upper = get_array_upper_bound(tp, i);
540
541                         if (is_Const(lower))
542                                 write_long(env, get_tarval_long(get_Const_tarval(lower)));
543                         else
544                                 panic("Lower array bound is not constant");
545
546                         if (is_Const(upper))
547                                 write_long(env, get_tarval_long(get_Const_tarval(upper)));
548                         else if (is_Unknown(upper))
549                                 fputs("unknown ", f);
550                         else
551                                 panic("Upper array bound is not constant");
552                 }
553                 break;
554         }
555
556         case tpo_method: {
557                 int nparams  = get_method_n_params(tp);
558                 int nresults = get_method_n_ress(tp);
559                 fprintf(f, "%u %u %d %d ", get_method_calling_convention(tp),
560                         get_method_additional_properties(tp), nparams, nresults);
561                 for (i = 0; i < nparams; i++)
562                         write_long(env, get_type_nr(get_method_param_type(tp, i)));
563                 for (i = 0; i < nresults; i++)
564                         write_long(env, get_type_nr(get_method_res_type(tp, i)));
565                 fprintf(f, "%d ", get_method_first_variadic_param_index(tp));
566                 break;
567         }
568
569         case tpo_pointer:
570                 write_mode(env, get_type_mode(tp));
571                 write_long(env, get_type_nr(get_pointer_points_to_type(tp)));
572                 break;
573
574         case tpo_enumeration:
575                 fprintf(stderr, "Enumeration type not handled yet by exporter\n");
576                 break;
577
578         default:
579                 printf("export_type: Unknown type code \"%s\".\n",
580                        get_type_tpop_name(tp));
581                 break;
582         }
583         fputc('\n', f);
584 }
585
586 static void export_entity(io_env_t *env, ir_entity *ent)
587 {
588         FILE          *file       = env->file;
589         ir_type       *owner      = get_entity_owner(ent);
590         ir_visibility  visibility = get_entity_visibility(ent);
591         ir_linkage     linkage    = get_entity_linkage(ent);
592
593         /* we don't dump array_element_ent entities. They're a strange concept
594          * and lead to cycles in type_graph.
595          */
596         if (is_Array_type(owner))
597                 return;
598
599         fprintf(env->file, "\tentity %ld \"%s\" ",
600                 get_entity_nr(ent), get_entity_name(ent));
601         if (ent->ld_name != NULL) {
602                 fprintf(env->file, "\"%s\" ", get_entity_ld_name(ent));
603         } else {
604                 fprintf(env->file, "NULL ");
605         }
606
607         /* visibility + linkage */
608         if (visibility != ir_visibility_default) {
609                 fprintf(file, "%s ", get_visibility_name(visibility));
610         }
611         if (linkage & IR_LINKAGE_CONSTANT)
612                 fputs("constant ", file);
613         if (linkage & IR_LINKAGE_WEAK)
614                 fputs("weak ", file);
615         if (linkage & IR_LINKAGE_GARBAGE_COLLECT)
616                 fputs("garbage_collect ", file);
617         if (linkage & IR_LINKAGE_MERGE)
618                 fputs("merge ", file);
619         if (linkage & IR_LINKAGE_HIDDEN_USER)
620                 fputs("hidden_user ", file);
621
622         fprintf(file, "%ld %ld %d %u %d %s ",
623                         get_type_nr(get_entity_type(ent)),
624                         get_type_nr(owner),
625                         get_entity_offset(ent),
626                         (unsigned) get_entity_offset_bits_remainder(ent),
627                         is_entity_compiler_generated(ent),
628                         get_volatility_name(get_entity_volatility(ent)));
629
630         if (ent->initializer != NULL) {
631                 fputs("initializer ", env->file);
632                 write_initializer(env, get_entity_initializer(ent));
633         } else if (entity_has_compound_ent_values(ent)) {
634                 int i, n = get_compound_ent_n_values(ent);
635                 fputs("compoundgraph ", env->file);
636                 fprintf(env->file, "%d ", n);
637                 for (i = 0; i < n; i++) {
638                         ir_entity *member = get_compound_ent_value_member(ent, i);
639                         ir_node   *irn    = get_compound_ent_value(ent, i);
640                         fprintf(env->file, "%ld %ld ", get_entity_nr(member), get_irn_node_nr(irn));
641                 }
642         } else {
643                 fputs("none", env->file);
644         }
645
646         fputc('\n', env->file);
647 }
648
649 static void export_type_or_ent_pre(type_or_ent tore, void *ctx)
650 {
651         io_env_t *env = (io_env_t *) ctx;
652         if (get_kind(tore.typ) == k_type)
653                 export_type_pre(env, tore.typ);
654 }
655
656 static void export_type_or_ent_post(type_or_ent tore, void *ctx)
657 {
658         io_env_t *env = (io_env_t *) ctx;
659
660         switch (get_kind(tore.ent)) {
661         case k_entity:
662                 export_entity(env, tore.ent);
663                 break;
664
665         case k_type:
666                 export_type_post(env, tore.typ);
667                 break;
668
669         default:
670                 panic("export_type_or_ent_post: Unknown type or entity.");
671                 break;
672         }
673 }
674
675 /**
676  * Walker: exports every node.
677  */
678 static void export_node(ir_node *irn, void *ctx)
679 {
680         io_env_t *env = (io_env_t *) ctx;
681         int i, n;
682         unsigned opcode = get_irn_opcode(irn);
683
684         if (env->ignoreblocks && opcode == iro_Block)
685                 return;
686
687         fprintf(env->file, "\t%s %ld [ ", get_irn_opname(irn), get_irn_node_nr(irn));
688
689         n = get_irn_arity(irn);
690         if (!is_Block(irn)) {
691                 fprintf(env->file, "%ld ", get_irn_node_nr(get_nodes_block(irn)));
692         }
693
694         for (i = 0; i < n; i++) {
695                 ir_node *pred = get_irn_n(irn, i);
696                 if (pred == NULL) {
697                         /* Anchor node may have NULL predecessors */
698                         assert(is_Anchor(irn));
699                         fputs("-1 ", env->file);
700                 } else {
701                         write_long(env, get_irn_node_nr(pred));
702                 }
703         }
704
705         fprintf(env->file, "] { ");
706
707         switch (opcode) {
708         case iro_Start:
709         case iro_End:
710         case iro_Block:
711         case iro_Anchor:
712                 break;
713         case iro_SymConst:
714                 /* TODO: only symconst_addr_ent implemented yet */
715                 assert(get_SymConst_kind(irn) == symconst_addr_ent);
716                 fprintf(env->file, "%ld ", get_entity_nr(get_SymConst_entity(irn)));
717                 break;
718         case iro_Proj:
719                 write_mode(env, get_irn_mode(irn));
720                 fprintf(env->file, "%ld ", get_Proj_proj(irn));
721                 break;
722 #include "gen_irio_export.inl"
723         default:
724                 panic("no export code for node %+F\n", irn);
725         }
726         fputs("}\n", env->file);
727 }
728
729 static const char *get_mode_sort_name(ir_mode_sort sort)
730 {
731         switch (sort) {
732         case irms_auxiliary:        return "auxiliary";
733         case irms_control_flow:     return "control_flow";
734         case irms_memory:           return "memory";
735         case irms_internal_boolean: return "internal_boolean";
736         case irms_reference:        return "reference";
737         case irms_int_number:       return "int_number";
738         case irms_float_number:     return "float_number";
739         }
740         panic("invalid mode sort found");
741 }
742
743 static void export_modes(io_env_t *env)
744 {
745         int i, n_modes = get_irp_n_modes();
746
747         fputs("modes {\n", env->file);
748
749         for (i = 0; i < n_modes; i++) {
750                 ir_mode *mode = get_irp_mode(i);
751                 switch (get_mode_sort(mode)) {
752                 case irms_auxiliary:
753                 case irms_control_flow:
754                 case irms_memory:
755                 case irms_internal_boolean:
756                         /* skip "internal" modes, which may not be user defined */
757                         continue;
758                 default:
759                         break;
760                 }
761
762                 fprintf(env->file, "\tmode \"%s\" %s %u %d %s %u %u ",
763                         get_mode_name(mode), get_mode_sort_name(get_mode_sort(mode)),
764                         get_mode_size_bits(mode), get_mode_sign(mode),
765                         get_mode_arithmetic_name(get_mode_arithmetic(mode)),
766                         get_mode_modulo_shift(mode),
767                         get_mode_n_vector_elems(mode));
768                 if (mode_is_reference(mode)) {
769                         write_mode(env, get_reference_mode_signed_eq(mode));
770                         write_mode(env, get_reference_mode_unsigned_eq(mode));
771                 }
772                 fputc('\n', env->file);
773         }
774
775         fputs("}\n", env->file);
776 }
777
778 static void export_program(io_env_t *env)
779 {
780         FILE         *f = env->file;
781         ir_segment_t  s;
782
783         fputs("\nprogram {\n", f);
784         if (irp_prog_name_is_set()) {
785                 fprintf(f, "\tname \"%s\"\n", get_irp_name());
786         }
787         /* We need numbers for irgs... */
788 #if 0
789         if (get_irp_main_irg() != NULL) {
790                 fprintf(f, "\tmain_irg %d\n", get_irp_main_irg
791 #endif
792
793         for (s = IR_SEGMENT_FIRST; s <= IR_SEGMENT_LAST; ++s) {
794                 ir_type *segment_type = get_segment_type(s);
795                 fprintf(f, "\tsegment_type %s", get_segment_name(s));
796                 if (segment_type == NULL) {
797                         fputs(" NULL\n", f);
798                 } else {
799                         fprintf(f, " %ld\n", get_type_nr(segment_type));
800                 }
801         }
802         fputs("}\n", f);
803 }
804
805 void ir_export(const char *filename)
806 {
807         FILE *file = fopen(filename, "wt");
808         if (file == NULL) {
809                 perror(filename);
810                 return;
811         }
812
813         ir_export_file(file, filename);
814         fclose(file);
815 }
816
817 /* Exports the whole irp to the given file in a textual form. */
818 void ir_export_file(FILE *file, const char *outputname)
819 {
820         io_env_t env;
821         int i, n_irgs = get_irp_n_irgs();
822
823         (void) outputname;
824         env.file = file;
825
826         export_modes(&env);
827
828         fputs("\ntypegraph {\n", env.file);
829         type_walk_prog(export_type_or_ent_pre, export_type_or_ent_post, &env);
830         fputs("}\n", env.file);
831
832         for (i = 0; i < n_irgs; i++) {
833                 ir_graph *irg       = get_irp_irg(i);
834                 ir_type  *valuetype = get_irg_value_param_type(irg);
835
836                 fprintf(env.file, "\nirg %ld %ld %ld {\n",
837                         get_entity_nr(get_irg_entity(irg)),
838                         get_type_nr(get_irg_frame_type(irg)),
839                         valuetype == NULL ? -1 : get_type_nr(valuetype));
840
841                 env.ignoreblocks = 0;
842                 irg_block_walk_graph(irg, NULL, export_node, &env);
843
844                 env.ignoreblocks = 1;
845                 irg_walk_anchors(irg, NULL, export_node, &env);
846
847                 fputs("}\n", env.file);
848         }
849
850         fprintf(env.file, "\nconstirg %ld {\n", get_irn_node_nr(get_const_code_irg()->current_block));
851
852         walk_const_code(NULL, export_node, &env);
853         fputs("}\n", env.file);
854
855         export_program(&env);
856 }
857
858 /* Exports the given irg to the given file. */
859 void ir_export_irg(ir_graph *irg, FILE *file, const char *outputname)
860 {
861         io_env_t env;
862
863         (void) outputname;
864         env.file = file;
865
866         export_modes(&env);
867
868         fputs("typegraph {\n", env.file);
869
870         type_walk_irg(irg, export_type_or_ent_pre, export_type_or_ent_post, &env);
871
872         fprintf(env.file, "}\n\nirg %ld {\n", get_entity_nr(get_irg_entity(irg)));
873
874         env.ignoreblocks = 0;
875         irg_block_walk_graph(irg, NULL, export_node, &env);
876
877         env.ignoreblocks = 1;
878         irg_walk_anchors(irg, NULL, export_node, &env);
879
880         /* TODO: Only output needed constants */
881         fprintf(env.file, "}\n\nconstirg %ld {\n", get_irn_node_nr(get_const_code_irg()->current_block));
882         walk_const_code(NULL, export_node, &env);
883         fputs("}\n", env.file);
884 }
885
886 static void read_c(io_env_t *env)
887 {
888         int c = fgetc(env->file);
889         env->c = c;
890         if (c == '\n')
891                 env->line++;
892 }
893
894 /** Returns the first non-whitespace character or EOF. **/
895 static void skip_ws(io_env_t *env)
896 {
897         while (true) {
898                 switch (env->c) {
899                 case ' ':
900                 case '\t':
901                 case '\n':
902                 case '\r':
903                         read_c(env);
904                         continue;
905
906                 default:
907                         return;
908                 }
909         }
910 }
911
912 static void skip_to(io_env_t *env, char to_ch)
913 {
914         while (env->c != to_ch && env->c != EOF) {
915                 read_c(env);
916         }
917 }
918
919 static int expect_char(io_env_t *env, char ch)
920 {
921         skip_ws(env);
922         if (env->c != ch) {
923                 parse_error(env, "Unexpected char '%c', expected '%c'\n",
924                             env->c, ch);
925                 return 0;
926         }
927         read_c(env);
928         return 1;
929 }
930
931 #define EXPECT(c) if (expect_char(env, (c))) {} else return 0
932
933 static char *read_word(io_env_t *env)
934 {
935         skip_ws(env);
936
937         assert(obstack_object_size(&env->obst) == 0);
938         while (true) {
939                 int c = env->c;
940                 switch (c) {
941                 case EOF:
942                 case ' ':
943                 case '\t':
944                 case '\n':
945                 case '\r':
946                         goto endofword;
947
948                 default:
949                         obstack_1grow(&env->obst, c);
950                         break;
951                 }
952                 read_c(env);
953         }
954
955 endofword:
956         obstack_1grow(&env->obst, '\0');
957         return (char*)obstack_finish(&env->obst);
958 }
959
960 static char *read_quoted_string(io_env_t *env)
961 {
962         skip_ws(env);
963         if (env->c != '\"') {
964                 parse_error(env, "Expected '\"', found '%c'\n", env->c);
965                 exit(1);
966         }
967         read_c(env);
968
969         assert(obstack_object_size(&env->obst) == 0);
970         while (true) {
971                 int ch = env->c;
972                 if (ch == EOF) {
973                         parse_error(env, "Unexpected end of quoted string!\n");
974                         exit(1);
975                 }
976                 if (ch == '\"') {
977                         read_c(env);
978                         break;
979                 }
980                 obstack_1grow(&env->obst, ch);
981                 read_c(env);
982         }
983         obstack_1grow(&env->obst, '\0');
984
985         return (char*)obstack_finish(&env->obst);
986 }
987
988 static ident *read_ident(io_env_t *env)
989 {
990         char  *str = read_quoted_string(env);
991         ident *res = new_id_from_str(str);
992         obstack_free(&env->obst, str);
993
994         return res;
995 }
996
997 /*
998  * reads a "quoted string" or alternatively the token NULL
999  */
1000 static char *read_quoted_string_null(io_env_t *env)
1001 {
1002         skip_ws(env);
1003         if (env->c == 'N') {
1004                 char *str = read_word(env);
1005                 if (strcmp(str, "NULL") == 0) {
1006                         obstack_free(&env->obst, str);
1007                         return NULL;
1008                 }
1009         } else if (env->c == '"') {
1010                 return read_quoted_string(env);
1011         }
1012
1013         parse_error(env, "Expected \"string\" or NULL\n");
1014         exit(1);
1015 }
1016
1017 static ident *read_ident_null(io_env_t *env)
1018 {
1019         ident *res;
1020         char  *str = read_quoted_string_null(env);
1021         if (str == NULL)
1022                 return NULL;
1023
1024         res = new_id_from_str(str);
1025         obstack_free(&env->obst, str);
1026         return res;
1027 }
1028
1029 static long read_long(io_env_t *env)
1030 {
1031         long  result;
1032         char *str;
1033
1034         skip_ws(env);
1035         if (!isdigit(env->c) && env->c != '-') {
1036                 parse_error(env, "Expected number, got '%c'\n", env->c);
1037                 exit(1);
1038         }
1039
1040         assert(obstack_object_size(&env->obst) == 0);
1041         do {
1042                 obstack_1grow(&env->obst, env->c);
1043                 read_c(env);
1044         } while (isdigit(env->c));
1045         obstack_1grow(&env->obst, 0);
1046
1047         str = (char*)obstack_finish(&env->obst);
1048         result = atol(str);
1049         obstack_free(&env->obst, str);
1050
1051         return result;
1052 }
1053
1054 static int read_int(io_env_t *env)
1055 {
1056         return (int) read_long(env);
1057 }
1058
1059 static unsigned read_unsigned(io_env_t *env)
1060 {
1061         return (unsigned) read_long(env);
1062 }
1063
1064 static ir_node *get_node_or_null(io_env_t *env, long nodenr)
1065 {
1066         ir_node *node = (ir_node *) get_id(env, nodenr);
1067         if (node && node->kind != k_ir_node) {
1068                 panic("Irn ID %ld collides with something else in line %d\n",
1069                       nodenr, env->line);
1070         }
1071         return node;
1072 }
1073
1074 static ir_node *get_node_or_dummy(io_env_t *env, long nodenr)
1075 {
1076         ir_node *node = get_node_or_null(env, nodenr);
1077         if (node == NULL) {
1078                 node = new_r_Dummy(env->irg, mode_X);
1079                 set_id(env, nodenr, node);
1080         }
1081         return node;
1082 }
1083
1084 static ir_type *get_type(io_env_t *env, long typenr)
1085 {
1086         ir_type *type = (ir_type *) get_id(env, typenr);
1087         if (type == NULL)
1088                 panic("unknown type: %ld in line %d\n", typenr, env->line);
1089         else if (type->kind != k_type)
1090                 panic("type ID %ld collides with something else in line %d\n",
1091                       typenr, env->line);
1092         return type;
1093 }
1094
1095 static ir_type *read_type(io_env_t *env)
1096 {
1097         return get_type(env, read_long(env));
1098 }
1099
1100 static ir_entity *get_entity(io_env_t *env, long entnr)
1101 {
1102         ir_entity *entity = (ir_entity *) get_id(env, entnr);
1103         if (entity == NULL) {
1104                 parse_error(env, "unknown entity: %ld\n", entnr);
1105                 exit(1);
1106         } else if (entity->kind != k_entity) {
1107                 panic("Entity ID %ld collides with something else in line %d\n",
1108                       entnr, env->line);
1109         }
1110
1111         return entity;
1112 }
1113
1114 static ir_entity *read_entity(io_env_t *env)
1115 {
1116         return get_entity(env, read_long(env));
1117 }
1118
1119 static ir_mode *read_mode(io_env_t *env)
1120 {
1121         char *str = read_word(env);
1122         int i, n;
1123
1124         n = get_irp_n_modes();
1125         for (i = 0; i < n; i++) {
1126                 ir_mode *mode = get_irp_mode(i);
1127                 if (strcmp(str, get_mode_name(mode)) == 0) {
1128                         obstack_free(&env->obst, str);
1129                         return mode;
1130                 }
1131         }
1132
1133         parse_error(env, "unknown mode \"%s\"\n", str);
1134         exit(1);
1135 }
1136
1137 static const char *get_typetag_name(typetag_t typetag)
1138 {
1139         switch (typetag) {
1140         case tt_align:              return "align";
1141         case tt_allocation:         return "allocation";
1142         case tt_builtin:            return "builtin kind";
1143         case tt_cond_jmp_predicate: return "cond_jmp_predicate";
1144         case tt_initializer:        return "initializer kind";
1145         case tt_iro:                return "opcode";
1146         case tt_keyword:            return "keyword";
1147         case tt_linkage:            return "linkage";
1148         case tt_mode_arithmetic:    return "mode_arithmetic";
1149         case tt_mode_sort:          return "mode_sort";
1150         case tt_pin_state:          return "pin state";
1151         case tt_segment:            return "segment";
1152         case tt_tpo:                return "type";
1153         case tt_type_state:         return "type state";
1154         case tt_volatility:         return "volatility";
1155         case tt_visibility:         return "visibility";
1156         }
1157         return "<UNKNOWN>";
1158 }
1159
1160 /**
1161  * Read and decode an enum constant.
1162  */
1163 static unsigned read_enum(io_env_t *env, typetag_t typetag)
1164 {
1165         char     *str  = read_word(env);
1166         unsigned  code = symbol(str, typetag);
1167
1168         if (code != SYMERROR) {
1169                 obstack_free(&env->obst, str);
1170                 return code;
1171         }
1172
1173         parse_error(env, "invalid %s: \"%s\"\n", get_typetag_name(typetag), str);
1174         return 0;
1175 }
1176
1177 #define read_align(env)              ((ir_align)              read_enum(env, tt_align))
1178 #define read_allocation(env)         ((ir_allocation)         read_enum(env, tt_allocation))
1179 #define read_builtin_kind(env)       ((ir_builtin_kind)       read_enum(env, tt_builtin))
1180 #define read_cond_jmp_predicate(env) ((cond_jmp_predicate)    read_enum(env, tt_cond_jmp_predicate))
1181 #define read_initializer_kind(env)   ((ir_initializer_kind_t) read_enum(env, tt_initializer))
1182 #define read_mode_arithmetic(env)    ((ir_mode_arithmetic)    read_enum(env, tt_mode_arithmetic))
1183 #define read_peculiarity(env)        ((ir_peculiarity)        read_enum(env, tt_peculiarity))
1184 #define read_pin_state(env)          ((op_pin_state)          read_enum(env, tt_pin_state))
1185 #define read_type_state(env)         ((ir_type_state)         read_enum(env, tt_type_state))
1186 #define read_variability(env)        ((ir_variability)        read_enum(env, tt_variability))
1187 #define read_volatility(env)         ((ir_volatility)         read_enum(env, tt_volatility))
1188
1189 static ir_cons_flags get_cons_flags(io_env_t *env)
1190 {
1191         ir_cons_flags flags = cons_none;
1192
1193         op_pin_state pinstate = read_pin_state(env);
1194         switch (pinstate) {
1195         case op_pin_state_floats: flags |= cons_floats; break;
1196         case op_pin_state_pinned: break;
1197         default:
1198                 panic("Error in %d: Invalid pinstate: %s", env->line,
1199                       get_op_pin_state_name(pinstate));
1200         }
1201
1202         if (read_volatility(env) == volatility_is_volatile)
1203                 flags |= cons_volatile;
1204         if (read_align(env) == align_non_aligned)
1205                 flags |= cons_unaligned;
1206
1207         return flags;
1208 }
1209
1210 static ir_tarval *read_tv(io_env_t *env)
1211 {
1212         ir_mode   *tvmode = read_mode(env);
1213         char      *str    = read_word(env);
1214         ir_tarval *tv     = new_tarval_from_str(str, strlen(str), tvmode);
1215         obstack_free(&env->obst, str);
1216
1217         return tv;
1218 }
1219
1220 static ir_initializer_t *read_initializer(io_env_t *env)
1221 {
1222         ir_initializer_kind_t ini_kind = read_initializer_kind(env);
1223
1224         switch (ini_kind) {
1225         case IR_INITIALIZER_CONST: {
1226                 ir_node *irn = get_node_or_dummy(env, read_long(env));
1227                 return create_initializer_const(irn);
1228         }
1229
1230         case IR_INITIALIZER_TARVAL:
1231                 return create_initializer_tarval(read_tv(env));
1232
1233         case IR_INITIALIZER_NULL:
1234                 return get_initializer_null();
1235
1236         case IR_INITIALIZER_COMPOUND: {
1237                 unsigned i, n = (unsigned) read_long(env);
1238                 ir_initializer_t *ini = create_initializer_compound(n);
1239                 for (i = 0; i < n; i++) {
1240                         ir_initializer_t *curini = read_initializer(env);
1241                         set_initializer_compound_value(ini, i, curini);
1242                 }
1243                 return ini;
1244         }
1245
1246         default:
1247                 panic("Unknown initializer kind");
1248         }
1249 }
1250
1251
1252 /** Reads a type description and remembers it by its id. */
1253 static void import_type(io_env_t *env)
1254 {
1255         int            i;
1256         ir_type       *type;
1257         long           typenr = read_long(env);
1258         tp_opcode      tpop   = (tp_opcode) read_enum(env, tt_tpo);
1259         unsigned       size   = (unsigned) read_long(env);
1260         unsigned       align  = (unsigned) read_long(env);
1261         ir_type_state  state  = read_type_state(env);
1262         unsigned       flags  = (unsigned) read_long(env);
1263
1264         switch (tpop) {
1265         case tpo_array: {
1266                 int ndims = (int) read_long(env);
1267                 long elemtypenr = read_long(env);
1268                 ir_type *elemtype = get_type(env, elemtypenr);
1269
1270                 type = new_type_array(ndims, elemtype);
1271                 for (i = 0; i < ndims; i++) {
1272                         char *str = read_word(env);
1273                         if (strcmp(str, "unknown") != 0) {
1274                                 long lowerbound = atol(str);
1275                                 set_array_lower_bound_int(type, i, lowerbound);
1276                         }
1277                         obstack_free(&env->obst, str);
1278
1279                         str = read_word(env);
1280                         if (strcmp(str, "unknown") != 0) {
1281                                 long upperbound = atol(str);
1282                                 set_array_upper_bound_int(type, i, upperbound);
1283                         }
1284                         obstack_free(&env->obst, str);
1285                 }
1286                 set_type_size_bytes(type, size);
1287                 break;
1288         }
1289
1290         case tpo_class: {
1291                 const char *name = read_quoted_string_null(env);
1292                 ident      *id   = name != NULL ? new_id_from_str(name) : NULL;
1293
1294                 if (typenr == (long) IR_SEGMENT_GLOBAL)
1295                         type = get_glob_type();
1296                 else
1297                         type = new_type_class(id);
1298                 set_type_size_bytes(type, size);
1299                 break;
1300         }
1301
1302         case tpo_method: {
1303                 unsigned                  callingconv = (unsigned) read_long(env);
1304                 mtp_additional_properties addprops    = (mtp_additional_properties) read_long(env);
1305                 int nparams          = (int)      read_long(env);
1306                 int nresults         = (int)      read_long(env);
1307                 int variaindex;
1308
1309                 type = new_type_method(nparams, nresults);
1310
1311                 for (i = 0; i < nparams; i++) {
1312                         long     typenr = read_long(env);
1313                         ir_type *paramtype = get_type(env, typenr);
1314
1315                         set_method_param_type(type, i, paramtype);
1316                 }
1317                 for (i = 0; i < nresults; i++) {
1318                         long typenr = read_long(env);
1319                         ir_type *restype = get_type(env, typenr);
1320
1321                         set_method_res_type(type, i, restype);
1322                 }
1323
1324                 variaindex = (int) read_long(env);
1325                 if (variaindex != -1) {
1326                         set_method_variadicity(type, variadicity_variadic);
1327                         if (variaindex != nparams)
1328                                 set_method_first_variadic_param_index(type, variaindex);
1329                 }
1330
1331                 set_method_calling_convention(type, callingconv);
1332                 set_method_additional_properties(type, addprops);
1333                 break;
1334         }
1335
1336         case tpo_pointer: {
1337                 ir_mode *mode     = read_mode(env);
1338                 ir_type *pointsto = get_type(env, read_long(env));
1339                 type = new_type_pointer(pointsto);
1340                 set_type_mode(type, mode);
1341                 break;
1342         }
1343
1344         case tpo_primitive: {
1345                 ir_mode *mode = read_mode(env);
1346                 type = new_type_primitive(mode);
1347                 break;
1348         }
1349
1350         case tpo_struct: {
1351                 const char *name = read_quoted_string_null(env);
1352                 ident      *id   = name != NULL ? new_id_from_str(name) : NULL;
1353                 type = new_type_struct(id);
1354                 set_type_size_bytes(type, size);
1355                 break;
1356         }
1357
1358         case tpo_union: {
1359                 const char *name = read_quoted_string_null(env);
1360                 ident      *id   = name != NULL ? new_id_from_str(name) : NULL;
1361
1362                 type = new_type_union(id);
1363                 set_type_size_bytes(type, size);
1364                 break;
1365         }
1366
1367         case tpo_unknown:
1368                 return;   /* ignore unknown type */
1369
1370         default:
1371                 parse_error(env, "unknown type kind: \"%d\"\n", tpop);
1372                 skip_to(env, '\n');
1373                 return;
1374         }
1375
1376         set_type_alignment_bytes(type, align);
1377         type->flags = flags;
1378
1379         if (state == layout_fixed)
1380                 ARR_APP1(ir_type *, env->fixedtypes, type);
1381
1382         set_id(env, typenr, type);
1383 }
1384
1385 /** Reads an entity description and remembers it by its id. */
1386 static void import_entity(io_env_t *env)
1387 {
1388         long           entnr      = read_long(env);
1389         ident         *name       = read_ident(env);
1390         ident         *ld_name    = read_ident_null(env);
1391         ir_visibility  visibility = ir_visibility_default;
1392         ir_linkage     linkage    = IR_LINKAGE_DEFAULT;
1393         long           typenr;
1394         long           ownertypenr;
1395         const char    *str;
1396         ir_type       *type;
1397         ir_type       *ownertype;
1398         ir_entity     *entity;
1399
1400         skip_ws(env);
1401         while (!isdigit(env->c)) {
1402                 char     *str = read_word(env);
1403                 unsigned  v;
1404
1405                 skip_ws(env);
1406
1407                 v = symbol(str, tt_visibility);
1408                 if (v != SYMERROR) {
1409                         visibility = (ir_visibility)v;
1410                         continue;
1411                 }
1412                 v = symbol(str, tt_linkage);
1413                 if (v != SYMERROR) {
1414                         linkage |= (ir_linkage)v;
1415                         continue;
1416                 }
1417                 printf("Parser error, expected visibility or linkage, got '%s'\n",
1418                        str);
1419                 break;
1420         }
1421
1422         typenr      = read_long(env);
1423         ownertypenr = read_long(env);
1424
1425         type      = get_type(env, typenr);
1426         ownertype = !ownertypenr ? get_glob_type() : get_type(env, ownertypenr);
1427         entity    = new_entity(ownertype, name, type);
1428
1429         if (ld_name != NULL)
1430                 set_entity_ld_ident(entity, ld_name);
1431         set_entity_offset(entity, (int) read_long(env));
1432         set_entity_offset_bits_remainder(entity, (unsigned char) read_long(env));
1433         set_entity_compiler_generated(entity, (int) read_long(env));
1434         set_entity_volatility(entity, read_volatility(env));
1435         set_entity_visibility(entity, visibility);
1436         set_entity_linkage(entity, linkage);
1437
1438         str = read_word(env);
1439         if (strcmp(str, "initializer") == 0) {
1440                 set_entity_initializer(entity, read_initializer(env));
1441         } else if (strcmp(str, "compoundgraph") == 0) {
1442                 int n = (int) read_long(env);
1443                 int i;
1444                 for (i = 0; i < n; i++) {
1445                         ir_entity *member = get_entity(env, read_long(env));
1446                         ir_node   *irn    = get_node_or_dummy(env, read_long(env));
1447                         add_compound_ent_value(entity, irn, member);
1448                 }
1449         } else if (strcmp(str, "none") == 0) {
1450                 /* do nothing */
1451         } else {
1452                 parse_error(env, "expected 'initializer', 'compoundgraph' or 'none' got '%s'\n", str);
1453                 exit(1);
1454         }
1455
1456         set_id(env, entnr, entity);
1457 }
1458
1459 /** Parses the whole type graph. */
1460 static int parse_typegraph(io_env_t *env)
1461 {
1462         ir_graph *old_irg = env->irg;
1463         keyword_t kwkind;
1464
1465         EXPECT('{');
1466
1467         env->irg = get_const_code_irg();
1468
1469         /* parse all types first */
1470         while (true) {
1471                 skip_ws(env);
1472                 if (env->c == '}') {
1473                         read_c(env);
1474                         break;
1475                 }
1476
1477                 kwkind = (keyword_t) read_enum(env, tt_keyword);
1478                 switch (kwkind) {
1479                 case kw_type:
1480                         import_type(env);
1481                         break;
1482
1483                 case kw_entity:
1484                         import_entity(env);
1485                         break;
1486
1487                 default:
1488                         parse_error(env, "type graph element not supported yet: %d\n", kwkind);
1489                         skip_to(env, '\n');
1490                         break;
1491                 }
1492         }
1493         env->irg = old_irg;
1494         return 1;
1495 }
1496
1497 static int read_node_header(io_env_t *env, long *nodenr, ir_node ***preds,
1498                             const char **nodename)
1499 {
1500         int numpreds;
1501
1502         *nodename = read_word(env);
1503         *nodenr   = read_long(env);
1504
1505         ARR_RESIZE(ir_node*, *preds, 0);
1506
1507         EXPECT('[');
1508         for (numpreds = 0; !feof(env->file); numpreds++) {
1509                 long val;
1510                 ir_node *pred;
1511
1512                 skip_ws(env);
1513                 if (env->c == ']') {
1514                         read_c(env);
1515                         break;
1516                 }
1517                 val = read_long(env);
1518                 pred = get_node_or_dummy(env, val);
1519                 ARR_APP1(ir_node*, *preds, pred);
1520         }
1521
1522         return numpreds;
1523 }
1524
1525 /** Parses an IRG. */
1526 static int parse_graph(io_env_t *env, ir_graph *irg)
1527 {
1528         ir_node   **preds = NEW_ARR_F(ir_node*,0);
1529         int         i, numpreds, ret = 1;
1530         long        nodenr;
1531         const char *nodename;
1532         ir_node    *node, *newnode;
1533
1534         env->irg = irg;
1535
1536         EXPECT('{');
1537
1538         while (true) {
1539                 skip_ws(env);
1540                 if (env->c == '}') {
1541                         read_c(env);
1542                         break;
1543                 }
1544
1545                 numpreds = read_node_header(env, &nodenr, &preds, &nodename);
1546
1547                 node = get_node_or_null(env, nodenr);
1548                 newnode = NULL;
1549
1550                 EXPECT('{');
1551
1552                 switch (symbol(nodename, tt_iro)) {
1553                 case iro_End: {
1554                         ir_node *newendblock = preds[0];
1555                         newnode = get_irg_end(irg);
1556                         exchange(get_nodes_block(newnode), newendblock);
1557                         for (i = 1; i < numpreds; i++)
1558                                 add_irn_n(newnode, preds[i]);
1559                         break;
1560                 }
1561
1562                 case iro_Start: {
1563                         ir_node *newstartblock = preds[0];
1564                         newnode = get_irg_start(irg);
1565                         exchange(get_nodes_block(newnode), newstartblock);
1566                         break;
1567                 }
1568
1569                 case iro_Block:
1570                         newnode = new_r_Block(irg, numpreds, preds);
1571                         break;
1572
1573                 case iro_Anchor:
1574                         newnode = irg->anchor;
1575                         for (i = 1; i < numpreds; i++)
1576                                 set_irn_n(newnode, i-1, preds[i]);
1577                         set_nodes_block(newnode, preds[0]);
1578                         break;
1579
1580                 case iro_SymConst: {
1581                         long entnr = read_long(env);
1582                         union symconst_symbol sym;
1583                         sym.entity_p = get_entity(env, entnr);
1584                         newnode = new_r_SymConst(irg, mode_P, sym, symconst_addr_ent);
1585                         break;
1586                 }
1587
1588                 case iro_Proj: {
1589                         ir_mode *mode = read_mode(env);
1590                         long     pn   = read_long(env);
1591                         newnode = new_r_Proj(preds[1], mode, pn);
1592                         /* explicitely set block, since preds[1] might be a dummy node
1593                          * which is always in the startblock */
1594                         set_nodes_block(newnode, preds[0]);
1595                         break;
1596                 }
1597
1598                 #include "gen_irio_import.inl"
1599
1600                 default:
1601                         goto notsupported;
1602                 }
1603
1604                 EXPECT('}');
1605
1606                 if (!newnode) {
1607 notsupported:
1608                         parse_error(env, "node type not supported yet: %s\n", nodename);
1609                         abort();
1610                 }
1611
1612                 if (node)
1613                         exchange(node, newnode);
1614                 /* Always update hash entry to avoid more uses of id nodes */
1615                 set_id(env, nodenr, newnode);
1616         }
1617
1618         DEL_ARR_F(preds);
1619
1620         return ret;
1621 }
1622
1623 static int parse_modes(io_env_t *env)
1624 {
1625         EXPECT('{');
1626
1627         while (true) {
1628                 keyword_t kwkind;
1629
1630                 skip_ws(env);
1631                 if (env->c == '}') {
1632                         read_c(env);
1633                         break;
1634                 }
1635
1636                 kwkind = (keyword_t) read_enum(env, tt_keyword);
1637                 switch (kwkind) {
1638                 case kw_mode: {
1639                         const char *name = read_quoted_string(env);
1640                         ir_mode_sort sort = (ir_mode_sort)read_enum(env, tt_mode_sort);
1641                         int size = read_long(env);
1642                         int sign = read_long(env);
1643                         ir_mode_arithmetic arith = read_mode_arithmetic(env);
1644                         unsigned modulo_shift = read_long(env);
1645                         int vector_elems = read_long(env);
1646                         ir_mode *mode;
1647
1648                         if (vector_elems != 1) {
1649                                 panic("no support for import of vector modes yes");
1650                         }
1651
1652                         mode = new_ir_mode(name, sort, size, sign, arith, modulo_shift);
1653                         if (mode_is_reference(mode)) {
1654                                 set_reference_mode_signed_eq(mode, read_mode(env));
1655                                 set_reference_mode_unsigned_eq(mode, read_mode(env));
1656                         }
1657                         break;
1658                 }
1659
1660                 default:
1661                         skip_to(env, '\n');
1662                         break;
1663                 }
1664         }
1665         return 1;
1666 }
1667
1668 static int parse_program(io_env_t *env)
1669 {
1670         EXPECT('{');
1671
1672         while (true) {
1673                 keyword_t kwkind;
1674
1675                 skip_ws(env);
1676                 if (env->c == '}') {
1677                         read_c(env);
1678                         break;
1679                 }
1680
1681                 kwkind = (keyword_t) read_enum(env, tt_keyword);
1682                 switch (kwkind) {
1683                 case kw_segment_type: {
1684                         ir_segment_t  segment = (ir_segment_t) read_enum(env, tt_segment);
1685                         ir_type      *type    = read_type(env);
1686                         set_segment_type(segment, type);
1687                         break;
1688                 }
1689                 default:
1690                         parse_error(env, "unexpected keyword %d\n", kwkind);
1691                         skip_to(env, '\n');
1692                 }
1693         }
1694         return 1;
1695 }
1696
1697 void ir_import(const char *filename)
1698 {
1699         FILE *file = fopen(filename, "rt");
1700         if (file == NULL) {
1701                 perror(filename);
1702                 exit(1);
1703         }
1704
1705         ir_import_file(file, filename);
1706
1707         fclose(file);
1708 }
1709
1710 void ir_import_file(FILE *input, const char *inputname)
1711 {
1712         int oldoptimize = get_optimize();
1713         firm_verification_t oldver = get_node_verification_mode();
1714         io_env_t ioenv;
1715         io_env_t *env = &ioenv;
1716         int i, n;
1717
1718         symtbl_init();
1719
1720         memset(env, 0, sizeof(*env));
1721         obstack_init(&env->obst);
1722         env->idset      = new_set(id_cmp, 128);
1723         env->fixedtypes = NEW_ARR_F(ir_type *, 0);
1724         env->inputname  = inputname;
1725         env->file       = input;
1726         env->line       = 1;
1727
1728         /* read first character */
1729         read_c(env);
1730
1731         set_optimize(0);
1732         do_node_verification(FIRM_VERIFICATION_OFF);
1733
1734         while (true) {
1735                 keyword_t kw;
1736
1737                 skip_ws(env);
1738                 if (env->c == EOF)
1739                         break;
1740
1741                 kw = (keyword_t)read_enum(env, tt_keyword);
1742                 switch (kw) {
1743                 case kw_modes:
1744                         if (!parse_modes(env)) goto end;
1745                         break;
1746
1747                 case kw_typegraph:
1748                         if (!parse_typegraph(env)) goto end;
1749                         break;
1750
1751                 case kw_irg:
1752                 {
1753                         ir_entity *irgent = get_entity(env, read_long(env));
1754                         long valuetypeid;
1755                         ir_graph *irg = new_ir_graph(irgent, 0);
1756                         set_irg_frame_type(irg, get_type(env, read_long(env)));
1757                         valuetypeid = read_long(env);
1758                         if (valuetypeid != -1)
1759                                 set_method_value_param_type(get_entity_type(irgent),
1760                                                 get_type(env, valuetypeid));
1761
1762                         if (!parse_graph(env, irg)) goto end;
1763                         break;
1764                 }
1765
1766                 case kw_constirg: {
1767                         ir_graph *constirg = get_const_code_irg();
1768                         long bodyblockid = read_long(env);
1769                         set_id(env, bodyblockid, constirg->current_block);
1770                         if (!parse_graph(env, constirg)) goto end;
1771                         break;
1772                 }
1773
1774                 case kw_program:
1775                         parse_program(env);
1776                         break;
1777
1778                 default: {
1779                         parse_error(env, "Unexpected keyword %d at toplevel\n", kw);
1780                         exit(1);
1781                 }
1782                 }
1783         }
1784
1785 end:
1786         n = ARR_LEN(env->fixedtypes);
1787         for (i = 0; i < n; i++)
1788                 set_type_state(env->fixedtypes[i], layout_fixed);
1789
1790         DEL_ARR_F(env->fixedtypes);
1791
1792         del_set(env->idset);
1793
1794         irp_finalize_cons();
1795
1796         do_node_verification(oldver);
1797         set_optimize(oldoptimize);
1798
1799         obstack_free(&env->obst, NULL);
1800 }