forked from Shopify/ruby
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhir.rs
More file actions
8595 lines (8016 loc) · 422 KB
/
hir.rs
File metadata and controls
8595 lines (8016 loc) · 422 KB
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
//! High-level intermediary representation (IR) in static single-assignment (SSA) form.
// We use the YARV bytecode constants which have a CRuby-style name
#![allow(non_upper_case_globals)]
#![allow(clippy::if_same_then_else)]
#![allow(clippy::match_like_matches_macro)]
use crate::{
backend::lir::C_ARG_OPNDS,
cast::IntoUsize, codegen::local_idx_to_ep_offset, cruby::*, invariants::has_singleton_class_method_shadowing, payload::{get_or_create_iseq_payload, IseqPayload}, options::{debug, get_option, DumpHIR}, state::ZJITState, json::Json
};
use std::{
cell::RefCell, collections::{BTreeSet, HashMap, HashSet, VecDeque}, ffi::{c_void, c_uint, c_int, CStr}, fmt::Display, mem::{align_of, size_of}, ptr, slice::Iter
};
use crate::hir_type::{Type, types};
use crate::hir_effect::{Effect, abstract_heaps, effects};
use crate::bitset::BitSet;
use crate::profile::{TypeDistributionSummary, ProfiledType};
use crate::stats::Counter;
use SendFallbackReason::*;
pub(crate) mod tests;
mod opt_tests;
/// An index of an [`Insn`] in a [`Function`]. This is a popular
/// type since this effectively acts as a pointer to an [`Insn`].
/// See also: [`Function::find`].
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
pub struct InsnId(pub usize);
impl From<InsnId> for usize {
fn from(val: InsnId) -> Self {
val.0
}
}
impl std::fmt::Display for InsnId {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "v{}", self.0)
}
}
/// The index of a [`Block`], which effectively acts like a pointer.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, PartialOrd, Ord)]
pub struct BlockId(pub usize);
impl From<BlockId> for usize {
fn from(val: BlockId) -> Self {
val.0
}
}
impl std::fmt::Display for BlockId {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "bb{}", self.0)
}
}
type InsnSet = BitSet<InsnId>;
type BlockSet = BitSet<BlockId>;
fn write_vec<T: std::fmt::Display>(f: &mut std::fmt::Formatter, objs: &Vec<T>) -> std::fmt::Result {
write!(f, "[")?;
let mut prefix = "";
for obj in objs {
write!(f, "{prefix}{obj}")?;
prefix = ", ";
}
write!(f, "]")
}
impl std::fmt::Display for VALUE {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.print(&PtrPrintMap::identity()).fmt(f)
}
}
impl VALUE {
pub fn print(self, ptr_map: &PtrPrintMap) -> VALUEPrinter<'_> {
VALUEPrinter { inner: self, ptr_map }
}
}
/// Print adaptor for [`VALUE`]. See [`PtrPrintMap`].
pub struct VALUEPrinter<'a> {
inner: VALUE,
ptr_map: &'a PtrPrintMap,
}
impl<'a> std::fmt::Display for VALUEPrinter<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self.inner {
val if val.fixnum_p() => write!(f, "{}", val.as_fixnum()),
Qnil => write!(f, "nil"),
Qtrue => write!(f, "true"),
Qfalse => write!(f, "false"),
val => write!(f, "VALUE({:p})", self.ptr_map.map_ptr(val.as_ptr::<VALUE>())),
}
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct BranchEdge {
pub target: BlockId,
pub args: Vec<InsnId>,
}
impl std::fmt::Display for BranchEdge {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}(", self.target)?;
let mut prefix = "";
for arg in &self.args {
write!(f, "{prefix}{arg}")?;
prefix = ", ";
}
write!(f, ")")
}
}
/// Invalidation reasons
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Invariant {
/// Basic operation is redefined
BOPRedefined {
/// {klass}_REDEFINED_OP_FLAG
klass: RedefinitionFlag,
/// BOP_{bop}
bop: ruby_basic_operators,
},
MethodRedefined {
/// The class object whose method we want to assume unchanged
klass: VALUE,
/// The method ID of the method we want to assume unchanged
method: ID,
/// The callable method entry that we want to track
cme: *const rb_callable_method_entry_t,
},
/// A list of constant expression path segments that must have not been written to for the
/// following code to be valid.
StableConstantNames {
idlist: *const ID,
},
/// TracePoint is not enabled. If TracePoint is enabled, this is invalidated.
NoTracePoint,
/// cfp->ep is not escaped to the heap on the ISEQ
NoEPEscape(IseqPtr),
/// There is one ractor running. If a non-root ractor gets spawned, this is invalidated.
SingleRactorMode,
/// No singleton class of an instance of this class has a method that shadows a method
/// on this class. When such a shadowing method is defined, this is invalidated.
NoSingletonClassWithShadowingMethod {
klass: VALUE,
},
}
impl Invariant {
pub fn print(self, ptr_map: &PtrPrintMap) -> InvariantPrinter<'_> {
InvariantPrinter { inner: self, ptr_map }
}
}
impl Display for Invariant {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.print(&PtrPrintMap::identity()).fmt(f)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SpecialObjectType {
VMCore = 1,
CBase = 2,
ConstBase = 3,
}
impl From<u32> for SpecialObjectType {
fn from(value: u32) -> Self {
match value {
VM_SPECIAL_OBJECT_VMCORE => SpecialObjectType::VMCore,
VM_SPECIAL_OBJECT_CBASE => SpecialObjectType::CBase,
VM_SPECIAL_OBJECT_CONST_BASE => SpecialObjectType::ConstBase,
_ => panic!("Invalid special object type: {value}"),
}
}
}
impl From<SpecialObjectType> for u64 {
fn from(special_type: SpecialObjectType) -> Self {
special_type as u64
}
}
impl std::fmt::Display for SpecialObjectType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
SpecialObjectType::VMCore => write!(f, "VMCore"),
SpecialObjectType::CBase => write!(f, "CBase"),
SpecialObjectType::ConstBase => write!(f, "ConstBase"),
}
}
}
/// Print adaptor for [`Invariant`]. See [`PtrPrintMap`].
pub struct InvariantPrinter<'a> {
inner: Invariant,
ptr_map: &'a PtrPrintMap,
}
impl<'a> std::fmt::Display for InvariantPrinter<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self.inner {
Invariant::BOPRedefined { klass, bop } => {
write!(f, "BOPRedefined(")?;
match klass {
INTEGER_REDEFINED_OP_FLAG => write!(f, "INTEGER_REDEFINED_OP_FLAG")?,
STRING_REDEFINED_OP_FLAG => write!(f, "STRING_REDEFINED_OP_FLAG")?,
ARRAY_REDEFINED_OP_FLAG => write!(f, "ARRAY_REDEFINED_OP_FLAG")?,
HASH_REDEFINED_OP_FLAG => write!(f, "HASH_REDEFINED_OP_FLAG")?,
_ => write!(f, "{klass}")?,
}
write!(f, ", ")?;
match bop {
BOP_PLUS => write!(f, "BOP_PLUS")?,
BOP_MINUS => write!(f, "BOP_MINUS")?,
BOP_MULT => write!(f, "BOP_MULT")?,
BOP_DIV => write!(f, "BOP_DIV")?,
BOP_MOD => write!(f, "BOP_MOD")?,
BOP_EQ => write!(f, "BOP_EQ")?,
BOP_EQQ => write!(f, "BOP_EQQ")?,
BOP_LT => write!(f, "BOP_LT")?,
BOP_LE => write!(f, "BOP_LE")?,
BOP_LTLT => write!(f, "BOP_LTLT")?,
BOP_AREF => write!(f, "BOP_AREF")?,
BOP_ASET => write!(f, "BOP_ASET")?,
BOP_LENGTH => write!(f, "BOP_LENGTH")?,
BOP_SIZE => write!(f, "BOP_SIZE")?,
BOP_EMPTY_P => write!(f, "BOP_EMPTY_P")?,
BOP_NIL_P => write!(f, "BOP_NIL_P")?,
BOP_SUCC => write!(f, "BOP_SUCC")?,
BOP_GT => write!(f, "BOP_GT")?,
BOP_GE => write!(f, "BOP_GE")?,
BOP_NOT => write!(f, "BOP_NOT")?,
BOP_NEQ => write!(f, "BOP_NEQ")?,
BOP_MATCH => write!(f, "BOP_MATCH")?,
BOP_FREEZE => write!(f, "BOP_FREEZE")?,
BOP_UMINUS => write!(f, "BOP_UMINUS")?,
BOP_MAX => write!(f, "BOP_MAX")?,
BOP_MIN => write!(f, "BOP_MIN")?,
BOP_HASH => write!(f, "BOP_HASH")?,
BOP_CALL => write!(f, "BOP_CALL")?,
BOP_AND => write!(f, "BOP_AND")?,
BOP_OR => write!(f, "BOP_OR")?,
BOP_CMP => write!(f, "BOP_CMP")?,
BOP_DEFAULT => write!(f, "BOP_DEFAULT")?,
BOP_PACK => write!(f, "BOP_PACK")?,
BOP_INCLUDE_P => write!(f, "BOP_INCLUDE_P")?,
_ => write!(f, "{bop}")?,
}
write!(f, ")")
}
Invariant::MethodRedefined { klass, method, cme } => {
let class_name = get_class_name(klass);
write!(f, "MethodRedefined({class_name}@{:p}, {}@{:p}, cme:{:p})",
self.ptr_map.map_ptr(klass.as_ptr::<VALUE>()),
method.contents_lossy(),
self.ptr_map.map_id(method.0),
self.ptr_map.map_ptr(cme)
)
}
Invariant::StableConstantNames { idlist } => {
write!(f, "StableConstantNames({:p}, ", self.ptr_map.map_ptr(idlist))?;
let mut idx = 0;
let mut sep = "";
loop {
let id = unsafe { *idlist.wrapping_add(idx) };
if id.0 == 0 {
break;
}
write!(f, "{sep}{}", id.contents_lossy())?;
sep = "::";
idx += 1;
}
write!(f, ")")
}
Invariant::NoTracePoint => write!(f, "NoTracePoint"),
Invariant::NoEPEscape(iseq) => write!(f, "NoEPEscape({})", &iseq_name(iseq)),
Invariant::SingleRactorMode => write!(f, "SingleRactorMode"),
Invariant::NoSingletonClassWithShadowingMethod { klass } => {
let class_name = get_class_name(klass);
write!(f, "NoSingletonClassWithShadowingMethod({}@{:p})",
class_name,
self.ptr_map.map_ptr(klass.as_ptr::<VALUE>()))
}
}
}
}
#[derive(Debug, Clone, PartialEq, Copy)]
pub enum Const {
Value(VALUE),
CBool(bool),
CInt8(i8),
CInt16(i16),
CInt32(i32),
CInt64(i64),
CUInt8(u8),
CUInt16(u16),
CUInt32(u32),
CShape(ShapeId),
CUInt64(u64),
CPtr(*const u8),
CDouble(f64),
}
impl std::fmt::Display for Const {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.print(&PtrPrintMap::identity()).fmt(f)
}
}
impl Const {
pub fn print<'a>(&'a self, ptr_map: &'a PtrPrintMap) -> ConstPrinter<'a> {
ConstPrinter { inner: self, ptr_map }
}
}
#[derive(Clone, Copy)]
pub enum RangeType {
Inclusive = 0, // include the end value
Exclusive = 1, // exclude the end value
}
impl std::fmt::Display for RangeType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", match self {
RangeType::Inclusive => "NewRangeInclusive",
RangeType::Exclusive => "NewRangeExclusive",
})
}
}
impl std::fmt::Debug for RangeType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{self}")
}
}
impl From<u32> for RangeType {
fn from(flag: u32) -> Self {
match flag {
0 => RangeType::Inclusive,
1 => RangeType::Exclusive,
_ => panic!("Invalid range flag: {flag}"),
}
}
}
/// Special regex backref symbol types
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SpecialBackrefSymbol {
LastMatch, // $&
PreMatch, // $`
PostMatch, // $'
LastGroup, // $+
}
impl TryFrom<u8> for SpecialBackrefSymbol {
type Error = String;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value as char {
'&' => Ok(SpecialBackrefSymbol::LastMatch),
'`' => Ok(SpecialBackrefSymbol::PreMatch),
'\'' => Ok(SpecialBackrefSymbol::PostMatch),
'+' => Ok(SpecialBackrefSymbol::LastGroup),
c => Err(format!("invalid backref symbol: '{c}'")),
}
}
}
/// Print adaptor for [`Const`]. See [`PtrPrintMap`].
pub struct ConstPrinter<'a> {
inner: &'a Const,
ptr_map: &'a PtrPrintMap,
}
impl<'a> std::fmt::Display for ConstPrinter<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self.inner {
Const::Value(val) => write!(f, "Value({})", val.print(self.ptr_map)),
// TODO: Break out CPtr as a special case. For some reason,
// when we do that now, {:p} prints a completely different
// number than {:?} does and we don't know why.
// We'll have to resolve that first.
Const::CPtr(val) => write!(f, "CPtr({:?})", self.ptr_map.map_ptr(val)),
&Const::CShape(shape_id) => write!(f, "CShape({:p})", self.ptr_map.map_shape(shape_id)),
_ => write!(f, "{:?}", self.inner),
}
}
}
/// For output stability in tests, we assign each pointer with a stable
/// address the first time we see it. This mapping is off by default;
/// set [`PtrPrintMap::map_ptrs`] to switch it on.
///
/// Because this is extra state external to any pointer being printed, a
/// printing adapter struct that wraps the pointer along with this map is
/// required to make use of this effectively. The [`std::fmt::Display`]
/// implementation on the adapter struct can then be reused to implement
/// `Display` on the inner type with a default [`PtrPrintMap`], which
/// does not perform any mapping.
pub struct PtrPrintMap {
inner: RefCell<PtrPrintMapInner>,
map_ptrs: bool,
}
struct PtrPrintMapInner {
map: HashMap<*const c_void, *const c_void>,
next_ptr: *const c_void,
}
impl PtrPrintMap {
/// Return a mapper that maps the pointer to itself.
pub fn identity() -> Self {
Self {
map_ptrs: false,
inner: RefCell::new(PtrPrintMapInner {
map: HashMap::default(), next_ptr:
ptr::without_provenance(0x1000) // Simulate 4 KiB zero page
})
}
}
}
struct Offset(i32);
impl std::fmt::LowerHex for Offset {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let prefix = if f.alternate() { "0x" } else { "" };
let bare_hex = format!("{:x}", self.0.abs());
f.pad_integral(self.0 >= 0, prefix, &bare_hex)
}
}
impl PtrPrintMap {
/// Map a pointer for printing
pub fn map_ptr<T>(&self, ptr: *const T) -> *const T {
// When testing, address stability is not a concern so print real address to enable code
// reuse
if !self.map_ptrs {
return ptr;
}
use std::collections::hash_map::Entry::*;
let ptr = ptr.cast();
let inner = &mut *self.inner.borrow_mut();
match inner.map.entry(ptr) {
Occupied(entry) => entry.get().cast(),
Vacant(entry) => {
// Pick a fake address that is suitably aligns for T and remember it in the map
let mapped = inner.next_ptr.wrapping_add(inner.next_ptr.align_offset(align_of::<T>()));
entry.insert(mapped);
// Bump for the next pointer
inner.next_ptr = mapped.wrapping_add(size_of::<T>());
mapped.cast()
}
}
}
/// Map a Ruby ID (index into intern table) for printing
fn map_id(&self, id: u64) -> *const c_void {
self.map_ptr(id as *const c_void)
}
/// Map an index into a Ruby object (e.g. for an ivar) for printing
fn map_index(&self, id: u64) -> *const c_void {
self.map_ptr(id as *const c_void)
}
fn map_offset(&self, id: i32) -> Offset {
Offset(self.map_ptr(id as *const c_void) as i32)
}
/// Map shape ID into a pointer for printing
pub fn map_shape(&self, id: ShapeId) -> *const c_void {
self.map_ptr(id.0 as *const c_void)
}
}
#[derive(Debug, Clone, Copy)]
pub enum SideExitReason {
UnhandledNewarraySend(vm_opt_newarray_send_type),
UnhandledDuparraySend(u64),
UnknownSpecialVariable(u64),
UnhandledHIRInsn(InsnId),
UnhandledYARVInsn(u32),
UnhandledCallType(CallType),
UnhandledBlockArg,
TooManyKeywordParameters,
FixnumAddOverflow,
FixnumSubOverflow,
FixnumMultOverflow,
FixnumLShiftOverflow,
GuardType(Type),
GuardTypeNot(Type),
GuardShape(ShapeId),
ExpandArray,
GuardNotFrozen,
GuardNotShared,
GuardLess,
GuardGreaterEq,
GuardSuperMethodEntry,
PatchPoint(Invariant),
CalleeSideExit,
ObjToStringFallback,
Interrupt,
BlockParamProxyModified,
BlockParamProxyNotIseqOrIfunc,
BlockParamProxyNotNil,
BlockParamWbRequired,
StackOverflow,
FixnumModByZero,
FixnumDivByZero,
BoxFixnumOverflow,
}
#[derive(Debug, Clone, Copy)]
pub enum MethodType {
Iseq,
Cfunc,
Attrset,
Ivar,
Bmethod,
Zsuper,
Alias,
Undefined,
NotImplemented,
Optimized,
Missing,
Refined,
Null,
}
impl From<u32> for MethodType {
fn from(value: u32) -> Self {
match value {
VM_METHOD_TYPE_ISEQ => MethodType::Iseq,
VM_METHOD_TYPE_CFUNC => MethodType::Cfunc,
VM_METHOD_TYPE_ATTRSET => MethodType::Attrset,
VM_METHOD_TYPE_IVAR => MethodType::Ivar,
VM_METHOD_TYPE_BMETHOD => MethodType::Bmethod,
VM_METHOD_TYPE_ZSUPER => MethodType::Zsuper,
VM_METHOD_TYPE_ALIAS => MethodType::Alias,
VM_METHOD_TYPE_UNDEF => MethodType::Undefined,
VM_METHOD_TYPE_NOTIMPLEMENTED => MethodType::NotImplemented,
VM_METHOD_TYPE_OPTIMIZED => MethodType::Optimized,
VM_METHOD_TYPE_MISSING => MethodType::Missing,
VM_METHOD_TYPE_REFINED => MethodType::Refined,
_ => unreachable!("unknown send_without_block def_type: {}", value),
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum OptimizedMethodType {
Send,
Call,
BlockCall,
StructAref,
StructAset,
}
impl From<u32> for OptimizedMethodType {
fn from(value: u32) -> Self {
match value {
OPTIMIZED_METHOD_TYPE_SEND => OptimizedMethodType::Send,
OPTIMIZED_METHOD_TYPE_CALL => OptimizedMethodType::Call,
OPTIMIZED_METHOD_TYPE_BLOCK_CALL => OptimizedMethodType::BlockCall,
OPTIMIZED_METHOD_TYPE_STRUCT_AREF => OptimizedMethodType::StructAref,
OPTIMIZED_METHOD_TYPE_STRUCT_ASET => OptimizedMethodType::StructAset,
_ => unreachable!("unknown send_without_block optimized method type: {}", value),
}
}
}
impl std::fmt::Display for SideExitReason {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
SideExitReason::UnhandledYARVInsn(opcode) => write!(f, "UnhandledYARVInsn({})", insn_name(*opcode as usize)),
SideExitReason::UnhandledNewarraySend(VM_OPT_NEWARRAY_SEND_MAX) => write!(f, "UnhandledNewarraySend(MAX)"),
SideExitReason::UnhandledNewarraySend(VM_OPT_NEWARRAY_SEND_MIN) => write!(f, "UnhandledNewarraySend(MIN)"),
SideExitReason::UnhandledNewarraySend(VM_OPT_NEWARRAY_SEND_HASH) => write!(f, "UnhandledNewarraySend(HASH)"),
SideExitReason::UnhandledNewarraySend(VM_OPT_NEWARRAY_SEND_PACK) => write!(f, "UnhandledNewarraySend(PACK)"),
SideExitReason::UnhandledNewarraySend(VM_OPT_NEWARRAY_SEND_PACK_BUFFER) => write!(f, "UnhandledNewarraySend(PACK_BUFFER)"),
SideExitReason::UnhandledNewarraySend(VM_OPT_NEWARRAY_SEND_INCLUDE_P) => write!(f, "UnhandledNewarraySend(INCLUDE_P)"),
SideExitReason::UnhandledDuparraySend(method_id) => write!(f, "UnhandledDuparraySend({method_id})"),
SideExitReason::GuardType(guard_type) => write!(f, "GuardType({guard_type})"),
SideExitReason::GuardTypeNot(guard_type) => write!(f, "GuardTypeNot({guard_type})"),
SideExitReason::GuardNotShared => write!(f, "GuardNotShared"),
SideExitReason::PatchPoint(invariant) => write!(f, "PatchPoint({invariant})"),
_ => write!(f, "{self:?}"),
}
}
}
/// Result of resolving the receiver type for method dispatch optimization.
/// Represents whether we know the receiver's class statically at compile-time,
/// have profiled type information, or know nothing about it.
pub enum ReceiverTypeResolution {
/// No profile information available for the receiver
NoProfile,
/// The receiver has a monomorphic profile (single type observed, guard needed)
Monomorphic { profiled_type: ProfiledType },
/// The receiver is polymorphic (multiple types, none dominant)
Polymorphic,
/// The receiver has a skewed polymorphic profile (dominant type with some other types, guard needed)
SkewedPolymorphic { profiled_type: ProfiledType },
/// More than N types seen with no clear winner
Megamorphic,
/// Megamorphic, but with a significant skew towards one type
SkewedMegamorphic { profiled_type: ProfiledType },
/// The receiver's class is statically known at JIT compile-time (no guard needed)
StaticallyKnown { class: VALUE },
}
/// Reason why a send-ish instruction cannot be optimized from a fallback instruction
#[derive(Debug, Clone, Copy)]
pub enum SendFallbackReason {
SendWithoutBlockPolymorphic,
SendWithoutBlockMegamorphic,
SendWithoutBlockNoProfiles,
SendWithoutBlockCfuncNotVariadic,
SendWithoutBlockCfuncArrayVariadic,
SendWithoutBlockNotOptimizedMethodType(MethodType),
SendWithoutBlockNotOptimizedMethodTypeOptimized(OptimizedMethodType),
SendWithoutBlockNotOptimizedNeedPermission,
SendWithoutBlockBopRedefined,
SendWithoutBlockOperandsNotFixnum,
SendWithoutBlockPolymorphicFallback,
SendDirectKeywordMismatch,
SendDirectKeywordCountMismatch,
SendDirectMissingKeyword,
SendDirectTooManyKeywords,
SendPolymorphic,
SendMegamorphic,
SendNoProfiles,
SendCfuncVariadic,
SendCfuncArrayVariadic,
SendNotOptimizedMethodType(MethodType),
SendNotOptimizedNeedPermission,
CCallWithFrameTooManyArgs,
ObjToStringNotString,
TooManyArgsForLir,
/// The Proc object for a BMETHOD is not defined by an ISEQ. (See `enum rb_block_type`.)
BmethodNonIseqProc,
/// Caller supplies too few or too many arguments than what the callee's parameters expects.
ArgcParamMismatch,
/// The call has at least one feature on the caller or callee side that the optimizer does not
/// support.
ComplexArgPass,
/// Caller has keyword arguments but callee doesn't expect them; need to convert to hash.
UnexpectedKeywordArgs,
/// A singleton class with a shadowing method has been seen for the receiver class,
/// so we skip the optimization to avoid an invalidation loop.
SingletonClassWithShadowingMethodSeen,
/// The super call is passed a block that the optimizer does not support.
SuperCallWithBlock,
/// When the `super` is in a block, finding the running CME for guarding requires a loop. Not
/// supported for now.
SuperFromBlock,
/// The profiled super class cannot be found.
SuperClassNotFound,
/// The `super` call uses a complex argument pattern that the optimizer does not support.
SuperComplexArgsPass,
/// The cached target of a `super` call could not be found.
SuperTargetNotFound,
/// Attempted to specialize a `super` call that doesn't have profile data.
SuperNoProfiles,
/// Cannot optimize the `super` call due to the target method.
SuperNotOptimizedMethodType(MethodType),
/// The `super` call is polymorpic.
SuperPolymorphic,
/// The `super` target call uses a complex argument pattern that the optimizer does not support.
SuperTargetComplexArgsPass,
/// Initial fallback reason for every instruction, which should be mutated to
/// a more actionable reason when an attempt to specialize the instruction fails.
Uncategorized(ruby_vminsn_type),
}
impl Display for SendFallbackReason {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
SendWithoutBlockPolymorphic => write!(f, "SendWithoutBlock: polymorphic call site"),
SendWithoutBlockMegamorphic => write!(f, "SendWithoutBlock: megamorphic call site"),
SendWithoutBlockNoProfiles => write!(f, "SendWithoutBlock: no profile data available"),
SendWithoutBlockCfuncNotVariadic => write!(f, "SendWithoutBlock: C function is not variadic"),
SendWithoutBlockCfuncArrayVariadic => write!(f, "SendWithoutBlock: C function expects array variadic"),
SendWithoutBlockNotOptimizedMethodType(method_type) => write!(f, "SendWithoutBlock: unsupported method type {:?}", method_type),
SendWithoutBlockNotOptimizedMethodTypeOptimized(opt_type) => write!(f, "SendWithoutBlock: unsupported optimized method type {:?}", opt_type),
SendWithoutBlockNotOptimizedNeedPermission => write!(f, "SendWithoutBlock: method private or protected and no FCALL"),
SendNotOptimizedNeedPermission => write!(f, "Send: method private or protected and no FCALL"),
SendWithoutBlockBopRedefined => write!(f, "SendWithoutBlock: basic operation was redefined"),
SendWithoutBlockOperandsNotFixnum => write!(f, "SendWithoutBlock: operands are not fixnums"),
SendWithoutBlockPolymorphicFallback => write!(f, "SendWithoutBlock: polymorphic fallback"),
SendDirectKeywordMismatch => write!(f, "SendDirect: keyword mismatch"),
SendDirectKeywordCountMismatch => write!(f, "SendDirect: keyword count mismatch"),
SendDirectMissingKeyword => write!(f, "SendDirect: missing keyword"),
SendDirectTooManyKeywords => write!(f, "SendDirect: too many keywords for fixnum bitmask"),
SendPolymorphic => write!(f, "Send: polymorphic call site"),
SendMegamorphic => write!(f, "Send: megamorphic call site"),
SendNoProfiles => write!(f, "Send: no profile data available"),
SendCfuncVariadic => write!(f, "Send: C function is variadic"),
SendCfuncArrayVariadic => write!(f, "Send: C function expects array variadic"),
SendNotOptimizedMethodType(method_type) => write!(f, "Send: unsupported method type {:?}", method_type),
CCallWithFrameTooManyArgs => write!(f, "CCallWithFrame: too many arguments"),
ObjToStringNotString => write!(f, "ObjToString: result is not a string"),
TooManyArgsForLir => write!(f, "Too many arguments for LIR"),
BmethodNonIseqProc => write!(f, "Bmethod: Proc object is not defined by an ISEQ"),
ArgcParamMismatch => write!(f, "Argument count does not match parameter count"),
ComplexArgPass => write!(f, "Complex argument passing"),
UnexpectedKeywordArgs => write!(f, "Unexpected Keyword Args"),
SingletonClassWithShadowingMethodSeen => write!(f, "Singleton class with shadowing method previously seen for receiver class"),
SuperFromBlock => write!(f, "super: call from within a block"),
SuperCallWithBlock => write!(f, "super: call made with a block"),
SuperClassNotFound => write!(f, "super: profiled class cannot be found"),
SuperComplexArgsPass => write!(f, "super: complex argument passing to `super` call"),
SuperNoProfiles => write!(f, "super: no profile data available"),
SuperNotOptimizedMethodType(method_type) => write!(f, "super: unsupported target method type {:?}", method_type),
SuperPolymorphic => write!(f, "super: polymorphic call site"),
SuperTargetNotFound => write!(f, "super: profiled target method cannot be found"),
SuperTargetComplexArgsPass => write!(f, "super: complex argument passing to `super` target call"),
Uncategorized(insn) => write!(f, "Uncategorized({})", insn_name(*insn as usize)),
}
}
}
/// An instruction in the SSA IR. The output of an instruction is referred to by the index of
/// the instruction ([`InsnId`]). SSA form enables this, and [`UnionFind`] ([`Function::find`])
/// helps with editing.
#[derive(Debug, Clone)]
pub enum Insn {
Const { val: Const },
/// SSA block parameter. Also used for function parameters in the function's entry block.
Param,
/// Load a function argument from the calling convention.
/// Used in JIT entry blocks. idx is the calling convention index, id is for display.
LoadArg { idx: u32, id: ID, val_type: Type },
/// Synthetic terminator for the entries superblock. Targets all entry blocks
/// so that CFG analyses see a single root. Not lowered to machine code.
Entries { targets: Vec<BlockId> },
StringCopy { val: InsnId, chilled: bool, state: InsnId },
StringIntern { val: InsnId, state: InsnId },
StringConcat { strings: Vec<InsnId>, state: InsnId },
/// Call rb_str_getbyte with known-Fixnum index
StringGetbyte { string: InsnId, index: InsnId },
StringSetbyteFixnum { string: InsnId, index: InsnId, value: InsnId },
StringAppend { recv: InsnId, other: InsnId, state: InsnId },
StringAppendCodepoint { recv: InsnId, other: InsnId, state: InsnId },
/// Combine count stack values into a regexp
ToRegexp { opt: usize, values: Vec<InsnId>, state: InsnId },
/// Put special object (VMCORE, CBASE, etc.) based on value_type
PutSpecialObject { value_type: SpecialObjectType },
/// Call `to_a` on `val` if the method is defined, or make a new array `[val]` otherwise.
ToArray { val: InsnId, state: InsnId },
/// Call `to_a` on `val` if the method is defined, or make a new array `[val]` otherwise. If we
/// called `to_a`, duplicate the returned array.
ToNewArray { val: InsnId, state: InsnId },
NewArray { elements: Vec<InsnId>, state: InsnId },
/// NewHash contains a vec of (key, value) pairs
NewHash { elements: Vec<InsnId>, state: InsnId },
NewRange { low: InsnId, high: InsnId, flag: RangeType, state: InsnId },
NewRangeFixnum { low: InsnId, high: InsnId, flag: RangeType, state: InsnId },
ArrayDup { val: InsnId, state: InsnId },
ArrayHash { elements: Vec<InsnId>, state: InsnId },
ArrayMax { elements: Vec<InsnId>, state: InsnId },
ArrayInclude { elements: Vec<InsnId>, target: InsnId, state: InsnId },
ArrayPackBuffer { elements: Vec<InsnId>, fmt: InsnId, buffer: InsnId, state: InsnId },
DupArrayInclude { ary: VALUE, target: InsnId, state: InsnId },
/// Extend `left` with the elements from `right`. `left` and `right` must both be `Array`.
ArrayExtend { left: InsnId, right: InsnId, state: InsnId },
/// Push `val` onto `array`, where `array` is already `Array`.
ArrayPush { array: InsnId, val: InsnId, state: InsnId },
ArrayAref { array: InsnId, index: InsnId },
ArrayAset { array: InsnId, index: InsnId, val: InsnId },
ArrayPop { array: InsnId, state: InsnId },
/// Return the length of the array as a C `long` ([`types::CInt64`])
ArrayLength { array: InsnId },
HashAref { hash: InsnId, key: InsnId, state: InsnId },
HashAset { hash: InsnId, key: InsnId, val: InsnId, state: InsnId },
HashDup { val: InsnId, state: InsnId },
/// Allocate an instance of the `val` object without calling `#initialize` on it.
/// This can:
/// * raise an exception if `val` is not a class
/// * run arbitrary code if `val` is a class with a custom allocator
ObjectAlloc { val: InsnId, state: InsnId },
/// Allocate an instance of the `val` class without calling `#initialize` on it.
/// This requires that `class` has the default allocator (for example via `IsMethodCfunc`).
/// This won't raise or run arbitrary code because `class` has the default allocator.
ObjectAllocClass { class: VALUE, state: InsnId },
/// Check if the value is truthy and "return" a C boolean. In reality, we will likely fuse this
/// with IfTrue/IfFalse in the backend to generate jcc.
Test { val: InsnId },
/// Return C `true` if `val` is `Qnil`, else `false`.
IsNil { val: InsnId },
/// Return C `true` if `val`'s method on cd resolves to the cfunc.
IsMethodCfunc { val: InsnId, cd: *const rb_call_data, cfunc: *const u8, state: InsnId },
/// Return C `true` if left == right
IsBitEqual { left: InsnId, right: InsnId },
/// Return C `true` if left != right
IsBitNotEqual { left: InsnId, right: InsnId },
/// Convert a C `bool` to a Ruby `Qtrue`/`Qfalse`. Same as `RBOOL` macro.
BoxBool { val: InsnId },
/// Convert a C `long` to a Ruby `Fixnum`. Side exit on overflow.
BoxFixnum { val: InsnId, state: InsnId },
UnboxFixnum { val: InsnId },
FixnumAref { recv: InsnId, index: InsnId },
// TODO(max): In iseq body types that are not ISEQ_TYPE_METHOD, rewrite to Constant false.
Defined { op_type: usize, obj: VALUE, pushval: VALUE, v: InsnId, state: InsnId },
GetConstant { klass: InsnId, id: ID, allow_nil: InsnId, state: InsnId },
GetConstantPath { ic: *const iseq_inline_constant_cache, state: InsnId },
/// Kernel#block_given? but without pushing a frame. Similar to [`Insn::Defined`] with
/// `DEFINED_YIELD`
IsBlockGiven { lep: InsnId },
/// Test the bit at index of val, a Fixnum.
/// Return Qtrue if the bit is set, else Qfalse.
FixnumBitCheck { val: InsnId, index: u8 },
/// Return Qtrue if `val` is an instance of `class`, else Qfalse.
/// Equivalent to `class_search_ancestor(CLASS_OF(val), class)`.
IsA { val: InsnId, class: InsnId },
/// Get a global variable named `id`
GetGlobal { id: ID, state: InsnId },
/// Set a global variable named `id` to `val`
SetGlobal { id: ID, val: InsnId, state: InsnId },
//NewObject?
/// Get an instance variable `id` from `self_val`, using the inline cache `ic` if present
GetIvar { self_val: InsnId, id: ID, ic: *const iseq_inline_iv_cache_entry, state: InsnId },
/// Set `self_val`'s instance variable `id` to `val`, using the inline cache `ic` if present
SetIvar { self_val: InsnId, id: ID, val: InsnId, ic: *const iseq_inline_iv_cache_entry, state: InsnId },
/// Check whether an instance variable exists on `self_val`
DefinedIvar { self_val: InsnId, id: ID, pushval: VALUE, state: InsnId },
/// Load cfp->pc
LoadPC,
/// Load EC
LoadEC,
/// Load cfp->self
LoadSelf,
LoadField { recv: InsnId, id: ID, offset: i32, return_type: Type },
/// Write `val` at an offset of `recv`.
/// When writing a Ruby object to a Ruby object, one must use GuardNotFrozen (or equivalent) before and WriteBarrier after.
StoreField { recv: InsnId, id: ID, offset: i32, val: InsnId },
WriteBarrier { recv: InsnId, val: InsnId },
/// Get a local variable from a higher scope or the heap.
/// If `use_sp` is true, it uses the SP register to optimize the read.
/// `rest_param` is used by infer_types to infer the ArrayExact type.
/// TODO: Replace the level == 0 + use_sp path with LoadSP + LoadField.
GetLocal { level: u32, ep_offset: u32, use_sp: bool, rest_param: bool },
/// Check whether VM_FRAME_FLAG_MODIFIED_BLOCK_PARAM is set in the environment flags.
/// Returns CBool (0/1).
IsBlockParamModified { ep: InsnId },
/// Get the block parameter as a Proc.
GetBlockParam { level: u32, ep_offset: u32, state: InsnId },
/// Set a local variable in a higher scope or the heap
SetLocal { level: u32, ep_offset: u32, val: InsnId },
GetSpecialSymbol { symbol_type: SpecialBackrefSymbol, state: InsnId },
GetSpecialNumber { nth: u64, state: InsnId },
/// Get a class variable `id`
GetClassVar { id: ID, ic: *const iseq_inline_cvar_cache_entry, state: InsnId },
/// Set a class variable `id` to `val`
SetClassVar { id: ID, val: InsnId, ic: *const iseq_inline_cvar_cache_entry, state: InsnId },
/// Get the EP at the given level from the current CFP.
GetEP { level: u32 },
/// Get the EP of the ISeq of the containing method, or "local level", skipping over block-level EPs.
/// Equivalent of GET_LEP() macro.
GetLEP,
/// Own a FrameState so that instructions can look up their dominating FrameState when
/// generating deopt side-exits and frame reconstruction metadata. Does not directly generate
/// any code.
Snapshot { state: FrameState },
/// Unconditional jump
Jump(BranchEdge),
/// Conditional branch instructions
IfTrue { val: InsnId, target: BranchEdge },
IfFalse { val: InsnId, target: BranchEdge },
/// Call a C function without pushing a frame
/// `name` is for printing purposes only
CCall { cfunc: *const u8, recv: InsnId, args: Vec<InsnId>, name: ID, return_type: Type, elidable: bool },
/// Call a C function that pushes a frame
CCallWithFrame {
cd: *const rb_call_data, // cd for falling back to Send
cfunc: *const u8,
recv: InsnId,
args: Vec<InsnId>,
cme: *const rb_callable_method_entry_t,
name: ID,
state: InsnId,
return_type: Type,
elidable: bool,
blockiseq: Option<IseqPtr>,
},
/// Call a variadic C function with signature: func(int argc, VALUE *argv, VALUE recv)
/// This handles frame setup, argv creation, and frame teardown all in one
CCallVariadic {
cfunc: *const u8,
recv: InsnId,
args: Vec<InsnId>,
cme: *const rb_callable_method_entry_t,
name: ID,
state: InsnId,
return_type: Type,
elidable: bool,
blockiseq: Option<IseqPtr>,
},
/// Un-optimized fallback implementation (dynamic dispatch) for send-ish instructions
/// Ignoring keyword arguments etc for now
Send {
recv: InsnId,
cd: *const rb_call_data,
blockiseq: Option<IseqPtr>,
args: Vec<InsnId>,
state: InsnId,
reason: SendFallbackReason,
},
SendForward {
recv: InsnId,
cd: *const rb_call_data,
blockiseq: IseqPtr,
args: Vec<InsnId>,
state: InsnId,
reason: SendFallbackReason,
},
InvokeSuper {
recv: InsnId,
cd: *const rb_call_data,
blockiseq: IseqPtr,
args: Vec<InsnId>,
state: InsnId,
reason: SendFallbackReason,
},
InvokeSuperForward {
recv: InsnId,
cd: *const rb_call_data,
blockiseq: IseqPtr,
args: Vec<InsnId>,
state: InsnId,
reason: SendFallbackReason,
},
InvokeBlock {
cd: *const rb_call_data,
args: Vec<InsnId>,
state: InsnId,
reason: SendFallbackReason,
},
/// Call Proc#call optimized method type.
InvokeProc {
recv: InsnId,
args: Vec<InsnId>,
state: InsnId,
kw_splat: bool,
},
/// Optimized ISEQ call
SendDirect {
recv: InsnId,
cd: *const rb_call_data,
cme: *const rb_callable_method_entry_t,
iseq: IseqPtr,
args: Vec<InsnId>,
kw_bits: u32,
blockiseq: Option<IseqPtr>,
state: InsnId,
},
// Invoke a builtin function
InvokeBuiltin {
bf: rb_builtin_function,
recv: InsnId,
args: Vec<InsnId>,
state: InsnId,