forked from ruby/ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyjit_codegen.c
5124 lines (4224 loc) · 175 KB
/
yjit_codegen.c
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is a fragment of the yjit.o compilation unit. See yjit.c.
#include "internal.h"
#include "gc.h"
#include "internal/compile.h"
#include "internal/class.h"
#include "internal/hash.h"
#include "internal/object.h"
#include "internal/sanitizers.h"
#include "internal/string.h"
#include "internal/struct.h"
#include "internal/variable.h"
#include "internal/re.h"
#include "probes.h"
#include "probes_helper.h"
#include "yjit.h"
#include "yjit_iface.h"
#include "yjit_core.h"
#include "yjit_codegen.h"
#include "yjit_asm.h"
// Map from YARV opcodes to code generation functions
static codegen_fn gen_fns[VM_INSTRUCTION_SIZE] = { NULL };
// Map from method entries to code generation functions
static st_table *yjit_method_codegen_table = NULL;
// Code for exiting back to the interpreter from the leave instruction
static void *leave_exit_code;
// Code for full logic of returning from C method and exiting to the interpreter
static uint32_t outline_full_cfunc_return_pos;
// For implementing global code invalidation
struct codepage_patch {
uint32_t inline_patch_pos;
uint32_t outlined_target_pos;
};
typedef rb_darray(struct codepage_patch) patch_array_t;
static patch_array_t global_inval_patches = NULL;
// Print the current source location for debugging purposes
RBIMPL_ATTR_MAYBE_UNUSED()
static void
jit_print_loc(jitstate_t *jit, const char *msg)
{
char *ptr;
long len;
VALUE path = rb_iseq_path(jit->iseq);
RSTRING_GETMEM(path, ptr, len);
fprintf(stderr, "%s %.*s:%u\n", msg, (int)len, ptr, rb_iseq_line_no(jit->iseq, jit->insn_idx));
}
// dump an object for debugging purposes
RBIMPL_ATTR_MAYBE_UNUSED()
static void
jit_obj_info_dump(codeblock_t *cb, x86opnd_t opnd) {
push_regs(cb);
mov(cb, C_ARG_REGS[0], opnd);
call_ptr(cb, REG0, (void *)rb_obj_info_dump);
pop_regs(cb);
}
// Get the current instruction's opcode
static int
jit_get_opcode(jitstate_t *jit)
{
return jit->opcode;
}
// Get the index of the next instruction
static uint32_t
jit_next_insn_idx(jitstate_t *jit)
{
return jit->insn_idx + insn_len(jit_get_opcode(jit));
}
// Get an instruction argument by index
static VALUE
jit_get_arg(jitstate_t *jit, size_t arg_idx)
{
RUBY_ASSERT(arg_idx + 1 < (size_t)insn_len(jit_get_opcode(jit)));
return *(jit->pc + arg_idx + 1);
}
// Load a VALUE into a register and keep track of the reference if it is on the GC heap.
static void
jit_mov_gc_ptr(jitstate_t *jit, codeblock_t *cb, x86opnd_t reg, VALUE ptr)
{
RUBY_ASSERT(reg.type == OPND_REG && reg.num_bits == 64);
// Load the pointer constant into the specified register
mov(cb, reg, const_ptr_opnd((void*)ptr));
// The pointer immediate is encoded as the last part of the mov written out
uint32_t ptr_offset = cb->write_pos - sizeof(VALUE);
if (!SPECIAL_CONST_P(ptr)) {
rb_darray_append(&jit->block->gc_object_offsets, ptr_offset);
}
}
// Check if we are compiling the instruction at the stub PC
// Meaning we are compiling the instruction that is next to execute
static bool
jit_at_current_insn(jitstate_t *jit)
{
const VALUE *ec_pc = jit->ec->cfp->pc;
return (ec_pc == jit->pc);
}
// Peek at the nth topmost value on the Ruby stack.
// Returns the topmost value when n == 0.
static VALUE
jit_peek_at_stack(jitstate_t *jit, ctx_t *ctx, int n)
{
RUBY_ASSERT(jit_at_current_insn(jit));
// Note: this does not account for ctx->sp_offset because
// this is only available when hitting a stub, and while
// hitting a stub, cfp->sp needs to be up to date in case
// codegen functions trigger GC. See :stub-sp-flush:.
VALUE *sp = jit->ec->cfp->sp;
return *(sp - 1 - n);
}
static VALUE
jit_peek_at_self(jitstate_t *jit, ctx_t *ctx)
{
return jit->ec->cfp->self;
}
RBIMPL_ATTR_MAYBE_UNUSED()
static VALUE
jit_peek_at_local(jitstate_t *jit, ctx_t *ctx, int n)
{
RUBY_ASSERT(jit_at_current_insn(jit));
int32_t local_table_size = jit->iseq->body->local_table_size;
RUBY_ASSERT(n < (int)jit->iseq->body->local_table_size);
const VALUE *ep = jit->ec->cfp->ep;
return ep[-VM_ENV_DATA_SIZE - local_table_size + n + 1];
}
// Save the incremented PC on the CFP
// This is necessary when calleees can raise or allocate
static void
jit_save_pc(jitstate_t *jit, x86opnd_t scratch_reg)
{
codeblock_t *cb = jit->cb;
mov(cb, scratch_reg, const_ptr_opnd(jit->pc + insn_len(jit->opcode)));
mov(cb, mem_opnd(64, REG_CFP, offsetof(rb_control_frame_t, pc)), scratch_reg);
}
// Save the current SP on the CFP
// This realigns the interpreter SP with the JIT SP
// Note: this will change the current value of REG_SP,
// which could invalidate memory operands
static void
jit_save_sp(jitstate_t *jit, ctx_t *ctx)
{
if (ctx->sp_offset != 0) {
x86opnd_t stack_pointer = ctx_sp_opnd(ctx, 0);
codeblock_t *cb = jit->cb;
lea(cb, REG_SP, stack_pointer);
mov(cb, member_opnd(REG_CFP, rb_control_frame_t, sp), REG_SP);
ctx->sp_offset = 0;
}
}
// jit_save_pc() + jit_save_sp(). Should be used before calling a routine that
// could:
// - Perform GC allocation
// - Take the VM lock through RB_VM_LOCK_ENTER()
// - Perform Ruby method call
static void
jit_prepare_routine_call(jitstate_t *jit, ctx_t *ctx, x86opnd_t scratch_reg)
{
jit->record_boundary_patch_point = true;
jit_save_pc(jit, scratch_reg);
jit_save_sp(jit, ctx);
// In case the routine calls Ruby methods, it can set local variables
// through Kernel#binding and other means.
ctx_clear_local_types(ctx);
}
// Record the current codeblock write position for rewriting into a jump into
// the outlined block later. Used to implement global code invalidation.
static void
record_global_inval_patch(const codeblock_t *cb, uint32_t outline_block_target_pos)
{
struct codepage_patch patch_point = { cb->write_pos, outline_block_target_pos };
rb_darray_append(&global_inval_patches, patch_point);
}
static bool jit_guard_known_klass(jitstate_t *jit, ctx_t *ctx, VALUE known_klass, insn_opnd_t insn_opnd, VALUE sample_instance, const int max_chain_depth, uint8_t *side_exit);
#if YJIT_STATS
// Add a comment at the current position in the code block
static void
_add_comment(codeblock_t *cb, const char *comment_str)
{
// We can't add comments to the outlined code block
if (cb == ocb)
return;
// Avoid adding duplicate comment strings (can happen due to deferred codegen)
size_t num_comments = rb_darray_size(yjit_code_comments);
if (num_comments > 0) {
struct yjit_comment last_comment = rb_darray_get(yjit_code_comments, num_comments - 1);
if (last_comment.offset == cb->write_pos && strcmp(last_comment.comment, comment_str) == 0) {
return;
}
}
struct yjit_comment new_comment = (struct yjit_comment){ cb->write_pos, comment_str };
rb_darray_append(&yjit_code_comments, new_comment);
}
// Comments for generated machine code
#define ADD_COMMENT(cb, comment) _add_comment((cb), (comment))
// Verify the ctx's types and mappings against the compile-time stack, self,
// and locals.
static void
verify_ctx(jitstate_t *jit, ctx_t *ctx)
{
// Only able to check types when at current insn
RUBY_ASSERT(jit_at_current_insn(jit));
VALUE self_val = jit_peek_at_self(jit, ctx);
if (type_diff(yjit_type_of_value(self_val), ctx->self_type) == INT_MAX) {
rb_bug("verify_ctx: ctx type (%s) incompatible with actual value of self: %s", yjit_type_name(ctx->self_type), rb_obj_info(self_val));
}
for (int i = 0; i < ctx->stack_size && i < MAX_TEMP_TYPES; i++) {
temp_type_mapping_t learned = ctx_get_opnd_mapping(ctx, OPND_STACK(i));
VALUE val = jit_peek_at_stack(jit, ctx, i);
val_type_t detected = yjit_type_of_value(val);
if (learned.mapping.kind == TEMP_SELF) {
if (self_val != val) {
rb_bug("verify_ctx: stack value was mapped to self, but values did not match\n"
" stack: %s\n"
" self: %s",
rb_obj_info(val),
rb_obj_info(self_val));
}
}
if (learned.mapping.kind == TEMP_LOCAL) {
int local_idx = learned.mapping.idx;
VALUE local_val = jit_peek_at_local(jit, ctx, local_idx);
if (local_val != val) {
rb_bug("verify_ctx: stack value was mapped to local, but values did not match\n"
" stack: %s\n"
" local %i: %s",
rb_obj_info(val),
local_idx,
rb_obj_info(local_val));
}
}
if (type_diff(detected, learned.type) == INT_MAX) {
rb_bug("verify_ctx: ctx type (%s) incompatible with actual value on stack: %s", yjit_type_name(learned.type), rb_obj_info(val));
}
}
int32_t local_table_size = jit->iseq->body->local_table_size;
for (int i = 0; i < local_table_size && i < MAX_TEMP_TYPES; i++) {
val_type_t learned = ctx->local_types[i];
VALUE val = jit_peek_at_local(jit, ctx, i);
val_type_t detected = yjit_type_of_value(val);
if (type_diff(detected, learned) == INT_MAX) {
rb_bug("verify_ctx: ctx type (%s) incompatible with actual value of local: %s", yjit_type_name(learned), rb_obj_info(val));
}
}
}
#else
#define ADD_COMMENT(cb, comment) ((void)0)
#define verify_ctx(jit, ctx) ((void)0)
#endif // if YJIT_STATS
#if YJIT_STATS
// Increment a profiling counter with counter_name
#define GEN_COUNTER_INC(cb, counter_name) _gen_counter_inc(cb, &(yjit_runtime_counters . counter_name))
static void
_gen_counter_inc(codeblock_t *cb, int64_t *counter)
{
if (!rb_yjit_opts.gen_stats) return;
// Use REG1 because there might be return value in REG0
mov(cb, REG1, const_ptr_opnd(counter));
cb_write_lock_prefix(cb); // for ractors.
add(cb, mem_opnd(64, REG1, 0), imm_opnd(1));
}
// Increment a counter then take an existing side exit.
#define COUNTED_EXIT(jit, side_exit, counter_name) _counted_side_exit(jit, side_exit, &(yjit_runtime_counters . counter_name))
static uint8_t *
_counted_side_exit(jitstate_t* jit, uint8_t *existing_side_exit, int64_t *counter)
{
if (!rb_yjit_opts.gen_stats) return existing_side_exit;
uint8_t *start = cb_get_ptr(jit->ocb, jit->ocb->write_pos);
_gen_counter_inc(jit->ocb, counter);
jmp_ptr(jit->ocb, existing_side_exit);
return start;
}
#else
#define GEN_COUNTER_INC(cb, counter_name) ((void)0)
#define COUNTED_EXIT(jit, side_exit, counter_name) side_exit
#endif // if YJIT_STATS
// Generate an exit to return to the interpreter
static uint32_t
yjit_gen_exit(VALUE *exit_pc, ctx_t *ctx, codeblock_t *cb)
{
const uint32_t code_pos = cb->write_pos;
ADD_COMMENT(cb, "exit to interpreter");
// Generate the code to exit to the interpreters
// Write the adjusted SP back into the CFP
if (ctx->sp_offset != 0) {
x86opnd_t stack_pointer = ctx_sp_opnd(ctx, 0);
lea(cb, REG_SP, stack_pointer);
mov(cb, member_opnd(REG_CFP, rb_control_frame_t, sp), REG_SP);
}
// Update CFP->PC
mov(cb, RAX, const_ptr_opnd(exit_pc));
mov(cb, member_opnd(REG_CFP, rb_control_frame_t, pc), RAX);
// Accumulate stats about interpreter exits
#if YJIT_STATS
if (rb_yjit_opts.gen_stats) {
mov(cb, RDI, const_ptr_opnd(exit_pc));
call_ptr(cb, RSI, (void *)&yjit_count_side_exit_op);
}
#endif
pop(cb, REG_SP);
pop(cb, REG_EC);
pop(cb, REG_CFP);
mov(cb, RAX, imm_opnd(Qundef));
ret(cb);
return code_pos;
}
// Generate a continuation for gen_leave() that exits to the interpreter at REG_CFP->pc.
static uint8_t *
yjit_gen_leave_exit(codeblock_t *cb)
{
uint8_t *code_ptr = cb_get_ptr(cb, cb->write_pos);
// Note, gen_leave() fully reconstructs interpreter state and leaves the
// return value in RAX before coming here.
// Every exit to the interpreter should be counted
GEN_COUNTER_INC(cb, leave_interp_return);
pop(cb, REG_SP);
pop(cb, REG_EC);
pop(cb, REG_CFP);
ret(cb);
return code_ptr;
}
// Fill code_for_exit_from_stub. This is used by branch_stub_hit() to exit
// to the interpreter when it cannot service a stub by generating new code.
// Before coming here, branch_stub_hit() takes care of fully reconstructing
// interpreter state.
static void
gen_code_for_exit_from_stub(void)
{
codeblock_t *cb = ocb;
code_for_exit_from_stub = cb_get_ptr(cb, cb->write_pos);
GEN_COUNTER_INC(cb, exit_from_branch_stub);
pop(cb, REG_SP);
pop(cb, REG_EC);
pop(cb, REG_CFP);
mov(cb, RAX, imm_opnd(Qundef));
ret(cb);
}
// :side-exit:
// Get an exit for the current instruction in the outlined block. The code
// for each instruction often begins with several guards before proceeding
// to do work. When guards fail, an option we have is to exit to the
// interpreter at an instruction boundary. The piece of code that takes
// care of reconstructing interpreter state and exiting out of generated
// code is called the side exit.
//
// No guards change the logic for reconstructing interpreter state at the
// moment, so there is one unique side exit for each context. Note that
// it's incorrect to jump to the side exit after any ctx stack push/pop operations
// since they change the logic required for reconstructing interpreter state.
static uint8_t *
yjit_side_exit(jitstate_t *jit, ctx_t *ctx)
{
if (!jit->side_exit_for_pc) {
codeblock_t *ocb = jit->ocb;
uint32_t pos = yjit_gen_exit(jit->pc, ctx, ocb);
jit->side_exit_for_pc = cb_get_ptr(ocb, pos);
}
return jit->side_exit_for_pc;
}
// Ensure that there is an exit for the start of the block being compiled.
// Block invalidation uses this exit.
static void
jit_ensure_block_entry_exit(jitstate_t *jit)
{
block_t *block = jit->block;
if (block->entry_exit) return;
if (jit->insn_idx == block->blockid.idx) {
// We are compiling the first instruction in the block.
// Generate the exit with the cache in jitstate.
block->entry_exit = yjit_side_exit(jit, &block->ctx);
}
else {
VALUE *pc = yjit_iseq_pc_at_idx(block->blockid.iseq, block->blockid.idx);
uint32_t pos = yjit_gen_exit(pc, &block->ctx, ocb);
block->entry_exit = cb_get_ptr(ocb, pos);
}
}
// Generate a runtime guard that ensures the PC is at the start of the iseq,
// otherwise take a side exit. This is to handle the situation of optional
// parameters. When a function with optional parameters is called, the entry
// PC for the method isn't necessarily 0, but we always generated code that
// assumes the entry point is 0.
static void
yjit_pc_guard(codeblock_t *cb, const rb_iseq_t *iseq)
{
RUBY_ASSERT(cb != NULL);
mov(cb, REG0, member_opnd(REG_CFP, rb_control_frame_t, pc));
mov(cb, REG1, const_ptr_opnd(iseq->body->iseq_encoded));
xor(cb, REG0, REG1);
// xor should impact ZF, so we can jz here
uint32_t pc_is_zero = cb_new_label(cb, "pc_is_zero");
jz_label(cb, pc_is_zero);
// We're not starting at the first PC, so we need to exit.
GEN_COUNTER_INC(cb, leave_start_pc_non_zero);
pop(cb, REG_SP);
pop(cb, REG_EC);
pop(cb, REG_CFP);
mov(cb, RAX, imm_opnd(Qundef));
ret(cb);
// PC should be at the beginning
cb_write_label(cb, pc_is_zero);
cb_link_labels(cb);
}
// The code we generate in gen_send_cfunc() doesn't fire the c_return TracePoint event
// like the interpreter. When tracing for c_return is enabled, we patch the code after
// the C method return to call into this to fire the event.
static void
full_cfunc_return(rb_execution_context_t *ec, VALUE return_value)
{
rb_control_frame_t *cfp = ec->cfp;
RUBY_ASSERT_ALWAYS(cfp == GET_EC()->cfp);
const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(cfp);
RUBY_ASSERT_ALWAYS(RUBYVM_CFUNC_FRAME_P(cfp));
RUBY_ASSERT_ALWAYS(me->def->type == VM_METHOD_TYPE_CFUNC);
// CHECK_CFP_CONSISTENCY("full_cfunc_return"); TODO revive this
// Pop the C func's frame and fire the c_return TracePoint event
// Note that this is the same order as vm_call_cfunc_with_frame().
rb_vm_pop_frame(ec);
EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_RETURN, cfp->self, me->def->original_id, me->called_id, me->owner, return_value);
// Note, this deviates from the interpreter in that users need to enable
// a c_return TracePoint for this DTrace hook to work. A reasonable change
// since the Ruby return event works this way as well.
RUBY_DTRACE_CMETHOD_RETURN_HOOK(ec, me->owner, me->def->original_id);
// Push return value into the caller's stack. We know that it's a frame that
// uses cfp->sp because we are patching a call done with gen_send_cfunc().
ec->cfp->sp[0] = return_value;
ec->cfp->sp++;
}
// Landing code for when c_return tracing is enabled. See full_cfunc_return().
static void
gen_full_cfunc_return(void)
{
codeblock_t *cb = ocb;
outline_full_cfunc_return_pos = ocb->write_pos;
// This chunk of code expect REG_EC to be filled properly and
// RAX to contain the return value of the C method.
// Call full_cfunc_return()
mov(cb, C_ARG_REGS[0], REG_EC);
mov(cb, C_ARG_REGS[1], RAX);
call_ptr(cb, REG0, (void *)full_cfunc_return);
// Count the exit
GEN_COUNTER_INC(cb, traced_cfunc_return);
// Return to the interpreter
pop(cb, REG_SP);
pop(cb, REG_EC);
pop(cb, REG_CFP);
mov(cb, RAX, imm_opnd(Qundef));
ret(cb);
}
/*
Compile an interpreter entry block to be inserted into an iseq
Returns `NULL` if compilation fails.
*/
static uint8_t *
yjit_entry_prologue(codeblock_t *cb, const rb_iseq_t *iseq)
{
RUBY_ASSERT(cb != NULL);
enum { MAX_PROLOGUE_SIZE = 1024 };
// Check if we have enough executable memory
if (cb->write_pos + MAX_PROLOGUE_SIZE >= cb->mem_size) {
return NULL;
}
const uint32_t old_write_pos = cb->write_pos;
// Align the current write position to cache line boundaries
cb_align_pos(cb, 64);
uint8_t *code_ptr = cb_get_ptr(cb, cb->write_pos);
ADD_COMMENT(cb, "yjit entry");
push(cb, REG_CFP);
push(cb, REG_EC);
push(cb, REG_SP);
// We are passed EC and CFP
mov(cb, REG_EC, C_ARG_REGS[0]);
mov(cb, REG_CFP, C_ARG_REGS[1]);
// Load the current SP from the CFP into REG_SP
mov(cb, REG_SP, member_opnd(REG_CFP, rb_control_frame_t, sp));
// Setup cfp->jit_return
// TODO: this could use an IP relative LEA instead of an 8 byte immediate
mov(cb, REG0, const_ptr_opnd(leave_exit_code));
mov(cb, member_opnd(REG_CFP, rb_control_frame_t, jit_return), REG0);
// We're compiling iseqs that we *expect* to start at `insn_idx`. But in
// the case of optional parameters, the interpreter can set the pc to a
// different location depending on the optional parameters. If an iseq
// has optional parameters, we'll add a runtime check that the PC we've
// compiled for is the same PC that the interpreter wants us to run with.
// If they don't match, then we'll take a side exit.
if (iseq->body->param.flags.has_opt) {
yjit_pc_guard(cb, iseq);
}
// Verify MAX_PROLOGUE_SIZE
RUBY_ASSERT_ALWAYS(cb->write_pos - old_write_pos <= MAX_PROLOGUE_SIZE);
return code_ptr;
}
// Generate code to check for interrupts and take a side-exit.
// Warning: this function clobbers REG0
static void
yjit_check_ints(codeblock_t *cb, uint8_t *side_exit)
{
// Check for interrupts
// see RUBY_VM_CHECK_INTS(ec) macro
ADD_COMMENT(cb, "RUBY_VM_CHECK_INTS(ec)");
mov(cb, REG0_32, member_opnd(REG_EC, rb_execution_context_t, interrupt_mask));
not(cb, REG0_32);
test(cb, member_opnd(REG_EC, rb_execution_context_t, interrupt_flag), REG0_32);
jnz_ptr(cb, side_exit);
}
// Generate a stubbed unconditional jump to the next bytecode instruction.
// Blocks that are part of a guard chain can use this to share the same successor.
static void
jit_jump_to_next_insn(jitstate_t *jit, const ctx_t *current_context)
{
// Reset the depth since in current usages we only ever jump to to
// chain_depth > 0 from the same instruction.
ctx_t reset_depth = *current_context;
reset_depth.chain_depth = 0;
blockid_t jump_block = { jit->iseq, jit_next_insn_idx(jit) };
// We are at the end of the current instruction. Record the boundary.
if (jit->record_boundary_patch_point) {
uint32_t exit_pos = yjit_gen_exit(jit->pc + insn_len(jit->opcode), &reset_depth, jit->ocb);
record_global_inval_patch(jit->cb, exit_pos);
jit->record_boundary_patch_point = false;
}
// Generate the jump instruction
gen_direct_jump(
jit,
&reset_depth,
jump_block
);
}
// Compile a sequence of bytecode instructions for a given basic block version.
// Part of gen_block_version().
static block_t *
gen_single_block(blockid_t blockid, const ctx_t *start_ctx, rb_execution_context_t *ec)
{
RUBY_ASSERT(cb != NULL);
verify_blockid(blockid);
// Allocate the new block
block_t *block = calloc(1, sizeof(block_t));
if (!block) {
return NULL;
}
// Copy the starting context to avoid mutating it
ctx_t ctx_copy = *start_ctx;
ctx_t *ctx = &ctx_copy;
// Limit the number of specialized versions for this block
*ctx = limit_block_versions(blockid, ctx);
// Save the starting context on the block.
block->blockid = blockid;
block->ctx = *ctx;
RUBY_ASSERT(!(blockid.idx == 0 && start_ctx->stack_size > 0));
const rb_iseq_t *iseq = block->blockid.iseq;
const unsigned int iseq_size = iseq->body->iseq_size;
uint32_t insn_idx = block->blockid.idx;
const uint32_t starting_insn_idx = insn_idx;
// Initialize a JIT state object
jitstate_t jit = {
.cb = cb,
.ocb = ocb,
.block = block,
.iseq = iseq,
.ec = ec
};
// Mark the start position of the block
block->start_addr = cb_get_write_ptr(cb);
// For each instruction to compile
while (insn_idx < iseq_size) {
// Get the current pc and opcode
VALUE *pc = yjit_iseq_pc_at_idx(iseq, insn_idx);
int opcode = yjit_opcode_at_pc(iseq, pc);
RUBY_ASSERT(opcode >= 0 && opcode < VM_INSTRUCTION_SIZE);
// opt_getinlinecache wants to be in a block all on its own. Cut the block short
// if we run into it. See gen_opt_getinlinecache() for details.
if (opcode == BIN(opt_getinlinecache) && insn_idx > starting_insn_idx) {
jit_jump_to_next_insn(&jit, ctx);
break;
}
// Set the current instruction
jit.insn_idx = insn_idx;
jit.opcode = opcode;
jit.pc = pc;
jit.side_exit_for_pc = NULL;
// If previous instruction requested to record the boundary
if (jit.record_boundary_patch_point) {
// Generate an exit to this instruction and record it
uint32_t exit_pos = yjit_gen_exit(jit.pc, ctx, ocb);
record_global_inval_patch(cb, exit_pos);
jit.record_boundary_patch_point = false;
}
// Verify our existing assumption (DEBUG)
if (jit_at_current_insn(&jit)) {
verify_ctx(&jit, ctx);
}
// Lookup the codegen function for this instruction
codegen_fn gen_fn = gen_fns[opcode];
codegen_status_t status = YJIT_CANT_COMPILE;
if (gen_fn) {
if (0) {
fprintf(stderr, "compiling %d: %s\n", insn_idx, insn_name(opcode));
print_str(cb, insn_name(opcode));
}
// :count-placement:
// Count bytecode instructions that execute in generated code.
// Note that the increment happens even when the output takes side exit.
GEN_COUNTER_INC(cb, exec_instruction);
// Add a comment for the name of the YARV instruction
ADD_COMMENT(cb, insn_name(opcode));
// Call the code generation function
status = gen_fn(&jit, ctx, cb);
}
// If we can't compile this instruction
// exit to the interpreter and stop compiling
if (status == YJIT_CANT_COMPILE) {
// TODO: if the codegen function makes changes to ctx and then return YJIT_CANT_COMPILE,
// the exit this generates would be wrong. We could save a copy of the entry context
// and assert that ctx is the same here.
uint32_t exit_off = yjit_gen_exit(jit.pc, ctx, cb);
// If this is the first instruction in the block, then we can use
// the exit for block->entry_exit.
if (insn_idx == block->blockid.idx) {
block->entry_exit = cb_get_ptr(cb, exit_off);
}
break;
}
// For now, reset the chain depth after each instruction as only the
// first instruction in the block can concern itself with the depth.
ctx->chain_depth = 0;
// Move to the next instruction to compile
insn_idx += insn_len(opcode);
// If the instruction terminates this block
if (status == YJIT_END_BLOCK) {
break;
}
}
// Mark the end position of the block
block->end_addr = cb_get_write_ptr(cb);
// Store the index of the last instruction in the block
block->end_idx = insn_idx;
// We currently can't handle cases where the request is for a block that
// doesn't go to the next instruction.
RUBY_ASSERT(!jit.record_boundary_patch_point);
// If code for the block doesn't fit, free the block and fail.
if (cb->dropped_bytes || ocb->dropped_bytes) {
yjit_free_block(block);
return NULL;
}
if (YJIT_DUMP_MODE >= 2) {
// Dump list of compiled instrutions
fprintf(stderr, "Compiled the following for iseq=%p:\n", (void *)iseq);
for (uint32_t idx = block->blockid.idx; idx < insn_idx; ) {
int opcode = yjit_opcode_at_pc(iseq, yjit_iseq_pc_at_idx(iseq, idx));
fprintf(stderr, " %04d %s\n", idx, insn_name(opcode));
idx += insn_len(opcode);
}
}
return block;
}
static codegen_status_t gen_opt_send_without_block(jitstate_t *jit, ctx_t *ctx, codeblock_t *cb);
static codegen_status_t
gen_nop(jitstate_t *jit, ctx_t *ctx, codeblock_t *cb)
{
// Do nothing
return YJIT_KEEP_COMPILING;
}
static codegen_status_t
gen_dup(jitstate_t *jit, ctx_t *ctx, codeblock_t *cb)
{
// Get the top value and its type
x86opnd_t dup_val = ctx_stack_pop(ctx, 0);
temp_type_mapping_t mapping = ctx_get_opnd_mapping(ctx, OPND_STACK(0));
// Push the same value on top
x86opnd_t loc0 = ctx_stack_push_mapping(ctx, mapping);
mov(cb, REG0, dup_val);
mov(cb, loc0, REG0);
return YJIT_KEEP_COMPILING;
}
// duplicate stack top n elements
static codegen_status_t
gen_dupn(jitstate_t *jit, ctx_t *ctx, codeblock_t *cb)
{
rb_num_t n = (rb_num_t)jit_get_arg(jit, 0);
// In practice, seems to be only used for n==2
if (n != 2) {
return YJIT_CANT_COMPILE;
}
x86opnd_t opnd1 = ctx_stack_opnd(ctx, 1);
x86opnd_t opnd0 = ctx_stack_opnd(ctx, 0);
temp_type_mapping_t mapping1 = ctx_get_opnd_mapping(ctx, OPND_STACK(1));
temp_type_mapping_t mapping0 = ctx_get_opnd_mapping(ctx, OPND_STACK(0));
x86opnd_t dst1 = ctx_stack_push_mapping(ctx, mapping1);
mov(cb, REG0, opnd1);
mov(cb, dst1, REG0);
x86opnd_t dst0 = ctx_stack_push_mapping(ctx, mapping0);
mov(cb, REG0, opnd0);
mov(cb, dst0, REG0);
return YJIT_KEEP_COMPILING;
}
static void
stack_swap(ctx_t *ctx, codeblock_t *cb, int offset0, int offset1, x86opnd_t reg0, x86opnd_t reg1)
{
x86opnd_t opnd0 = ctx_stack_opnd(ctx, offset0);
x86opnd_t opnd1 = ctx_stack_opnd(ctx, offset1);
temp_type_mapping_t mapping0 = ctx_get_opnd_mapping(ctx, OPND_STACK(offset0));
temp_type_mapping_t mapping1 = ctx_get_opnd_mapping(ctx, OPND_STACK(offset1));
mov(cb, reg0, opnd0);
mov(cb, reg1, opnd1);
mov(cb, opnd0, reg1);
mov(cb, opnd1, reg0);
ctx_set_opnd_mapping(ctx, OPND_STACK(offset0), mapping1);
ctx_set_opnd_mapping(ctx, OPND_STACK(offset1), mapping0);
}
// Swap top 2 stack entries
static codegen_status_t
gen_swap(jitstate_t *jit, ctx_t *ctx, codeblock_t *cb)
{
stack_swap(ctx , cb, 0, 1, REG0, REG1);
return YJIT_KEEP_COMPILING;
}
// set Nth stack entry to stack top
static codegen_status_t
gen_setn(jitstate_t *jit, ctx_t *ctx, codeblock_t *cb)
{
rb_num_t n = (rb_num_t)jit_get_arg(jit, 0);
// Set the destination
x86opnd_t top_val = ctx_stack_pop(ctx, 0);
x86opnd_t dst_opnd = ctx_stack_opnd(ctx, (int32_t)n);
mov(cb, REG0, top_val);
mov(cb, dst_opnd, REG0);
temp_type_mapping_t mapping = ctx_get_opnd_mapping(ctx, OPND_STACK(0));
ctx_set_opnd_mapping(ctx, OPND_STACK(n), mapping);
return YJIT_KEEP_COMPILING;
}
// get nth stack value, then push it
static codegen_status_t
gen_topn(jitstate_t *jit, ctx_t *ctx, codeblock_t *cb)
{
int32_t n = (int32_t)jit_get_arg(jit, 0);
// Get top n type / operand
x86opnd_t top_n_val = ctx_stack_opnd(ctx, n);
temp_type_mapping_t mapping = ctx_get_opnd_mapping(ctx, OPND_STACK(n));
x86opnd_t loc0 = ctx_stack_push_mapping(ctx, mapping);
mov(cb, REG0, top_n_val);
mov(cb, loc0, REG0);
return YJIT_KEEP_COMPILING;
}
static codegen_status_t
gen_pop(jitstate_t *jit, ctx_t *ctx, codeblock_t *cb)
{
// Decrement SP
ctx_stack_pop(ctx, 1);
return YJIT_KEEP_COMPILING;
}
// Pop n values off the stack
static codegen_status_t
gen_adjuststack(jitstate_t *jit, ctx_t *ctx, codeblock_t *cb)
{
rb_num_t n = (rb_num_t)jit_get_arg(jit, 0);
ctx_stack_pop(ctx, n);
return YJIT_KEEP_COMPILING;
}
// new array initialized from top N values
static codegen_status_t
gen_newarray(jitstate_t *jit, ctx_t *ctx, codeblock_t *cb)
{
rb_num_t n = (rb_num_t)jit_get_arg(jit, 0);
// Save the PC and SP because we are allocating
jit_prepare_routine_call(jit, ctx, REG0);
x86opnd_t values_ptr = ctx_sp_opnd(ctx, -(int32_t)(sizeof(VALUE) * (uint32_t)n));
// call rb_ec_ary_new_from_values(struct rb_execution_context_struct *ec, long n, const VALUE *elts);
mov(cb, C_ARG_REGS[0], REG_EC);
mov(cb, C_ARG_REGS[1], imm_opnd(n));
lea(cb, C_ARG_REGS[2], values_ptr);
call_ptr(cb, REG0, (void *)rb_ec_ary_new_from_values);
ctx_stack_pop(ctx, n);
x86opnd_t stack_ret = ctx_stack_push(ctx, TYPE_ARRAY);
mov(cb, stack_ret, RAX);
return YJIT_KEEP_COMPILING;
}
// dup array
static codegen_status_t
gen_duparray(jitstate_t *jit, ctx_t *ctx, codeblock_t *cb)
{
VALUE ary = jit_get_arg(jit, 0);
// Save the PC and SP because we are allocating
jit_prepare_routine_call(jit, ctx, REG0);
// call rb_ary_resurrect(VALUE ary);
jit_mov_gc_ptr(jit, cb, C_ARG_REGS[0], ary);
call_ptr(cb, REG0, (void *)rb_ary_resurrect);
x86opnd_t stack_ret = ctx_stack_push(ctx, TYPE_ARRAY);
mov(cb, stack_ret, RAX);
return YJIT_KEEP_COMPILING;
}
// dup hash
static codegen_status_t
gen_duphash(jitstate_t *jit, ctx_t *ctx, codeblock_t *cb)
{
VALUE hash = jit_get_arg(jit, 0);
// Save the PC and SP because we are allocating
jit_prepare_routine_call(jit, ctx, REG0);
// call rb_hash_resurrect(VALUE hash);
jit_mov_gc_ptr(jit, cb, C_ARG_REGS[0], hash);
call_ptr(cb, REG0, (void *)rb_hash_resurrect);
x86opnd_t stack_ret = ctx_stack_push(ctx, TYPE_HASH);
mov(cb, stack_ret, RAX);
return YJIT_KEEP_COMPILING;
}
VALUE rb_vm_splat_array(VALUE flag, VALUE ary);
// call to_a on the array on the stack
static codegen_status_t
gen_splatarray(jitstate_t *jit, ctx_t *ctx, codeblock_t *cb)
{
VALUE flag = (VALUE) jit_get_arg(jit, 0);
// Save the PC and SP because the callee may allocate
// Note that this modifies REG_SP, which is why we do it first
jit_prepare_routine_call(jit, ctx, REG0);
// Get the operands from the stack
x86opnd_t ary_opnd = ctx_stack_pop(ctx, 1);
// Call rb_vm_splat_array(flag, ary)