forked from ruby/ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.rs
2069 lines (1708 loc) · 67.3 KB
/
core.rs
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
use crate::asm::x86_64::*;
use crate::asm::*;
use crate::codegen::*;
use crate::virtualmem::CodePtr;
use crate::cruby::*;
use crate::options::*;
use crate::stats::*;
use crate::utils::*;
use core::ffi::c_void;
use std::cell::*;
use std::hash::{Hash, Hasher};
use std::mem;
use std::rc::{Rc};
use InsnOpnd::*;
use TempMapping::*;
// Maximum number of temp value types we keep track of
pub const MAX_TEMP_TYPES: usize = 8;
// Maximum number of local variable types we keep track of
const MAX_LOCAL_TYPES: usize = 8;
// Represent the type of a value (local/stack/self) in YJIT
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Type {
Unknown,
UnknownImm,
UnknownHeap,
Nil,
True,
False,
Fixnum,
Flonum,
Array,
Hash,
ImmSymbol,
#[allow(unused)]
HeapSymbol,
TString, // An object with the T_STRING flag set, possibly an rb_cString
CString, // An un-subclassed string of type rb_cString (can have instance vars in some cases)
}
// Default initialization
impl Default for Type {
fn default() -> Self {
Type::Unknown
}
}
impl Type {
/// This returns an appropriate Type based on a known value
pub fn from(val: VALUE) -> Type {
if val.special_const_p() {
if val.fixnum_p() {
Type::Fixnum
} else if val.nil_p() {
Type::Nil
} else if val == Qtrue {
Type::True
} else if val == Qfalse {
Type::False
} else if val.static_sym_p() {
Type::ImmSymbol
} else if val.flonum_p() {
Type::Flonum
} else {
unreachable!()
}
} else {
// Core.rs can't reference rb_cString because it's linked by Rust-only tests.
// But CString vs TString is only an optimisation and shouldn't affect correctness.
#[cfg(not(test))]
if val.class_of() == unsafe { rb_cString } {
return Type::CString;
}
match val.builtin_type() {
RUBY_T_ARRAY => Type::Array,
RUBY_T_HASH => Type::Hash,
RUBY_T_STRING => Type::TString,
_ => Type::UnknownHeap,
}
}
}
/// Check if the type is an immediate
pub fn is_imm(&self) -> bool {
match self {
Type::UnknownImm => true,
Type::Nil => true,
Type::True => true,
Type::False => true,
Type::Fixnum => true,
Type::Flonum => true,
Type::ImmSymbol => true,
_ => false,
}
}
/// Returns true when the type is not specific.
pub fn is_unknown(&self) -> bool {
match self {
Type::Unknown | Type::UnknownImm | Type::UnknownHeap => true,
_ => false,
}
}
/// Returns true when we know the VALUE is a specific handle type,
/// such as a static symbol ([Type::ImmSymbol], i.e. true from RB_STATIC_SYM_P()).
/// Opposite of [Self::is_unknown].
pub fn is_specific(&self) -> bool {
!self.is_unknown()
}
/// Check if the type is a heap object
pub fn is_heap(&self) -> bool {
match self {
Type::UnknownHeap => true,
Type::Array => true,
Type::Hash => true,
Type::HeapSymbol => true,
Type::TString => true,
Type::CString => true,
_ => false,
}
}
/// Compute a difference between two value types
/// Returns 0 if the two are the same
/// Returns > 0 if different but compatible
/// Returns usize::MAX if incompatible
pub fn diff(self, dst: Self) -> usize {
// Perfect match, difference is zero
if self == dst {
return 0;
}
// Any type can flow into an unknown type
if dst == Type::Unknown {
return 1;
}
// A CString is also a TString.
if self == Type::CString && dst == Type::TString {
return 1;
}
// Specific heap type into unknown heap type is imperfect but valid
if self.is_heap() && dst == Type::UnknownHeap {
return 1;
}
// Specific immediate type into unknown immediate type is imperfect but valid
if self.is_imm() && dst == Type::UnknownImm {
return 1;
}
// Incompatible types
return usize::MAX;
}
/// Upgrade this type into a more specific compatible type
/// The new type must be compatible and at least as specific as the previously known type.
fn upgrade(&mut self, src: Self) {
// Here we're checking that src is more specific than self
assert!(src.diff(*self) != usize::MAX);
*self = src;
}
}
// Potential mapping of a value on the temporary stack to
// self, a local variable or constant so that we can track its type
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum TempMapping {
MapToStack, // Normal stack value
MapToSelf, // Temp maps to the self operand
MapToLocal(u8), // Temp maps to a local variable with index
//ConstMapping, // Small constant (0, 1, 2, Qnil, Qfalse, Qtrue)
}
impl Default for TempMapping {
fn default() -> Self {
MapToStack
}
}
// Operand to a bytecode instruction
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum InsnOpnd {
// The value is self
SelfOpnd,
// Temporary stack operand with stack index
StackOpnd(u16),
}
/// Code generation context
/// Contains information we can use to specialize/optimize code
/// There are a lot of context objects so we try to keep the size small.
#[derive(Copy, Clone, Default, Debug)]
pub struct Context {
// Number of values currently on the temporary stack
stack_size: u16,
// Offset of the JIT SP relative to the interpreter SP
// This represents how far the JIT's SP is from the "real" SP
sp_offset: i16,
// Depth of this block in the sidechain (eg: inline-cache chain)
chain_depth: u8,
// Local variable types we keep track of
local_types: [Type; MAX_LOCAL_TYPES],
// Temporary variable types we keep track of
temp_types: [Type; MAX_TEMP_TYPES],
// Type we track for self
self_type: Type,
// Mapping of temp stack entries to types we track
temp_mapping: [TempMapping; MAX_TEMP_TYPES],
}
/// Tuple of (iseq, idx) used to identify basic blocks
/// There are a lot of blockid objects so we try to keep the size small.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct BlockId {
/// Instruction sequence
pub iseq: IseqPtr,
/// Index in the iseq where the block starts
pub idx: u32,
}
/// Branch code shape enumeration
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum BranchShape {
Next0, // Target 0 is next
Next1, // Target 1 is next
Default, // Neither target is next
}
// Branch code generation function signature
type BranchGenFn =
fn(cb: &mut CodeBlock, target0: CodePtr, target1: Option<CodePtr>, shape: BranchShape) -> ();
/// Store info about an outgoing branch in a code segment
/// Note: care must be taken to minimize the size of branch objects
struct Branch {
// Block this is attached to
block: BlockRef,
// Positions where the generated code starts and ends
start_addr: Option<CodePtr>,
end_addr: Option<CodePtr>,
// Context right after the branch instruction
#[allow(unused)] // set but not read at the moment
src_ctx: Context,
// Branch target blocks and their contexts
targets: [Option<BlockId>; 2],
target_ctxs: [Context; 2],
blocks: [Option<BlockRef>; 2],
// Jump target addresses
dst_addrs: [Option<CodePtr>; 2],
// Branch code generation function
gen_fn: BranchGenFn,
// Shape of the branch
shape: BranchShape,
}
impl std::fmt::Debug for Branch {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// TODO: expand this if needed. #[derive(Debug)] on Branch gave a
// strange error related to BranchGenFn
formatter
.debug_struct("Branch")
.field("start", &self.start_addr)
.field("end", &self.end_addr)
.field("targets", &self.targets)
.finish()
}
}
impl Branch {
// Compute the size of the branch code
fn code_size(&self) -> usize {
(self.end_addr.unwrap().raw_ptr() as usize) - (self.start_addr.unwrap().raw_ptr() as usize)
}
}
// In case this block is invalidated, these two pieces of info
// help to remove all pointers to this block in the system.
#[derive(Debug)]
pub struct CmeDependency {
pub receiver_klass: VALUE,
pub callee_cme: *const rb_callable_method_entry_t,
}
/// Basic block version
/// Represents a portion of an iseq compiled with a given context
/// Note: care must be taken to minimize the size of block_t objects
#[derive(Debug)]
pub struct Block {
// Bytecode sequence (iseq, idx) this is a version of
blockid: BlockId,
// Index one past the last instruction for this block in the iseq
end_idx: u32,
// Context at the start of the block
// This should never be mutated
ctx: Context,
// Positions where the generated code starts and ends
start_addr: Option<CodePtr>,
end_addr: Option<CodePtr>,
// List of incoming branches (from predecessors)
// These are reference counted (ownership shared between predecessor and successors)
incoming: Vec<BranchRef>,
// NOTE: we might actually be able to store the branches here without refcounting
// however, using a RefCell makes it easy to get a pointer to Branch objects
//
// List of outgoing branches (to successors)
outgoing: Vec<BranchRef>,
// FIXME: should these be code pointers instead?
// Offsets for GC managed objects in the mainline code block
gc_object_offsets: Vec<u32>,
// CME dependencies of this block, to help to remove all pointers to this
// block in the system.
cme_dependencies: Vec<CmeDependency>,
// Code address of an exit for `ctx` and `blockid`.
// Used for block invalidation.
pub entry_exit: Option<CodePtr>,
}
/// Reference-counted pointer to a block that can be borrowed mutably.
/// Wrapped so we could implement [Hash] and [Eq] for use with stdlib collections.
#[derive(Debug)]
pub struct BlockRef(Rc<RefCell<Block>>);
/// Reference-counted pointer to a branch that can be borrowed mutably
type BranchRef = Rc<RefCell<Branch>>;
/// List of block versions for a given blockid
type VersionList = Vec<BlockRef>;
/// Map from iseq indices to lists of versions for that given blockid
/// An instance of this is stored on each iseq
type VersionMap = Vec<VersionList>;
impl BlockRef {
/// Constructor
pub fn new(rc: Rc<RefCell<Block>>) -> Self {
Self(rc)
}
/// Borrow the block through [RefCell].
pub fn borrow(&self) -> Ref<'_, Block> {
self.0.borrow()
}
/// Borrow the block for mutation through [RefCell].
pub fn borrow_mut(&self) -> RefMut<'_, Block> {
self.0.borrow_mut()
}
}
impl Clone for BlockRef {
/// Clone the [Rc]
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl Hash for BlockRef {
/// Hash the reference by hashing the pointer
fn hash<H: Hasher>(&self, state: &mut H) {
let rc_ptr = Rc::as_ptr(&self.0);
rc_ptr.hash(state);
}
}
impl PartialEq for BlockRef {
/// Equality defined by allocation identity
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
/// It's comparison by identity so all the requirements are statisfied
impl Eq for BlockRef {}
/// This is all the data YJIT stores on an iseq
/// This will be dynamically allocated by C code
/// C code should pass an &mut IseqPayload to us
/// when calling into YJIT
#[derive(Default)]
pub struct IseqPayload {
version_map: VersionMap,
}
impl IseqPayload {
/// Remove all block versions from the payload and then return them as an iterator
pub fn take_all_blocks(&mut self) -> impl Iterator<Item = BlockRef> {
// Empty the blocks
let version_map = mem::take(&mut self.version_map);
// Turn it into an iterator that owns the blocks and return
version_map.into_iter().flatten()
}
}
/// Get the payload for an iseq. For safety it's up to the caller to ensure the returned `&mut`
/// upholds aliasing rules and that the argument is a valid iseq.
pub unsafe fn load_iseq_payload(iseq: IseqPtr) -> Option<&'static mut IseqPayload> {
let payload = rb_iseq_get_yjit_payload(iseq);
let payload: *mut IseqPayload = payload.cast();
payload.as_mut()
}
/// Get the payload object associated with an iseq. Create one if none exists.
fn get_iseq_payload(iseq: IseqPtr) -> &'static mut IseqPayload {
type VoidPtr = *mut c_void;
let payload_non_null = unsafe {
let payload = rb_iseq_get_yjit_payload(iseq);
if payload.is_null() {
// Increment the compiled iseq count
incr_counter!(compiled_iseq_count);
// Allocate a new payload with Box and transfer ownership to the GC.
// We drop the payload with Box::from_raw when the GC frees the iseq and calls us.
// NOTE(alan): Sometimes we read from an iseq without ever writing to it.
// We allocate in those cases anyways.
let new_payload = Box::into_raw(Box::new(IseqPayload::default()));
rb_iseq_set_yjit_payload(iseq, new_payload as VoidPtr);
new_payload
} else {
payload as *mut IseqPayload
}
};
// SAFETY: we should have the VM lock and all other Ruby threads should be asleep. So we have
// exclusive mutable access.
// Hmm, nothing seems to stop calling this on the same
// iseq twice, though, which violates aliasing rules.
unsafe { payload_non_null.as_mut() }.unwrap()
}
/// Free the per-iseq payload
#[no_mangle]
pub extern "C" fn rb_yjit_iseq_free(payload: *mut c_void) {
let payload = {
if payload.is_null() {
// Nothing to free.
return;
} else {
payload as *mut IseqPayload
}
};
use crate::invariants;
// Take ownership of the payload with Box::from_raw().
// It drops right before this function returns.
// SAFETY: We got the pointer from Box::into_raw().
let payload = unsafe { Box::from_raw(payload) };
// Remove all blocks in the payload from global invariants table.
for versions in &payload.version_map {
for block in versions {
invariants::block_assumptions_free(&block);
}
}
}
/// GC callback for marking GC objects in the the per-iseq payload.
#[no_mangle]
pub extern "C" fn rb_yjit_iseq_mark(payload: *mut c_void) {
let payload = if payload.is_null() {
// Nothing to mark.
return;
} else {
// SAFETY: It looks like the GC takes the VM lock while marking
// so we should be satisfying aliasing rules here.
unsafe { &*(payload as *const IseqPayload) }
};
// For marking VALUEs written into the inline code block.
// We don't write VALUEs in the outlined block.
let cb: &CodeBlock = CodegenGlobals::get_inline_cb();
for versions in &payload.version_map {
for block in versions {
let block = block.borrow();
unsafe { rb_gc_mark_movable(block.blockid.iseq.into()) };
// Mark method entry dependencies
for cme_dep in &block.cme_dependencies {
unsafe { rb_gc_mark_movable(cme_dep.receiver_klass) };
unsafe { rb_gc_mark_movable(cme_dep.callee_cme.into()) };
}
// Mark outgoing branch entries
for branch in &block.outgoing {
let branch = branch.borrow();
for target in &branch.targets {
if let Some(target) = target {
unsafe { rb_gc_mark_movable(target.iseq.into()) };
}
}
}
// Walk over references to objects in generated code.
for offset in &block.gc_object_offsets {
let value_address: *const u8 = cb.get_ptr(offset.as_usize()).raw_ptr();
// Creating an unaligned pointer is well defined unlike in C.
let value_address = value_address as *const VALUE;
// SAFETY: these point to YJIT's code buffer
unsafe {
let object = value_address.read_unaligned();
rb_gc_mark_movable(object);
};
}
}
}
}
/// GC callback for updating GC objects in the the per-iseq payload.
/// This is a mirror of [rb_yjit_iseq_mark].
#[no_mangle]
pub extern "C" fn rb_yjit_iseq_update_references(payload: *mut c_void) {
let payload = if payload.is_null() {
// Nothing to update.
return;
} else {
// SAFETY: It looks like the GC takes the VM lock while updating references
// so we should be satisfying aliasing rules here.
unsafe { &*(payload as *const IseqPayload) }
};
// Evict other threads from generated code since we are about to patch them.
// Also acts as an assert that we hold the VM lock.
unsafe { rb_vm_barrier() };
// For updating VALUEs written into the inline code block.
let cb = CodegenGlobals::get_inline_cb();
for versions in &payload.version_map {
for block in versions {
let mut block = block.borrow_mut();
block.blockid.iseq = unsafe { rb_gc_location(block.blockid.iseq.into()) }.as_iseq();
// Update method entry dependencies
for cme_dep in &mut block.cme_dependencies {
cme_dep.receiver_klass = unsafe { rb_gc_location(cme_dep.receiver_klass) };
cme_dep.callee_cme = unsafe { rb_gc_location(cme_dep.callee_cme.into()) }.as_cme();
}
// Update outgoing branch entries
for branch in &block.outgoing {
let mut branch = branch.borrow_mut();
for target in &mut branch.targets {
if let Some(target) = target {
target.iseq = unsafe { rb_gc_location(target.iseq.into()) }.as_iseq();
}
}
}
// Walk over references to objects in generated code.
for offset in &block.gc_object_offsets {
let offset_to_value = offset.as_usize();
let value_code_ptr = cb.get_ptr(offset_to_value);
let value_ptr: *const u8 = value_code_ptr.raw_ptr();
// Creating an unaligned pointer is well defined unlike in C.
let value_ptr = value_ptr as *mut VALUE;
// SAFETY: these point to YJIT's code buffer
let object = unsafe { value_ptr.read_unaligned() };
let new_addr = unsafe { rb_gc_location(object) };
// Only write when the VALUE moves, to be copy-on-write friendly.
if new_addr != object {
for (byte_idx, &byte) in new_addr.as_u64().to_le_bytes().iter().enumerate() {
let byte_code_ptr = value_code_ptr.add_bytes(byte_idx);
cb.get_mem().write_byte(byte_code_ptr, byte)
.expect("patching existing code should be within bounds");
}
}
}
}
}
// Note that we would have returned already if YJIT is off.
cb.mark_all_executable();
CodegenGlobals::get_outlined_cb()
.unwrap()
.mark_all_executable();
}
/// Get all blocks for a particular place in an iseq.
fn get_version_list(blockid: BlockId) -> &'static mut VersionList {
let payload = get_iseq_payload(blockid.iseq);
let insn_idx = blockid.idx.as_usize();
// Expand the version map as necessary
if insn_idx >= payload.version_map.len() {
payload
.version_map
.resize(insn_idx + 1, VersionList::default());
}
return payload.version_map.get_mut(insn_idx).unwrap();
}
/// Take all of the blocks for a particular place in an iseq
pub fn take_version_list(blockid: BlockId) -> VersionList {
let payload = get_iseq_payload(blockid.iseq);
let insn_idx = blockid.idx.as_usize();
if insn_idx >= payload.version_map.len() {
VersionList::default()
} else {
mem::take(&mut payload.version_map[insn_idx])
}
}
/// Count the number of block versions matching a given blockid
fn get_num_versions(blockid: BlockId) -> usize {
let insn_idx = blockid.idx.as_usize();
let payload = get_iseq_payload(blockid.iseq);
payload
.version_map
.get(insn_idx)
.map(|versions| versions.len())
.unwrap_or(0)
}
/// Get a list of block versions generated for an iseq
/// This is used for disassembly (see disasm.rs)
pub fn get_iseq_block_list(iseq: IseqPtr) -> Vec<BlockRef> {
let payload = get_iseq_payload(iseq);
let mut blocks = Vec::<BlockRef>::new();
// For each instruction index
for insn_idx in 0..payload.version_map.len() {
let version_list = &payload.version_map[insn_idx];
// For each version at this instruction index
for version in version_list {
// Clone the block ref and add it to the list
blocks.push(version.clone());
}
}
return blocks;
}
/// Retrieve a basic block version for an (iseq, idx) tuple
/// This will return None if no version is found
fn find_block_version(blockid: BlockId, ctx: &Context) -> Option<BlockRef> {
let versions = get_version_list(blockid);
// Best match found
let mut best_version: Option<BlockRef> = None;
let mut best_diff = usize::MAX;
// For each version matching the blockid
for blockref in versions.iter_mut() {
let block = blockref.borrow();
let diff = ctx.diff(&block.ctx);
// Note that we always prefer the first matching
// version found because of inline-cache chains
if diff < best_diff {
best_version = Some(blockref.clone());
best_diff = diff;
}
}
// If greedy versioning is enabled
if get_option!(greedy_versioning) {
// If we're below the version limit, don't settle for an imperfect match
if versions.len() + 1 < get_option!(max_versions) && best_diff > 0 {
return None;
}
}
return best_version;
}
/// Produce a generic context when the block version limit is hit for a blockid
pub fn limit_block_versions(blockid: BlockId, ctx: &Context) -> Context {
// Guard chains implement limits separately, do nothing
if ctx.chain_depth > 0 {
return *ctx;
}
// If this block version we're about to add will hit the version limit
if get_num_versions(blockid) + 1 >= get_option!(max_versions) {
// Produce a generic context that stores no type information,
// but still respects the stack_size and sp_offset constraints.
// This new context will then match all future requests.
let mut generic_ctx = Context::default();
generic_ctx.stack_size = ctx.stack_size;
generic_ctx.sp_offset = ctx.sp_offset;
// Mutate the incoming context
return generic_ctx;
}
return *ctx;
}
/// Keep track of a block version. Block should be fully constructed.
/// Uses `cb` for running write barriers.
fn add_block_version(blockref: &BlockRef, cb: &CodeBlock) {
let block = blockref.borrow();
// Function entry blocks must have stack size 0
assert!(!(block.blockid.idx == 0 && block.ctx.stack_size > 0));
let version_list = get_version_list(block.blockid);
version_list.push(blockref.clone());
// By writing the new block to the iseq, the iseq now
// contains new references to Ruby objects. Run write barriers.
let iseq: VALUE = block.blockid.iseq.into();
for dep in block.iter_cme_deps() {
obj_written!(iseq, dep.receiver_klass);
obj_written!(iseq, dep.callee_cme.into());
}
// Run write barriers for all objects in generated code.
for offset in &block.gc_object_offsets {
let value_address: *const u8 = cb.get_ptr(offset.as_usize()).raw_ptr();
// Creating an unaligned pointer is well defined unlike in C.
let value_address: *const VALUE = value_address.cast();
let object = unsafe { value_address.read_unaligned() };
obj_written!(iseq, object);
}
incr_counter!(compiled_block_count);
}
/// Remove a block version from the version map of its parent ISEQ
fn remove_block_version(blockref: &BlockRef) {
let block = blockref.borrow();
let version_list = get_version_list(block.blockid);
// Retain the versions that are not this one
version_list.retain(|other| blockref != other);
}
//===========================================================================
// I put the implementation of traits for core.rs types below
// We can move these closer to the above structs later if we want.
//===========================================================================
impl Block {
pub fn new(blockid: BlockId, ctx: &Context) -> BlockRef {
let block = Block {
blockid,
end_idx: 0,
ctx: *ctx,
start_addr: None,
end_addr: None,
incoming: Vec::new(),
outgoing: Vec::new(),
gc_object_offsets: Vec::new(),
cme_dependencies: Vec::new(),
entry_exit: None,
};
// Wrap the block in a reference counted refcell
// so that the block ownership can be shared
BlockRef::new(Rc::new(RefCell::new(block)))
}
pub fn get_blockid(&self) -> BlockId {
self.blockid
}
pub fn get_end_idx(&self) -> u32 {
self.end_idx
}
pub fn get_ctx(&self) -> Context {
self.ctx
}
#[allow(unused)]
pub fn get_start_addr(&self) -> Option<CodePtr> {
self.start_addr
}
#[allow(unused)]
pub fn get_end_addr(&self) -> Option<CodePtr> {
self.end_addr
}
/// Get an immutable iterator over cme dependencies
pub fn iter_cme_deps(&self) -> std::slice::Iter<'_, CmeDependency> {
self.cme_dependencies.iter()
}
/// Set the starting address in the generated code for the block
/// This can be done only once for a block
pub fn set_start_addr(&mut self, addr: CodePtr) {
assert!(self.start_addr.is_none());
self.start_addr = Some(addr);
}
/// Set the end address in the generated for the block
/// This can be done only once for a block
pub fn set_end_addr(&mut self, addr: CodePtr) {
// The end address can only be set after the start address is set
assert!(self.start_addr.is_some());
// TODO: assert constraint that blocks can shrink but not grow in length
self.end_addr = Some(addr);
}
/// Set the index of the last instruction in the block
/// This can be done only once for a block
pub fn set_end_idx(&mut self, end_idx: u32) {
assert!(self.end_idx == 0);
self.end_idx = end_idx;
}
pub fn add_gc_object_offset(self: &mut Block, ptr_offset: u32) {
self.gc_object_offsets.push(ptr_offset);
}
/// Instantiate a new CmeDependency struct and add it to the list of
/// dependencies for this block.
pub fn add_cme_dependency(
&mut self,
receiver_klass: VALUE,
callee_cme: *const rb_callable_method_entry_t,
) {
self.cme_dependencies.push(CmeDependency {
receiver_klass,
callee_cme,
});
}
// Compute the size of the block code
pub fn code_size(&self) -> usize {
(self.end_addr.unwrap().raw_ptr() as usize) - (self.start_addr.unwrap().raw_ptr() as usize)
}
}
impl Context {
pub fn new_with_stack_size(size: i16) -> Self {
return Context {
stack_size: size as u16,
sp_offset: size,
chain_depth: 0,
local_types: [Type::Unknown; MAX_LOCAL_TYPES],
temp_types: [Type::Unknown; MAX_TEMP_TYPES],
self_type: Type::Unknown,
temp_mapping: [MapToStack; MAX_TEMP_TYPES],
};
}
pub fn new() -> Self {
return Self::new_with_stack_size(0);
}
pub fn get_stack_size(&self) -> u16 {
self.stack_size
}
pub fn get_sp_offset(&self) -> i16 {
self.sp_offset
}
pub fn set_sp_offset(&mut self, offset: i16) {
self.sp_offset = offset;
}
pub fn get_chain_depth(&self) -> u8 {
self.chain_depth
}
pub fn reset_chain_depth(&mut self) {
self.chain_depth = 0;
}
pub fn increment_chain_depth(&mut self) {
self.chain_depth += 1;
}
/// Get an operand for the adjusted stack pointer address
pub fn sp_opnd(&self, offset_bytes: isize) -> X86Opnd {
let offset = ((self.sp_offset as isize) * (SIZEOF_VALUE as isize)) + offset_bytes;
let offset = offset as i32;
return mem_opnd(64, REG_SP, offset);
}
/// Push one new value on the temp stack with an explicit mapping
/// Return a pointer to the new stack top
pub fn stack_push_mapping(&mut self, (mapping, temp_type): (TempMapping, Type)) -> X86Opnd {
// If type propagation is disabled, store no types
if get_option!(no_type_prop) {
return self.stack_push_mapping((mapping, Type::Unknown));
}
let stack_size: usize = self.stack_size.into();
// Keep track of the type and mapping of the value
if stack_size < MAX_TEMP_TYPES {
self.temp_mapping[stack_size] = mapping;
self.temp_types[stack_size] = temp_type;
if let MapToLocal(idx) = mapping {
assert!((idx as usize) < MAX_LOCAL_TYPES);
}
}
self.stack_size += 1;
self.sp_offset += 1;
// SP points just above the topmost value
let offset = ((self.sp_offset as i32) - 1) * (SIZEOF_VALUE as i32);
return mem_opnd(64, REG_SP, offset);
}
/// Push one new value on the temp stack
/// Return a pointer to the new stack top
pub fn stack_push(&mut self, val_type: Type) -> X86Opnd {
return self.stack_push_mapping((MapToStack, val_type));
}
/// Push the self value on the stack
pub fn stack_push_self(&mut self) -> X86Opnd {
return self.stack_push_mapping((MapToSelf, Type::Unknown));
}
/// Push a local variable on the stack
pub fn stack_push_local(&mut self, local_idx: usize) -> X86Opnd {
if local_idx >= MAX_LOCAL_TYPES {
return self.stack_push(Type::Unknown);
}
return self.stack_push_mapping((MapToLocal(local_idx as u8), Type::Unknown));
}
// Pop N values off the stack
// Return a pointer to the stack top before the pop operation
pub fn stack_pop(&mut self, n: usize) -> X86Opnd {
assert!(n <= self.stack_size.into());
// SP points just above the topmost value
let offset = ((self.sp_offset as i32) - 1) * (SIZEOF_VALUE as i32);
let top = mem_opnd(64, REG_SP, offset);
// Clear the types of the popped values
for i in 0..n {
let idx: usize = (self.stack_size as usize) - i - 1;
if idx < MAX_TEMP_TYPES {
self.temp_types[idx] = Type::Unknown;
self.temp_mapping[idx] = MapToStack;
}
}
self.stack_size -= n as u16;
self.sp_offset -= n as i16;
return top;
}
/// Get an operand pointing to a slot on the temp stack
pub fn stack_opnd(&self, idx: i32) -> X86Opnd {
// SP points just above the topmost value
let offset = ((self.sp_offset as i32) - 1 - idx) * (SIZEOF_VALUE as i32);
let opnd = mem_opnd(64, REG_SP, offset);