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