b81883abbb6267ab764136d1e92f96652d6afb3a
[libfirm] / scripts / gen_ir_io.py
1 #!/usr/bin/python
2 import sys
3 from jinja2 import Environment, Template
4 import ir_spec
5
6 def format_args(arglist):
7         #argstrings = map(lambda arg : arg["name"], arglist)
8         #return ", ".join(argstrings)
9         s = ", ".join(arglist)
10         if len(s) == 0:
11           return "";
12         return ", " + s;
13
14 def format_ifnset(string, node, key):
15         if key in node:
16                 return ""
17         return string
18
19 def format_block(node):
20         if node.get("knownBlock"):
21                 return ""
22         else:
23                 return ", get_node(env, preds[0])"
24
25 env = Environment()
26 env.filters['args']   = format_args
27 env.filters['ifnset'] = format_ifnset
28 env.filters['block']  = format_block
29
30 def get_io_type(type, attrname, nodename):
31         if type == "tarval*":
32                 importcmd = "tarval *%s = read_tv(env);" % attrname
33                 exportcmd = "write_tarval(env, %(val)s);";
34         elif type == "ir_mode*":
35                 importcmd = "ir_mode *%s = read_mode(env);" % attrname
36                 exportcmd = "write_mode(env, %(val)s);"
37         elif type == "ir_entity*":
38                 importcmd = "ir_entity *%s = read_entity(env);" % attrname
39                 exportcmd = """fprintf(env->file, "%%ld ", get_entity_nr(%(val)s));"""
40         elif type == "ir_type*":
41                 importcmd = "ir_type *%s = read_type(env);" % attrname
42                 exportcmd = """fprintf(env->file, "%%ld ", get_type_nr(%(val)s));"""
43         elif type == "long" and nodename == "Proj":
44                 importcmd = "long %s = read_long(env);" % attrname
45                 exportcmd = """fprintf(env->file, "%%ld ", %(val)s);"""
46         elif type == "pn_Cmp" or type == "ir_where_alloc":
47                 importcmd = "%s %s = (%s) read_long(env);" % (type, attrname, type)
48                 exportcmd = """fprintf(env->file, "%%ld ", (long) %(val)s);"""
49         elif type == "cons_flags" and nodename == "Store":
50                 importcmd = "ir_cons_flags %s = get_cons_flags(env);" % attrname
51                 exportcmd = """write_pin_state(env, irn);
52                         write_volatility(env, irn);
53                         write_align(env, irn);"""
54         elif type == "cons_flags" and nodename == "Load":
55                 importcmd = "ir_cons_flags %s = get_cons_flags(env);" % attrname
56                 exportcmd = """write_pin_state(env, irn);
57                         write_volatility(env, irn);
58                         write_align(env, irn);"""
59         elif type == "op_pin_state":
60                 importcmd = "op_pin_state %s = read_pin_state(env);" % attrname
61                 exportcmd = "write_pin_state(env, irn);"
62         elif type == "ir_builtin_kind":
63                 importcmd = "ir_builtin_kind %s = read_builtin_kind(env);" % attrname
64                 exportcmd = "write_builtin_kind(env, irn);"
65         else:
66                 print "UNKNOWN TYPE: %s" % type
67                 importcmd = """// BAD: %s %s
68                         %s %s = (%s) 0;""" % (type, attrname, type, attrname, type)
69                 exportcmd = "// BAD: %s" % type
70         return (importcmd, exportcmd)
71
72 """     if type == "ir_type*":
73                 java_type    = "firm.Type"
74                 wrap_type    = "Pointer"
75                 to_wrapper   = "%s.ptr"
76                 from_wrapper = "firm.Type.createWrapper(%s)"
77         elif type == "ir_mode*":
78                 java_type    = "firm.Mode"
79                 wrap_type    = "Pointer"
80                 to_wrapper   = "%s.ptr"
81                 from_wrapper = "new firm.Mode(%s)"
82         elif type == "tarval*":
83                 java_type    = "firm.TargetValue"
84                 wrap_type    = "Pointer"
85                 to_wrapper   = "%s.ptr"
86                 from_wrapper = "new firm.TargetValue(%s)"
87         elif type == "pn_Cmp":
88                 java_type    = "int"
89                 wrap_type    = "int"
90                 to_wrapper   = "%s"
91                 from_wrapper = "%s"
92         elif type == "long":
93                 java_type    = "int"
94                 wrap_type    = "com.sun.jna.NativeLong"
95                 to_wrapper   = "new com.sun.jna.NativeLong(%s)"
96                 from_wrapper = "%s.intValue()"
97         elif type == "cons_flags":
98                 java_type    = "firm.bindings.binding_ircons.ir_cons_flags"
99                 wrap_type    = "int"
100                 to_wrapper   = "%s.val"
101                 from_wrapper = "firm.bindings.binding_ircons.ir_cons_flags.getEnum(%s)"
102         elif type == "ir_where_alloc":
103                 java_type    = "firm.bindings.binding_ircons.ir_where_alloc"
104                 wrap_type    = "int"
105                 to_wrapper   = "%s.val"
106                 from_wrapper = "firm.bindings.binding_ircons.ir_where_alloc.getEnum(%s)"
107         elif type == "ir_entity*":
108                 java_type    = "firm.Entity"
109                 wrap_type    = "Pointer"
110                 to_wrapper   = "%s.ptr"
111                 from_wrapper = "new firm.Entity(%s)"
112         else:
113                 print "UNKNOWN TYPE"
114                 java_type    = "BAD"
115                 wrap_type    = "BAD"
116                 to_wrapper   = "BAD"
117                 from_wrapper = "BAD"
118         return (java_type,wrap_type,to_wrapper,from_wrapper)"""
119
120 def prepare_attr(nodename, attr):
121         (importcmd,exportcmd) = get_io_type(attr["type"], attr["name"], nodename)
122         attr["importcmd"] = importcmd
123         attr["exportcmd"] = exportcmd % {"val": "get_%s_%s(irn)" % (nodename, attr["name"])}
124
125 def preprocess_node(nodename, node):
126         if "is_a" in node:
127                 parent = ir_spec.nodes[node["is_a"]]
128                 node["ins"] = parent["ins"]
129                 if "outs" in parent:
130                         node["outs"] = parent["outs"]
131         if "ins" not in node:
132                 node["ins"] = []
133         if "outs" in node:
134                 node["mode"] = "mode_T"
135         if "arity" not in node:
136                 node["arity"] = len(node["ins"])
137         if "attrs" not in node:
138                 node["attrs"] = []
139         if "constructor_args" not in node:
140                 node["constructor_args"] = []
141
142         # construct node arguments
143         arguments = [ ]
144         i = 0
145         for input in node["ins"]:
146                 arguments.append("prednodes[%i]" % i)
147                 i += 1
148
149         # Special case for Builtin...
150         if nodename == "Builtin":
151                 for attr in node["attrs"]:
152                         if attr["name"] == "kind":
153                                 prepare_attr(nodename, attr)
154                                 arguments.append(attr["name"])
155
156         if node["arity"] == "variable" or node["arity"] == "dynamic":
157                 arguments.append("numpreds - %i" % (i + 1))
158                 arguments.append("prednodes + %i" % i)
159
160         if "mode" not in node:
161                 arguments.append("mode")
162
163         for attr in node["attrs"]:
164                 if nodename == "Builtin" and attr["name"] == "kind":
165                         continue
166                 prepare_attr(nodename, attr)
167                 arguments.append(attr["name"])
168
169         for arg in node["constructor_args"]:
170                 prepare_attr(nodename, arg)
171                 arguments.append(arg["name"])
172
173         node["arguments"] = arguments
174
175 export_attrs_template = env.from_string('''
176         case iro_{{nodename}}:
177                 {{"write_mode(env, get_irn_mode(irn));"|ifnset(node,"mode")}}
178                 {% for attr in node.attrs %}{{attr.exportcmd}}
179                 {% endfor %}
180                 {% for attr in node.constructor_args %}{{attr.exportcmd}}
181                 {% endfor %}break;''')
182
183 import_attrs_template = env.from_string('''
184         case iro_{{nodename}}:
185         {
186                 {{"ir_mode *mode = read_mode(env);"|ifnset(node,"mode")}}
187                 {% for attr in node.attrs %}{{attr.importcmd}}
188                 {% endfor %}
189                 {% for attr in node.constructor_args %}{{attr.importcmd}}
190                 {% endfor %}newnode = new_r_{{nodename}}(current_ir_graph{{node|block}}{{node["arguments"]|args}});
191                 break;
192         }
193 ''')
194
195 def main(argv):
196         """the main function"""
197
198         if len(argv) < 3:
199                 print "usage: %s specname(ignored) destdirectory" % argv[0]
200                 sys.exit(1)
201
202         gendir = argv[2]
203
204         file = open(gendir + "/gen_irio_export.inl", "w");
205         for nodename, node in ir_spec.nodes.iteritems():
206                 preprocess_node(nodename, node)
207                 if not "abstract" in node:
208                         file.write(export_attrs_template.render(vars()))
209         file.write("\n")
210         file.close()
211
212         file = open(gendir + "/gen_irio_import.inl", "w");
213         for nodename, node in ir_spec.nodes.iteritems():
214                 if not "abstract" in node and nodename != "Start" and nodename != "End" and nodename != "Anchor" and nodename != "SymConst" and nodename != "Block":
215                         file.write(import_attrs_template.render(vars()))
216         # TODO: SymConst
217         file.write("\n")
218         file.close()
219
220         file = open(gendir + "/gen_irio_lex.inl", "w");
221         for nodename, node in ir_spec.nodes.iteritems():
222                 if not "abstract" in node:
223                         file.write("\tINSERT(\"" + nodename + "\", tt_iro, iro_" + nodename + ");\n");
224         file.close()
225
226 if __name__ == "__main__":
227         main(sys.argv)