use "=" instead of "|=", fix typo
[openssl.git] / crypto / perlasm / x86_64-xlate.pl
1 #!/usr/bin/env perl
2
3 # Ascetic x86_64 AT&T to MASM assembler translator by <appro>.
4 #
5 # Why AT&T to MASM and not vice versa? Several reasons. Because AT&T
6 # format is way easier to parse. Because it's simpler to "gear" from
7 # Unix ABI to Windows one [see cross-reference "card" at the end of
8 # file]. Because Linux targets were available first...
9 #
10 # In addition the script also "distills" code suitable for GNU
11 # assembler, so that it can be compiled with more rigid assemblers,
12 # such as Solaris /usr/ccs/bin/as.
13 #
14 # This translator is not designed to convert *arbitrary* assembler
15 # code from AT&T format to MASM one. It's designed to convert just
16 # enough to provide for dual-ABI OpenSSL modules development...
17 # There *are* limitations and you might have to modify your assembler
18 # code or this script to achieve the desired result...
19 #
20 # Currently recognized limitations:
21 #
22 # - can't use multiple ops per line;
23 # - indirect calls and jumps are not supported;
24 #
25 # Dual-ABI styling rules.
26 #
27 # 1. Adhere to Unix register and stack layout [see the end for
28 #    explanation].
29 # 2. Forget about "red zone," stick to more traditional blended
30 #    stack frame allocation. If volatile storage is actually required
31 #    that is. If not, just leave the stack as is.
32 # 3. Functions tagged with ".type name,@function" get crafted with
33 #    unified Win64 prologue and epilogue automatically. If you want
34 #    to take care of ABI differences yourself, tag functions as
35 #    ".type name,@abi-omnipotent" instead.
36 # 4. To optimize the Win64 prologue you can specify number of input
37 #    arguments as ".type name,@function,N." Keep in mind that if N is
38 #    larger than 6, then you *have to* write "abi-omnipotent" code,
39 #    because >6 cases can't be addressed with unified prologue.
40 # 5. Name local labels as .L*, do *not* use dynamic labels such as 1:
41 #    (sorry about latter).
42 # 6. Don't use [or hand-code with .byte] "rep ret." "ret" mnemonic is
43 #    required to identify the spots, where to inject Win64 epilogue!
44 #    But on the pros, it's then prefixed with rep automatically:-)
45 # 7. Due to MASM limitations [and certain general counter-intuitivity
46 #    of ip-relative addressing] generation of position-independent
47 #    code is assisted by synthetic directive, .picmeup, which puts
48 #    address of the *next* instruction into target register.
49 #
50 #    Example 1:
51 #               .picmeup        %rax
52 #               lea             .Label-.(%rax),%rax
53 #    Example 2:
54 #               .picmeup        %rcx
55 #       .Lpic_point:
56 #               ...
57 #               lea             .Label-.Lpic_point(%rcx),%rbp
58
59 my $output = shift;
60 open STDOUT,">$output" || die "can't open $output: $!";
61
62 my $masm=1 if ($output =~ /\.asm/);
63
64 my $current_segment;
65 my $current_function;
66
67 { package opcode;       # pick up opcodes
68     sub re {
69         my      $self = shift;  # single instance in enough...
70         local   *line = shift;
71         undef   $ret;
72
73         if ($line =~ /^([a-z]+)/i) {
74             $self->{op} = $1;
75             $ret = $self;
76             $line = substr($line,@+[0]); $line =~ s/^\s+//;
77
78             undef $self->{sz};
79             if ($self->{op} =~ /(movz)b.*/) {   # movz is pain...
80                 $self->{op} = $1;
81                 $self->{sz} = "b";
82             } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])/) {
83                 $self->{op} = $1;
84                 $self->{sz} = $2;
85             }
86         }
87         $ret;
88     }
89     sub size {
90         my $self = shift;
91         my $sz   = shift;
92         $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
93         $self->{sz};
94     }
95     sub out {
96         my $self = shift;
97         if (!$masm) {
98             if ($self->{op} eq "movz") {        # movz in pain...
99                 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
100             } elsif ($self->{op} eq "ret") {
101                 ".byte  0xf3,0xc3";
102             } else {
103                 "$self->{op}$self->{sz}";
104             }
105         } else {
106             $self->{op} =~ s/movz/movzx/;
107             if ($self->{op} eq "ret") {
108                 $self->{op} = "";
109                 if ($current_function->{abi} eq "svr4") {
110                     $self->{op} = "mov  rdi,QWORD PTR 8[rsp]\t;WIN64 epilogue\n\t".
111                                   "mov  rsi,QWORD PTR 16[rsp]\n\t";
112                 }
113                 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
114             }
115             $self->{op};
116         }
117     }
118 }
119 { package const;        # pick up constants, which start with $
120     sub re {
121         my      $self = shift;  # single instance in enough...
122         local   *line = shift;
123         undef   $ret;
124
125         if ($line =~ /^\$([^,]+)/) {
126             $self->{value} = $1;
127             $ret = $self;
128             $line = substr($line,@+[0]); $line =~ s/^\s+//;
129         }
130         $ret;
131     }
132     sub out {
133         my $self = shift;
134
135         if (!$masm) {
136             sprintf "\$%s",$self->{value};
137         } else {
138             $self->{value} =~ s/0x([0-9a-f]+)/0$1h/ig;
139             sprintf "%s",$self->{value};
140         }
141     }
142 }
143 { package ea;           # pick up effective addresses: expr(%reg,%reg,scale)
144     sub re {
145         my      $self = shift;  # single instance in enough...
146         local   *line = shift;
147         undef   $ret;
148
149         if ($line =~ /^([^\(,]*)\(([%\w,]+)\)/) {
150             $self->{label} = $1;
151             ($self->{base},$self->{index},$self->{scale})=split(/,/,$2);
152             $self->{scale} = 1 if (!defined($self->{scale}));
153             $ret = $self;
154             $line = substr($line,@+[0]); $line =~ s/^\s+//;
155
156             $self->{base}  =~ s/^%//;
157             $self->{index} =~ s/^%// if (defined($self->{index}));
158         }
159         $ret;
160     }
161     sub size {}
162     sub out {
163         my $self = shift;
164         my $sz = shift;
165
166         if (!$masm) {
167             # elder GNU assembler insists on 64-bit EAs:-(
168             # on pros side, this results in more compact code:-)
169             $self->{index} =~ s/^[er](.?[0-9xp])[d]?$/r\1/;
170             $self->{base}  =~ s/^[er](.?[0-9xp])[d]?$/r\1/;
171
172             if (defined($self->{index})) {
173                 sprintf "%s(%%%s,%%%s,%d)",
174                                         $self->{label},$self->{base},
175                                         $self->{index},$self->{scale};
176             } else {
177                 sprintf "%s(%%%s)",     $self->{label},$self->{base};
178             }
179         } else {
180             %szmap = ( b=>"BYTE", w=>"WORD", l=>"DWORD", q=>"QWORD" );
181
182             $self->{label} =~ s/\./\$/g;
183             $self->{label} =~ s/0x([0-9a-f]+)/0$1h/ig;
184             $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
185
186             if (defined($self->{index})) {
187                 sprintf "%s PTR %s[%s*%d+%s]",$szmap{$sz},
188                                         $self->{label},
189                                         $self->{index},$self->{scale},
190                                         $self->{base};
191             } else {
192                 sprintf "%s PTR %s[%s]",$szmap{$sz},
193                                         $self->{label},$self->{base};
194             }
195         }
196     }
197 }
198 { package register;     # pick up registers, which start with %.
199     sub re {
200         my      $class = shift; # muliple instances...
201         my      $self = {};
202         local   *line = shift;
203         undef   $ret;
204
205         if ($line =~ /^%(\w+)/) {
206             bless $self,$class;
207             $self->{value} = $1;
208             $ret = $self;
209             $line = substr($line,@+[0]); $line =~ s/^\s+//;
210         }
211         $ret;
212     }
213     sub size {
214         my      $self = shift;
215         undef   $ret;
216
217         if    ($self->{value} =~ /^r[\d]+b$/i)  { $ret="b"; }
218         elsif ($self->{value} =~ /^r[\d]+w$/i)  { $ret="w"; }
219         elsif ($self->{value} =~ /^r[\d]+d$/i)  { $ret="l"; }
220         elsif ($self->{value} =~ /^r[\w]+$/i)   { $ret="q"; }
221         elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
222         elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
223         elsif ($self->{value} =~ /^[\w]{2}$/i)  { $ret="w"; }
224         elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
225
226         $ret;
227     }
228     sub out {
229         my $self = shift;
230         sprintf $masm?"%s":"%%%s",$self->{value};
231     }
232 }
233 { package label;        # pick up labels, which end with :
234     sub re {
235         my      $self = shift;  # single instance is enough...
236         local   *line = shift;
237         undef   $ret;
238
239         if ($line =~ /(^[\.\w]+\:)/) {
240             $self->{value} = $1;
241             $ret = $self;
242             $line = substr($line,@+[0]); $line =~ s/^\s+//;
243
244             $self->{value} =~ s/\.L/\$L/ if ($masm);
245         }
246         $ret;
247     }
248     sub out {
249         my $self = shift;
250
251         if (!$masm) {
252             $self->{value};
253         } elsif ($self->{value} ne "$current_function->{name}:") {
254             $self->{value};
255         } elsif ($current_function->{abi} eq "svr4") {
256             my $func =  "$current_function->{name}      PROC\n".
257                         "       mov     QWORD PTR 8[rsp],rdi\t;WIN64 prologue\n".
258                         "       mov     QWORD PTR 16[rsp],rsi\n";
259             my $narg = $current_function->{narg};
260             $narg=6 if (!defined($narg));
261             $func .= "  mov     rdi,rcx\n" if ($narg>0);
262             $func .= "  mov     rsi,rdx\n" if ($narg>1);
263             $func .= "  mov     rdx,r8\n"  if ($narg>2);
264             $func .= "  mov     rcx,r9\n"  if ($narg>3);
265             $func .= "  mov     r8,QWORD PTR 40[rsp]\n" if ($narg>4);
266             $func .= "  mov     r9,QWORD PTR 48[rsp]\n" if ($narg>5);
267             $func .= "\n";
268         } else {
269            "$current_function->{name}   PROC";
270         }
271     }
272 }
273 { package expr;         # pick up expressioins
274     sub re {
275         my      $self = shift;  # single instance is enough...
276         local   *line = shift;
277         undef   $ret;
278
279         if ($line =~ /(^[^,]+)/) {
280             $self->{value} = $1;
281             $ret = $self;
282             $line = substr($line,@+[0]); $line =~ s/^\s+//;
283
284             $self->{value} =~ s/\.L/\$L/g if ($masm);
285         }
286         $ret;
287     }
288     sub out {
289         my $self = shift;
290         $self->{value};
291     }
292 }
293 { package directive;    # pick up directives, which start with .
294     sub re {
295         my      $self = shift;  # single instance is enough...
296         local   *line = shift;
297         undef   $ret;
298         my      $dir;
299         my      %opcode =       # lea 2f-1f(%rip),%dst; 1: nop; 2:
300                 (       "%rax"=>0x01058d48,     "%rcx"=>0x010d8d48,
301                         "%rdx"=>0x01158d48,     "%rbx"=>0x011d8d48,
302                         "%rsp"=>0x01258d48,     "%rbp"=>0x012d8d48,
303                         "%rsi"=>0x01358d48,     "%rdi"=>0x013d8d48,
304                         "%r8" =>0x01058d4c,     "%r9" =>0x010d8d4c,
305                         "%r10"=>0x01158d4c,     "%r11"=>0x011d8d4c,
306                         "%r12"=>0x01258d4c,     "%r13"=>0x012d8d4c,
307                         "%r14"=>0x01358d4c,     "%r15"=>0x013d8d4c      );
308
309         if ($line =~ /^\s*(\.\w+)/) {
310             if (!$masm) {
311                 $self->{value} = $1;
312                 $line =~ s/\@abi\-omnipotent/\@function/;
313                 $line =~ s/\@function.*/\@function/;
314                 if ($line =~ /\.picmeup\s+(%r[\w]+)/i) {
315                     $self->{value} = sprintf "\t.long\t0x%x,0x90000000",$opcode{$1};
316                 } else {
317                     $self->{value} = $line;
318                 }
319                 $line = "";
320                 return $self;
321             }
322
323             $dir = $1;
324             $ret = $self;
325             undef $self->{value};
326             $line = substr($line,@+[0]); $line =~ s/^\s+//;
327             SWITCH: for ($dir) {
328                 /\.(text)/
329                             && do { my $v=undef;
330                                     $v="$current_segment\tENDS\n" if ($current_segment);
331                                     $current_segment = "_$1\$";
332                                     $current_segment =~ tr/[a-z]/[A-Z]/;
333                                     $v.="$current_segment\tSEGMENT ALIGN(64) 'CODE'";
334                                     $self->{value} = $v;
335                                     last;
336                                   };
337                 /\.globl/   && do { $self->{value} = "PUBLIC\t".$line; last; };
338                 /\.type/    && do { ($sym,$type,$narg) = split(',',$line);
339                                     if ($type eq "\@function") {
340                                         undef $current_function;
341                                         $current_function->{name} = $sym;
342                                         $current_function->{abi}  = "svr4";
343                                         $current_function->{narg} = $narg;
344                                     } elsif ($type eq "\@abi-omnipotent") {
345                                         undef $current_function;
346                                         $current_function->{name} = $sym;
347                                     }
348                                     last;
349                                   };
350                 /\.size/    && do { if (defined($current_function)) {
351                                         $self->{value}="$current_function->{name}\tENDP";
352                                         undef $current_function;
353                                     }
354                                     last;
355                                   };
356                 /\.align/   && do { $self->{value} = "ALIGN\t".$line; last; };
357                 /\.(byte|value|long|quad)/
358                             && do { my @arr = split(',',$line);
359                                     my $sz  = substr($1,0,1);
360                                     my $last = pop(@arr);
361
362                                     $sz =~ tr/bvlq/BWDQ/;
363                                     $self->{value} = "\tD$sz\t";
364                                     for (@arr) { $self->{value} .= sprintf"0%Xh,",oct; }
365                                     $self->{value} .= sprintf"0%Xh",oct($last);
366                                     last;
367                                   };
368                 /\.picmeup/ && do { $self->{value} = sprintf"\tDD\t 0%Xh,090000000h",$opcode{$line};
369                                     last;
370                                   };
371             }
372             $line = "";
373         }
374
375         $ret;
376     }
377     sub out {
378         my $self = shift;
379         $self->{value};
380     }
381 }
382
383 while($line=<>) {
384
385     chomp($line);
386
387     $line =~ s|[#!].*$||;       # get rid of asm-style comments...
388     $line =~ s|/\*.*\*/||;      # ... and C-style comments...
389     $line =~ s|^\s+||;          # ... and skip white spaces in beginning
390
391     undef $label;
392     undef $opcode;
393     undef $dst;
394     undef $src;
395     undef $sz;
396
397     if ($label=label->re(\$line))       { print $label->out(); }
398
399     if (directive->re(\$line)) {
400         printf "%s",directive->out();
401     } elsif ($opcode=opcode->re(\$line)) { ARGUMENT: {
402
403         if ($src=register->re(\$line))  { opcode->size($src->size()); }
404         elsif ($src=const->re(\$line))  { }
405         elsif ($src=ea->re(\$line))     { }
406         elsif ($src=expr->re(\$line))   { }
407
408         last ARGUMENT if ($line !~ /^,/);
409
410         $line = substr($line,1); $line =~ s/^\s+//;
411
412         if ($dst=register->re(\$line))  { opcode->size($dst->size()); }
413         elsif ($dst=const->re(\$line))  { }
414         elsif ($dst=ea->re(\$line))     { }
415
416         } # ARGUMENT:
417
418         $sz=opcode->size();
419
420         if (defined($dst)) {
421             if (!$masm) {
422                 printf "\t%s\t%s,%s",   $opcode->out($dst->size()),
423                                         $src->out($sz),$dst->out($sz);
424             } else {
425                 printf "\t%s\t%s,%s",   $opcode->out(),
426                                         $dst->out($sz),$src->out($sz);
427             }
428         } elsif (defined($src)) {
429             printf "\t%s\t%s",$opcode->out(),$src->out($sz);
430         } else {
431             printf "\t%s",$opcode->out();
432         }
433     }
434
435     print $line,"\n";
436 }
437
438 print "\n$current_segment\tENDS\nEND\n" if ($masm);
439
440 close STDOUT;
441
442 #################################################
443 # Cross-reference x86_64 ABI "card"
444 #
445 #               Unix            Win64
446 # %rax          *               *
447 # %rbx          -               -
448 # %rcx          #4              #1
449 # %rdx          #3              #2
450 # %rsi          #2              -
451 # %rdi          #1              -
452 # %rbp          -               -
453 # %rsp          -               -
454 # %r8           #5              #3
455 # %r9           #6              #4
456 # %r10          *               *
457 # %r11          *               *
458 # %r12          -               -
459 # %r13          -               -
460 # %r14          -               -
461 # %r15          -               -
462
463 # (*)   volatile register
464 # (-)   preserved by callee
465 # (#)   Nth argument, volatile
466 #
467 # In Unix terms top of stack is argument transfer area for arguments
468 # which could not be accomodated in registers. Or in other words 7th
469 # [integer] argument resides at 8(%rsp) upon function entry point.
470 # 128 bytes above %rsp constitute a "red zone" which is not touched
471 # by signal handlers and can be used as temporal storage without
472 # allocating a frame.
473 #
474 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
475 # which belongs to/can be overwritten by callee. N is the number of
476 # arguments passed to callee, *but* not less than 4! This means that
477 # upon function entry point 5th argument resides at 40(%rsp), as well
478 # as that 32 bytes from 8(%rsp) can always be used as temporal
479 # storage [without allocating a frame].
480 #
481 # All the above means that if assembler programmer adheres to Unix
482 # register and stack layout, but disregards the "red zone" existense,
483 # it's possible to use following prologue and epilogue to "gear" from
484 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
485 #
486 # omnipotent_function:
487 # ifdef WIN64
488 #       movq    %rdi,8(%rsp)
489 #       movq    %rsi,16(%rsp)
490 #       movq    %rcx,%rdi       ; if 1st argument is actually present
491 #       movq    %rdx,%rsi       ; if 2nd argument is actually ...
492 #       movq    %r8,%rdx        ; if 3rd argument is ...
493 #       movq    %r9,%rcx        ; if 4th argument ...
494 #       movq    40(%rsp),%r8    ; if 5th ...
495 #       movq    48(%rsp),%r9    ; if 6th ...
496 # endif
497 #       ...
498 # ifdef WIN64
499 #       movq    8(%rsp),%rdi
500 #       movq    16(%rsp),%rsi
501 # endif
502 #       ret