738247add830c32751ba80c7d487f697f1b14809
[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
30 #include "irio.h"
31
32 #include "irnode_t.h"
33 #include "irprog.h"
34 #include "irgraph_t.h"
35 #include "ircons.h"
36 #include "irgmod.h"
37 #include "irflag_t.h"
38 #include "irgwalk.h"
39 #include "tv.h"
40 #include "array.h"
41 #include "error.h"
42 #include "adt/set.h"
43
44 #define SYMERROR ((unsigned) ~0)
45
46 typedef struct io_env
47 {
48         FILE *file;
49         set *idset;               /**< id_entry set, which maps from file ids to new Firm elements */
50         int ignoreblocks;
51         int line, col;
52         ir_type **fixedtypes;
53 } io_env_t;
54
55 typedef enum typetag_t
56 {
57         tt_iro,
58         tt_tpo,
59         tt_align,
60         tt_allocation,
61         tt_peculiarity,
62         tt_pin_state,
63         tt_type_state,
64         tt_variability,
65         tt_visibility,
66         tt_volatility,
67         tt_initializer
68 } typetag_t;
69
70 typedef struct symbol_t
71 {
72         const char *str;      /**< The name of this symbol. */
73         typetag_t   typetag;  /**< The type tag of this symbol. */
74         unsigned    code;     /**< The value of this symbol. */
75 } symbol_t;
76
77 typedef struct id_entry
78 {
79         long id;
80         void *elem;
81 } id_entry;
82
83 /** The symbol table, a set of symbol_t elements. */
84 static set *symtbl;
85
86
87 /**
88  * Calculate a hash value for a string.
89  */
90 static unsigned string_hash(const char *str, int len)
91 {
92         return str[0] * 27893 ^ str[len-1] * 81 ^ str[len >> 1];
93 }
94
95 /**
96  * Compare two symbol table entries.
97  */
98 static int symbol_cmp(const void *elt, const void *key, size_t size)
99 {
100         const symbol_t *entry = (const symbol_t *) elt;
101         const symbol_t *keyentry = (const symbol_t *) key;
102         (void) size;
103         return strcmp(entry->str, keyentry->str);
104 }
105
106 static int id_cmp(const void *elt, const void *key, size_t size)
107 {
108         const id_entry *entry = (const id_entry *) elt;
109         const id_entry *keyentry = (const id_entry *) key;
110         (void) size;
111         return entry->id - keyentry->id;
112 }
113
114 /** Initializes the symbol table. May be called more than once without problems. */
115 static void symtbl_init(void)
116 {
117         symbol_t key;
118
119         /* Only initialize once */
120         if(symtbl != NULL)
121                 return;
122
123         symtbl = new_set(symbol_cmp, 32);
124
125 #define INSERT(s, tt, cod)                                       \
126         key.str = (s);                                               \
127         key.typetag = (tt);                                          \
128         key.code = (cod);                                            \
129         set_insert(symtbl, &key, sizeof(key), string_hash(s, sizeof(s)-1))
130
131 #define INSERTENUM(tt, e) INSERT(#e, tt, e)
132
133         INSERT("array", tt_tpo, tpo_array);
134         INSERT("class", tt_tpo, tpo_class);
135         INSERT("method", tt_tpo, tpo_method);
136         INSERT("pointer", tt_tpo, tpo_pointer);
137         INSERT("primitive", tt_tpo, tpo_primitive);
138         INSERT("struct", tt_tpo, tpo_struct);
139         INSERT("Unknown", tt_tpo, tpo_unknown);
140
141 #include "gen_irio_lex.inl"
142
143         INSERTENUM(tt_align, align_non_aligned);
144         INSERTENUM(tt_align, align_is_aligned);
145
146         INSERTENUM(tt_allocation, allocation_automatic);
147         INSERTENUM(tt_allocation, allocation_parameter);
148         INSERTENUM(tt_allocation, allocation_dynamic);
149         INSERTENUM(tt_allocation, allocation_static);
150
151         INSERTENUM(tt_pin_state, op_pin_state_floats);
152         INSERTENUM(tt_pin_state, op_pin_state_pinned);
153         INSERTENUM(tt_pin_state, op_pin_state_exc_pinned);
154         INSERTENUM(tt_pin_state, op_pin_state_mem_pinned);
155
156         INSERTENUM(tt_type_state, layout_undefined);
157         INSERTENUM(tt_type_state, layout_fixed);
158
159         INSERTENUM(tt_variability, variability_uninitialized);
160         INSERTENUM(tt_variability, variability_initialized);
161         INSERTENUM(tt_variability, variability_part_constant);
162         INSERTENUM(tt_variability, variability_constant);
163
164         INSERTENUM(tt_visibility, visibility_local);
165         INSERTENUM(tt_visibility, visibility_external_visible);
166         INSERTENUM(tt_visibility, visibility_external_allocated);
167
168         INSERTENUM(tt_volatility, volatility_non_volatile);
169         INSERTENUM(tt_volatility, volatility_is_volatile);
170
171         INSERTENUM(tt_peculiarity, peculiarity_description);
172         INSERTENUM(tt_peculiarity, peculiarity_inherited);
173         INSERTENUM(tt_peculiarity, peculiarity_existent);
174
175         INSERTENUM(tt_initializer, IR_INITIALIZER_CONST);
176         INSERTENUM(tt_initializer, IR_INITIALIZER_TARVAL);
177         INSERTENUM(tt_initializer, IR_INITIALIZER_NULL);
178         INSERTENUM(tt_initializer, IR_INITIALIZER_COMPOUND);
179
180 #undef INSERTENUM
181 #undef INSERT
182 }
183
184 /** Returns the according symbol value for the given string and tag, or SYMERROR if none was found. */
185 static unsigned symbol(const char *str, typetag_t typetag)
186 {
187         symbol_t key, *entry;
188
189         key.str = str;
190
191         entry = set_find(symtbl, &key, sizeof(key), string_hash(str, strlen(str)));
192         if (entry && entry->typetag == typetag) {
193                 return entry->code;
194         }
195         return SYMERROR;
196 }
197
198 static void *get_id(io_env_t *env, long id)
199 {
200         id_entry key, *entry;
201         key.id = id;
202
203         entry = set_find(env->idset, &key, sizeof(key), (unsigned) id);
204         return entry ? entry->elem : NULL;
205 }
206
207 static void set_id(io_env_t *env, long id, void *elem)
208 {
209         id_entry key;
210         key.id = id;
211         key.elem = elem;
212         set_insert(env->idset, &key, sizeof(key), (unsigned) id);
213 }
214
215 static void write_mode(io_env_t *env, ir_mode *mode)
216 {
217         fputs(get_mode_name(mode), env->file);
218         fputc(' ', env->file);
219 }
220
221 static void write_tarval(io_env_t *env, tarval *tv)
222 {
223         char buf[1024];
224         write_mode(env, get_tarval_mode(tv));
225         tarval_snprintf(buf, sizeof(buf), tv);
226         fputs(buf, env->file);
227         fputc(' ', env->file);
228 }
229
230 static void write_pin_state(io_env_t *env, ir_node *irn)
231 {
232         fputs(get_op_pin_state_name(get_irn_pinned(irn)), env->file);
233         fputc(' ', env->file);
234 }
235
236 static void write_volatility(io_env_t *env, ir_node *irn)
237 {
238         ir_volatility vol;
239
240         if(is_Load(irn)) vol = get_Load_volatility(irn);
241         else if(is_Store(irn)) vol = get_Store_volatility(irn);
242         else assert(0 && "Invalid optype for write_volatility");
243
244         fputs(get_volatility_name(vol), env->file);
245         fputc(' ', env->file);
246 }
247
248 static void write_align(io_env_t *env, ir_node *irn)
249 {
250         ir_align align;
251
252         if(is_Load(irn)) align = get_Load_align(irn);
253         else if(is_Store(irn)) align = get_Store_align(irn);
254         else assert(0 && "Invalid optype for write_align");
255
256         fputs(get_align_name(align), env->file);
257         fputc(' ', env->file);
258 }
259
260 static void write_initializer(io_env_t *env, ir_initializer_t *ini)
261 {
262         FILE *f = env->file;
263         ir_initializer_kind_t ini_kind = get_initializer_kind(ini);
264         fputs(get_initializer_kind_name(ini_kind), f);
265         fputc(' ', f);
266
267         switch(ini_kind)
268         {
269                 case IR_INITIALIZER_CONST:
270                         fprintf(f, "%ld ", get_irn_node_nr(get_initializer_const_value(ini)));
271                         break;
272
273                 case IR_INITIALIZER_TARVAL:
274                         write_tarval(env, get_initializer_tarval_value(ini));
275                         break;
276
277                 case IR_INITIALIZER_NULL:
278                         break;
279
280                 case IR_INITIALIZER_COMPOUND:
281                 {
282                         unsigned i, n = get_initializer_compound_n_entries(ini);
283                         fprintf(f, "%d ", n);
284                         for(i = 0; i < n; i++)
285                                 write_initializer(env, get_initializer_compound_value(ini, i));
286                         break;
287                 }
288
289                 default:
290                         panic("Unknown initializer kind");
291         }
292 }
293
294 static void export_type(io_env_t *env, ir_type *tp)
295 {
296         FILE *f = env->file;
297         int i;
298         fprintf(f, "\ttype %ld %s \"%s\" %u %u %s %s ",
299                         get_type_nr(tp),
300                         get_type_tpop_name(tp),
301                         get_type_name(tp),
302                         get_type_size_bytes(tp),
303                         get_type_alignment_bytes(tp),
304                         get_type_state_name(get_type_state(tp)),
305                         get_visibility_name(get_type_visibility(tp)));
306
307         switch(get_type_tpop_code(tp))
308         {
309                 case tpo_array:
310                 {
311                         int n = get_array_n_dimensions(tp);
312                         fprintf(f, "%i %ld ", n, get_type_nr(get_array_element_type(tp)));
313                         for(i = 0; i < n; i++)
314                         {
315                                 ir_node *lower = get_array_lower_bound(tp, i);
316                                 ir_node *upper = get_array_upper_bound(tp, i);
317
318                                 if(is_Const(lower)) fprintf(f, "%ld ", get_tarval_long(get_Const_tarval(lower)));
319                                 else panic("Lower array bound is not constant");
320
321                                 if(is_Const(upper)) fprintf(f, "%ld ", get_tarval_long(get_Const_tarval(upper)));
322                                 else if(is_Unknown(upper)) fputs("unknown ", f);
323                                 else panic("Upper array bound is not constant");
324                         }
325                         break;
326                 }
327
328                 case tpo_class:
329                         /* TODO: inheritance stuff not supported yet */
330                         printf("Inheritance of classes not supported yet!\n");
331                         break;
332
333                 case tpo_method:
334                 {
335                         int nparams = get_method_n_params(tp);
336                         int nresults = get_method_n_ress(tp);
337                         fprintf(f, "%i %i ", nparams, nresults);
338                         for(i = 0; i < nparams; i++)
339                                 fprintf(f, "%ld ", get_type_nr(get_method_param_type(tp, i)));
340                         for(i = 0; i < nresults; i++)
341                                 fprintf(f, "%ld ", get_type_nr(get_method_res_type(tp, i)));
342                         break;
343                 }
344
345                 case tpo_pointer:
346                         write_mode(env, get_type_mode(tp));
347                         fprintf(f, "%ld ", get_type_nr(get_pointer_points_to_type(tp)));
348                         break;
349
350                 case tpo_primitive:
351                         write_mode(env, get_type_mode(tp));
352                         break;
353
354                 case tpo_struct:
355                         break;
356
357                 case tpo_unknown:
358                         break;
359
360                 default:
361                         printf("export_type: Unknown type code \"%s\".\n", get_type_tpop_name(tp));
362                         break;
363         }
364         fputc('\n', f);
365 }
366
367 static void export_entity(io_env_t *env, ir_entity *ent)
368 {
369         ir_type *owner = get_entity_owner(ent);
370         fprintf(env->file, "\tentity %ld \"%s\" \"%s\" %ld %ld %d %u %s %s %s %s %s ",
371                         get_entity_nr(ent),
372                         get_entity_name(ent),
373                         ent->ld_name ? get_id_str(ent->ld_name) : "",
374                         get_type_nr(get_entity_type(ent)),
375                         get_type_nr(owner),
376                         get_entity_offset(ent),
377                         (unsigned) get_entity_offset_bits_remainder(ent),
378                         get_allocation_name(get_entity_allocation(ent)),
379                         get_visibility_name(get_entity_visibility(ent)),
380                         get_variability_name(get_entity_variability(ent)),
381                         get_peculiarity_name(get_entity_peculiarity(ent)),
382                         get_volatility_name(get_entity_volatility(ent)));
383
384         // TODO: inheritance stuff for class entities not supported yet
385         if(is_Class_type(owner) && owner != get_glob_type())
386                 printf("Inheritance of class entities not supported yet!\n");
387
388         if(get_entity_variability(ent) != variability_uninitialized
389                 && get_entity_visibility(ent) != visibility_external_allocated)
390         {
391                 if(is_compound_entity(ent))
392                 {
393                         if(has_entity_initializer(ent))
394                         {
395                                 fputs("initializer ", env->file);
396                                 write_initializer(env, get_entity_initializer(ent));
397                         }
398                         else
399                         {
400                                 fputs("noninitializer ", env->file);
401                                 int i, n = get_compound_ent_n_values(ent);
402                                 fprintf(env->file, "%d ", n);
403                                 for(i = 0; i < n; i++)
404                                 {
405                                         ir_entity *member = get_compound_ent_value_member(ent, i);
406                                         ir_node   *irn    = get_compound_ent_value(ent, i);
407                                         fprintf(env->file, "%ld %ld ", get_entity_nr(member), get_irn_node_nr(irn));
408                                 }
409                         }
410                 }
411                 else
412                 {
413                         ir_node *irn = get_atomic_ent_value(ent);
414                         fprintf(env->file, "%ld ", get_irn_node_nr(irn));
415                 }
416         }
417
418         fputc('\n', env->file);
419 }
420
421 static void export_type_or_ent(type_or_ent tore, void *ctx)
422 {
423         io_env_t *env = (io_env_t *) ctx;
424
425         switch(get_kind(tore.ent))
426         {
427                 case k_entity:
428                         export_entity(env, tore.ent);
429                         break;
430
431                 case k_type:
432                         export_type(env, tore.typ);
433                         break;
434
435                 default:
436                         printf("export_type_or_ent: Unknown type or entity.\n");
437                         break;
438         }
439 }
440
441 static void export_node(ir_node *irn, void *ctx)
442 {
443         io_env_t *env = (io_env_t *) ctx;
444         int i, n;
445         unsigned opcode = get_irn_opcode(irn);
446         char buf[1024];
447
448         if(env->ignoreblocks && opcode == iro_Block)
449                 return;
450
451         n = get_irn_arity(irn);
452
453         fprintf(env->file, "\t%s %ld [ ", get_irn_opname(irn), get_irn_node_nr(irn));
454
455         for(i = -1; i < n; i++)
456         {
457                 ir_node *pred = get_irn_n(irn, i);
458                 if(pred == NULL) {
459                         /* Anchor node may have NULL predecessors */
460                         assert(is_Anchor(irn));
461                         fputs("-1 ", env->file);
462                 } else {
463                         fprintf(env->file, "%ld ", get_irn_node_nr(pred));
464                 }
465         }
466
467         fprintf(env->file, "] { ");
468
469         switch(opcode)
470         {
471                 #include "gen_irio_export.inl"
472         }
473         fputs("}\n", env->file);
474 }
475
476 /** Exports the whole irp to the given file in a textual form. */
477 void ir_export(const char *filename)
478 {
479         io_env_t env;
480         int i, n_irgs = get_irp_n_irgs(), n_pseudoirgs = get_irp_n_pseudo_irgs();
481
482         env.file = fopen(filename, "wt");
483         if(!env.file)
484         {
485                 perror(filename);
486                 return;
487         }
488
489         fputs("typegraph {\n", env.file);
490
491         type_walk(NULL, export_type_or_ent, &env);
492         /* TODO: Visit frame types and "types for value params"? */
493
494         for(i = 0; i < n_irgs; i++)
495         {
496                 ir_graph *irg = get_irp_irg(i);
497
498                 fprintf(env.file, "}\n\nirg %ld {\n", get_entity_nr(get_irg_entity(irg)));
499
500                 env.ignoreblocks = 0;
501                 irg_block_walk_graph(irg, NULL, export_node, &env);
502
503                 env.ignoreblocks = 1;
504                 irg_walk_anchors(irg, NULL, export_node, &env);
505         }
506
507         fputs("}\n\nconstirg {\n", env.file);
508         walk_const_code(NULL, export_node, &env);
509         fputs("}\n", env.file);
510
511         fclose(env.file);
512 }
513
514 /** Exports the given irg to the given file. */
515 void ir_export_irg(ir_graph *irg, const char *filename)
516 {
517         io_env_t env;
518
519         env.file = fopen(filename, "wt");
520         if(!env.file)
521         {
522                 perror(filename);
523                 return;
524         }
525
526         fputs("typegraph {\n", env.file);
527
528         type_walk_irg(irg, NULL, export_type_or_ent, &env);
529
530         fprintf(env.file, "}\n\nirg %ld {\n", get_entity_nr(get_irg_entity(irg)));
531
532         env.ignoreblocks = 0;
533         irg_block_walk_graph(irg, NULL, export_node, &env);
534
535         env.ignoreblocks = 1;
536         irg_walk_anchors(irg, NULL, export_node, &env);
537
538         /* TODO: Only output needed constants */
539         fputs("}\n\nconstirg {\n", env.file);
540         walk_const_code(NULL, export_node, &env);
541         fputs("}\n", env.file);
542
543         fclose(env.file);
544 }
545
546 static int read_c(io_env_t *env)
547 {
548         int ch = fgetc(env->file);
549         switch(ch)
550         {
551                 case '\t':
552                         env->col += 4;
553                         break;
554
555                 case '\n':
556                         env->col = 0;
557                         env->line++;
558                         break;
559
560                 default:
561                         env->col++;
562                         break;
563         }
564         return ch;
565 }
566
567 /** Returns the first non-whitespace character or EOF. **/
568 static int skip_ws(io_env_t *env)
569 {
570         while(1)
571         {
572                 int ch = read_c(env);
573                 switch(ch)
574                 {
575                         case ' ':
576                         case '\t':
577                         case '\n':
578                         case '\r':
579                                 break;
580
581                         default:
582                                 return ch;
583                 }
584         }
585 }
586
587 static void skip_to(io_env_t *env, char to_ch)
588 {
589         int ch;
590         do
591         {
592                 ch = read_c(env);
593         }
594         while(ch != to_ch && ch != EOF);
595 }
596
597 static int expect_char(io_env_t *env, char ch)
598 {
599         int curch = skip_ws(env);
600         if(curch != ch)
601         {
602                 printf("Unexpected char '%c', expected '%c' in line %i:%i\n", curch, ch, env->line, env->col);
603                 return 0;
604         }
605         return 1;
606 }
607
608 #define EXPECT(c) if(expect_char(env, (c))) {} else return 0
609 #define EXPECT_OR_EXIT(c) if(expect_char(env, (c))) {} else exit(1)
610
611 inline static const char *read_str_to(io_env_t *env, char *buf, size_t bufsize)
612 {
613         size_t i;
614         for(i = 0; i < bufsize - 1; i++)
615         {
616                 int ch = read_c(env);
617                 if(ch == EOF) break;
618                 switch(ch)
619                 {
620                         case ' ':
621                         case '\t':
622                         case '\n':
623                         case '\r':
624                                 if(i != 0)
625                                         goto endofword;
626                                 i--;    // skip whitespace
627                                 break;
628
629                         default:
630                                 buf[i] = ch;
631                                 break;
632                 }
633         }
634 endofword:
635         buf[i] = 0;
636         return buf;
637 }
638
639 static const char *read_str(io_env_t *env)
640 {
641         static char buf[1024];
642         return read_str_to(env, buf, sizeof(buf));
643 }
644
645 static const char *read_qstr_to(io_env_t *env, char *buf, size_t bufsize)
646 {
647         size_t i;
648         EXPECT_OR_EXIT('\"');
649         for(i = 0; i < bufsize - 1; i++)
650         {
651                 int ch = read_c(env);
652                 if(ch == EOF)
653                 {
654                         printf("Unexpected end of quoted string!\n");
655                         exit(1);
656                 }
657                 if(ch == '\"') break;
658
659                 buf[i] = ch;
660         }
661         if(i == bufsize - 1)
662         {
663                 printf("Quoted string too long!\n");
664                 exit(1);
665         }
666         buf[i] = 0;
667         return buf;
668 }
669
670 static long read_long2(io_env_t *env, char **endptr)
671 {
672         static char buf[1024];
673         return strtol(read_str_to(env, buf, sizeof(buf)), endptr, 0);
674 }
675
676 static long read_long(io_env_t *env)
677 {
678         return read_long2(env, NULL);
679 }
680
681 static ir_node *get_node_or_null(io_env_t *env, long nodenr)
682 {
683         ir_node *node = (ir_node *) get_id(env, nodenr);
684         if(node && node->kind != k_ir_node)
685         {
686                 panic("Irn ID %ld collides with something else in line %i:%i\n", nodenr, env->line, env->col);
687         }
688         return node;
689 }
690
691 static ir_node *get_node(io_env_t *env, long nodenr)
692 {
693         ir_node *node = get_node_or_null(env, nodenr);
694         if(!node)
695                 panic("Unknown node: %ld in line %i:%i\n", nodenr, env->line, env->col);
696
697         return node;
698 }
699
700 static ir_node *get_node_or_dummy(io_env_t *env, long nodenr)
701 {
702         ir_node *node = get_node_or_null(env, nodenr);
703         if(!node)
704         {
705                 node = new_Dummy(mode_X);
706                 set_id(env, nodenr, node);
707         }
708         return node;
709 }
710
711 static ir_type *get_type(io_env_t *env, long typenr)
712 {
713         ir_type *type = (ir_type *) get_id(env, typenr);
714         if(!type)
715         {
716                 panic("Unknown type: %ld in line %i:%i\n", typenr, env->line, env->col);
717         }
718         else if(type->kind != k_type)
719         {
720                 panic("Type ID %ld collides with something else in line %i:%i\n", typenr, env->line, env->col);
721         }
722         return type;
723 }
724
725 static ir_type *read_type(io_env_t *env)
726 {
727         return get_type(env, read_long(env));
728 }
729
730 static ir_entity *get_entity(io_env_t *env, long entnr)
731 {
732         ir_entity *entity = (ir_entity *) get_id(env, entnr);
733         if(!entity)
734         {
735                 printf("Unknown entity: %ld in line %i:%i\n", entnr, env->line, env->col);
736                 exit(1);
737         }
738         else if(entity->kind != k_entity)
739         {
740                 panic("Entity ID %ld collides with something else in line %i:%i\n", entnr, env->line, env->col);
741         }
742         return entity;
743 }
744
745 static ir_entity *read_entity(io_env_t *env)
746 {
747         return get_entity(env, read_long(env));
748 }
749
750 static ir_mode *read_mode(io_env_t *env)
751 {
752         static char buf[128];
753         int i, n;
754
755         read_str_to(env, buf, sizeof(buf));
756
757         n = get_irp_n_modes();
758         for(i = 0; i < n; i++)
759         {
760                 ir_mode *mode = get_irp_mode(i);
761                 if(!strcmp(buf, get_mode_name(mode)))
762                         return mode;
763         }
764
765         printf("Unknown mode \"%s\" in line %i:%i\n", buf, env->line, env->col);
766         return mode_ANY;
767 }
768
769 static const char *get_typetag_name(typetag_t typetag)
770 {
771         switch(typetag)
772         {
773                 case tt_iro:         return "opcode";
774                 case tt_tpo:         return "type";
775                 case tt_align:       return "align";
776                 case tt_allocation:  return "allocation";
777                 case tt_peculiarity: return "peculiarity";
778                 case tt_pin_state:   return "pin state";
779                 case tt_type_state:  return "type state";
780                 case tt_variability: return "variability";
781                 case tt_visibility:  return "visibility";
782                 case tt_volatility:  return "volatility";
783                 default: return "<UNKNOWN>";
784         }
785 }
786
787 /**
788  * Read and decode an enum constant.
789  */
790 static unsigned read_enum(io_env_t *env, typetag_t typetag)
791 {
792         static char buf[128];
793         unsigned code = symbol(read_str_to(env, buf, sizeof(buf)), typetag);
794         if(code != SYMERROR)
795                 return code;
796
797         printf("Invalid %s: \"%s\" in %i:%i\n", get_typetag_name(typetag), buf, env->line, env->col);
798         return 0;
799 }
800
801 #define read_align(env)       ((ir_align)       read_enum(env, tt_align))
802 #define read_allocation(env)  ((ir_allocation)  read_enum(env, tt_allocation))
803 #define read_peculiarity(env) ((ir_peculiarity) read_enum(env, tt_peculiarity))
804 #define read_pin_state(env)   ((op_pin_state)   read_enum(env, tt_pin_state))
805 #define read_type_state(env)  ((ir_type_state)  read_enum(env, tt_type_state))
806 #define read_variability(env) ((ir_variability) read_enum(env, tt_variability))
807 #define read_visibility(env)  ((ir_visibility)  read_enum(env, tt_visibility))
808 #define read_volatility(env)  ((ir_volatility)  read_enum(env, tt_volatility))
809
810 static ir_cons_flags get_cons_flags(io_env_t *env)
811 {
812         ir_cons_flags flags = cons_none;
813
814         op_pin_state pinstate = read_pin_state(env);
815         switch(pinstate)
816         {
817                 case op_pin_state_floats: flags |= cons_floats; break;
818                 case op_pin_state_pinned: break;
819                 default:
820                         panic("Error in %i:%i: Invalid pinstate: %s", env->line, env->col, get_op_pin_state_name(pinstate));
821         }
822
823         if(read_volatility(env) == volatility_is_volatile) flags |= cons_volatile;
824         if(read_align(env) == align_non_aligned) flags |= cons_unaligned;
825
826         return flags;
827 }
828
829 static tarval *read_tv(io_env_t *env)
830 {
831         static char buf[128];
832         ir_mode *tvmode = read_mode(env);
833         read_str_to(env, buf, sizeof(buf));
834         return new_tarval_from_str(buf, strlen(buf), tvmode);
835 }
836
837 /** Reads a type description and remembers it by its id. */
838 static void import_type(io_env_t *env)
839 {
840         char           buf[1024];
841         int            i;
842         ir_type       *type;
843         long           typenr = read_long(env);
844         const char    *tpop   = read_str(env);
845         const char    *name   = read_qstr_to(env, buf, sizeof(buf));
846         unsigned       size   = (unsigned) read_long(env);
847         unsigned       align  = (unsigned) read_long(env);
848         ir_type_state  state  = read_type_state(env);
849         ir_visibility  vis    = read_visibility(env);
850
851         ident         *id     = new_id_from_str(name);
852
853         switch(symbol(tpop, tt_tpo))
854         {
855                 case tpo_array:
856                 {
857                         int ndims = (int) read_long(env);
858                         long elemtypenr = read_long(env);
859                         ir_type *elemtype = get_type(env, elemtypenr);
860
861                         type = new_type_array(id, ndims, elemtype);
862                         for(i = 0; i < ndims; i++)
863                         {
864                                 const char *str = read_str(env);
865                                 if(strcmp(str, "unknown"))
866                                 {
867                                         long lowerbound = strtol(str, NULL, 0);
868                                         set_array_lower_bound_int(type, i, lowerbound);
869                                 }
870                                 str = read_str(env);
871                                 if(strcmp(str, "unknown"))
872                                 {
873                                         long upperbound = strtol(str, NULL, 0);
874                                         set_array_upper_bound_int(type, i, upperbound);
875                                 }
876                         }
877                         set_type_size_bytes(type, size);
878                         break;
879                 }
880
881                 case tpo_class:
882                         type = new_type_class(id);
883                         set_type_size_bytes(type, size);
884                         break;
885
886                 case tpo_method:
887                 {
888                         int nparams  = (int) read_long(env);
889                         int nresults = (int) read_long(env);
890
891                         type = new_type_method(id, nparams, nresults);
892
893                         for(i = 0; i < nparams; i++)
894                         {
895                                 long     typenr = read_long(env);
896                                 ir_type *paramtype = get_type(env, typenr);
897
898                                 set_method_param_type(type, i, paramtype);
899                         }
900                         for(i = 0; i < nresults; i++)
901                         {
902                                 long typenr = read_long(env);
903                                 ir_type *restype = get_type(env, typenr);
904
905                                 set_method_res_type(type, i, restype);
906                         }
907                         break;
908                 }
909
910                 case tpo_pointer:
911                 {
912                         ir_mode *mode = read_mode(env);
913                         ir_type *pointsto = get_type(env, read_long(env));
914                         type = new_type_pointer(id, pointsto, mode);
915                         break;
916                 }
917
918                 case tpo_primitive:
919                 {
920                         ir_mode *mode = read_mode(env);
921                         type = new_type_primitive(id, mode);
922                         break;
923                 }
924
925                 case tpo_struct:
926                         type = new_type_struct(id);
927                         set_type_size_bytes(type, size);
928                         break;
929
930                 case tpo_union:
931                         type = new_type_union(id);
932                         set_type_size_bytes(type, size);
933                         break;
934
935                 case tpo_unknown:
936                         return;   // ignore unknown type
937
938                 default:
939                         if(typenr != 0)  // ignore global type
940                                 printf("Unknown type kind: \"%s\" in line %i:%i\n", tpop, env->line, env->col);
941                         skip_to(env, '\n');
942                         return;
943         }
944
945         set_type_alignment_bytes(type, align);
946         set_type_visibility(type, vis);
947
948         if(state == layout_fixed)
949                 ARR_APP1(ir_type *, env->fixedtypes, type);
950
951         set_id(env, typenr, type);
952         printf("Insert type %s %ld\n", name, typenr);
953 }
954
955 /** Reads an entity description and remembers it by its id. */
956 static void import_entity(io_env_t *env)
957 {
958         char          buf[1024], buf2[1024];
959         long          entnr       = read_long(env);
960         const char   *name        = read_qstr_to(env, buf, sizeof(buf));
961         const char   *ld_name     = read_qstr_to(env, buf2, sizeof(buf2));
962         long          typenr      = read_long(env);
963         long          ownertypenr = read_long(env);
964
965         ir_type   *type      = get_type(env, typenr);
966         ir_type   *ownertype = !ownertypenr ? get_glob_type() : get_type(env, ownertypenr);
967         ir_entity *entity    = new_entity(ownertype, new_id_from_str(name), type);
968
969         if(*ld_name) set_entity_ld_ident(entity, new_id_from_str(ld_name));
970         set_entity_offset     (entity, (int) read_long(env));
971         set_entity_offset_bits_remainder(entity, (unsigned char) read_long(env));
972         set_entity_allocation (entity, read_allocation(env));
973         set_entity_visibility (entity, read_visibility(env));
974         set_entity_variability(entity, read_variability(env));
975         set_entity_peculiarity(entity, read_peculiarity(env));
976         set_entity_volatility (entity, read_volatility(env));
977
978         if(get_entity_variability(entity) != variability_uninitialized
979                 && get_entity_visibility(entity) != visibility_external_allocated)
980         {
981                 if(is_compound_entity(entity))
982                 {
983                         if(!strcmp(read_str_to(env, buf2, sizeof(buf2)), "initializer"))
984                         {
985                                 panic("moep");
986                         }
987                         else
988                         {
989                                 int i, n = (int) read_long(env);
990                                 for(i = 0; i < n; i++)
991                                 {
992                                         ir_entity *member = get_entity(env, read_long(env));
993                                         ir_node   *irn    = get_node_or_dummy(env, read_long(env));
994                                         add_compound_ent_value(entity, irn, member);
995                                 }
996                         }
997                 }
998                 else
999                 {
1000                         ir_node *irn = get_node_or_dummy(env, read_long(env));
1001                         set_atomic_ent_value(entity, irn);
1002                 }
1003         }
1004
1005         set_id(env, entnr, entity);
1006         printf("Insert entity %s %ld\n", name, entnr);
1007 }
1008
1009 /** Parses the whole type graph. */
1010 static int parse_typegraph(io_env_t *env)
1011 {
1012         const char *kind;
1013         long curfpos;
1014
1015         EXPECT('{');
1016
1017         curfpos = ftell(env->file);
1018
1019         current_ir_graph = get_const_code_irg();
1020
1021         // parse all types first
1022         while(1)
1023         {
1024                 kind = read_str(env);
1025                 if(kind[0] == '}' && !kind[1]) break;
1026
1027                 if(!strcmp(kind, "type"))
1028                         import_type(env);
1029                 else
1030                         skip_to(env, '\n');
1031         }
1032
1033         // now parse rest
1034         fseek(env->file, curfpos, SEEK_SET);
1035         while(1)
1036         {
1037                 kind = read_str(env);
1038                 if(kind[0] == '}' && !kind[1]) break;
1039
1040                 if(!strcmp(kind, "type"))
1041                         skip_to(env, '\n');
1042                 else if(!strcmp(kind, "entity"))
1043                         import_entity(env);
1044                 else
1045                 {
1046                         printf("Type graph element not supported yet: \"%s\"\n", kind);
1047                         skip_to(env, '\n');
1048                 }
1049         }
1050         return 1;
1051 }
1052
1053 static int read_node_header(io_env_t *env, long *nodenr, long **preds, const char **nodename)
1054 {
1055         int numpreds;
1056         *nodename = read_str(env);
1057         if((*nodename)[0] == '}' && !(*nodename)[1]) return -1;  // end-of-graph
1058
1059         *nodenr = read_long(env);
1060
1061         ARR_RESIZE(ir_node *, *preds, 0);
1062
1063         EXPECT('[');
1064         for(numpreds = 0; !feof(env->file); numpreds++)
1065         {
1066                 char *endptr;
1067                 ARR_APP1(long, *preds, read_long2(env, &endptr));
1068                 if(*endptr == ']') break;
1069         }
1070         return numpreds;
1071 }
1072
1073 /** Parses an IRG. */
1074 static int parse_graph(io_env_t *env, ir_graph *irg)
1075 {
1076         long       *preds = NEW_ARR_F(long, 16);
1077         ir_node   **prednodes = NEW_ARR_F(ir_node *, 16);
1078         int         i, numpreds, ret = 1;
1079         long        nodenr;
1080         const char *nodename;
1081         ir_node    *node, *newnode;
1082
1083         current_ir_graph = irg;
1084
1085         EXPECT('{');
1086
1087         while(1)
1088         {
1089                 numpreds = read_node_header(env, &nodenr, &preds, &nodename);
1090                 if(numpreds == -1) break;  // end-of-graph
1091                 if(!numpreds)
1092                 {
1093                         printf("Node %s %ld is missing predecessors!", nodename, nodenr);
1094                         ret = 0;
1095                         break;
1096                 }
1097
1098                 ARR_RESIZE(ir_node *, prednodes, numpreds);
1099                 for(i = 0; i < numpreds - 1; i++)
1100                         prednodes[i] = get_node_or_dummy(env, preds[i + 1]);
1101
1102                 node = get_node_or_null(env, nodenr);
1103                 newnode = NULL;
1104
1105                 EXPECT('{');
1106
1107                 switch(symbol(nodename, tt_iro))
1108                 {
1109                         case iro_End:
1110                         {
1111                                 ir_node *newendblock = get_node(env, preds[0]);
1112                                 newnode = get_irg_end(current_ir_graph);
1113                                 exchange(get_nodes_block(newnode), newendblock);
1114                                 for(i = 0; i < numpreds - 1; i++)
1115                                         add_irn_n(newnode, prednodes[i]);
1116                                 break;
1117                         }
1118
1119                         case iro_Start:
1120                         {
1121                                 ir_node *newstartblock = get_node(env, preds[0]);
1122                                 newnode = get_irg_start(current_ir_graph);
1123                                 exchange(get_nodes_block(newnode), newstartblock);
1124                                 break;
1125                         }
1126
1127                         case iro_Block:
1128                         {
1129                                 if(preds[0] != nodenr)
1130                                 {
1131                                         printf("Invalid block: preds[0] != nodenr (%ld != %ld)\n",
1132                                                 preds[0], nodenr);
1133                                         ret = 0;
1134                                         goto endloop;
1135                                 }
1136
1137                                 newnode = new_Block(numpreds - 1, prednodes);
1138                                 break;
1139                         }
1140
1141                         case iro_Anchor:
1142                                 newnode = current_ir_graph->anchor;
1143                                 for(i = 0; i < numpreds - 1; i++)
1144                                         set_irn_n(newnode, i, prednodes[i]);
1145                                 set_irn_n(newnode, -1, get_node(env, preds[0]));
1146                                 break;
1147
1148                         case iro_SymConst:
1149                         {
1150                                 long entnr = read_long(env);
1151                                 union symconst_symbol sym;
1152                                 sym.entity_p = get_entity(env, entnr);
1153                                 newnode = new_SymConst(mode_P, sym, symconst_addr_ent);
1154                                 break;
1155                         }
1156
1157                         #include "gen_irio_import.inl"
1158
1159                         default:
1160                                 goto notsupported;
1161                 }
1162
1163                 EXPECT('}');
1164
1165                 if(!newnode)
1166                 {
1167 notsupported:
1168                         panic("Node type not supported yet: %s in line %i:%i\n", nodename, env->line, env->col);
1169                 }
1170
1171                 if(node)
1172                         exchange(node, newnode);
1173                 /* Always update hash entry to avoid more uses of id nodes */
1174                 set_id(env, nodenr, newnode);
1175                 //printf("Insert %s %ld\n", nodename, nodenr);
1176         }
1177
1178 endloop:
1179         DEL_ARR_F(preds);
1180         DEL_ARR_F(prednodes);
1181
1182         return ret;
1183 }
1184
1185 /** Imports an previously exported textual representation of an (maybe partial) irp */
1186 void ir_import(const char *filename)
1187 {
1188         int oldoptimize = get_optimize();
1189         firm_verification_t oldver = get_node_verification_mode();
1190         io_env_t ioenv;
1191         io_env_t *env = &ioenv;
1192         int i, n;
1193
1194         symtbl_init();
1195
1196         memset(env, 0, sizeof(*env));
1197         env->idset = new_set(id_cmp, 128);
1198         env->fixedtypes = NEW_ARR_F(ir_type *, 0);
1199
1200         env->file = fopen(filename, "rt");
1201         if(!env->file)
1202         {
1203                 perror(filename);
1204                 exit(1);
1205         }
1206
1207         set_optimize(0);
1208         do_node_verification(FIRM_VERIFICATION_OFF);
1209
1210         while(1)
1211         {
1212                 const char *str = read_str(env);
1213                 if(!*str) break;
1214                 if(!strcmp(str, "typegraph"))
1215                 {
1216                         if(!parse_typegraph(env)) break;
1217                 }
1218                 else if(!strcmp(str, "irg"))
1219                 {
1220                         ir_graph *irg = new_ir_graph(get_entity(env, read_long(env)), 0);
1221                         if(!parse_graph(env, irg)) break;
1222                 }
1223                 else if(!strcmp(str, "constirg"))
1224                 {
1225                         if(!parse_graph(env, get_const_code_irg())) break;
1226                 }
1227         }
1228
1229         n = ARR_LEN(env->fixedtypes);
1230         for(i = 0; i < n; i++)
1231                 set_type_state(env->fixedtypes[i], layout_fixed);
1232
1233         DEL_ARR_F(env->fixedtypes);
1234
1235         del_set(env->idset);
1236
1237         irp_finalize_cons();
1238
1239         do_node_verification(oldver);
1240         set_optimize(oldoptimize);
1241
1242         fclose(env->file);
1243 }