be: rework op_attr handling
[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         push(@obst_new_irop, "\n\tmemset(&ops, 0, sizeof(ops));\n");
656         push(@obst_new_irop, "\tops.be_ops        = be_ops;\n");
657         push(@obst_new_irop, "\tops.dump_node     = ${dump_func};\n");
658
659         if (defined($cmp_attr_func)) {
660                 push(@obst_new_irop, "\tops.node_cmp_attr = ${cmp_attr_func};\n");
661         }
662         my $copy_attr_func = $copy_attr{$attr_type};
663         if (!defined($copy_attr_func)) {
664                 if ($attr_type eq "") {
665                         $copy_attr_func = "NULL";
666                 } else {
667                         $copy_attr_func = $default_copy_attr;
668                 }
669         }
670         if (defined($copy_attr_func)) {
671                 push(@obst_new_irop, "\tops.copy_attr = ${copy_attr_func};\n");
672         }
673         if (defined($hash_func)) {
674                 push(@obst_new_irop, "\tops.hash = ${hash_func};\n");
675         }
676
677         my %known_flags = map { $_ => 1 } (
678                 "none", "labeled", "commutative", "cfopcode", "unknown_jump", "fragile",
679                 "forking", "highlevel", "constlike", "always_opt", "keep",
680                 "start_block", "uses_memory", "dump_noblock", "dump_noinput",
681                 "cse_neutral"
682         );
683         my $is_fragile = 0;
684         foreach my $flag (@{$n{"op_flags"}}) {
685                 if (not defined($known_flags{$flag})) {
686                         print STDERR "WARNING: Flag '$flag' in opcode $op is unknown\n";
687                 }
688                 if ($flag eq "fragile") {
689                         $is_fragile = 1;
690                 }
691         }
692         my @mapped = map { "irop_flag_$_" } @{$n{"op_flags"}};
693         my $op_flags = join('|', @mapped);
694
695         my $attr_size = "0";
696         if ($attr_type ne "") {
697                 $attr_size = "sizeof(${attr_type})"
698         }
699
700         $n_opcodes++;
701         $temp  = "\top = new_ir_op(cur_opcode + iro_$op, \"$op\", op_pin_state_".$n{"state"}.", $op_flags";
702         $temp .= ", ".translate_arity($arity).", 0, ${attr_size}, &ops);\n";
703         push(@obst_new_irop, $temp);
704         if ($is_fragile) {
705                 push(@obst_new_irop, "\tir_op_set_memory_index(op, n_${op}_mem);\n");
706                 push(@obst_new_irop, "\tir_op_set_fragile_indices(op, pn_${op}_X_regular, pn_${op}_X_except);\n");
707         }
708         push(@obst_new_irop, "\tset_op_tag(op, $arch\_op_tag);\n");
709         if(defined($n{op_attr_init})) {
710                 push(@obst_new_irop, "\t".$n{op_attr_init}."\n");
711         }
712         push(@obst_new_irop, "\top_${op} = op;\n");
713
714         push(@obst_free_irop, "\tfree_ir_op(op_$op); op_$op = NULL;\n");
715
716         push(@obst_enum_op, "\tiro_$op,\n");
717
718         $obst_header .= "\n";
719 }
720 push(@obst_enum_op, "\tiro_$arch\_last_generated,\n");
721 push(@obst_enum_op, "\tiro_$arch\_last = iro_$arch\_last_generated");
722 push(@obst_enum_op, " + $additional_opcodes") if (defined($additional_opcodes));
723 push(@obst_enum_op, "\n} $arch\_opcodes;\n\n");
724
725 # emit the code
726
727 open(OUT, ">$target_c") || die("Fatal error: Could not open $target_c, reason: $!\n");
728
729 print OUT "#include \"gen_$arch\_regalloc_if.h\"\n";
730 print OUT "#include \"irverify_t.h\"\n";
731 print OUT "#include \"fourcc.h\"\n";
732 print OUT "\n";
733 print OUT @obst_cmp_attr;
734 print OUT "\n";
735 print OUT @obst_opvar;
736 print OUT "\n";
737 print OUT @obst_get_opvar;
738 print OUT "\n";
739
740 print OUT<<EOF;
741
742 static int $arch\_opcode_start = -1;
743 static int $arch\_opcode_end   = -1;
744
745 EOF
746
747 # build the FOURCC arguments from $arch
748
749 my ($a, $b, $c, $d) = ('\0', '\0', '\0', '\0');
750
751 if (length($arch) >= 1) {
752         $a = uc(substr($arch, 0, 1));
753 }
754
755 if (length($arch) >= 2) {
756         $b = uc(substr($arch, 1, 1));
757 }
758
759 if (length($arch) >= 3) {
760         $c = uc(substr($arch, 2, 1));
761 }
762
763 if (length($arch) >= 4) {
764         $d = uc(substr($arch, 3, 1));
765 }
766
767 print OUT<<ENDOFISIRN;
768
769 /** A tag for the $arch opcodes. Note that the address is used as a tag value, NOT the FOURCC code. */
770 #define $arch\_op_tag FOURCC('$a', '$b', '$c', '$d')
771
772 /** Return the opcode number of the first $arch opcode. */
773 int get_$arch\_opcode_first(void) {
774         return $arch\_opcode_start;
775 }
776
777 /** Return the opcode number of the last $arch opcode + 1. */
778 int get_$arch\_opcode_last(void) {
779         return $arch\_opcode_end;
780 }
781
782 /** Return 1 if the given opcode is a $arch machine op, 0 otherwise */
783 int is_$arch\_op(const ir_op *op) {
784         return get_op_tag(op) == $arch\_op_tag;
785 }
786
787 /** Return 1 if the given node is a $arch machine node, 0 otherwise */
788 int is_$arch\_irn(const ir_node *node) {
789         return is_$arch\_op(get_irn_op(node));
790 }
791
792 int get_$arch\_irn_opcode(const ir_node *node) {
793         if (is_$arch\_irn(node))
794                 return get_irn_opcode(node) - $arch\_opcode_start;
795         return -1;
796 }
797
798 ENDOFISIRN
799
800 print OUT <<END;
801 #ifdef BIT
802 #undef BIT
803 #endif
804 #define BIT(x)  (1 << (x))
805
806 END
807
808 print OUT @obst_limit_func;
809 print OUT "\n";
810
811 print OUT @obst_reg_reqs;
812 print OUT "\n";
813
814 print OUT<<ENDOFMAIN;
815 $obst_constructor
816
817 /**
818  * Creates the $arch specific Firm machine operations
819  * needed for the assembler irgs.
820  */
821 void $arch\_create_opcodes(const arch_irn_ops_t *be_ops)
822 {
823         ir_op_ops  ops;
824         ir_op     *op;
825         int        cur_opcode = get_next_ir_opcodes(iro_$arch\_last);
826
827         $arch\_opcode_start = cur_opcode;
828 ENDOFMAIN
829
830 print OUT @obst_new_irop;
831 print OUT "\n";
832 print OUT "\t$arch\_register_additional_opcodes(cur_opcode);\n" if (defined($additional_opcodes));
833 print OUT "\t$arch\_opcode_end = cur_opcode + iro_$arch\_last";
834 print OUT " + $additional_opcodes" if (defined($additional_opcodes));
835 print OUT ";\n";
836 print OUT <<ENDOFMAIN;
837 }
838
839 void $arch\_free_opcodes(void)
840 {
841 ENDOFMAIN
842
843 print OUT @obst_free_irop;
844
845 print OUT <<ENDOFMAIN;
846 }
847 ENDOFMAIN
848
849 close(OUT);
850
851 open(OUT, ">$target_h") || die("Fatal error: Could not open $target_h, reason: $!\n");
852
853 my $creation_time = localtime(time());
854 my $tmp = uc($arch);
855
856 print OUT<<EOF;
857 /**
858  * \@file
859  * \@brief Function prototypes for the new opcode functions.
860  * \@note  DO NOT EDIT THIS FILE, your changes will be lost.
861  *        Edit $specfile instead.
862  *        created by: $0 $specfile $target_dir
863  * \@date  $creation_time
864  */
865 #ifndef FIRM_BE_${tmp}_GEN_${tmp}_NEW_NODES_H
866 #define FIRM_BE_${tmp}_GEN_${tmp}_NEW_NODES_H
867
868 EOF
869
870 print OUT @obst_enum_op;
871 print OUT <<EOF;
872 int is_${arch}_irn(const ir_node *node);
873 int is_${arch}_op(const ir_op *op);
874
875 int get_${arch}_opcode_first(void);
876 int get_${arch}_opcode_last(void);
877 int get_${arch}_irn_opcode(const ir_node *node);
878 ${obst_header}
879 ${obst_proj}
880
881 #endif
882 EOF
883
884 close(OUT);
885
886 ###
887 # Translates numeric arity into string constant.
888 ###
889 sub translate_arity {
890         my $arity = shift;
891
892         if ($arity =~ /^\d+$/) {
893                 if    ($arity == 0) {
894                         return "oparity_zero";
895                 }
896                 elsif ($arity == 1) {
897                         return "oparity_unary";
898                 }
899                 elsif ($arity == 2) {
900                         return "oparity_binary";
901                 }
902                 elsif ($arity == 3) {
903                         return "oparity_trinary";
904                 }
905                 else {
906                         return "oparity_any";
907                 }
908         } elsif ($arity == $ARITY_VARIABLE) {
909                 return "oparity_variable";
910         } elsif ($arity == $ARITY_DYNAMIC) {
911                 return "oparity_dynamic";
912         } else {
913                 die "Fatal error: Unknown arity $arity";
914         }
915 }
916
917 sub mangle_requirements {
918         my $reqs  = shift;
919         my $class = shift;
920         my $flags = shift;
921
922         my @alternatives = split(/ /, $reqs);
923         for(my $idx = 0; $idx < scalar(@alternatives); $idx++) {
924                 $alternatives[$idx] =~ s/!/not_/g;
925         }
926
927         @alternatives = sort @alternatives;
928
929         my $name = $class."_".join('_', @alternatives);
930         if (defined($flags)) {
931                 $flags =~ s/\|/_/g;
932                 $name .= "_$flags";
933         }
934
935         return $name;
936 }
937
938 ###
939 # Determines whether $name is a specified register class or not.
940 # @return 1 if name is register class, 0 otherwise
941 ###
942 sub is_reg_class {
943     my $name = shift;
944     return 1 if exists($reg_classes{"$name"});
945     return 0;
946 }
947
948 ###
949 # Returns the register class for a given register.
950 # @return class or undef
951 ###
952 sub get_reg_class {
953     my $reg = shift;
954     $reg = substr($reg, 1) if ($reg =~ /!.*/);
955     return $reg2class{"$reg"}{"class"} if (exists($reg2class{"$reg"}));
956     return undef;
957 }
958
959 ###
960 # Returns the index of a given register within its register class.
961 # @return index or undef
962 ###
963 sub get_reg_index {
964     my $reg = shift;
965     return $reg2class{"$reg"}{"index"} if (exists($reg2class{"$reg"}));
966     return undef;
967 }
968
969 ###
970 # Remember the register class for each index in the given requirements.
971 # We need this information for requirements like "in_sX" or "out_dX"
972 # @return array of classes corresponding to the requirement for each index
973 ###
974 sub build_inout_idx_class {
975         my $n     = shift;
976         my $op    = shift;
977         my $is_in = shift;
978         my @idx_class;
979
980         my $inout = ($is_in ? "in" : "out");
981
982         if (exists($n->{"reg_req"}{"$inout"})) {
983                 my @reqs = @{ $n->{"reg_req"}{"$inout"} };
984
985                 for (my $idx = 0; $idx <= $#reqs; $idx++) {
986                         my $class = undef;
987                         my ($req,) = split(/:/, $reqs[$idx]);
988
989                         if ($req eq "none") {
990                                 $class = "none";
991                         } elsif (is_reg_class($req)) {
992                                 $class = $req;
993                         } else {
994                                 my @regs = split(/ /, $req);
995 GET_CLASS:              foreach my $reg (@regs) {
996                                         if ($reg =~ /!?(in|out)\_r\d+/ || $reg =~ /!in/) {
997                                                 $class = "UNKNOWN_CLASS";
998                                         } else {
999                                                 $class = get_reg_class($reg);
1000                                                 if (!defined $class) {
1001                                                         die("Fatal error: Could not get ".uc($inout)." register class for '$op' pos $idx (reg $reg) ... exiting.\n");
1002                                                 } else {
1003                                                         last GET_CLASS;
1004                                                 } # !defined class
1005                                         } # if (reg =~ ...
1006                                 } # foreach
1007                         } # if
1008
1009                         push(@idx_class, $class);
1010                 } # for
1011         } # if
1012
1013         return @idx_class;
1014 }
1015
1016 ###
1017 # Generates the function for a given $op and a given IN-index
1018 # which returns a subset of possible register from a register class
1019 # @return classname from which the subset is derived or undef and
1020 #         pos which corresponds to in/out reference position or undef
1021 ###
1022 sub build_subset_class_func {
1023         my $neg           = undef;
1024         my $class         = undef;
1025         my $has_limit     = 0;
1026         my $limit_name;
1027         my $same_pos      = 0;
1028         my $different_pos = 0;
1029         my $temp;
1030         my @obst_init;
1031         my @obst_limits;
1032         my @obst_ignore;
1033         my @limit_array;
1034         my $limit_reqs;   #used for name mangling
1035
1036         # build function header
1037         my $node  = shift;
1038         my $op    = shift;
1039         my $idx   = shift;
1040         my $is_in = shift;
1041         my @regs  = split(/ /, shift);
1042         my $flags = shift;
1043
1044         my @idx_class = build_inout_idx_class($node, $op, !$is_in);
1045
1046         # set/unset registers
1047 CHECK_REQS: foreach (@regs) {
1048                 if (!$is_in && /(!)?in_r(\d+)/) {
1049                         my $bit_pos = 1 << ($2 - 1);
1050                         if ($different_pos & $bit_pos) {
1051                                 if ($1) {
1052                                         print STDERR "duplicate !in constraint\n";
1053                                 } else {
1054                                         print STDERR "conflicting !in and in constraints\n";
1055                                 }
1056                                 return (undef, undef, undef, undef);
1057                         }
1058
1059                         if ($same_pos & $bit_pos) {
1060                                 if ($1) {
1061                                         print STDERR "conflicting !in and in constraints\n";
1062                                 } else {
1063                                         print STDERR "duplicate in constraint\n";
1064                                 }
1065                                 return (undef, undef, undef, undef);
1066                         }
1067
1068                         if ($1) {
1069                                 $different_pos |= $bit_pos;
1070                         } else {
1071                                 $same_pos      |= $bit_pos;
1072                         }
1073
1074                         $class = $idx_class[$2 - 1];
1075                         next CHECK_REQS;
1076                 }
1077
1078                 # check for negate
1079                 if (substr($_, 0, 1) eq "!") {
1080                         if (defined($neg) && $neg == 0) {
1081                                 # we have seen a positiv constraint as first one but this one is negative
1082                                 # this doesn't make sense
1083                                 print STDERR "Mixed positive and negative constraints for the same slot are not allowed.\n";
1084                                 return (undef, undef, undef, undef);
1085                         }
1086
1087                         if (!defined($neg)) {
1088                                 $has_limit = 1;
1089                         }
1090
1091                         $_   = substr($_, 1); # skip '!'
1092                         $neg = 1;
1093                 } else {
1094                         if (defined($neg) && $neg == 1) {
1095                                 # we have seen a negative constraint as first one but this one is positive
1096                                 # this doesn't make sense
1097                                 print STDERR "Mixed positive and negative constraints for the same slot are not allowed.\n";
1098                                 return (undef, undef, undef, undef);
1099                         }
1100
1101                         $has_limit = 1;
1102                         $neg = 0;
1103                 }
1104
1105                 # check if register belongs to one of the given classes
1106                 $temp = get_reg_class($_);
1107                 if (!defined($temp)) {
1108                         print STDERR "Unknown register '$_'!\n";
1109                         return (undef, undef, undef, undef);
1110                 }
1111
1112                 # set class
1113                 if (!defined($class)) {
1114                         $class = $temp;
1115                 } elsif ($class ne $temp) {
1116                         # all registers must belong to the same class
1117                         print STDERR "Registerclass mismatch. '$_' is not member of class '$class'.\n";
1118                         return (undef, undef, undef, undef);
1119                 }
1120
1121                 # calculate position inside the initializer bitfield (only 32 bits per
1122                 # element)
1123                 my $regidx = get_reg_index($_);
1124                 my $arrayp = $regidx / 32;
1125                 push(@{$limit_array[$arrayp]}, $_);
1126                 $limit_reqs .= "$_ ";
1127         }
1128
1129         # don't allow ignore regs in negative constraints
1130         if($neg) {
1131                 my @cur_class = @{ $reg_classes{"$class"} };
1132                 for (my $idx = 0; $idx <= $#cur_class; $idx++) {
1133                         if (defined($cur_class[$idx]{"type"}) && ($cur_class[$idx]{"type"} & 4)) {
1134                                 my $reg    = $cur_class[$idx]{"name"};
1135                                 my $regix  = get_reg_index($reg);
1136                                 my $arrayp = $regix / 32;
1137                                 push(@{$limit_array[$arrayp]}, $reg);
1138                                 $limit_reqs .= "$reg ";
1139                         }
1140                 }
1141         }
1142
1143         if ($has_limit == 1) {
1144                 $limit_name = "${arch}_limit_".mangle_requirements($limit_reqs, $class);
1145
1146                 if(defined($limit_bitsets{$limit_name})) {
1147                         $limit_name = $limit_bitsets{$limit_name};
1148                         return ($class, $limit_name, $same_pos, $different_pos);
1149                 }
1150
1151                 $limit_bitsets{$limit_name} = $limit_name;
1152
1153                 push(@obst_limit_func, "static const unsigned " . $limit_name . "[] = { ");
1154                 my $first = 1;
1155                 my $limitbitsetlen = $regclass2len{$class};
1156                 my $limitarraylen = ($limitbitsetlen+31) / 32;
1157                 for(my $i = 0; $i < $limitarraylen; $i++) {
1158
1159                         my $limitarraypart = $limit_array[$i];
1160                         if($first) {
1161                                 $first = 0;
1162                         } else {
1163                                 push(@obst_limit_func, ", ");
1164                         }
1165                         my $temp;
1166                         if($neg) {
1167                                 $temp = "0xFFFFFFFF";
1168                         }
1169                         foreach my $reg (@{$limitarraypart}) {
1170                                 if($neg) {
1171                                         $temp .= " & ~";
1172                                 } elsif(defined($temp)) {
1173                                         $temp .= " | ";
1174                                 }
1175                                 my $firstreg = uc($reg_classes{$class}[0]->{"name"});
1176                                 my $classuc = uc($class);
1177                                 my $reguc = uc($reg);
1178                                 $temp .= "BIT(REG_${classuc}_${reguc})";
1179                         }
1180                         if(defined($temp)) {
1181                                 push(@obst_limit_func, "${temp}");
1182                         } else {
1183                                 push(@obst_limit_func, "0");
1184                         }
1185                 }
1186                 push(@obst_limit_func, " };\n");
1187         }
1188
1189         return ($class, $limit_name, $same_pos, $different_pos);
1190 }
1191
1192 ###
1193 # Generate register requirements structure
1194 ###
1195 sub generate_requirements {
1196         my ($reqs, $flags) = split(/:/, shift);
1197         my $node  = shift;
1198         my $op    = shift;
1199         my $idx   = shift;
1200         my $is_in = shift;
1201         my $class = "";
1202         my $width = 1;
1203         my $result;
1204
1205         my @req_type_mask;
1206         if (defined($flags)) {
1207                 foreach my $f (split(/|/, $flags)) {
1208                         if ($f eq "I") {
1209                                 push(@req_type_mask, "arch_register_req_type_ignore");
1210                         } elsif ($f eq "S") {
1211                                 push(@req_type_mask, "arch_register_req_type_produces_sp");
1212                         } elsif ($f eq "a") {
1213                                 push(@req_type_mask, "arch_register_req_type_aligned");
1214                         } elsif ($f eq "2" or $f eq "4" or $f eq "8") {
1215                                 $width = int($f);
1216                         }
1217                 }
1218         }
1219
1220         if ($reqs eq "none") {
1221
1222                 $result = <<EOF;
1223 {
1224         arch_register_req_type_none,
1225         NULL,                         /* regclass */
1226         NULL,                         /* limit bitset */
1227         0,                            /* same pos */
1228         0,                            /* different pos */
1229         0                             /* width */
1230 };
1231
1232 EOF
1233         } elsif (is_reg_class($reqs)) {
1234                 push(@req_type_mask, "arch_register_req_type_normal");
1235                 my $reqtype = join(" | ", @req_type_mask);
1236                 $class  = $reqs;
1237                 $result = <<EOF;
1238 {
1239         ${reqtype},
1240         & ${arch}_reg_classes[CLASS_${arch}_${class}],
1241         NULL,        /* limit bitset */
1242         0,           /* same pos */
1243         0,           /* different pos */
1244         $width            /* width */
1245 };
1246
1247 EOF
1248
1249         } else {
1250                 my ($regclass, $limit_bitset, $same_pos, $different_pos)
1251                         = build_subset_class_func($node, $op, $idx, $is_in, $reqs, $flags);
1252
1253                 if (!defined($regclass)) {
1254                         die("Fatal error: Could not build subset for requirements '$reqs' of '$op' pos $idx ... exiting.\n");
1255                 }
1256
1257                 if (defined($limit_bitset) && $limit_bitset ne "NULL") {
1258                         push(@req_type_mask, "arch_register_req_type_limited");
1259                 }
1260                 if ($same_pos != 0) {
1261                         push(@req_type_mask, "arch_register_req_type_should_be_same");
1262                 }
1263                 if ($different_pos != 0) {
1264                         push(@req_type_mask, "arch_register_req_type_must_be_different");
1265                 }
1266                 my $reqtype = join(" | ", @req_type_mask);
1267
1268                 if(!defined($limit_bitset)) {
1269                         $limit_bitset = "NULL";
1270                 }
1271
1272                 $class  = $regclass;
1273                 $result = <<EOF;
1274 {
1275         ${reqtype},
1276         & ${arch}_reg_classes[CLASS_${arch}_${class}],
1277         ${limit_bitset},
1278         ${same_pos},        /* same pos */
1279         ${different_pos},       /* different pos */
1280         $width             /* width */
1281 };
1282
1283 EOF
1284         }
1285
1286         my $name = "${arch}_requirements_".mangle_requirements($reqs, $class, $flags);
1287         if(defined($requirements{$name})) {
1288                 return $name;
1289         }
1290         $requirements{$name} = $name;
1291         push(@obst_reg_reqs, <<EOF);
1292 static const arch_register_req_t ${name} = ${result}
1293 EOF
1294
1295         return $name;
1296 }