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