rename popcnt to popcount; avoid inline assembly in favor of gcc builtin functions
[libfirm] / scripts / gen_ir.py
1 #!/usr/bin/env python
2 import sys
3 import re
4 from jinja2 import Environment, Template
5 from jinja2.filters import do_dictsort
6 from spec_util import is_dynamic_pinned, verify_node, isAbstract, setdefault
7 from ir_spec import nodes
8
9 def format_parameterlist(parameterlist):
10         return "\n".join(parameterlist)
11
12 def format_nodearguments(node):
13         arguments = map(lambda arg: arg["name"], node.arguments)
14         return format_parameterlist(arguments)
15
16 def format_nodeparameters(node):
17         parameters = map(lambda arg: arg["type"] + " " + arg["name"], node.arguments)
18         return format_parameterlist(parameters)
19
20 def format_blockparameter(node):
21         if hasattr(node, "knownBlock"):
22                 if hasattr(node, "knownGraph"):
23                         return ""
24                 return "ir_graph *irg"
25         else:
26                 return "ir_node *block"
27
28 def format_blockargument(node):
29         if hasattr(node, "knownBlock"):
30                 if hasattr(node, "knownGraph"):
31                         return ""
32                 return "irg"
33         else:
34                 return "block"
35
36 def format_irgassign(node):
37         if hasattr(node, "knownGraph"):
38                 return "ir_graph *irg = %s;\n" % node.graph
39
40         if hasattr(node, "knownBlock"):
41                 return ""
42         else:
43                 return "ir_graph *irg = get_Block_irg(block);\n"
44
45 def format_curblock(node):
46         if hasattr(node, "knownBlock"):
47                 if hasattr(node, "knownGraph"):
48                         return ""
49                 return "current_ir_graph"
50         else:
51                 return "current_ir_graph->current_block"
52
53 def format_insdecl(node):
54         arity = node.arity
55         if arity == "variable" and len(node.ins) == 0 or arity == "dynamic" or arity == 0:
56                 return ""
57
58         if arity == "variable":
59                 insarity = len(node.ins)
60                 res = "int r_arity = arity + " + `insarity` + ";\n\tir_node **r_in;\n\t" \
61                         + "NEW_ARR_A(ir_node *, r_in, r_arity);\n\t"
62                 i = 0
63                 for input in node.ins:
64                         res += "r_in[" + `i` + "] = irn_" + input + ";\n\t"
65                         i += 1
66                 res += "memcpy(&r_in[" + `insarity` + "], in, sizeof(ir_node *) * arity);\n\t"
67         else:
68                 res = "ir_node *in[" + `arity` + "];\n\t"
69                 i = 0
70                 for input in node.ins:
71                         res += "in[" + `i` + "] = irn_" + input + ";\n\t"
72                         i += 1
73         return res
74
75 def format_arity_and_ins(node):
76         arity = node.arity
77         if arity == "dynamic":
78                 return "-1, NULL"
79         elif arity == "variable":
80                 if len(node.ins) == 0:
81                         return "arity, in"
82                 else:
83                         return "r_arity, r_in"
84         elif arity == 0:
85                 return "0, NULL"
86         else:
87                 return `arity` + ", in"
88
89 def format_arity(node):
90         if hasattr(node, "arity_override"):
91                 return node.arity_override
92         arity = node.arity
93         if arity == "dynamic":
94                 return "oparity_dynamic"
95         if arity == "variable":
96                 return "oparity_variable"
97         if arity == 0:
98                 return "oparity_zero"
99         if arity == 1:
100                 return "oparity_unary"
101         if arity == 2:
102                 return "oparity_binary"
103         if arity == 3:
104                 return "oparity_trinary"
105         return "oparity_any"
106
107 def format_pinned(node):
108         pinned = node.pinned
109         if pinned == "yes":
110                 return "op_pin_state_pinned"
111         if pinned == "no":
112                 return "op_pin_state_floats"
113         if pinned == "exception":
114                 return "op_pin_state_exc_pinned"
115         if pinned == "memory":
116                 return "op_pin_state_mem_pinned"
117         print "WARNING: Unknown pinned state %s in format pined" % pinned
118         return ""
119
120 def format_flags(node):
121         flags = map(lambda x : "irop_flag_" + x, node.flags)
122         if flags == []:
123                 flags = [ "irop_flag_none" ]
124         return " | ".join(flags)
125
126 def format_attr_size(node):
127         if not hasattr(node, "attr_struct"):
128                 return "0"
129         return "sizeof(%s)" % node.attr_struct
130
131 def format_opindex(node):
132         if hasattr(node, "op_index"):
133                 return node.op_index
134         return "-1"
135
136 def filter_isnot(list, flag):
137         result = []
138         for node in list:
139                 if hasattr(node, flag):
140                         continue
141                 result.append(node)
142         return result
143
144 def format_arguments(string, voidwhenempty = False):
145         args = re.split('\s*\n\s*', string)
146         if args[0] == '':
147                 args = args[1:]
148         if len(args) > 0 and args[-1] == '':
149                 args = args[:-1]
150         if len(args) == 0 and voidwhenempty:
151                 return "void"
152         return ", ".join(args)
153
154 def format_parameters(string):
155         return format_arguments(string, voidwhenempty = True)
156
157 env = Environment()
158 env.filters['parameterlist']  = format_parameterlist
159 env.filters['nodearguments']  = format_nodearguments
160 env.filters['nodeparameters'] = format_nodeparameters
161 env.filters['blockparameter'] = format_blockparameter
162 env.filters['blockargument']  = format_blockargument
163 env.filters['irgassign']      = format_irgassign
164 env.filters['curblock']       = format_curblock
165 env.filters['insdecl']        = format_insdecl
166 env.filters['arity_and_ins']  = format_arity_and_ins
167 env.filters['arity']          = format_arity
168 env.filters['pinned']         = format_pinned
169 env.filters['flags']          = format_flags
170 env.filters['attr_size']      = format_attr_size
171 env.filters['opindex']        = format_opindex
172 env.filters['isnot']          = filter_isnot
173 env.filters['arguments']      = format_arguments
174 env.filters['parameters']     = format_parameters
175
176 def prepare_attr(attr):
177         if "init" in attr:
178                 return dict(type = attr["type"], name = attr["name"], init = attr["init"])
179         else:
180                 return dict(type = attr["type"], name = attr["name"])
181
182 def preprocess_node(node):
183         verify_node(node)
184
185         setdefault(node, "attrs_name", node.name.lower())
186         setdefault(node, "block", "block")
187
188         # construct node arguments
189         arguments = [ ]
190         initattrs = [ ]
191         specialconstrs = [ ]
192         for input in node.ins:
193                 arguments.append(dict(type = "ir_node *", name = "irn_" + input))
194
195         if node.arity == "variable" or node.arity == "dynamic":
196                 arguments.append(dict(type = "int", name = "arity"))
197                 arguments.append(dict(type = "ir_node **", name = "in"))
198
199         if not hasattr(node, "mode"):
200                 arguments.append(dict(type = "ir_mode *", name = "mode"))
201                 node.mode = "mode"
202
203         attrs_with_special = 0
204         for attr in node.attrs:
205                 attr.setdefault("initname", "." + attr["name"])
206
207                 if "special" in attr:
208                         if not "init" in attr:
209                                 print "Node type %s has an attribute with a \"special\" entry but without \"init\"" % node.name
210                                 sys.exit(1)
211
212                         if attrs_with_special != 0:
213                                 print "Node type %s has more than one attribute with a \"special\" entry" % node.name
214                                 sys.exit(1)
215
216                         attrs_with_special += 1
217
218                         if "prefix" in attr["special"]:
219                                 specialname = attr["special"]["prefix"] + node.name
220                         elif "suffix" in attr["special"]:
221                                 specialname = node.name + attr["special"]["suffix"]
222                         else:
223                                 print "Unknown special constructor type for node type %s" % node.name
224                                 sys.exit(1)
225
226                         specialconstrs.append(
227                                 dict(
228                                         constrname = specialname,
229                                         attr = attr
230                                 )
231                         )
232                 elif not "init" in attr:
233                         arguments.append(prepare_attr(attr))
234
235         # dynamic pin state means more constructor arguments
236         if is_dynamic_pinned(node):
237                 if hasattr(node, "pinned_init"):
238                         initattrs.append(dict(
239                                 initname = ".exc.pin_state",
240                                 init     = node.pinned_init
241                         ))
242                 else:
243                         node.constructor_args.append(
244                                 dict(
245                                         name = "pin_state",
246                                         type = "op_pin_state"
247                                 )
248                         )
249                         initattrs.append(dict(
250                                 initname = ".exc.pin_state",
251                                 init     = "pin_state"
252                         ))
253
254         for arg in node.constructor_args:
255                 arguments.append(prepare_attr(arg))
256                 if arg["type"] == "ir_cons_flags":
257                         name = arg["name"]
258                         initattrs.append(dict(initname = ".exc.pin_state",
259                                 init = name + " & cons_floats ? op_pin_state_floats : op_pin_state_pinned"))
260                         initattrs.append(dict(initname = ".volatility",
261                                 init = name + " & cons_volatile ? volatility_is_volatile : volatility_non_volatile"))
262                         initattrs.append(dict(initname = ".aligned",
263                                 init = name + " & cons_unaligned ? align_non_aligned : align_is_aligned"))
264
265         node.arguments = arguments
266         node.initattrs = initattrs
267         node.special_constructors = specialconstrs
268
269 #############################
270
271 constructor_template = env.from_string('''
272
273 ir_node *new_rd_{{node.constrname}}(
274         {%- filter parameters %}
275                 dbg_info *dbgi
276                 {{node|blockparameter}}
277                 {{node|nodeparameters}}
278         {% endfilter %})
279 {
280         ir_node *res;
281         ir_graph *rem = current_ir_graph;
282         {{node|irgassign}}
283         {{node|insdecl}}
284         current_ir_graph = irg;
285         res = new_ir_node(
286                 {%- filter arguments %}
287                         dbgi
288                         irg
289                         {{node.block}}
290                         op_{{node.name}}
291                         {{node.mode}}
292                         {{node|arity_and_ins}}
293                 {% endfilter %});
294         {% for attr in node.attrs -%}
295                 res->attr.{{node.attrs_name}}{{attr["initname"]}} =
296                 {%- if "init" in attr %} {{ attr["init"] -}};
297                 {%- else              %} {{ attr["name"] -}};
298                 {% endif %}
299         {% endfor %}
300         {%- for attr in node.initattrs -%}
301                 res->attr.{{node.attrs_name}}{{attr["initname"]}} = {{ attr["init"] -}};
302         {%- endfor %}
303         {{- node.init }}
304         {% if node.optimize != False -%}
305                 res = optimize_node(res);
306         {% endif -%}
307         IRN_VRFY_IRG(res, irg);
308         current_ir_graph = rem;
309         return res;
310 }
311
312 ir_node *new_r_{{node.constrname}}(
313                 {%- filter parameters %}
314                         {{node|blockparameter}}
315                         {{node|nodeparameters}}
316                 {% endfilter %})
317 {
318         return new_rd_{{node.constrname}}(
319                 {%- filter arguments %}
320                         NULL
321                         {{node|blockargument}}
322                         {{node|nodearguments}}
323                 {% endfilter %});
324 }
325
326 ir_node *new_d_{{node.constrname}}(
327                 {%- filter parameters %}
328                         dbg_info *dbgi
329                         {{node|nodeparameters}}
330                 {% endfilter %})
331 {
332         ir_node *res;
333         {{ node.d_pre }}
334         res = new_rd_{{node.constrname}}(
335                 {%- filter parameters %}
336                         dbgi
337                         {{node|curblock}}
338                         {{node|nodearguments}}
339                 {% endfilter %});
340         {{ node.d_post }}
341         return res;
342 }
343
344 ir_node *new_{{node.constrname}}(
345                 {%- filter parameters %}
346                         {{node|nodeparameters}}
347                 {% endfilter %})
348 {
349         return new_d_{{node.constrname}}(
350                 {%- filter arguments %}
351                         NULL
352                         {{node|nodearguments}}
353                 {% endfilter %});
354 }
355 ''')
356
357 # not used - as we have the pn_ declarations in libfirm/irnode.h where they
358 # contain informative comments
359 # {% for node in nodes %}
360 # {% if node.outs %}
361 # typedef enum {
362 #       {%- for out in node.outs %}
363 #       pn_{{node.name}}_{{out}},
364 #       {%- endfor %}
365 #       pn_{{node.name}}_max
366 # } pn_{{node.name}};
367 # {% endif %}
368 # {% endfor %}
369
370 irnode_h_template = env.from_string('''
371 /* Warning: automatically generated code */
372
373 {% for node in nodes|isnot('custom_is') %}
374 static inline int _is_{{node.name}}(const ir_node *node)
375 {
376         assert(node != NULL);
377         return _get_irn_op(node) == op_{{node.name}};
378 }
379 {% endfor %}
380
381 {% for node in nodes %}
382 #define is_{{node.name}}(node)    _is_{{node.name}}(node)
383 {%- endfor %}
384
385 ''')
386
387 irnode_template = env.from_string('''
388 /* Warning: automatically generated code */
389 {% for node in nodes %}
390 int (is_{{node.name}})(const ir_node *node)
391 {
392         return _is_{{node.name}}(node);
393 }
394 {% endfor %}
395 ''')
396
397 irop_template = env.from_string('''
398 /* Warning: automatically generated code */
399 {% for node in nodes %}
400 ir_op *op_{{node.name}}; ir_op *get_op_{{node.name}}(void) { return op_{{node.name}}; }
401 {%- endfor %}
402
403 void init_op(void)
404 {
405         {% for node in nodes %}
406         op_{{node.name}} = new_ir_op(
407                 {%- filter arguments %}
408                         iro_{{node.name}}
409                         "{{node.name}}"
410                         {{node|pinned}}
411                         {{node|flags}}
412                         {{node|arity}}
413                         {{node|opindex}}
414                         {{node|attr_size}}
415                         NULL
416                 {% endfilter %});
417         {%- endfor %}
418
419         be_init_op();
420 }
421
422 void finish_op(void)
423 {
424         {% for node in nodes %}
425         free_ir_op(op_{{node.name}}); op_{{node.name}} = NULL;
426         {%- endfor %}
427 }
428
429 ''')
430
431 #############################
432
433 def main(argv):
434         if len(argv) < 3:
435                 print "usage: %s specname(ignored) destdirectory" % argv[0]
436                 sys.exit(1)
437
438         gendir = argv[2]
439
440         # List of TODOs
441         niymap = [ "ASM", "Const", "Phi", "SymConst", "Sync"]
442
443         real_nodes = []
444         for node in nodes:
445                 if isAbstract(node):
446                         continue
447                 real_nodes.append(node)
448
449         file = open(gendir + "/gen_ir_cons.c.inl", "w")
450         for node in real_nodes:
451                 preprocess_node(node)
452
453                 if node.name in niymap:
454                         continue
455
456                 if not isAbstract(node) and not hasattr(node, "singleton"):
457                         file.write(constructor_template.render(vars()))
458
459                         if hasattr(node, "special_constructors"):
460                                 for special in node.special_constructors:
461                                         node.constrname = special["constrname"]
462                                         special["attr"]["init"] = special["attr"]["special"]["init"]
463                                         file.write(constructor_template.render(vars()))
464         file.write("\n")
465         file.close()
466
467         file = open(gendir + "/gen_irnode.h", "w")
468         file.write(irnode_h_template.render(nodes = real_nodes))
469         file.close()
470
471         file = open(gendir + "/gen_irnode.c.inl", "w")
472         file.write(irnode_template.render(nodes = real_nodes))
473         file.close()
474
475         file = open(gendir + "/gen_irop.c.inl", "w")
476         file.write(irop_template.render(nodes = real_nodes))
477         file.close()
478
479 main(sys.argv)