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