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