Add {vex3} and {vex2} prefixes by analogy with {evex}
[platform/upstream/nasm.git] / insns.pl
1 #!/usr/bin/perl
2 ## --------------------------------------------------------------------------
3 ##
4 ##   Copyright 1996-2013 The NASM Authors - All Rights Reserved
5 ##   See the file AUTHORS included with the NASM distribution for
6 ##   the specific copyright holders.
7 ##
8 ##   Redistribution and use in source and binary forms, with or without
9 ##   modification, are permitted provided that the following
10 ##   conditions are met:
11 ##
12 ##   * Redistributions of source code must retain the above copyright
13 ##     notice, this list of conditions and the following disclaimer.
14 ##   * Redistributions in binary form must reproduce the above
15 ##     copyright notice, this list of conditions and the following
16 ##     disclaimer in the documentation and/or other materials provided
17 ##     with the distribution.
18 ##
19 ##     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
20 ##     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
21 ##     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
22 ##     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23 ##     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
24 ##     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 ##     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26 ##     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 ##     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 ##     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 ##     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
30 ##     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
31 ##     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 ##
33 ## --------------------------------------------------------------------------
34
35 #
36 # insns.pl
37 #
38 # Parse insns.dat and produce generated source code files
39
40 require 'insns-iflags.pl';
41
42 # Opcode prefixes which need their own opcode tables
43 # LONGER PREFIXES FIRST!
44 @disasm_prefixes = qw(0F24 0F25 0F38 0F3A 0F7A 0FA6 0FA7 0F);
45
46 # This should match MAX_OPERANDS from nasm.h
47 $MAX_OPERANDS = 5;
48
49 # Add VEX/XOP prefixes
50 @vex_class = ( 'vex', 'xop', 'evex' );
51 $vex_classes = scalar(@vex_class);
52 @vexlist = ();
53 %vexmap = ();
54 for ($c = 0; $c < $vex_classes; $c++) {
55     $vexmap{$vex_class[$c]} = $c;
56     for ($m = 0; $m < 32; $m++) {
57         for ($p = 0; $p < 4; $p++) {
58             push(@vexlist, sprintf("%s%02X%01X", $vex_class[$c], $m, $p));
59         }
60     }
61 }
62 @disasm_prefixes = (@vexlist, @disasm_prefixes);
63
64 @bytecode_count = (0) x 256;
65
66 print STDERR "Reading insns.dat...\n";
67
68 @args   = ();
69 undef $output;
70 foreach $arg ( @ARGV ) {
71     if ( $arg =~ /^\-/ ) {
72         if  ( $arg =~ /^\-([abdin]|f[hc])$/ ) {
73             $output = $1;
74         } else {
75             die "$0: Unknown option: ${arg}\n";
76         }
77     } else {
78         push (@args, $arg);
79     }
80 }
81
82 $fname = "insns.dat" unless $fname = $args[0];
83 open (F, $fname) || die "unable to open $fname";
84
85 %dinstables = ();
86 @bytecode_list = ();
87
88 $line = 0;
89 $insns = 0;
90 while (<F>) {
91     $line++;
92     chomp;
93     next if ( /^\s*(\;.*|)$/ );   # comments or blank lines
94
95     unless (/^\s*(\S+)\s+(\S+)\s+(\S+|\[.*\])\s+(\S+)\s*$/) {
96         warn "line $line does not contain four fields\n";
97         next;
98     }
99     @fields = ($1, $2, $3, $4);
100     @field_list = ([@fields, 0]);
101
102     if ($fields[1] =~ /\*/) {
103         # This instruction has relaxed form(s)
104         if ($fields[2] !~ /^\[/) {
105             warn "line $line has an * operand but uses raw bytecodes\n";
106             next;
107         }
108
109         $opmask = 0;
110         @ops = split(/,/, $fields[1]);
111         for ($oi = 0; $oi < scalar @ops; $oi++) {
112             if ($ops[$oi] =~ /\*$/) {
113                 if ($oi == 0) {
114                     warn "line $line has a first operand with a *\n";
115                     next;
116                 }
117                 $opmask |= 1 << $oi;
118             }
119         }
120
121         for ($oi = 1; $oi < (1 << scalar @ops); $oi++) {
122             if (($oi & ~$opmask) == 0) {
123                 my @xops = ();
124                 my $omask = ~$oi;
125                 for ($oj = 0; $oj < scalar(@ops); $oj++) {
126                     if ($omask & 1) {
127                         push(@xops, $ops[$oj]);
128                     }
129                     $omask >>= 1;
130                 }
131                 push(@field_list, [$fields[0], join(',', @xops),
132                      $fields[2], $fields[3], $oi]);
133             }
134         }
135     }
136
137     foreach $fptr (@field_list) {
138         @fields = @$fptr;
139         ($formatted, $nd) = format_insn(@fields);
140         if ($formatted) {
141             $insns++;
142             $aname = "aa_$fields[0]";
143             push @$aname, $formatted;
144         }
145         if ( $fields[0] =~ /cc$/ ) {
146             # Conditional instruction
147             $k_opcodes_cc{$fields[0]}++;
148         } else {
149             # Unconditional instruction
150             $k_opcodes{$fields[0]}++;
151         }
152         if ($formatted && !$nd) {
153             push @big, $formatted;
154             my @sseq = startseq($fields[2], $fields[4]);
155             foreach $i (@sseq) {
156                 if (!defined($dinstables{$i})) {
157                     $dinstables{$i} = [];
158                 }
159                 push(@{$dinstables{$i}}, $#big);
160             }
161         }
162     }
163 }
164
165 close F;
166
167 #
168 # Generate the bytecode array.  At this point, @bytecode_list contains
169 # the full set of bytecodes.
170 #
171
172 # Sort by descending length
173 @bytecode_list = sort { scalar(@$b) <=> scalar(@$a) } @bytecode_list;
174 @bytecode_array = ();
175 %bytecode_pos = ();
176 $bytecode_next = 0;
177 foreach $bl (@bytecode_list) {
178     my $h = hexstr(@$bl);
179     next if (defined($bytecode_pos{$h}));
180
181     push(@bytecode_array, $bl);
182     while ($h ne '') {
183         $bytecode_pos{$h} = $bytecode_next;
184         $h = substr($h, 2);
185         $bytecode_next++;
186     }
187 }
188 undef @bytecode_list;
189
190 @opcodes    = sort keys(%k_opcodes);
191 @opcodes_cc = sort keys(%k_opcodes_cc);
192
193 if ( !defined($output) || $output eq 'b') {
194     print STDERR "Writing insnsb.c...\n";
195
196     open B, ">insnsb.c";
197
198     print B "/* This file auto-generated from insns.dat by insns.pl" .
199         " - don't edit it */\n\n";
200
201     print B "#include \"nasm.h\"\n";
202     print B "#include \"insns.h\"\n\n";
203
204     print B "const uint8_t nasm_bytecodes[$bytecode_next] = {\n";
205
206     $p = 0;
207     foreach $bl (@bytecode_array) {
208         printf B "    /* %5d */ ", $p;
209         foreach $d (@$bl) {
210             printf B "%#o,", $d;
211             $p++;
212         }
213         printf B "\n";
214     }
215     print B "};\n";
216
217     print B "\n";
218     print B "/*\n";
219     print B " * Bytecode frequencies (including reuse):\n";
220     print B " *\n";
221     for ($i = 0; $i < 32; $i++) {
222         print B " *";
223         for ($j = 0; $j < 256; $j += 32) {
224             print B " |" if ($j);
225             printf B " %3o:%4d", $i+$j, $bytecode_count[$i+$j];
226         }
227         print B "\n";
228     }
229     print B " */\n";
230
231     close B;
232 }
233
234 if ( !defined($output) || $output eq 'a' ) {
235     print STDERR "Writing insnsa.c...\n";
236
237     open A, ">insnsa.c";
238
239     print A "/* This file auto-generated from insns.dat by insns.pl" .
240         " - don't edit it */\n\n";
241
242     print A "#include \"nasm.h\"\n";
243     print A "#include \"insns.h\"\n\n";
244
245     foreach $i (@opcodes, @opcodes_cc) {
246         print A "static const struct itemplate instrux_${i}[] = {\n";
247         $aname = "aa_$i";
248         foreach $j (@$aname) {
249             print A "    ", codesubst($j), "\n";
250         }
251         print A "    ITEMPLATE_END\n};\n\n";
252     }
253     print A "const struct itemplate * const nasm_instructions[] = {\n";
254     foreach $i (@opcodes, @opcodes_cc) {
255         print A "    instrux_${i},\n";
256     }
257     print A "};\n";
258
259     close A;
260 }
261
262 if ( !defined($output) || $output eq 'd' ) {
263     print STDERR "Writing insnsd.c...\n";
264
265     open D, ">insnsd.c";
266
267     print D "/* This file auto-generated from insns.dat by insns.pl" .
268         " - don't edit it */\n\n";
269
270     print D "#include \"nasm.h\"\n";
271     print D "#include \"insns.h\"\n\n";
272
273     print D "static const struct itemplate instrux[] = {\n";
274     $n = 0;
275     foreach $j (@big) {
276         printf D "    /* %4d */ %s\n", $n++, codesubst($j);
277     }
278     print D "};\n";
279
280     foreach $h (sort(keys(%dinstables))) {
281         next if ($h eq ''); # Skip pseudo-instructions
282             print D "\nstatic const struct itemplate * const itable_${h}[] = {\n";
283         foreach $j (@{$dinstables{$h}}) {
284             print D "    instrux + $j,\n";
285         }
286         print D "};\n";
287     }
288
289     @prefix_list = ();
290     foreach $h (@disasm_prefixes, '') {
291         for ($c = 0; $c < 256; $c++) {
292             $nn = sprintf("%s%02X", $h, $c);
293             if ($is_prefix{$nn} || defined($dinstables{$nn})) {
294                 # At least one entry in this prefix table
295                 push(@prefix_list, $h);
296                 $is_prefix{$h} = 1;
297                 last;
298             }
299         }
300     }
301
302     foreach $h (@prefix_list) {
303         print D "\n";
304         print D "static " unless ($h eq '');
305         print D "const struct disasm_index ";
306         print D ($h eq '') ? 'itable' : "itable_$h";
307         print D "[256] = {\n";
308         for ($c = 0; $c < 256; $c++) {
309             $nn = sprintf("%s%02X", $h, $c);
310             if ($is_prefix{$nn}) {
311                 die "$fname: ambiguous decoding of $nn\n"
312                     if (defined($dinstables{$nn}));
313                 printf D "    /* 0x%02x */ { itable_%s, -1 },\n", $c, $nn;
314             } elsif (defined($dinstables{$nn})) {
315                 printf D "    /* 0x%02x */ { itable_%s, %u },\n", $c,
316                        $nn, scalar(@{$dinstables{$nn}});
317             } else {
318                 printf D "    /* 0x%02x */ { NULL, 0 },\n", $c;
319             }
320         }
321         print D "};\n";
322     }
323
324     printf D "\nconst struct disasm_index * const itable_vex[NASM_VEX_CLASSES][32][4] =\n";
325     print D "{\n";
326     for ($c = 0; $c < $vex_classes; $c++) {
327         print D "    {\n";
328         for ($m = 0; $m < 32; $m++) {
329             print D "        { ";
330             for ($p = 0; $p < 4; $p++) {
331                 $vp = sprintf("%s%02X%01X", $vex_class[$c], $m, $p);
332                 printf D "%-15s",
333                        ($is_prefix{$vp} ? sprintf("itable_%s,", $vp) : 'NULL,');
334             }
335             print D "},\n";
336         }
337         print D "    },\n";
338     }
339     print D "};\n";
340
341     close D;
342 }
343
344 if ( !defined($output) || $output eq 'i' ) {
345     print STDERR "Writing insnsi.h...\n";
346
347     open I, ">insnsi.h";
348
349     print I "/* This file is auto-generated from insns.dat by insns.pl" .
350         " - don't edit it */\n\n";
351     print I "/* This file in included by nasm.h */\n\n";
352
353     print I "/* Instruction names */\n\n";
354     print I "#ifndef NASM_INSNSI_H\n";
355     print I "#define NASM_INSNSI_H 1\n\n";
356     print I "enum opcode {\n";
357     $maxlen = 0;
358     foreach $i (@opcodes, @opcodes_cc) {
359         print I "\tI_${i},\n";
360         $len = length($i);
361         $len++ if ( $i =~ /cc$/ ); # Condition codes can be 3 characters long
362         $maxlen = $len if ( $len > $maxlen );
363     }
364     print I "\tI_none = -1\n";
365     print I "};\n\n";
366     print I "#define MAX_INSLEN ", $maxlen, "\n";
367     print I "#define NASM_VEX_CLASSES ", $vex_classes, "\n";
368     print I "#define NO_DECORATOR\t{", join(',',(0) x $MAX_OPERANDS), "}\n";
369     print I "#define FIRST_COND_OPCODE I_", $opcodes_cc[0], "\n\n";
370     print I "#endif /* NASM_INSNSI_H */\n";
371
372     close I;
373 }
374
375 if ( !defined($output) || $output eq 'n' ) {
376     print STDERR "Writing insnsn.c...\n";
377
378     open N, ">insnsn.c";
379
380     print N "/* This file is auto-generated from insns.dat by insns.pl" .
381         " - don't edit it */\n\n";
382     print N "#include \"tables.h\"\n\n";
383
384     print N "const char * const nasm_insn_names[] = {";
385     $first = 1;
386     foreach $i (@opcodes, @opcodes_cc) {
387         print N "," if ( !$first );
388         $first = 0;
389         $ilower = $i;
390         $ilower =~ s/cc$//;             # Remove conditional cc suffix
391         $ilower =~ tr/A-Z/a-z/;         # Change to lower case (Perl 4 compatible)
392         print N "\n\t\"${ilower}\"";
393     }
394     print N "\n};\n";
395     close N;
396 }
397
398 if ( !defined($output) || $output eq 'fh') {
399     write_iflaggen_h();
400 }
401
402 if ( !defined($output) || $output eq 'fc') {
403     write_iflag_c();
404 }
405
406 printf STDERR "Done: %d instructions\n", $insns;
407
408 # Count primary bytecodes, for statistics
409 sub count_bytecodes(@) {
410     my $skip = 0;
411     foreach my $bc (@_) {
412         if ($skip) {
413             $skip--;
414             next;
415         }
416         $bytecode_count[$bc]++;
417         if ($bc >= 01 && $bc <= 04) {
418             $skip = $bc;
419         } elsif (($bc & ~03) == 010) {
420             $skip = 1;
421         } elsif (($bc & ~013) == 0144) {
422             $skip = 1;
423         } elsif ($bc == 0172 || $bc == 0173) {
424             $skip = 1;
425         } elsif (($bc & ~3) == 0260 || $bc == 0270) {   # VEX
426             $skip = 2;
427         } elsif (($bc & ~3) == 0240 || $bc == 0250) {   # EVEX
428             $skip = 3;
429         } elsif ($bc == 0330) {
430             $skip = 1;
431         }
432     }
433 }
434
435 sub format_insn($$$$$) {
436     my ($opcode, $operands, $codes, $flags, $relax) = @_;
437     my $num, $nd = 0, $rawflags, $flagsindex;
438     my @bytecode;
439     my $op, @ops, $opp, @opx, @oppx, @decos, @opevex;
440
441     return (undef, undef) if $operands eq "ignore";
442
443     # format the operands
444     $operands =~ s/\*//g;
445     $operands =~ s/:/|colon,/g;
446     @ops = ();
447     @decos = ();
448     if ($operands ne 'void') {
449         foreach $op (split(/,/, $operands)) {
450             @opx = ();
451             @opevex = ();
452             foreach $opp (split(/\|/, $op)) {
453                 @oppx = ();
454                 if ($opp =~ s/^(b(32|64)|mask|z|er|sae)$//) {
455                     push(@opevex, $1);
456                 }
457
458                 if ($opp =~ s/(?<!\d)(8|16|32|64|80|128|256|512)$//) {
459                     push(@oppx, "bits$1");
460                 }
461                 $opp =~ s/^mem$/memory/;
462                 $opp =~ s/^memory_offs$/mem_offs/;
463                 $opp =~ s/^imm$/immediate/;
464                 $opp =~ s/^([a-z]+)rm$/rm_$1/;
465                 $opp =~ s/^rm$/rm_gpr/;
466                 $opp =~ s/^reg$/reg_gpr/;
467                 # only for evex insns, high-16 regs are allowed
468                 if ($codes !~ /(^|\s)evex\./) {
469                     $opp =~ s/^(rm_[xyz]mm)$/$1_l16/;
470                     $opp =~ s/^([xyz]mm)reg$/$1_l16/;
471                 }
472                 push(@opx, $opp, @oppx) if $opp;
473             }
474             $op = join('|', @opx);
475             push(@ops, $op);
476             push(@decos, (@opevex ? join('|', @opevex) : '0'));
477         }
478     }
479
480     $num = scalar(@ops);
481     while (scalar(@ops) < $MAX_OPERANDS) {
482         push(@ops, '0');
483         push(@decos, '0');
484     }
485     $operands = join(',', @ops);
486     $operands =~ tr/a-z/A-Z/;
487
488     $decorators = "{" . join(',', @decos) . "}";
489     if ($decorators =~ /^{(0,)+0}$/) {
490         $decorators = "NO_DECORATOR";
491     }
492     $decorators =~ tr/a-z/A-Z/;
493
494     # format the flags
495     $nd = 1 if $flags =~ /(^|\,)ND($|\,)/;
496     $flags =~ s/(^|\,)ND($|\,)/\1/g;
497     $flags =~ s/(^|\,)X64($|\,)/\1LONG,X86_64\2/g;
498     if ($codes =~ /evex\./) {
499         $flags .= ",EVEX";
500     } elsif ($codes =~ /(vex|xop)\./) {
501         $flags .= ",VEX";
502     }
503     $rawflags = $flags;
504     $flagsindex = insns_flag_index(split(',',$flags));
505
506     die "Error in flags $rawflags" if not defined($flagsindex);
507
508     @bytecode = (decodify($codes, $relax), 0);
509     push(@bytecode_list, [@bytecode]);
510     $codes = hexstr(@bytecode);
511     count_bytecodes(@bytecode);
512
513     ("{I_$opcode, $num, {$operands}, $decorators, \@\@CODES-$codes\@\@, $flagsindex},", $nd);
514 }
515
516 #
517 # Look for @@CODES-xxx@@ sequences and replace them with the appropriate
518 # offset into nasm_bytecodes
519 #
520 sub codesubst($) {
521     my($s) = @_;
522     my $n;
523
524     while ($s =~ /\@\@CODES-([0-9A-F]+)\@\@/) {
525         my $pos = $bytecode_pos{$1};
526         if (!defined($pos)) {
527             die "$fname: no position assigned to byte code $1\n";
528         }
529         $s = $` . "nasm_bytecodes+${pos}" . "$'";
530     }
531     return $s;
532 }
533
534 sub addprefix ($@) {
535     my ($prefix, @list) = @_;
536     my $x;
537     my @l = ();
538
539     foreach $x (@list) {
540         push(@l, sprintf("%s%02X", $prefix, $x));
541     }
542
543     return @l;
544 }
545
546 #
547 # Turn a code string into a sequence of bytes
548 #
549 sub decodify($$) {
550   # Although these are C-syntax strings, by convention they should have
551   # only octal escapes (for directives) and hexadecimal escapes
552   # (for verbatim bytes)
553     my($codestr, $relax) = @_;
554
555     if ($codestr =~ /^\s*\[([^\]]*)\]\s*$/) {
556         return byte_code_compile($1, $relax);
557     }
558
559     my $c = $codestr;
560     my @codes = ();
561
562     unless ($codestr eq 'ignore') {
563         while ($c ne '') {
564             if ($c =~ /^\\x([0-9a-f]+)(.*)$/i) {
565                 push(@codes, hex $1);
566                 $c = $2;
567                 next;
568             } elsif ($c =~ /^\\([0-7]{1,3})(.*)$/) {
569                 push(@codes, oct $1);
570                 $c = $2;
571                 next;
572             } else {
573                 die "$fname: unknown code format in \"$codestr\"\n";
574             }
575         }
576     }
577
578     return @codes;
579 }
580
581 # Turn a numeric list into a hex string
582 sub hexstr(@) {
583     my $s = '';
584     my $c;
585
586     foreach $c (@_) {
587         $s .= sprintf("%02X", $c);
588     }
589     return $s;
590 }
591
592 # Here we determine the range of possible starting bytes for a given
593 # instruction. We need only consider the codes:
594 # \[1234]      mean literal bytes, of course
595 # \1[0123]     mean byte plus register value
596 # \330         means byte plus condition code
597 # \0 or \340   mean give up and return empty set
598 # \34[4567]    mean PUSH/POP of segment registers: special case
599 # \17[234]     skip is4 control byte
600 # \26x \270    skip VEX control bytes
601 # \24x \250    skip EVEX control bytes
602 sub startseq($$) {
603     my ($codestr, $relax) = @_;
604     my $word, @range;
605     my @codes = ();
606     my $c = $codestr;
607     my $c0, $c1, $i;
608     my $prefix = '';
609
610     @codes = decodify($codestr, $relax);
611
612     while ($c0 = shift(@codes)) {
613         $c1 = $codes[0];
614         if ($c0 >= 01 && $c0 <= 04) {
615             # Fixed byte string
616             my $fbs = $prefix;
617             while (1) {
618                 if ($c0 >= 01 && $c0 <= 04) {
619                     while ($c0--) {
620                         $fbs .= sprintf("%02X", shift(@codes));
621                     }
622                 } else {
623                     last;
624                 }
625                 $c0 = shift(@codes);
626             }
627
628             foreach $pfx (@disasm_prefixes) {
629                 if (substr($fbs, 0, length($pfx)) eq $pfx) {
630                     $prefix = $pfx;
631                     $fbs = substr($fbs, length($pfx));
632                     last;
633                 }
634             }
635
636             if ($fbs ne '') {
637                 return ($prefix.substr($fbs,0,2));
638             }
639
640             unshift(@codes, $c0);
641         } elsif ($c0 >= 010 && $c0 <= 013) {
642             return addprefix($prefix, $c1..($c1+7));
643         } elsif (($c0 & ~013) == 0144) {
644             return addprefix($prefix, $c1, $c1|2);
645         } elsif ($c0 == 0330) {
646             return addprefix($prefix, $c1..($c1+15));
647         } elsif ($c0 == 0 || $c0 == 0340) {
648             return $prefix;
649         } elsif (($c0 & ~3) == 0260 || $c0 == 0270 ||
650                  ($c0 & ~3) == 0240 || $c0 == 0250) {
651             my $c,$m,$wlp;
652             $m   = shift(@codes);
653             $wlp = shift(@codes);
654             $c = ($m >> 6);
655             $m = $m & 31;
656             $prefix .= sprintf('%s%02X%01X', $vex_class[$c], $m, $wlp & 3);
657             if ($c0 < 0260) {
658                 my $tuple = shift(@codes);
659             }
660         } elsif ($c0 >= 0172 && $c0 <= 173) {
661             shift(@codes);      # Skip is4 control byte
662         } else {
663             # We really need to be able to distinguish "forbidden"
664             # and "ignorable" codes here
665         }
666     }
667     return $prefix;
668 }
669
670 # EVEX tuple types offset is 0300. e.g. 0301 is for full vector(fv).
671 sub tupletype($) {
672     my ($tuplestr) = @_;
673     my %tuple_codes = (
674         ''      => 000,
675         'fv'    => 001,
676         'hv'    => 002,
677         'fvm'   => 003,
678         't1s8'  => 004,
679         't1s16' => 005,
680         't1s'   => 006,
681         't1f32' => 007,
682         't1f64' => 010,
683         't2'    => 011,
684         't4'    => 012,
685         't8'    => 013,
686         'hvm'   => 014,
687         'qvm'   => 015,
688         'ovm'   => 016,
689         'm128'  => 017,
690         'dup'   => 020,
691     );
692
693     if (defined $tuple_codes{$tuplestr}) {
694         return 0300 + $tuple_codes{$tuplestr};
695     } else {
696         die "Undefined tuple type : $tuplestr\n";
697     }
698 }
699
700 #
701 # This function takes a series of byte codes in a format which is more
702 # typical of the Intel documentation, and encode it.
703 #
704 # The format looks like:
705 #
706 # [operands: opcodes]
707 #
708 # The operands word lists the order of the operands:
709 #
710 # r = register field in the modr/m
711 # m = modr/m
712 # v = VEX "v" field
713 # i = immediate
714 # s = register field of is4/imz2 field
715 # - = implicit (unencoded) operand
716 # x = indeX register of mib. 014..017 bytecodes are used.
717 #
718 # For an operand that should be filled into more than one field,
719 # enter it as e.g. "r+v".
720 #
721 sub byte_code_compile($$) {
722     my($str, $relax) = @_;
723     my $opr;
724     my $opc;
725     my @codes = ();
726     my $litix = undef;
727     my %oppos = ();
728     my $i;
729     my $op, $oq;
730     my $opex;
731
732     my %imm_codes = (
733         'ib'        => 020,     # imm8
734         'ib,u'      => 024,     # Unsigned imm8
735         'iw'        => 030,     # imm16
736         'ib,s'      => 0274,    # imm8 sign-extended to opsize or bits
737         'iwd'       => 034,     # imm16 or imm32, depending on opsize
738         'id'        => 040,     # imm32
739         'id,s'      => 0254,    # imm32 sign-extended to 64 bits
740         'iwdq'      => 044,     # imm16/32/64, depending on addrsize
741         'rel8'      => 050,
742         'iq'        => 054,
743         'rel16'     => 060,
744         'rel'       => 064,     # 16 or 32 bit relative operand
745         'rel32'     => 070,
746         'seg'       => 074,
747     );
748     my %plain_codes = (
749         'o16'       => 0320,    # 16-bit operand size
750         'o32'       => 0321,    # 32-bit operand size
751         'odf'       => 0322,    # Operand size is default
752         'o64'       => 0324,    # 64-bit operand size requiring REX.W
753         'o64nw'     => 0323,    # Implied 64-bit operand size (no REX.W)
754         'a16'       => 0310,
755         'a32'       => 0311,
756         'adf'       => 0312,    # Address size is default
757         'a64'       => 0313,
758         '!osp'      => 0364,
759         '!asp'      => 0365,
760         'f2i'       => 0332,    # F2 prefix, but 66 for operand size is OK
761         'f3i'       => 0333,    # F3 prefix, but 66 for operand size is OK
762         'mustrep'   => 0336,
763         'mustrepne' => 0337,
764         'rex.l'     => 0334,
765         'norexb'    => 0314,
766         'norexx'    => 0315,
767         'norexr'    => 0316,
768         'norexw'    => 0317,
769         'repe'      => 0335,
770         'nohi'      => 0325,    # Use spl/bpl/sil/dil even without REX
771         'nof3'      => 0326,    # No REP 0xF3 prefix permitted
772         'norep'     => 0331,    # No REP prefix permitted
773         'wait'      => 0341,    # Needs a wait prefix
774         'resb'      => 0340,
775         'jcc8'      => 0370,    # Match only if Jcc possible with single byte
776         'jmp8'      => 0371,    # Match only if JMP possible with single byte
777         'jlen'      => 0373,    # Length of jump
778         'hlexr'     => 0271,
779         'hlenl'     => 0272,
780         'hle'       => 0273,
781
782         # This instruction takes XMM VSIB
783         'vsibx'     => 0374,
784         'vm32x'     => 0374,
785         'vm64x'     => 0374,
786
787         # This instruction takes YMM VSIB
788         'vsiby'     => 0375,
789         'vm32y'     => 0375,
790         'vm64y'     => 0375,
791
792         # This instruction takes ZMM VSIB
793         'vsibz'     => 0376,
794         'vm32z'     => 0376,
795         'vm64z'     => 0376,
796     );
797
798     unless ($str =~ /^(([^\s:]*)\:*([^\s:]*)\:|)\s*(.*\S)\s*$/) {
799         die "$fname: $line: cannot parse: [$str]\n";
800     }
801     $opr = "\L$2";
802     $tuple = "\L$3";    # Tuple type for AVX512
803     $opc = "\L$4";
804
805     my $op = 0;
806     for ($i = 0; $i < length($opr); $i++) {
807         my $c = substr($opr,$i,1);
808         if ($c eq '+') {
809             $op--;
810         } else {
811             if ($relax & 1) {
812                 $op--;
813             }
814             $relax >>= 1;
815             $oppos{$c} = $op++;
816         }
817     }
818     $tup = tupletype($tuple);
819
820     my $last_imm = 'h';
821     my $prefix_ok = 1;
822     foreach $op (split(/\s*(?:\s|(?=[\/\\]))/, $opc)) {
823         my $pc = $plain_codes{$op};
824
825         if (defined $pc) {
826             # Plain code
827             push(@codes, $pc);
828         } elsif ($prefix_ok && $op =~ /^(66|f2|f3|np)$/) {
829             # 66/F2/F3 prefix used as an opcode extension, or np = no prefix
830             if ($op eq '66') {
831                 push(@codes, 0361);
832             } elsif ($op eq 'f2') {
833                 push(@codes, 0332);
834             } elsif ($op eq 'f3') {
835                 push(@codes, 0333);
836             } else {
837                 push(@codes, 0360);
838             }
839         } elsif ($op =~ /^[0-9a-f]{2}$/) {
840             if (defined($litix) && $litix+$codes[$litix]+1 == scalar @codes &&
841                 $codes[$litix] < 4) {
842                 $codes[$litix]++;
843                 push(@codes, hex $op);
844             } else {
845                 $litix = scalar(@codes);
846                 push(@codes, 01, hex $op);
847             }
848             $prefix_ok = 0;
849         } elsif ($op eq '/r') {
850             if (!defined($oppos{'r'}) || !defined($oppos{'m'})) {
851                 die "$fname: $line: $op requires r and m operands\n";
852             }
853             $opex = (($oppos{'m'} & 4) ? 06 : 0) |
854                 (($oppos{'r'} & 4) ? 05 : 0);
855             push(@codes, $opex) if ($opex);
856             # if mib is composed with two separate operands - ICC style
857             push(@codes, 014 + ($oppos{'x'} & 3)) if (defined($oppos{'x'}));
858             push(@codes, 0100 + (($oppos{'m'} & 3) << 3) + ($oppos{'r'} & 3));
859             $prefix_ok = 0;
860         } elsif ($op =~ m:^/([0-7])$:) {
861             if (!defined($oppos{'m'})) {
862                 die "$fname: $line: $op requires m operand\n";
863             }
864             push(@codes, 06) if ($oppos{'m'} & 4);
865             push(@codes, 0200 + (($oppos{'m'} & 3) << 3) + $1);
866             $prefix_ok = 0;
867         } elsif ($op =~ /^(vex|xop)(|\..*)$/) {
868             my $c = $vexmap{$1};
869             my ($m,$w,$l,$p) = (undef,2,undef,0);
870             my $has_nds = 0;
871             my @subops = split(/\./, $op);
872             shift @subops;      # Drop prefix
873                 foreach $oq (@subops) {
874                     if ($oq eq '128' || $oq eq 'l0' || $oq eq 'lz') {
875                         $l = 0;
876                     } elsif ($oq eq '256' || $oq eq 'l1') {
877                         $l = 1;
878                     } elsif ($oq eq 'lig') {
879                         $l = 2;
880                     } elsif ($oq eq 'w0') {
881                         $w = 0;
882                     } elsif ($oq eq 'w1') {
883                         $w = 1;
884                     } elsif ($oq eq 'wig') {
885                         $w = 2;
886                     } elsif ($oq eq 'ww') {
887                         $w = 3;
888                     } elsif ($oq eq 'p0') {
889                         $p = 0;
890                     } elsif ($oq eq '66' || $oq eq 'p1') {
891                         $p = 1;
892                     } elsif ($oq eq 'f3' || $oq eq 'p2') {
893                         $p = 2;
894                     } elsif ($oq eq 'f2' || $oq eq 'p3') {
895                         $p = 3;
896                     } elsif ($oq eq '0f') {
897                         $m = 1;
898                     } elsif ($oq eq '0f38') {
899                         $m = 2;
900                     } elsif ($oq eq '0f3a') {
901                         $m = 3;
902                     } elsif ($oq =~ /^m([0-9]+)$/) {
903                         $m = $1+0;
904                     } elsif ($oq eq 'nds' || $oq eq 'ndd' || $oq eq 'dds') {
905                         if (!defined($oppos{'v'})) {
906                             die "$fname: $line: vex.$oq without 'v' operand\n";
907                         }
908                         $has_nds = 1;
909                     } else {
910                         die "$fname: $line: undefined VEX subcode: $oq\n";
911                     }
912                 }
913             if (!defined($m) || !defined($w) || !defined($l) || !defined($p)) {
914                 die "$fname: $line: missing fields in VEX specification\n";
915             }
916             if (defined($oppos{'v'}) && !$has_nds) {
917                 die "$fname: $line: 'v' operand without vex.nds or vex.ndd\n";
918             }
919             push(@codes, defined($oppos{'v'}) ? 0260+($oppos{'v'} & 3) : 0270,
920                  ($c << 6)+$m, ($w << 4)+($l << 2)+$p);
921             $prefix_ok = 0;
922         } elsif ($op =~ /^(evex)(|\..*)$/) {
923             my $c = $vexmap{$1};
924             my ($m,$w,$l,$p) = (undef,2,undef,0);
925             my $has_nds = 0;
926             my @subops = split(/\./, $op);
927             shift @subops;      # Drop prefix
928                 foreach $oq (@subops) {
929                     if ($oq eq '128' || $oq eq 'l0' || $oq eq 'lz' || $oq eq 'lig') {
930                         $l = 0;
931                     } elsif ($oq eq '256' || $oq eq 'l1') {
932                         $l = 1;
933                     } elsif ($oq eq '512' || $oq eq 'l2') {
934                         $l = 2;
935                     } elsif ($oq eq 'w0') {
936                         $w = 0;
937                     } elsif ($oq eq 'w1') {
938                         $w = 1;
939                     } elsif ($oq eq 'wig') {
940                         $w = 2;
941                     } elsif ($oq eq 'ww') {
942                         $w = 3;
943                     } elsif ($oq eq 'p0') {
944                         $p = 0;
945                     } elsif ($oq eq '66' || $oq eq 'p1') {
946                         $p = 1;
947                     } elsif ($oq eq 'f3' || $oq eq 'p2') {
948                         $p = 2;
949                     } elsif ($oq eq 'f2' || $oq eq 'p3') {
950                         $p = 3;
951                     } elsif ($oq eq '0f') {
952                         $m = 1;
953                     } elsif ($oq eq '0f38') {
954                         $m = 2;
955                     } elsif ($oq eq '0f3a') {
956                         $m = 3;
957                     } elsif ($oq =~ /^m([0-9]+)$/) {
958                         $m = $1+0;
959                     } elsif ($oq eq 'nds' || $oq eq 'ndd' || $oq eq 'dds') {
960                         if (!defined($oppos{'v'})) {
961                             die "$fname: $line: evex.$oq without 'v' operand\n";
962                         }
963                         $has_nds = 1;
964                     } else {
965                         die "$fname: $line: undefined EVEX subcode: $oq\n";
966                     }
967                 }
968             if (!defined($m) || !defined($w) || !defined($l) || !defined($p)) {
969                 die "$fname: $line: missing fields in EVEX specification\n";
970             }
971             if (defined($oppos{'v'}) && !$has_nds) {
972                 die "$fname: $line: 'v' operand without evex.nds or evex.ndd\n";
973             }
974             push(@codes, defined($oppos{'v'}) ? 0240+($oppos{'v'} & 3) : 0250,
975                  ($c << 6)+$m, ($w << 4)+($l << 2)+$p, $tup);
976             $prefix_ok = 0;
977         } elsif (defined $imm_codes{$op}) {
978             if ($op eq 'seg') {
979                 if ($last_imm lt 'i') {
980                     die "$fname: $line: seg without an immediate operand\n";
981                 }
982             } else {
983                 $last_imm++;
984                 if ($last_imm gt 'j') {
985                     die "$fname: $line: too many immediate operands\n";
986                 }
987             }
988             if (!defined($oppos{$last_imm})) {
989                 die "$fname: $line: $op without '$last_imm' operand\n";
990             }
991             push(@codes, 05) if ($oppos{$last_imm} & 4);
992             push(@codes, $imm_codes{$op} + ($oppos{$last_imm} & 3));
993             $prefix_ok = 0;
994         } elsif ($op eq '/is4') {
995             if (!defined($oppos{'s'})) {
996                 die "$fname: $line: $op without 's' operand\n";
997             }
998             if (defined($oppos{'i'})) {
999                 push(@codes, 0172, ($oppos{'s'} << 3)+$oppos{'i'});
1000             } else {
1001                 push(@codes, 05) if ($oppos{'s'} & 4);
1002                 push(@codes, 0174+($oppos{'s'} & 3));
1003             }
1004             $prefix_ok = 0;
1005         } elsif ($op =~ /^\/is4\=([0-9]+)$/) {
1006             my $imm = $1;
1007             if (!defined($oppos{'s'})) {
1008                 die "$fname: $line: $op without 's' operand\n";
1009             }
1010             if ($imm < 0 || $imm > 15) {
1011                 die "$fname: $line: invalid imm4 value for $op: $imm\n";
1012             }
1013             push(@codes, 0173, ($oppos{'s'} << 4) + $imm);
1014             $prefix_ok = 0;
1015         } elsif ($op =~ /^([0-9a-f]{2})\+c$/) {
1016             push(@codes, 0330, hex $1);
1017             $prefix_ok = 0;
1018         } elsif ($op =~ /^([0-9a-f]{2})\+r$/) {
1019             if (!defined($oppos{'r'})) {
1020                 die "$fname: $line: $op without 'r' operand\n";
1021             }
1022             push(@codes, 05) if ($oppos{'r'} & 4);
1023             push(@codes, 010 + ($oppos{'r'} & 3), hex $1);
1024             $prefix_ok = 0;
1025         } elsif ($op =~ /^\\([0-7]+|x[0-9a-f]{2})$/) {
1026             # Escape to enter literal bytecodes
1027             push(@codes, oct $1);
1028         } else {
1029             die "$fname: $line: unknown operation: $op\n";
1030         }
1031     }
1032
1033     return @codes;
1034 }