Don't set copy_attr_func to NULL for nodes without attributes.
[libfirm] / ir / be / scripts / generate_new_opcodes.pl
1 #!/usr/bin/perl -w
2
3 #
4 # Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
5 #
6 # This file is part of libFirm.
7 #
8 # This file may be distributed and/or modified under the terms of the
9 # GNU General Public License version 2 as published by the Free Software
10 # Foundation and appearing in the file LICENSE.GPL included in the
11 # packaging of this file.
12 #
13 # Licensees holding valid libFirm Professional Edition licenses may use
14 # this file in accordance with the libFirm Commercial License.
15 # Agreement provided with the Software.
16 #
17 # This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
18 # WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 # PURPOSE.
20 #
21
22 # This script generates the C code which creates the irop's and
23 # their coresponding node constructors for all operations in a given spec
24 # so they can be used as normal firm nodes.
25 # Creation: 2005/10/19
26
27 use strict;
28 use Data::Dumper;
29
30 my $specfile   = $ARGV[0];
31 my $target_dir = $ARGV[1];
32 my $state      = 1;
33 my $cur_op     = "";
34 my $line_nr    = 0;
35
36 our $arch;
37 our $additional_opcodes;
38 our %nodes;
39 our %operands;
40 our %cpu;
41 our $default_op_attr_type;
42 our $default_attr_type;
43 our $default_cmp_attr;
44 our $default_copy_attr;
45 our %init_attr;
46 our $custom_init_attr_func;
47 our %compare_attr;
48 our %copy_attr;
49 our %reg_classes;
50 our %custom_irn_flags;
51
52 # include spec file
53
54 my $return;
55
56 no strict "subs";
57 unless ($return = do $specfile) {
58         die "Fatal error: couldn't parse $specfile: $@" if $@;
59         die "Fatal error: couldn't do $specfile: $!"    unless defined $return;
60         die "Fatal error: couldn't run $specfile"       unless $return;
61 }
62 use strict "subs";
63
64 my $target_c = $target_dir."/gen_".$arch."_new_nodes.c.inl";
65 my $target_h = $target_dir."/gen_".$arch."_new_nodes.h";
66
67 if(!defined($default_attr_type)) {
68         $default_attr_type = "${arch}_attr_t";
69 }
70 if(! %init_attr) {
71         %init_attr = (
72                 "$default_attr_type" => "\tinit_${arch}_attributes(res, irn_flags_, in_reqs, n_res);",
73         );
74 }
75 if(!defined($default_cmp_attr)) {
76         $default_cmp_attr = "${arch}_compare_attr";
77 }
78 if(! %compare_attr) {
79         %compare_attr = (
80                 "${default_attr_type}" => "${default_cmp_attr}",
81         );
82 }
83
84 # Operands are really just nodes with some special constraints, we check
85 # these and create new entries in the nodes hashmap
86 foreach my $op (keys(%operands)) {
87         my %operand = %{ $operands{"$op"} };
88         my %op_node;
89
90         # constraints
91         if(defined($operand{op_flags})) { die "Fatal error: operands can't have op_flags ($op)"; }
92         if(defined($operand{cmp_attr})) { die "Fatal error: cmp_attr not allowed for operands ($op)"; }
93         if(defined($operand{mode})) { die "Operand must not have a mode defined ($op)"; }
94         if(defined($operand{out_arity})) { die "operand must not have out_arity defined ($op)"; }
95         if(defined($nodes{$op})) { die "$op defined as operand and as node"; };
96
97
98         foreach my $flag (keys(%operand)) {
99                 $op_node{$flag} = $operand{$flag};
100         }
101         $op_node{op_flags} = "O";
102         $op_node{cmp_attr} = 'return 1;';
103         $op_node{mode}     = 'mode_ANY';
104
105         $nodes{$op} = \%op_node;
106 }
107
108 #print Dumper(%nodes);
109 #print Dumper(%operands);
110
111 # create c code file from specs
112
113 my @obst_limit_func;
114 my @obst_reg_reqs;
115 my @obst_opvar;       # stack for the "ir_op *op_<arch>_<op-name> = NULL;" statements
116 my @obst_get_opvar;   # stack for the get_op_<arch>_<op-name>() functions
117 my $obst_constructor; # stack for node constructor functions
118 my @obst_new_irop;    # stack for the new_ir_op calls
119 my @obst_free_irop;   # stack for free_ir_op calls
120 my @obst_enum_op;     # stack for creating the <arch>_opcode enum
121 my $obst_header;      # stack for function prototypes
122 my @obst_is_archirn;  # stack for the is_$arch_irn() function
123 my @obst_cmp_attr;    # stack for the compare attribute functions
124 my $obst_proj = "";   # stack for the pn_ numbers
125 my $orig_op;
126 my $arity;
127 my $cmp_attr_func;
128 my $temp;
129 my $n_opcodes = 0;    # number of opcodes
130 my $ARITY_VARIABLE = -1;
131 my $ARITY_DYNAMIC  = -2;
132 my %requirements = ();
133 my %limit_bitsets = ();
134 my %reg2class = ();
135 my %regclass2len = ();
136
137 # build register->class hashes
138 foreach my $class_name (keys(%reg_classes)) {
139         my @class         = @{ $reg_classes{"$class_name"} };
140         my $old_classname = $class_name;
141
142         pop(@class);
143
144         $class_name = $arch."_".$class_name;
145
146         my $idx = 0;
147         foreach (@class) {
148                 $reg2class{$_->{name}} = {
149                         "class" => $old_classname,
150                         "index" => $idx
151                 };
152                 $idx++;
153         }
154
155         $regclass2len{$old_classname} = $idx;
156 }
157
158
159 # for registering additional opcodes
160 $n_opcodes += $additional_opcodes if (defined($additional_opcodes));
161
162 $obst_header .= "void ${arch}_create_opcodes(const arch_irn_ops_t *be_ops);\n";
163 $obst_header .= "void ${arch}_free_opcodes(void);\n";
164
165 sub create_constructor {
166         my $op   = shift;
167         my $name = shift;
168         my $n    = shift;
169         my $on   = shift;
170         my $known_mode;
171
172         my $suffix = "";
173         if ($name ne "") {
174                 $suffix = "_${name}";
175         }
176
177         # determine mode
178         if (exists($n->{mode})) {
179                 $known_mode = $n->{mode};
180         }
181
182         # determine arity
183         my $arity = 0;
184         if(exists($n->{"arity"})) {
185                 $arity = $n->{"arity"};
186         } elsif (exists($n->{"reg_req"}) && exists($n->{"reg_req"}{"in"})) {
187                 $arity = scalar(@{ $n->{"reg_req"}{"in"} });
188         } elsif (exists($n->{"ins"})) {
189                 $arity = scalar(@{ $n->{"ins"} });
190         }
191         if($arity eq "variable") {
192                 $arity = $ARITY_VARIABLE;
193         } elsif($arity eq "dynamic") {
194                 $arity = $ARITY_DYNAMIC;
195         }
196
197         # determine out arity
198         my $out_arity = 0;
199         if(exists($n->{"out_arity"})) {
200                 $out_arity = $n->{"out_arity"};
201         } elsif (exists($n->{"reg_req"}) && exists($n->{"reg_req"}{"out"})) {
202                 $out_arity = scalar(@{ $n->{"reg_req"}{"out"} });
203         } elsif (exists($n->{"outs"})) {
204                 $out_arity = scalar(@{ $n->{"outs"} });
205         }
206         if($out_arity eq "variable") {
207                 $out_arity = $ARITY_VARIABLE;
208         } elsif($out_arity eq "dynamic") {
209                 $out_arity = $ARITY_DYNAMIC;
210         }
211         if ($out_arity != 0 && $out_arity != 1 && !defined($known_mode)) {
212                 $known_mode = "mode_T";
213         }
214
215         my $comment = $n->{"comment"};
216         if(!exists($n->{"comment"})) {
217                 $comment = "construct ${orig_op} node";
218         }
219         $comment =
220                 "/**\n".
221                 " * ${comment}\n".
222                 " */\n";
223
224         $obst_constructor .= $comment;
225
226         # create constructor head
227         my $complete_args = "";
228         $temp             = "";
229
230         $temp = "ir_node *new_bd_${arch}_${op}${suffix}(dbg_info *dbgi, ir_node *block";
231         if (!exists($n->{"args"})) { # default args
232                 if ($arity == $ARITY_VARIABLE) {
233                         $complete_args = ", int arity, ir_node *in[]";
234                 } elsif ($arity == $ARITY_DYNAMIC) {
235                         $complete_args = "";
236                 } else {
237                         for (my $i = 0; $i < $arity; $i++) {
238                                 my $opname = "op${i}";
239                                 if (exists($n->{"ins"})) {
240                                         my @ins = @{ $n->{"ins"} };
241                                         $opname = $ins[$i];
242                                 }
243
244                                 $complete_args .= ", ir_node *${opname}";
245                         }
246                 }
247                 if ($out_arity == $ARITY_VARIABLE) {
248                         $complete_args .= ", int n_res";
249                 }
250
251                 if (!defined($known_mode)) {
252                         $complete_args .= ", ir_mode *mode";
253                 }
254         } else { # user defined args
255                 for my $href (@{ $n->{"args"} }) {
256                         $href->{"type"} .= " " if ($href->{"type"} !~ / [*]?$/); # put a space between name and type if there is none at the end
257                         $complete_args  .= ", ".$href->{"type"}.$href->{"name"};
258                 }
259         }
260
261         # we have additional attribute arguements
262         if (exists($n->{"attr"})) {
263                 $complete_args .= ", ".$n->{"attr"};
264         }
265
266         $temp .= "$complete_args)";
267         $obst_constructor .= "${temp}\n{\n";
268
269         $obst_header .= $comment;
270         $obst_header .= "${temp};\n";
271
272         # emit constructor code
273         $temp = <<EOF;
274         ir_graph         *irg        = get_irn_irg(block);
275         ir_op            *op         = op_${arch}_${op};
276         arch_irn_flags_t  irn_flags_ = arch_irn_flags_none;
277         ir_node          *res;
278         backend_info_t   *info;
279 EOF
280
281         if($arity == $ARITY_DYNAMIC) {
282                 $temp .= <<EOF;
283         int             arity   = -1;
284         ir_node       **in      = NULL;
285 EOF
286         } elsif($arity == $ARITY_VARIABLE) {
287         } else {
288                 $temp .= <<EOF;
289         int             arity   = $arity;
290 EOF
291                 if($arity > 0) {
292                         $temp .= <<EOF;
293         ir_node        *in[$arity];
294 EOF
295                 } else {
296                         $temp .= <<EOF;
297         ir_node       **in      = NULL;
298 EOF
299                 }
300         }
301         if($out_arity == $ARITY_DYNAMIC) {
302                 $temp .= <<EOF;
303         int             n_res   = -1;
304 EOF
305         } elsif($out_arity == $ARITY_VARIABLE) {
306         } else {
307                 $temp .= <<EOF;
308         int             n_res   = ${out_arity};
309 EOF
310         }
311
312         if (defined($known_mode)) {
313                 $temp .= <<EOF;
314         ir_mode        *mode    = ${known_mode};
315 EOF
316         }
317
318         undef my $in_req_var;
319         undef my $out_req_var;
320
321         my $set_out_reqs = "";
322
323         # set up static variables for requirements and registers
324         if (exists($n->{"reg_req"})) {
325                 my %req = %{ $n->{"reg_req"} };
326                 my $idx;
327
328                 undef my @in;
329                 @in = @{ $req{"in"} } if (exists($req{"in"}));
330                 undef my @out;
331                 @out = @{ $req{"out"} } if exists(($req{"out"}));
332
333                 for(my $idx = 0; $idx < $#in; $idx++) {
334                         my $req = $in[$idx];
335                         generate_requirements($req, $n, "${arch}_${op}", $idx, 1);
336                 }
337                 for(my $idx = 0; $idx < $#out; $idx++) {
338                         my $req = $out[$idx];
339                         generate_requirements($req, $n, "${arch}_${op}", $idx, 0);
340                 }
341
342                 if (@in) {
343                         if($arity >= 0 && scalar(@in) != $arity) {
344                                 die "Fatal error: Arity and number of in requirements don't match for ${op}\n";
345                         }
346
347                         $temp .= "\tstatic const arch_register_req_t *in_reqs[] =\n";
348                         $temp .= "\t{\n";
349                         for ($idx = 0; $idx <= $#in; $idx++) {
350                                 my $req = $in[$idx];
351                                 my $reqstruct = generate_requirements($req, $n, "${arch}_${op}", $idx, 1);
352                                 $temp .= "\t\t& ${reqstruct},\n";
353                         }
354                         $temp .= "\t};\n";
355                 } else {
356                         if($arity > 0) {
357                                 die "Fatal error: need in requirements for ${op}\n";
358                         }
359                         $temp .= "\tstatic const arch_register_req_t **in_reqs = NULL;\n";
360                 }
361
362                 if (@out) {
363                         if($out_arity >= 0 && scalar(@out) != $out_arity) {
364                                 die "Fatal error: Out-Arity and number of out requirements don't match for ${op}\n";
365                         }
366
367                         for ($idx = 0; $idx <= $#out; $idx++) {
368                                 my $req = $out[$idx];
369                                 my $reqstruct = generate_requirements($req, $n, "${arch}_${op}", $idx, 0);
370                                 $set_out_reqs .= <<EOF;
371         info->out_infos[${idx}].req = &${reqstruct};
372 EOF
373                         }
374                 } else {
375                         if($out_arity > 0) {
376                                 die "Fatal error: need out requirements for ${op}\n";
377                         }
378                 }
379         } else {
380                 $temp .= "\tstatic const arch_register_req_t **in_reqs = NULL;\n";
381         }
382         my $attr_type = $on->{attr_type};
383         if(exists($n->{"init_attr"})) {
384                 $temp .= "\t${attr_type} *attr;\n";
385         }
386
387         $temp .= "\n";
388
389         if($arity > 0) {
390                 $temp .= "\t/* construct in array */\n";
391                 for (my $i = 0; $i < $arity; $i++) {
392                         my $opname = "op${i}";
393                         if (exists($n->{"ins"})) {
394                                 my @ins = @{ $n->{"ins"} };
395                                 $opname = $ins[$i];
396                         }
397
398                         $temp .= "\tin[${i}] = ${opname};\n";
399                 }
400                 $temp .= "\n";
401         }
402
403         # set flags
404         if (exists($n->{"irn_flags"})) {
405                 $temp .= "\t/* flags */\n";
406                 my %known_irn_flags = (
407                         "none"             => "arch_irn_flags_none",
408                         "dont_spill"       => "arch_irn_flags_dont_spill",
409                         "rematerializable" => "arch_irn_flags_rematerializable",
410                         "modify_flags"     => "arch_irn_flags_modify_flags",
411                         "simple_jump"      => "arch_irn_flags_simple_jump",
412                         "not_scheduled"    => "arch_irn_flags_not_scheduled",
413                 );
414                 if (%custom_irn_flags) {
415                         %known_irn_flags = (%known_irn_flags, %custom_irn_flags);
416                 }
417                 foreach my $flag (@{$n->{"irn_flags"}}) {
418                         if (not defined($known_irn_flags{$flag})) {
419                                 print STDERR "WARNING: irn_flag '$flag' in opcode $op is unknown\n";
420                         } else {
421                                 $temp .= "\tirn_flags_ |= " . $known_irn_flags{$flag} . ";\n";
422                         }
423                 }
424                 $temp .= "\n";
425         }
426
427         # lookup init function
428         my $attr_init_code = "(void)in;(void)irn_flags_;(void)in_reqs;(void)n_res;";
429         if ($attr_type ne "") {
430                 $attr_init_code = $init_attr{$attr_type};
431                 if(!defined($attr_init_code)) {
432                         die "Fatal error: Couldn't find attribute initialisation code for type '${attr_type}'";
433                 }
434         }
435         my $custominit = "";
436         if(defined($custom_init_attr_func)) {
437                 $custominit .= &$custom_init_attr_func($n, $on, "${arch}_${op}");
438         }
439         if(defined($n->{custominit})) {
440                 $custominit .= $n->{custominit};
441         }
442
443         $temp .= <<EOF;
444         /* create node */
445         assert(op != NULL);
446         res = new_ir_node(dbgi, irg, block, op, mode, arity, in);
447
448         /* init node attributes */
449         ${attr_init_code}
450         ${custominit}
451         info = be_get_info(res);
452         (void) info; /* avoid potential warning */
453 ${set_out_reqs}
454
455 EOF
456
457         if (exists($n->{"init_attr"})) {
458                 $temp .= "\tattr = (${attr_type}*)get_irn_generic_attr(res);\n";
459                 $temp .= "\t(void) attr; /* avoid potential warning */\n";
460                 $temp .= "\t".$n->{"init_attr"}."\n";
461         }
462
463         $temp .= <<EOF;
464         /* optimize node */
465         res = optimize_node(res);
466         irn_verify_irg(res, irg);
467
468         return res;
469 EOF
470
471         $obst_constructor .= $temp;
472
473         # close constructor function
474         $obst_constructor .= "}\n\n";
475 }
476
477 push(@obst_enum_op, "typedef enum ${arch}_opcodes {\n");
478 foreach my $op (keys(%nodes)) {
479         my %n        = %{ $nodes{"$op"} };
480         my $known_mode;
481         my $num_outs = 0;
482         my $out_arity;
483         my @out_flags;
484
485         # determine arity
486         $arity = 0;
487         if(exists($n{"arity"})) {
488                 $arity = $n{"arity"};
489         } elsif (exists($n{"reg_req"}) && exists($n{"reg_req"}{"in"})) {
490                 $arity = scalar(@{ $n{"reg_req"}{"in"} });
491         } elsif (exists($n{"ins"})) {
492                 $arity = scalar(@{ $n{"ins"} });
493         }
494         if($arity eq "variable") {
495                 $arity = $ARITY_VARIABLE;
496         } elsif($arity eq "dynamic") {
497                 $arity = $ARITY_DYNAMIC;
498         }
499
500         # determine out arity
501         $out_arity = 0;
502         if(exists($n{"out_arity"})) {
503                 $out_arity = $n{"out_arity"};
504         } elsif (exists($n{"reg_req"}) && exists($n{"reg_req"}{"out"})) {
505                 $out_arity = scalar(@{ $n{"reg_req"}{"out"} });
506         } elsif (exists($n{"outs"})) {
507                 $out_arity = scalar(@{ $n{"outs"} });
508         }
509         if($out_arity eq "variable") {
510                 $out_arity = $ARITY_VARIABLE;
511         } elsif($out_arity eq "dynamic") {
512                 $out_arity = $ARITY_DYNAMIC;
513         }
514
515         $orig_op = $op;
516         $op      = $arch."_".$op;
517         $temp    = "";
518
519         # define proj numbers and in numbers
520         if (exists($n{"outs"})) {
521                 undef my @outs;
522
523                 @outs = @{ $n{"outs"} };
524                 if($out_arity >= 0 && scalar(@outs) != $out_arity) {
525                         die "Fatal error: Op ${op} has different number of outs and out_arity\n";
526                 }
527
528                 $num_outs = $#outs + 1;
529
530                 if ($num_outs > 0) {
531                         $obst_proj .= "\nenum pn_${op} {\n";
532
533                         for (my $idx = 0; $idx <= $#outs; $idx++) {
534                                 # check, if we have additional flags annotated to out
535                                 if ($outs[$idx] =~ /:((S|I)(\|(S|I))*)/) {
536                                         push(@out_flags, $1);
537                                         $outs[$idx] =~ s/:((S|I)(\|(S|I))*)//;
538                                 }
539                                 $obst_proj .= "\tpn_${op}_".$outs[$idx]." = ${idx},\n";
540                         }
541
542                         $obst_proj .= "};\n";
543                 }
544                 # outs have names, it must be a mode_T node
545                 if (!defined($n{mode})) {
546                         $n{mode} = "mode_T";
547                 }
548         }
549         if (exists($n{"ins"})) {
550                 undef my @ins;
551
552                 @ins = @{ $n{"ins"} };
553                 if($arity >= 0 && scalar(@ins) != $arity) {
554                         die "Fatal error: Op ${op} has different number of ins and arity\n";
555                 }
556
557                 if ($#ins >= 0) {
558                         $obst_proj .= "\nenum n_$op {\n";
559                         for (my $idx = 0; $idx <= $#ins; $idx++) {
560                                 $obst_proj .= "\tn_${op}_".$ins[$idx]." = ${idx},\n";
561                         }
562                         $obst_proj .= "};\n";
563                 }
564         }
565
566         # Create opcode
567         push(@obst_opvar, "ir_op *op_$op = NULL;\n");
568         push(@obst_get_opvar, "ir_op *get_op_$op(void)         { return op_$op; }\n");
569         push(@obst_get_opvar, "int    is_$op(const ir_node *n) { return get_$arch\_irn_opcode(n) == iro_$op; }\n\n");
570
571         push(@obst_is_archirn, "is_$op(node)");
572
573         $obst_header .= <<EOF;
574 extern ir_op *op_${op};
575 ir_op *get_op_${op}(void);
576 int is_${op}(const ir_node *n);
577 EOF
578
579         my $attr_type= $n{attr_type};
580         if(!defined($attr_type)) {
581                 $attr_type = $default_attr_type;
582                 $n{attr_type} = $attr_type;
583         }
584
585         # determine hash function
586         my $hash_func;
587         if (exists($n{"hash_func"})) {
588                 $hash_func = $n{"hash_func"};
589         }
590
591         # determine compare function
592         my $cmp_attr_func;
593         if (exists($n{"cmp_attr"})) {
594                 my $cmpcode = $n{"cmp_attr"};
595
596                 push(@obst_cmp_attr, "static int cmp_attr_$op(const ir_node *a, const ir_node *b) {\n");
597                 if($cmpcode =~ m/attr_a/) {
598                         push(@obst_cmp_attr, "\tconst ${attr_type} *attr_a = get_irn_generic_attr_const(a);\n");
599                 } else {
600                         push(@obst_cmp_attr, "\t(void) a;\n");
601                 }
602                 if($cmpcode =~ m/attr_b/) {
603                         push(@obst_cmp_attr, "\tconst ${attr_type} *attr_b = get_irn_generic_attr_const(b);\n");
604                 } else {
605                         push(@obst_cmp_attr, "\t(void) b;\n");
606                 }
607                 push(@obst_cmp_attr, "\t${cmpcode}\n");
608                 push(@obst_cmp_attr, "}\n\n");
609
610                 $cmp_attr_func = "cmp_attr_${op}";
611         } elsif ($attr_type eq "") {
612                 $cmp_attr_func = "NULL";
613         } else {
614                 if(defined($compare_attr{${attr_type}})) {
615                         $cmp_attr_func = $compare_attr{${attr_type}};
616                 } else {
617                         die "Fatal error: No compare function defined for ${attr_type} attributes.";
618                 }
619         }
620
621         my %constructors;
622         if (exists($n{constructors})) {
623                 %constructors = %{ $n{constructors} };
624         } else {
625                 # Create 1 default constructor
626                 my %constructor = ();
627                 foreach my $a ("comment", "ins", "outs", "args", "attr", "units",
628                                 "reg_req", "init_attr", "irn_flags", "mode", "arity",
629                                 "out_arity", "custominit") {
630                         if (defined($n{$a})) {
631                                 $constructor{$a} = $n{$a};
632                         }
633                 }
634                 %constructors = ( "" => \%constructor );
635         }
636
637         foreach my $constr (keys(%constructors)) {
638                 my %cstr = %{ $constructors{$constr} };
639                 # Copy some values from outer node if they don't exists in the constr
640                 foreach my $a ("ins", "outs", "irn_flags", "mode", "args", "attr",
641                                "custominit") {
642                         if (!defined($cstr{$a}) && defined($n{$a})) {
643                                 $cstr{$a} = $n{$a};
644                         }
645                 }
646                 create_constructor($orig_op, $constr, \%cstr, \%n);
647         }
648
649         # set default values for state and flags if not given
650         $n{"state"}     = "floats" if (! exists($n{"state"}));
651         $n{"op_flags"}  = ["none"] if (! exists($n{"op_flags"}));
652         $n{"dump_func"} = "${arch}_dump_node" if (!exists($n{"dump_func"}));
653         my $dump_func = $n{"dump_func"};
654
655         my %known_flags = map { $_ => 1 } (
656                 "none", "commutative", "cfopcode", "unknown_jump", "fragile",
657                 "forking", "highlevel", "constlike", "keep", "start_block",
658                 "uses_memory", "dump_noblock", "cse_neutral"
659         );
660         my $is_fragile = 0;
661         foreach my $flag (@{$n{"op_flags"}}) {
662                 if (not defined($known_flags{$flag})) {
663                         print STDERR "WARNING: Flag '$flag' in opcode $op is unknown\n";
664                 }
665                 if ($flag eq "fragile") {
666                         $is_fragile = 1;
667                 }
668         }
669         my @mapped = map { "irop_flag_$_" } @{$n{"op_flags"}};
670         my $op_flags = join('|', @mapped);
671
672         my $attr_size = "0";
673         if ($attr_type ne "") {
674                 $attr_size = "sizeof(${attr_type})"
675         }
676
677         $n_opcodes++;
678         $temp  = "\top = new_ir_op(cur_opcode + iro_$op, \"$op\", op_pin_state_".$n{"state"}.", $op_flags";
679         $temp .= ", ".translate_arity($arity).", 0, ${attr_size});\n";
680         push(@obst_new_irop, $temp);
681         push(@obst_new_irop, "\top->ops.be_ops        = be_ops;\n");
682         push(@obst_new_irop, "\top->ops.dump_node     = ${dump_func};\n");
683         if (defined($cmp_attr_func)) {
684                 push(@obst_new_irop, "\top->ops.node_cmp_attr = ${cmp_attr_func};\n");
685         }
686         my $copy_attr_func = $copy_attr{$attr_type};
687         if (!defined($copy_attr_func)) {
688                 # don't set a copy_attr function if the node has no additional attributes.
689                 if ($attr_type ne "") {
690                         $copy_attr_func = $default_copy_attr;
691                 }
692         }
693         if (defined($copy_attr_func)) {
694                 push(@obst_new_irop, "\top->ops.copy_attr     = ${copy_attr_func};\n");
695         }
696         if (defined($hash_func)) {
697                 push(@obst_new_irop, "\top->ops.hash          = ${hash_func};\n");
698         }
699
700         if ($is_fragile) {
701                 push(@obst_new_irop, "\tir_op_set_memory_index(op, n_${op}_mem);\n");
702                 push(@obst_new_irop, "\tir_op_set_fragile_indices(op, pn_${op}_X_regular, pn_${op}_X_except);\n");
703         }
704         push(@obst_new_irop, "\tset_op_tag(op, $arch\_op_tag);\n");
705         if(defined($n{op_attr_init})) {
706                 push(@obst_new_irop, "\t".$n{op_attr_init}."\n");
707         }
708         push(@obst_new_irop, "\top_${op} = op;\n");
709
710         push(@obst_free_irop, "\tfree_ir_op(op_$op); op_$op = NULL;\n");
711
712         push(@obst_enum_op, "\tiro_$op,\n");
713
714         $obst_header .= "\n";
715 }
716 push(@obst_enum_op, "\tiro_$arch\_last_generated,\n");
717 push(@obst_enum_op, "\tiro_$arch\_last = iro_$arch\_last_generated");
718 push(@obst_enum_op, " + $additional_opcodes") if (defined($additional_opcodes));
719 push(@obst_enum_op, "\n} $arch\_opcodes;\n\n");
720
721 # emit the code
722
723 open(OUT, ">$target_c") || die("Fatal error: Could not open $target_c, reason: $!\n");
724
725 print OUT "#include \"gen_$arch\_regalloc_if.h\"\n";
726 print OUT "#include \"irverify_t.h\"\n";
727 print OUT "#include \"fourcc.h\"\n";
728 print OUT "\n";
729 print OUT @obst_cmp_attr;
730 print OUT "\n";
731 print OUT @obst_opvar;
732 print OUT "\n";
733 print OUT @obst_get_opvar;
734 print OUT "\n";
735
736 print OUT<<EOF;
737
738 static int $arch\_opcode_start = -1;
739 static int $arch\_opcode_end   = -1;
740
741 EOF
742
743 # build the FOURCC arguments from $arch
744
745 my ($a, $b, $c, $d) = ('\0', '\0', '\0', '\0');
746
747 if (length($arch) >= 1) {
748         $a = uc(substr($arch, 0, 1));
749 }
750
751 if (length($arch) >= 2) {
752         $b = uc(substr($arch, 1, 1));
753 }
754
755 if (length($arch) >= 3) {
756         $c = uc(substr($arch, 2, 1));
757 }
758
759 if (length($arch) >= 4) {
760         $d = uc(substr($arch, 3, 1));
761 }
762
763 print OUT<<ENDOFISIRN;
764
765 /** A tag for the $arch opcodes. Note that the address is used as a tag value, NOT the FOURCC code. */
766 #define $arch\_op_tag FOURCC('$a', '$b', '$c', '$d')
767
768 /** Return the opcode number of the first $arch opcode. */
769 int get_$arch\_opcode_first(void) {
770         return $arch\_opcode_start;
771 }
772
773 /** Return the opcode number of the last $arch opcode + 1. */
774 int get_$arch\_opcode_last(void) {
775         return $arch\_opcode_end;
776 }
777
778 /** Return 1 if the given opcode is a $arch machine op, 0 otherwise */
779 int is_$arch\_op(const ir_op *op) {
780         return get_op_tag(op) == $arch\_op_tag;
781 }
782
783 /** Return 1 if the given node is a $arch machine node, 0 otherwise */
784 int is_$arch\_irn(const ir_node *node) {
785         return is_$arch\_op(get_irn_op(node));
786 }
787
788 int get_$arch\_irn_opcode(const ir_node *node) {
789         if (is_$arch\_irn(node))
790                 return get_irn_opcode(node) - $arch\_opcode_start;
791         return -1;
792 }
793
794 ENDOFISIRN
795
796 print OUT <<END;
797 #ifdef BIT
798 #undef BIT
799 #endif
800 #define BIT(x)  (1 << (x))
801
802 END
803
804 print OUT @obst_limit_func;
805 print OUT "\n";
806
807 print OUT @obst_reg_reqs;
808 print OUT "\n";
809
810 print OUT<<ENDOFMAIN;
811 $obst_constructor
812
813 /**
814  * Creates the $arch specific Firm machine operations
815  * needed for the assembler irgs.
816  */
817 void $arch\_create_opcodes(const arch_irn_ops_t *be_ops)
818 {
819         ir_op *op;
820         int    cur_opcode = get_next_ir_opcodes(iro_$arch\_last);
821
822         $arch\_opcode_start = cur_opcode;
823 ENDOFMAIN
824
825 print OUT @obst_new_irop;
826 print OUT "\n";
827 print OUT "\t$arch\_register_additional_opcodes(cur_opcode);\n" if (defined($additional_opcodes));
828 print OUT "\t$arch\_opcode_end = cur_opcode + iro_$arch\_last";
829 print OUT " + $additional_opcodes" if (defined($additional_opcodes));
830 print OUT ";\n";
831 print OUT <<ENDOFMAIN;
832 }
833
834 void $arch\_free_opcodes(void)
835 {
836 ENDOFMAIN
837
838 print OUT @obst_free_irop;
839
840 print OUT <<ENDOFMAIN;
841 }
842 ENDOFMAIN
843
844 close(OUT);
845
846 open(OUT, ">$target_h") || die("Fatal error: Could not open $target_h, reason: $!\n");
847
848 my $creation_time = localtime(time());
849 my $tmp = uc($arch);
850
851 print OUT<<EOF;
852 /**
853  * \@file
854  * \@brief Function prototypes for the new opcode functions.
855  * \@note  DO NOT EDIT THIS FILE, your changes will be lost.
856  *        Edit $specfile instead.
857  *        created by: $0 $specfile $target_dir
858  * \@date  $creation_time
859  */
860 #ifndef FIRM_BE_${tmp}_GEN_${tmp}_NEW_NODES_H
861 #define FIRM_BE_${tmp}_GEN_${tmp}_NEW_NODES_H
862
863 EOF
864
865 print OUT @obst_enum_op;
866 print OUT <<EOF;
867 int is_${arch}_irn(const ir_node *node);
868 int is_${arch}_op(const ir_op *op);
869
870 int get_${arch}_opcode_first(void);
871 int get_${arch}_opcode_last(void);
872 int get_${arch}_irn_opcode(const ir_node *node);
873 ${obst_header}
874 ${obst_proj}
875
876 #endif
877 EOF
878
879 close(OUT);
880
881 ###
882 # Translates numeric arity into string constant.
883 ###
884 sub translate_arity {
885         my $arity = shift;
886
887         if ($arity =~ /^\d+$/) {
888                 if    ($arity == 0) {
889                         return "oparity_zero";
890                 }
891                 elsif ($arity == 1) {
892                         return "oparity_unary";
893                 }
894                 elsif ($arity == 2) {
895                         return "oparity_binary";
896                 }
897                 elsif ($arity == 3) {
898                         return "oparity_trinary";
899                 }
900                 else {
901                         return "oparity_any";
902                 }
903         } elsif ($arity == $ARITY_VARIABLE) {
904                 return "oparity_variable";
905         } elsif ($arity == $ARITY_DYNAMIC) {
906                 return "oparity_dynamic";
907         } else {
908                 die "Fatal error: Unknown arity $arity";
909         }
910 }
911
912 sub mangle_requirements {
913         my $reqs  = shift;
914         my $class = shift;
915         my $flags = shift;
916
917         my @alternatives = split(/ /, $reqs);
918         for(my $idx = 0; $idx < scalar(@alternatives); $idx++) {
919                 $alternatives[$idx] =~ s/!/not_/g;
920         }
921
922         @alternatives = sort @alternatives;
923
924         my $name = $class."_".join('_', @alternatives);
925         if (defined($flags)) {
926                 $flags =~ s/\|/_/g;
927                 $name .= "_$flags";
928         }
929
930         return $name;
931 }
932
933 ###
934 # Determines whether $name is a specified register class or not.
935 # @return 1 if name is register class, 0 otherwise
936 ###
937 sub is_reg_class {
938     my $name = shift;
939     return 1 if exists($reg_classes{"$name"});
940     return 0;
941 }
942
943 ###
944 # Returns the register class for a given register.
945 # @return class or undef
946 ###
947 sub get_reg_class {
948     my $reg = shift;
949     $reg = substr($reg, 1) if ($reg =~ /!.*/);
950     return $reg2class{"$reg"}{"class"} if (exists($reg2class{"$reg"}));
951     return undef;
952 }
953
954 ###
955 # Returns the index of a given register within its register class.
956 # @return index or undef
957 ###
958 sub get_reg_index {
959     my $reg = shift;
960     return $reg2class{"$reg"}{"index"} if (exists($reg2class{"$reg"}));
961     return undef;
962 }
963
964 ###
965 # Remember the register class for each index in the given requirements.
966 # We need this information for requirements like "in_sX" or "out_dX"
967 # @return array of classes corresponding to the requirement for each index
968 ###
969 sub build_inout_idx_class {
970         my $n     = shift;
971         my $op    = shift;
972         my $is_in = shift;
973         my @idx_class;
974
975         my $inout = ($is_in ? "in" : "out");
976
977         if (exists($n->{"reg_req"}{"$inout"})) {
978                 my @reqs = @{ $n->{"reg_req"}{"$inout"} };
979
980                 for (my $idx = 0; $idx <= $#reqs; $idx++) {
981                         my $class = undef;
982                         my ($req,) = split(/:/, $reqs[$idx]);
983
984                         if ($req eq "none") {
985                                 $class = "none";
986                         } elsif (is_reg_class($req)) {
987                                 $class = $req;
988                         } else {
989                                 my @regs = split(/ /, $req);
990 GET_CLASS:              foreach my $reg (@regs) {
991                                         if ($reg =~ /!?(in|out)\_r\d+/ || $reg =~ /!in/) {
992                                                 $class = "UNKNOWN_CLASS";
993                                         } else {
994                                                 $class = get_reg_class($reg);
995                                                 if (!defined $class) {
996                                                         die("Fatal error: Could not get ".uc($inout)." register class for '$op' pos $idx (reg $reg) ... exiting.\n");
997                                                 } else {
998                                                         last GET_CLASS;
999                                                 } # !defined class
1000                                         } # if (reg =~ ...
1001                                 } # foreach
1002                         } # if
1003
1004                         push(@idx_class, $class);
1005                 } # for
1006         } # if
1007
1008         return @idx_class;
1009 }
1010
1011 ###
1012 # Generates the function for a given $op and a given IN-index
1013 # which returns a subset of possible register from a register class
1014 # @return classname from which the subset is derived or undef and
1015 #         pos which corresponds to in/out reference position or undef
1016 ###
1017 sub build_subset_class_func {
1018         my $neg           = undef;
1019         my $class         = undef;
1020         my $has_limit     = 0;
1021         my $limit_name;
1022         my $same_pos      = 0;
1023         my $different_pos = 0;
1024         my $temp;
1025         my @obst_init;
1026         my @obst_limits;
1027         my @obst_ignore;
1028         my @limit_array;
1029         my $limit_reqs;   #used for name mangling
1030
1031         # build function header
1032         my $node  = shift;
1033         my $op    = shift;
1034         my $idx   = shift;
1035         my $is_in = shift;
1036         my @regs  = split(/ /, shift);
1037         my $flags = shift;
1038
1039         my @idx_class = build_inout_idx_class($node, $op, !$is_in);
1040
1041         # set/unset registers
1042 CHECK_REQS: foreach (@regs) {
1043                 if (!$is_in && /(!)?in_r(\d+)/) {
1044                         my $bit_pos = 1 << ($2 - 1);
1045                         if ($different_pos & $bit_pos) {
1046                                 if ($1) {
1047                                         print STDERR "duplicate !in constraint\n";
1048                                 } else {
1049                                         print STDERR "conflicting !in and in constraints\n";
1050                                 }
1051                                 return (undef, undef, undef, undef);
1052                         }
1053
1054                         if ($same_pos & $bit_pos) {
1055                                 if ($1) {
1056                                         print STDERR "conflicting !in and in constraints\n";
1057                                 } else {
1058                                         print STDERR "duplicate in constraint\n";
1059                                 }
1060                                 return (undef, undef, undef, undef);
1061                         }
1062
1063                         if ($1) {
1064                                 $different_pos |= $bit_pos;
1065                         } else {
1066                                 $same_pos      |= $bit_pos;
1067                         }
1068
1069                         $class = $idx_class[$2 - 1];
1070                         next CHECK_REQS;
1071                 }
1072
1073                 # check for negate
1074                 if (substr($_, 0, 1) eq "!") {
1075                         if (defined($neg) && $neg == 0) {
1076                                 # we have seen a positiv constraint as first one but this one is negative
1077                                 # this doesn't make sense
1078                                 print STDERR "Mixed positive and negative constraints for the same slot are not allowed.\n";
1079                                 return (undef, undef, undef, undef);
1080                         }
1081
1082                         if (!defined($neg)) {
1083                                 $has_limit = 1;
1084                         }
1085
1086                         $_   = substr($_, 1); # skip '!'
1087                         $neg = 1;
1088                 } else {
1089                         if (defined($neg) && $neg == 1) {
1090                                 # we have seen a negative constraint as first one but this one is positive
1091                                 # this doesn't make sense
1092                                 print STDERR "Mixed positive and negative constraints for the same slot are not allowed.\n";
1093                                 return (undef, undef, undef, undef);
1094                         }
1095
1096                         $has_limit = 1;
1097                         $neg = 0;
1098                 }
1099
1100                 # check if register belongs to one of the given classes
1101                 $temp = get_reg_class($_);
1102                 if (!defined($temp)) {
1103                         print STDERR "Unknown register '$_'!\n";
1104                         return (undef, undef, undef, undef);
1105                 }
1106
1107                 # set class
1108                 if (!defined($class)) {
1109                         $class = $temp;
1110                 } elsif ($class ne $temp) {
1111                         # all registers must belong to the same class
1112                         print STDERR "Registerclass mismatch. '$_' is not member of class '$class'.\n";
1113                         return (undef, undef, undef, undef);
1114                 }
1115
1116                 # calculate position inside the initializer bitfield (only 32 bits per
1117                 # element)
1118                 my $regidx = get_reg_index($_);
1119                 my $arrayp = $regidx / 32;
1120                 push(@{$limit_array[$arrayp]}, $_);
1121                 $limit_reqs .= "$_ ";
1122         }
1123
1124         # don't allow ignore regs in negative constraints
1125         if($neg) {
1126                 my @cur_class = @{ $reg_classes{"$class"} };
1127                 for (my $idx = 0; $idx <= $#cur_class; $idx++) {
1128                         if (defined($cur_class[$idx]{"type"}) && ($cur_class[$idx]{"type"} & 4)) {
1129                                 my $reg    = $cur_class[$idx]{"name"};
1130                                 my $regix  = get_reg_index($reg);
1131                                 my $arrayp = $regix / 32;
1132                                 push(@{$limit_array[$arrayp]}, $reg);
1133                                 $limit_reqs .= "$reg ";
1134                         }
1135                 }
1136         }
1137
1138         if ($has_limit == 1) {
1139                 $limit_name = "${arch}_limit_".mangle_requirements($limit_reqs, $class);
1140
1141                 if(defined($limit_bitsets{$limit_name})) {
1142                         $limit_name = $limit_bitsets{$limit_name};
1143                         return ($class, $limit_name, $same_pos, $different_pos);
1144                 }
1145
1146                 $limit_bitsets{$limit_name} = $limit_name;
1147
1148                 push(@obst_limit_func, "static const unsigned " . $limit_name . "[] = { ");
1149                 my $first = 1;
1150                 my $limitbitsetlen = $regclass2len{$class};
1151                 my $limitarraylen = ($limitbitsetlen+31) / 32;
1152                 for(my $i = 0; $i < $limitarraylen; $i++) {
1153
1154                         my $limitarraypart = $limit_array[$i];
1155                         if($first) {
1156                                 $first = 0;
1157                         } else {
1158                                 push(@obst_limit_func, ", ");
1159                         }
1160                         my $temp;
1161                         if($neg) {
1162                                 $temp = "0xFFFFFFFF";
1163                         }
1164                         foreach my $reg (@{$limitarraypart}) {
1165                                 if($neg) {
1166                                         $temp .= " & ~";
1167                                 } elsif(defined($temp)) {
1168                                         $temp .= " | ";
1169                                 }
1170                                 my $firstreg = uc($reg_classes{$class}[0]->{"name"});
1171                                 my $classuc = uc($class);
1172                                 my $reguc = uc($reg);
1173                                 $temp .= "BIT(REG_${classuc}_${reguc})";
1174                         }
1175                         if(defined($temp)) {
1176                                 push(@obst_limit_func, "${temp}");
1177                         } else {
1178                                 push(@obst_limit_func, "0");
1179                         }
1180                 }
1181                 push(@obst_limit_func, " };\n");
1182         }
1183
1184         return ($class, $limit_name, $same_pos, $different_pos);
1185 }
1186
1187 ###
1188 # Generate register requirements structure
1189 ###
1190 sub generate_requirements {
1191         my ($reqs, $flags) = split(/:/, shift);
1192         my $node  = shift;
1193         my $op    = shift;
1194         my $idx   = shift;
1195         my $is_in = shift;
1196         my $class = "";
1197         my $width = 1;
1198         my $result;
1199
1200         my @req_type_mask;
1201         if (defined($flags)) {
1202                 foreach my $f (split(/|/, $flags)) {
1203                         if ($f eq "I") {
1204                                 push(@req_type_mask, "arch_register_req_type_ignore");
1205                         } elsif ($f eq "S") {
1206                                 push(@req_type_mask, "arch_register_req_type_produces_sp");
1207                         } elsif ($f eq "a") {
1208                                 push(@req_type_mask, "arch_register_req_type_aligned");
1209                         } elsif ($f eq "2" or $f eq "4" or $f eq "8") {
1210                                 $width = int($f);
1211                         }
1212                 }
1213         }
1214
1215         if ($reqs eq "none") {
1216
1217                 $result = <<EOF;
1218 {
1219         arch_register_req_type_none,
1220         NULL,                         /* regclass */
1221         NULL,                         /* limit bitset */
1222         0,                            /* same pos */
1223         0,                            /* different pos */
1224         0                             /* width */
1225 };
1226
1227 EOF
1228         } elsif (is_reg_class($reqs)) {
1229                 push(@req_type_mask, "arch_register_req_type_normal");
1230                 my $reqtype = join(" | ", @req_type_mask);
1231                 $class  = $reqs;
1232                 $result = <<EOF;
1233 {
1234         ${reqtype},
1235         & ${arch}_reg_classes[CLASS_${arch}_${class}],
1236         NULL,        /* limit bitset */
1237         0,           /* same pos */
1238         0,           /* different pos */
1239         $width            /* width */
1240 };
1241
1242 EOF
1243
1244         } else {
1245                 my ($regclass, $limit_bitset, $same_pos, $different_pos)
1246                         = build_subset_class_func($node, $op, $idx, $is_in, $reqs, $flags);
1247
1248                 if (!defined($regclass)) {
1249                         die("Fatal error: Could not build subset for requirements '$reqs' of '$op' pos $idx ... exiting.\n");
1250                 }
1251
1252                 if (defined($limit_bitset) && $limit_bitset ne "NULL") {
1253                         push(@req_type_mask, "arch_register_req_type_limited");
1254                 }
1255                 if ($same_pos != 0) {
1256                         push(@req_type_mask, "arch_register_req_type_should_be_same");
1257                 }
1258                 if ($different_pos != 0) {
1259                         push(@req_type_mask, "arch_register_req_type_must_be_different");
1260                 }
1261                 my $reqtype = join(" | ", @req_type_mask);
1262
1263                 if(!defined($limit_bitset)) {
1264                         $limit_bitset = "NULL";
1265                 }
1266
1267                 $class  = $regclass;
1268                 $result = <<EOF;
1269 {
1270         ${reqtype},
1271         & ${arch}_reg_classes[CLASS_${arch}_${class}],
1272         ${limit_bitset},
1273         ${same_pos},        /* same pos */
1274         ${different_pos},       /* different pos */
1275         $width             /* width */
1276 };
1277
1278 EOF
1279         }
1280
1281         my $name = "${arch}_requirements_".mangle_requirements($reqs, $class, $flags);
1282         if(defined($requirements{$name})) {
1283                 return $name;
1284         }
1285         $requirements{$name} = $name;
1286         push(@obst_reg_reqs, <<EOF);
1287 static const arch_register_req_t ${name} = ${result}
1288 EOF
1289
1290         return $name;
1291 }