forked from grigory-rechistov/interpreters-comparison
-
Notifications
You must be signed in to change notification settings - Fork 2
/
asmoptll.S
749 lines (631 loc) · 15.2 KB
/
asmoptll.S
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
.set DBGCNT, 0
.set STEPCNT, 0
.set STEPLIMIT_CHECK, 0
.set MAX_PROGRAM_SIZE_CHECK, 0
.set STATE_RUNNING_CHECK, 0
.set STACK_CHECK, 1
# Оптимизации
.set OPT_CACHED, 0
.set OPT_ON_SITE, 0 # 3.590s
.set OPT_ON_SITE, 1 # 3.298s
.set OPT_CACHED, 1 # 3.004s
.set OPT_CACHED, 2 # 2.847s
# CPU_T
#define routines %rdi
#define prog_mem %rsi
#define steplimit %rcx
#define steps %r8
#define pc %r9
#define stack_max %rbp
#define stack_min %rbx
#define sp %rsp
#define top %rax
# 0 = Cpu_Running
#define subtop %r10
# 1 = Cpu_Halted
#define one %r11
# 2 = Cpu_Break
#define two %r12
# DECODE_T
#define opcode32 %edx
#define opcode64 %rdx
#define immed32 %r14d
#define immed64 %r14
#define state %r15
# ACCUMULATOR
# define acc %r13
.section .text
.macro FETCH_DECODE
FETCH_CHECKED
DECODE
.endm
.macro FETCH_CHECKED
.if MAX_PROGRAM_SIZE_CHECK
# Место для самомодификации
movq $512, acc
cmp pc, acc
jb handle_pc_out_of_bound # (pc > max_program_size)
.endif
FETCH
.endm
handle_pc_out_of_bound:
movq two, state # = 2 (Cpu_Break)
xor opcode64, opcode64 # = 0 (Instr_Break)
lea sz_pc_out_of_bound(%rip), acc
jmp save_rets_and_exit
.section .data
sz_pc_out_of_bound:
.asciz "PC out of bounds"
.section .text
.macro FETCH
movl (prog_mem, pc, 4), opcode32 # prog_mem[pc]
.endm
.macro DECODE
movl 4(prog_mem, pc, 4), immed32 # prog_mem[pc+1]
.endm
.macro BAIL_ON_ERROR
.if STATE_RUNNING_CHECK
test state, state
jne handle_state_is_not_running
.endif
.endm
.if STATE_RUNNING_CHECK
handle_state_is_not_running:
mov two, state # Cpu_Break
lea sz_state_is_not_running(%rip), acc
jmp save_rets_and_exit
.endif
.macro DISPATCH
jmp *(routines, opcode64, 8)
.endm
.macro ADVANCE_PC cnt:req
.if \cnt == 1
inc pc
.else
lea \cnt(pc), pc
.endif
.if (STEPLIMIT_CHECK || STEPCNT)
# Аксакалы верят что если разнести инкремент и проверку, то
# это позволит процессору заняться в промежутке чем-то еще
inc steps
.endif
.if STATE_RUNNING_CHECK
test state, state # Cpu_Running(0) != state
jne handle_state_not_running
.endif
.if STEPLIMIT_CHECK
cmp steps, steplimit # steps >= steplimit
jl handle_steplimit_reached
.endif
.endm
.if STATE_RUNNING_CHECK
handle_state_not_running:
lea sz_state_is_not_running(%rip), acc
jmp set_state_break
.endif
.if STEPLIMIT_CHECK
handle_steplimit_reached:
lea sz_steplimit_reached(%rip), acc
jmp set_state_break
.endif
.if (STATE_RUNNING_CHECK || STEPLIMIT_CHECK)
set_state_break:
mov two, state # Cpu_Break
lea sz_system_break(%rip), acc
jmp save_rets_and_exit
.endif
.section .data
sz_state_is_not_running:
.asciz "state is not running"
sz_steplimit_reached:
.asciz "steplimit reached"
.section .text
.macro PUSH_IMM reg
# PUSH_IMM_\@:
.if DBGCNT
incq cnt_LPush(%rip)
.endif
.if STACK_CHECK
cmp sp, stack_min
jae handle_overflow
.endif
push \reg
.endm
.if STACK_CHECK
handle_overflow:
mov two, state # Cpu_Break
lea sz_stack_overflow(%rip), acc
jmp save_rets_and_exit
.section .data
sz_stack_overflow:
.asciz "stack overflow"
.section .text
.endif
.macro VM_PUSH tmpreg args:vararg
.if DBGCNT
incq cnt_VM_Push(%rip)
.endif
# подсчитаем количество макро-аргументов
.set num_args, 0
.irp arg, \args
.set num_args, num_args + 1
.endr
.if STACK_CHECK
# смещение для LEA
.set offset, -8 * num_args
lea offset(sp), \tmpreg
# проверим не выходим ли за минимум
cmp \tmpreg, stack_min
jae handle_overflow
.endif
# push каждого аргумента
.irp reg, \args
push \reg
.endr
.endm
.macro POP_IMM reg
.if DBGCNT
incq cnt_LPop(%rip)
.endif
.if STACK_CHECK
cmp sp, stack_max
jb handle_underflow
.endif
pop \reg
.endm
.if STACK_CHECK
handle_underflow:
mov two, state # Cpu_Break
lea sz_stack_underflow(%rip), acc
jmp save_rets_and_exit
.section .data
sz_stack_underflow:
.asciz "stack underflow"
.section .text
.endif
.macro VM_POP tmpreg:req args:vararg
# VM_POP_\@:
.if DBGCNT
incq cnt_VM_Pop(%rip)
.endif
# подсчитаем количество макро-аргументов
.set num_args, 0
.irp arg, \args
.set num_args, num_args + 1
.endr
.if STACK_CHECK
# вычислим смещение для LEA
.set offset, 8*num_args
lea offset(sp), \tmpreg
# проверим не выходим ли за максимум
cmp \tmpreg, stack_max
jb handle_underflow
.endif
# pop каждого аргумента
.irp reg, \args
pop \reg
.endr
.endm
#### ROUTINES ####
.macro RTN name
.global srv_\name
.type srv_\name, @function
srv_\name:
.if DBGCNT
incq cnt_\name(%rip)
.endif
.endm
RTN Break ## <- NB! Not used
# No need to dispatch after Break
mov two, state
lea sz_system_break(%rip), acc
jmp save_rets_and_exit
RTN Halt
# No need to dispatch after Halt
mov one, state
lea sz_system_halted(%rip), acc
jmp save_rets_and_exit
RTN Nop ## <- NB! Not used
# Do nothing
ADVANCE_PC 1
FETCH_DECODE
DISPATCH
RTN Push
.if OPT_CACHED == 2
PUSH_IMM subtop
movq top, subtop
movq immed64, top
.endif
.if OPT_CACHED == 1
PUSH_IMM top
movq immed64, top
.endif
.if OPT_CACHED == 0
PUSH_IMM immed64
.endif
ADVANCE_PC 2
FETCH_DECODE
DISPATCH
RTN Drop
.if OPT_CACHED == 2
movq subtop, top
POP_IMM subtop
.endif
.if OPT_CACHED == 1
POP_IMM top
.endif
.if OPT_CACHED == 0
POP_IMM immed64
.endif
ADVANCE_PC 1
FETCH_DECODE
DISPATCH
RTN Dup ## <- NB! Not used
.if OPT_CACHED == 2
PUSH_IMM subtop
movq top, subtop
.endif
.if OPT_CACHED == 1
PUSH_IMM top
BAIL_ON_ERROR
.endif
.if OPT_CACHED == 0
.if OPT_ON_SITE == 1
# Возможно этот способ медленее, чем вариант
# из else, но т.к. эта RTN не используется,
# то это никак не проверить - пусть будет так
mov (sp), immed64
PUSH_IMM immed64
.else
POP_IMM immed64
BAIL_ON_ERROR
VM_PUSH opcode64 immed64 immed64
.endif
.endif
ADVANCE_PC 1
FETCH_DECODE
DISPATCH
RTN Swap
.if OPT_CACHED == 2
xchg top, subtop
.endif
.if OPT_CACHED == 1
#xchg top, (sp)
POP_IMM opcode64
xchg opcode64, top
push opcode64
.endif
.if OPT_CACHED == 0
.if OPT_ON_SITE == 1
# Этот способ серьезно замедляет работу, поэтому
# он закомментирован, и вместо него сюда
# скопирован и используется вариант из else
# mov (sp), acc
# xchg 8(sp), acc
# xchg (sp), acc
VM_POP opcode64 immed64 acc
BAIL_ON_ERROR
VM_PUSH opcode64 immed64 acc
.else
VM_POP opcode64 immed64 acc
BAIL_ON_ERROR
VM_PUSH opcode64 immed64 acc
.endif
.endif
ADVANCE_PC 1
FETCH_DECODE
DISPATCH
RTN Over
.if OPT_CACHED == 2
xchg top, subtop
PUSH_IMM top
.endif
.if OPT_CACHED == 1
PUSH_IMM top
movq 8(sp), top
.endif
.if OPT_CACHED == 0
.if OPT_ON_SITE == 1
movq 8(sp), acc
PUSH_IMM acc
.else
# мы можем использовать opcode64 как tmpreg, так как
# после FETCH он не используется и будет перезаписан
# в следующем FETCH
VM_POP opcode64 immed64 acc
BAIL_ON_ERROR
VM_PUSH opcode64 acc immed64 acc
.endif
.endif
ADVANCE_PC 1
FETCH_DECODE
DISPATCH
RTN Sub
.if OPT_CACHED == 2
subq subtop, top
POP_IMM subtop
.endif
.if OPT_CACHED == 1
POP_IMM opcode64
subq opcode64, top
.endif
.if OPT_CACHED == 0
.if OPT_ON_SITE == 1
POP_IMM immed64
subq immed64, (sp)
.else
VM_POP opcode64 immed64 acc
sub acc, immed64
PUSH_IMM immed64
.endif
.endif
ADVANCE_PC 1
FETCH_DECODE
DISPATCH
RTN Inc
.if OPT_CACHED == 2
inc top
.endif
.if OPT_CACHED == 1
inc top
.endif
.if OPT_CACHED == 0
.if OPT_ON_SITE == 1
incq (sp)
.else
POP_IMM immed64
BAIL_ON_ERROR
inc immed64
# Тут можно оптимизировать проверки, уже выполненные в POP_IMM
# а еще лучше - изменять прямо на месте, в памяти
PUSH_IMM immed64
.endif
.endif
ADVANCE_PC 1
FETCH_DECODE
DISPATCH
RTN Mod
.if OPT_CACHED == 2
# Так как мы для top выбрали RAX то не требуется
# делать mov top, %rax для подготовки к делению
test subtop, subtop
je handle_divide_zero
xor %rdx, %rdx # rdx = opcode64
div subtop # rdx:rax / operand -> rax, rdx
movq %rdx, top
POP_IMM subtop
.endif
.if OPT_CACHED == 1
# Так как мы для top выбрали RAX то не требуется
# делать mov top, %rax для подготовки к делению
POP_IMM immed64
BAIL_ON_ERROR
test immed64, immed64
je handle_divide_zero
xor %rdx, %rdx # rdx = opcode64
div immed64 # rdx:rax / operand -> rax, rdx
movq %rdx, top
.endif
.if OPT_CACHED == 0
VM_POP opcode64 %rax immed64
BAIL_ON_ERROR
test immed64, immed64
je handle_divide_zero
xor %rdx, %rdx # rdx = opcode64
div immed64 # rdx:rax / operand -> rax, rdx
PUSH_IMM %rdx
.endif
ADVANCE_PC 1
FETCH_DECODE
DISPATCH
handle_divide_zero:
mov two, state
lea sz_divide_zero(%rip), acc
jmp save_rets_and_exit
end_handle_divide_zero:
.section .data
sz_divide_zero:
.asciz "divide by zero"
.section .text
RTN Jump
# sal $2, immed32
movsx immed32, immed64
add immed64, pc
ADVANCE_PC 2
FETCH_DECODE
DISPATCH
RTN Je
.if OPT_CACHED == 2
movq top, acc
movq subtop, top
POP_IMM subtop
BAIL_ON_ERROR
test acc, acc
je 3f
ADVANCE_PC 2
FETCH_DECODE
DISPATCH
3:
movsx immed32, immed64
add immed64, pc
ADVANCE_PC 2
FETCH_DECODE
DISPATCH
.endif
.if OPT_CACHED == 1
movq top, acc
POP_IMM top
BAIL_ON_ERROR
test acc, acc
je 2f
ADVANCE_PC 2
FETCH_DECODE
DISPATCH
2:
movsx immed32, immed64
add immed64, pc
ADVANCE_PC 2
FETCH_DECODE
DISPATCH
.endif
.if OPT_CACHED == 0
POP_IMM acc
BAIL_ON_ERROR
test acc, acc
je 1f
ADVANCE_PC 2
FETCH_DECODE
DISPATCH
1:
movsx immed32, immed64
add immed64, pc
ADVANCE_PC 2
FETCH_DECODE
DISPATCH
.endif
RTN Print
.if OPT_CACHED == 2
movq top, acc
movq subtop, top
POP_IMM subtop
.endif
.if OPT_CACHED == 1
movq top, acc
POP_IMM top
.endif
.if OPT_CACHED == 0
POP_IMM acc
.endif
BAIL_ON_ERROR
push %rdi
push %rsi
push %rcx
push %rdx
push %r8
push %r9
push %r10
push %r11
lea sz_fmt_str(%rip), %rdi
movq acc, %rsi
xor acc, acc
call printf
pop %r11
pop %r10
pop %r9
pop %r8
pop %rdx
pop %rcx
pop %rsi
pop %rdi
ADVANCE_PC 1
FETCH_DECODE
DISPATCH
.section .data
sz_fmt_str:
.asciz "[%d]\n"
.quad 0
#### MAIN ####
.section .text
.global asm_main
.type asm_main, @function
# %rdi routines
# %rsi prog_mem
# %rdx state
# %rcx steplimit
# %r8 -
# %r9 -
asm_main:
pushq %rbp
pushq %rbx
pushq %r12
pushq %r13
pushq %r14
pushq %r15
movq %rsp, old_rsp(%rip)
mov %rdx, state
xor %r15, %r15
xor steps, steps
xor pc, pc
xor opcode64, opcode64
xor immed64, immed64
xor top, top
xor subtop, subtop
xor one, one
inc one
mov one, two
inc two
mov sp, stack_max
mov sp, stack_min
sub $0x100, stack_min # STACK_CAPACITY = 32
FETCH_DECODE
DISPATCH
save_rets_and_exit: # <----
test acc, acc
jz 1f
mov acc, ret_err_ptr(%rip)
1:
.if (STEPLIMIT_CHECK || STEPCNT)
movq steps, ret_steps(%rip)
.endif
movq state, ret_state(%rip)
movq pc, ret_pc(%rip)
# Save stack pos
movq stack_max, ret_sp(%rip)
sub sp, ret_sp(%rip)
shrq $3, ret_sp(%rip)
# Копируем стек
lea ret_stack(%rip), acc
mov ret_sp(%rip), %rcx
copy_loop:
popq immed64
movl immed32, (acc)
add $8, acc
loop copy_loop
# Теперь можно восстановить RSP
movq old_rsp(%rip), %rsp
# Востанавливаем все остальное
popq %r15
popq %r14
popq %r13
popq %r12
popq %rbx
popq %rbp
ret
#### DATA ####
.section .data
.macro var name
\name:
.quad 0
.endm
.macro vars names:vararg
.irp name, \names
var \name
.endr
.endm
.macro gvar name
.global \name
\name:
.quad 0
.endm
.macro gvars names:vararg
.irp name, \names
gvar \name
.endr
.endm
vars old_rsp
gvars ret_steps ret_state ret_pc ret_sp
gvars cnt_VM_Pop cnt_VM_Push cnt_LPop cnt_LPush cnt_Print cnt_Je cnt_Mod cnt_Sub cnt_Over cnt_Swap cnt_Dup cnt_Drop cnt_Push cnt_Nop cnt_Halt cnt_Break cnt_Inc cnt_Jump
sz_system_break:
.asciz "system break."
sz_system_halted:
.asciz "system halted."
no_err_msg:
.asciz "no errors."
.global ret_err_ptr
ret_err_ptr:
.quad no_err_msg
.global ret_stack
ret_stack:
.rept 32
.word 0
.endr