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