x86_64 assembler translator update.
[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
46 my $output = shift;
47 open STDOUT,">$output" || die "can't open $output: $!";
48
49 my $masm=1 if ($output =~ /\.asm/);
50
51 my $current_segment;
52 my $current_function;
53
54 { package opcode;       # pick up opcodes
55     sub re {
56         my      $self = shift;  # single instance in enough...
57         local   *line = shift;
58         undef   $ret;
59
60         if ($line =~ /^([a-z]+)/i) {
61             $self->{op} = $1;
62             $ret = $self;
63             $line = substr($line,@+[0]); $line =~ s/^\s+//;
64
65             undef $self->{sz};
66             if ($self->{op} =~ /(movz)b.*/) {   # movz is pain...
67                 $self->{op} = $1;
68                 $self->{sz} = "b";
69             } elsif ($self->{op} =~ /([a-z]{3,})([qlwb])/) {
70                 $self->{op} = $1;
71                 $self->{sz} = $2;
72             }
73         }
74         $ret;
75     }
76     sub size {
77         my $self = shift;
78         my $sz   = shift;
79         $self->{sz} = $sz if (defined($sz) && !defined($self->{sz}));
80         $self->{sz};
81     }
82     sub out {
83         my $self = shift;
84         if (!$masm) {
85             if ($self->{op} eq "movz") {        # movz in pain...
86                 sprintf "%s%s%s",$self->{op},$self->{sz},shift;
87             } elsif ($self->{op} eq "ret") {
88                 ".byte  0xf3,0xc3";
89             } else {
90                 "$self->{op}$self->{sz}";
91             }
92         } else {
93             $self->{op} =~ s/movz/movzx/;
94             if ($self->{op} eq "ret") {
95                 $self->{op} = "";
96                 if ($current_function->{abi} eq "svr4") {
97                     $self->{op} = "mov  rdi,QWORD PTR 8[rsp]\t;WIN64 epilogue\n\t".
98                                   "mov  rsi,QWORD PTR 16[rsp]\n\t";
99                 }
100                 $self->{op} .= "DB\t0F3h,0C3h\t\t;repret";
101             }
102             $self->{op};
103         }
104     }
105 }
106 { package const;        # pick up constants, which start with $
107     sub re {
108         my      $self = shift;  # single instance in enough...
109         local   *line = shift;
110         undef   $ret;
111
112         if ($line =~ /^\$([^,]+)/) {
113             $self->{value} = $1;
114             $ret = $self;
115             $line = substr($line,@+[0]); $line =~ s/^\s+//;
116
117             $self->{value} = oct($self->{value}) if ($self->{value} =~ /^0/);
118         }
119         $ret;
120     }
121     sub out {
122         my $self = shift;
123         sprintf $masm?"0%xh":"\$0x%x",$self->{value};
124     }
125 }
126 { package ea;           # pick up effective addresses: expr(%reg,%reg,scale)
127     sub re {
128         my      $self = shift;  # single instance in enough...
129         local   *line = shift;
130         undef   $ret;
131
132         if ($line =~ /^([^\(,]*)\(([%\w,]+)\)/) {
133             $self->{label} = $1;
134             ($self->{base},$self->{index},$self->{scale})=split(/,/,$2);
135             $self->{scale} = 1 if (!defined($self->{scale}));
136             $ret = $self;
137             $line = substr($line,@+[0]); $line =~ s/^\s+//;
138
139             $self->{base}  =~ s/^%//;
140             $self->{index} =~ s/^%// if (defined($self->{index}));
141         }
142         $ret;
143     }
144     sub size {}
145     sub out {
146         my $self = shift;
147         my $sz = shift;
148
149         if (!$masm) {
150             # elder GNU assembler insists on 64-bit EAs:-(
151             # on pros side, this results in more compact code:-)
152             $self->{index} =~ s/^[er](.?[0-9xp])[d]?$/r\1/;
153             $self->{base}  =~ s/^[er](.?[0-9xp])[d]?$/r\1/;
154
155             if (defined($self->{index})) {
156                 sprintf "%s(%%%s,%%%s,%d)",
157                                         $self->{label},$self->{base},
158                                         $self->{index},$self->{scale};
159             }
160             else {
161                 sprintf "%s(%%%s)",     $self->{label},$self->{base};
162             }
163         } else {
164             %szmap = ( b=>"BYTE", w=>"WORD", l=>"DWORD", q=>"QWORD" );
165
166             $self->{label} =~ s/\./\$/g;
167             $self->{label} =~ s/0x([0-9a-f]+)/0$1h/ig;
168             $self->{label} = "($self->{label})" if ($self->{label} =~ /[\*\+\-\/]/);
169
170             if (defined($self->{index})) {
171                 sprintf "%s PTR %s[%s*%d+%s]",$szmap{$sz},
172                                         $self->{label},
173                                         $self->{index},$self->{scale},
174                                         $self->{base};
175             }
176             else {
177                 sprintf "%s PTR %s[%s]",$szmap{$sz},
178                                         $self->{label},$self->{base};
179             }
180         }
181     }
182 }
183 { package register;     # pick up registers, which start with %.
184     sub re {
185         my      $class = shift; # muliple instances...
186         my      $self = {};
187         local   *line = shift;
188         undef   $ret;
189
190         if ($line =~ /^%(\w+)/) {
191             bless $self,$class;
192             $self->{value} = $1;
193             $ret = $self;
194             $line = substr($line,@+[0]); $line =~ s/^\s+//;
195         }
196         $ret;
197     }
198     sub size {
199         my      $self = shift;
200         undef   $ret;
201
202         if    ($self->{value} =~ /^r[\d]+b$/i)  { $ret="b"; }
203         elsif ($self->{value} =~ /^r[\d]+w$/i)  { $ret="w"; }
204         elsif ($self->{value} =~ /^r[\d]+d$/i)  { $ret="l"; }
205         elsif ($self->{value} =~ /^r[\w]+$/i)   { $ret="q"; }
206         elsif ($self->{value} =~ /^[a-d][hl]$/i){ $ret="b"; }
207         elsif ($self->{value} =~ /^[\w]{2}l$/i) { $ret="b"; }
208         elsif ($self->{value} =~ /^[\w]{2}$/i)  { $ret="w"; }
209         elsif ($self->{value} =~ /^e[a-z]{2}$/i){ $ret="l"; }
210
211         $ret;
212     }
213     sub out {
214         my $self = shift;
215         sprintf $masm?"%s":"%%%s",$self->{value};
216     }
217 }
218 { package label;        # pick up labels, which end with :
219     sub re {
220         my      $self = shift;  # single instance is enough...
221         local   *line = shift;
222         undef   $ret;
223
224         if ($line =~ /(^[\.\w]+\:)/) {
225             $self->{value} = $1;
226             $ret = $self;
227             $line = substr($line,@+[0]); $line =~ s/^\s+//;
228
229             $self->{value} =~ s/\.L/\$L/ if ($masm);
230         }
231         $ret;
232     }
233     sub out {
234         my $self = shift;
235
236         if (!$masm) {
237             $self->{value};
238         } elsif ($self->{value} ne "$current_function->{name}:") {
239             $self->{value};
240         } elsif ($current_function->{abi} eq "svr4") {
241             my $func =  "$current_function->{name}      PROC\n".
242                         "       mov     QWORD PTR 8[rsp],rdi\t;WIN64 prologue\n".
243                         "       mov     QWORD PTR 16[rsp],rsi\n";
244             my $narg = $current_function->{narg};
245             $narg=6 if (!defined($narg));
246             $func .= "  mov     rdi,rcx\n" if ($narg>0);
247             $func .= "  mov     rsi,rdx\n" if ($narg>1);
248             $func .= "  mov     rdx,r8\n"  if ($narg>2);
249             $func .= "  mov     rcx,r9\n"  if ($narg>3);
250             $func .= "  mov     r8,QWORD PTR 40[rsp]\n" if ($narg>4);
251             $func .= "  mov     r9,QWORD PTR 48[rsp]\n" if ($narg>5);
252             $func .= "\n";
253         } else {
254            "$current_function->{name}   PROC";
255         }
256     }
257 }
258 { package expr;         # pick up expressioins
259     sub re {
260         my      $self = shift;  # single instance is enough...
261         local   *line = shift;
262         undef   $ret;
263
264         if ($line =~ /(^[^,]+)/) {
265             $self->{value} = $1;
266             $ret = $self;
267             $line = substr($line,@+[0]); $line =~ s/^\s+//;
268
269             $self->{value} =~ s/\.L/\$L/g if ($masm);
270         }
271         $ret;
272     }
273     sub out {
274         my $self = shift;
275         $self->{value};
276     }
277 }
278 { package directive;    # pick up directives, which start with .
279     sub re {
280         my      $self = shift;  # single instance is enough...
281         local   *line = shift;
282         undef   $ret;
283         my      $dir;
284
285         if ($line =~ /^\s*(\.\w+)/) {
286             if (!$masm) {
287                 $self->{value} = $1;
288                 $line =~ s/\@abi\-omnipotent/\@function/;
289                 $line =~ s/\@function.*/\@function/;
290                 $self->{value} = $line;
291                 $line = "";
292                 return $self;
293             }
294
295             $dir = $1;
296             $ret = $self;
297             undef $self->{value};
298             $line = substr($line,@+[0]); $line =~ s/^\s+//;
299             SWITCH: for ($dir) {
300                 /\.(text|data)/
301                             && do { my $v=undef;
302                                     $v="$current_segment\tENDS\n" if ($current_segment);
303                                     $current_segment = "_$1";
304                                     $current_segment =~ tr/[a-z]/[A-Z]/;
305                                     $v.="$current_segment\tSEGMENT PARA";
306                                     $self->{value} = $v;
307                                     last;
308                                   };
309                 /\.globl/   && do { $self->{value} = "PUBLIC\t".$line; last; };
310                 /\.type/    && do { ($sym,$type,$narg) = split(',',$line);
311                                     if ($type eq "\@function")
312                                     {   undef $current_function;
313                                         $current_function->{name} = $sym;
314                                         $current_function->{abi}  = "svr4";
315                                         $current_function->{narg} = $narg;
316                                     }
317                                     elsif ($type eq "\@abi-omnipotent")
318                                     {   undef $current_function;
319                                         $current_function->{name} = $sym;
320                                     }
321                                     last;
322                                   };
323                 /\.size/    && do { if (defined($current_function))
324                                     {   $self->{value}="$current_function->{name}\tENDP";
325                                         undef $current_function;
326                                     }
327                                     last;
328                                   };
329                 /\.align/   && do { $self->{value} = "ALIGN\t".$line; last; };
330                 /\.(byte|value|long|quad)/
331                             && do { my @arr = split(',',$line);
332                                     my $sz  = substr($1,0,1);
333                                     my $last = pop(@arr);
334
335                                     $sz =~ tr/bvlq/BWDQ/;
336                                     $self->{value} = "\tD$sz\t";
337                                     for (@arr) { $self->{value} .= sprintf"0%Xh,",oct; }
338                                     $self->{value} .= sprintf"0%Xh",oct($last);
339                                     last;
340                                   };
341             }
342             $line = "";
343         }
344
345         $ret;
346     }
347     sub out {
348         my $self = shift;
349         $self->{value};
350     }
351 }
352
353 while($line=<>) {
354
355     chomp($line);
356
357     $line =~ s|[#!].*$||;       # get rid of asm-style comments...
358     $line =~ s|/\*.*\*/||;      # ... and C-style comments...
359     $line =~ s|^\s+||;          # ... and skip white spaces in beginning
360
361     undef $label;
362     undef $opcode;
363     undef $dst;
364     undef $src;
365     undef $sz;
366
367     if ($label=label->re(\$line))       { print $label->out(); }
368
369     if (directive->re(\$line)) {
370         printf "%s",directive->out();
371     } elsif ($opcode=opcode->re(\$line)) { ARGUMENT: {
372
373         if ($src=register->re(\$line))  { opcode->size($src->size()); }
374         elsif ($src=const->re(\$line))  { }
375         elsif ($src=ea->re(\$line))     { }
376         elsif ($src=expr->re(\$line))   { }
377
378         last ARGUMENT if ($line !~ /^,/);
379
380         $line = substr($line,1); $line =~ s/^\s+//;
381
382         if ($dst=register->re(\$line))  { opcode->size($dst->size()); }
383         elsif ($dst=const->re(\$line))  { }
384         elsif ($dst=ea->re(\$line))     { }
385
386         } # ARGUMENT:
387
388         $sz=opcode->size();
389
390         if (defined($dst)) {
391             if (!$masm) {
392                 printf "\t%s\t%s,%s",   $opcode->out($dst->size()),
393                                         $src->out($sz),$dst->out($sz);
394             }
395             else {
396                 printf "\t%s\t%s,%s",   $opcode->out(),
397                                         $dst->out($sz),$src->out($sz);
398             }
399         }
400         elsif (defined($src)) {
401             printf "\t%s\t%s",$opcode->out(),$src->out($sz);
402         } else {
403             printf "\t%s",$opcode->out();
404         }
405     }
406
407     print $line,"\n";
408 }
409
410 print "\n$current_segment\tENDS\nEND\n" if ($masm);
411
412 close STDOUT;
413
414 #################################################
415 # Cross-reference x86_64 ABI "card"
416 #
417 #               Unix            Win64
418 # %rax          *               *
419 # %rbx          -               -
420 # %rcx          #4              #1
421 # %rdx          #3              #2
422 # %rsi          #2              -
423 # %rdi          #1              -
424 # %rbp          -               -
425 # %rsp          -               -
426 # %r8           #5              #3
427 # %r9           #6              #4
428 # %r10          *               *
429 # %r11          *               *
430 # %r12          -               -
431 # %r13          -               -
432 # %r14          -               -
433 # %r15          -               -
434
435 # (*)   volatile register
436 # (-)   preserved by callee
437 # (#)   Nth argument, volatile
438 #
439 # In Unix terms top of stack is argument transfer area for arguments
440 # which could not be accomodated in registers. Or in other words 7th
441 # [integer] argument resides at 8(%rsp) upon function entry point.
442 # 128 bytes above %rsp constitute a "red zone" which is not touched
443 # by signal handlers and can be used as temporal storage without
444 # allocating a frame.
445 #
446 # In Win64 terms N*8 bytes on top of stack is argument transfer area,
447 # which belongs to/can be overwritten by callee. N is the number of
448 # arguments passed to callee, *but* not less than 4! This means that
449 # upon function entry point 5th argument resides at 40(%rsp), as well
450 # as that 32 bytes from 8(%rsp) can always be used as temporal
451 # storage [without allocating a frame].
452 #
453 # All the above means that if assembler programmer adheres to Unix
454 # register and stack layout, but disregards the "red zone" existense,
455 # it's possible to use following prologue and epilogue to "gear" from
456 # Unix to Win64 ABI in leaf functions with not more than 6 arguments.
457 #
458 # omnipotent_function:
459 # ifdef WIN64
460 #       movq    %rdi,8(%rsp)
461 #       movq    %rsi,16(%rsp)
462 #       movq    %rcx,%rdi       ; if 1st argument is actually present
463 #       movq    %rdx,%rsi       ; if 2nd argument is actually ...
464 #       movq    %r8,%rdx        ; if 3rd argument is ...
465 #       movq    %r9,%rcx        ; if 4th argument ...
466 #       movq    40(%rsp),%r8    ; if 5th ...
467 #       movq    48(%rsp),%r9    ; if 6th ...
468 # endif
469 #       ...
470 # ifdef WIN64
471 #       movq    8(%rsp),%rdi
472 #       movq    16(%rsp),%rsi
473 # endif
474 #       ret