Ruby 4.1.0dev (2026-12-05 revision ac1e8ed8497c5477f581a5df5f5b7dfb723e6ea8)
vm_insnhelper.c (ac1e8ed8497c5477f581a5df5f5b7dfb723e6ea8)
1/**********************************************************************
2
3 vm_insnhelper.c - instruction helper functions. Included into vm.c.
4
5 $Author$
6
7 Copyright (C) 2007 Koichi Sasada
8
9**********************************************************************/
10
11#include "ruby/internal/config.h"
12
13#include <math.h>
14
15#ifdef HAVE_STDATOMIC_H
16 #include <stdatomic.h>
17#endif
18
19#include "constant.h"
20#include "const_path.h"
21#include "debug_counter.h"
22#include "internal.h"
23#include "internal/class.h"
24#include "internal/compar.h"
25#include "internal/hash.h"
26#include "internal/numeric.h"
27#include "internal/proc.h"
28#include "internal/ractor.h"
29#include "internal/random.h"
30#include "internal/variable.h"
31#include "internal/set.h"
32#include "internal/set_table.h"
33#include "internal/struct.h"
34#include "ruby/thread.h"
35#include "variable.h"
36
37/* finish iseq array */
38#include "insns.inc"
39#include "insns_info.inc"
40
41extern rb_method_definition_t *rb_method_definition_create(rb_method_type_t type, ID mid);
42extern void rb_method_definition_set(const rb_method_entry_t *me, rb_method_definition_t *def, void *opts);
43extern int rb_method_definition_eq(const rb_method_definition_t *d1, const rb_method_definition_t *d2);
44extern VALUE rb_make_no_method_exception(VALUE exc, VALUE format, VALUE obj,
45 int argc, const VALUE *argv, int priv);
46
47/* control stack frame */
48
49static rb_control_frame_t *vm_get_ruby_level_caller_cfp(const rb_execution_context_t *ec, const rb_control_frame_t *cfp);
50
52ruby_vm_special_exception_copy(VALUE exc)
53{
55 rb_obj_copy_ivar(e, exc);
56 return e;
57}
58
59NORETURN(static void ec_stack_overflow(rb_execution_context_t *ec, int));
60static void
61ec_stack_overflow(rb_execution_context_t *ec, int setup)
62{
63 VALUE mesg = rb_ec_vm_ptr(ec)->special_exceptions[ruby_error_sysstack];
64 ec->raised_flag = RAISED_STACKOVERFLOW;
65 if (setup) {
66 VALUE at = rb_ec_backtrace_object(ec);
67 mesg = ruby_vm_special_exception_copy(mesg);
68 rb_ivar_set(mesg, idBt, at);
69 rb_ivar_set(mesg, idBt_locations, at);
70 }
71 ec->errinfo = mesg;
72 EC_JUMP_TAG(ec, TAG_RAISE);
73}
74
75NORETURN(static void vm_stackoverflow(void));
76
77static void
78vm_stackoverflow(void)
79{
80 ec_stack_overflow(GET_EC(), TRUE);
81}
82
83void
84rb_ec_stack_overflow(rb_execution_context_t *ec, ruby_stack_overflow_critical_level crit)
85{
86 if (rb_during_gc()) {
87 rb_bug("system stack overflow during GC. Faulty native extension?");
88 }
89 if (crit >= rb_stack_overflow_fatal) {
90 ec->raised_flag = RAISED_STACKOVERFLOW;
91 ec->errinfo = rb_ec_vm_ptr(ec)->special_exceptions[ruby_error_stackfatal];
92 EC_JUMP_TAG(ec, TAG_RAISE);
93 }
94 ec_stack_overflow(ec, crit < rb_stack_overflow_signal);
95}
96
97static inline void stack_check(rb_execution_context_t *ec);
98
99#if VM_CHECK_MODE > 0
100static int
101callable_class_p(VALUE klass)
102{
103#if VM_CHECK_MODE >= 2
104 if (!klass) return FALSE;
105 switch (RB_BUILTIN_TYPE(klass)) {
106 default:
107 break;
108 case T_ICLASS:
109 if (!RB_TYPE_P(RCLASS_SUPER(klass), T_MODULE)) break;
110 case T_MODULE:
111 return TRUE;
112 }
113 while (klass) {
114 if (klass == rb_cBasicObject) {
115 return TRUE;
116 }
117 klass = RCLASS_SUPER(klass);
118 }
119 return FALSE;
120#else
121 return klass != 0;
122#endif
123}
124
125static int
126callable_method_entry_p(const rb_callable_method_entry_t *cme)
127{
128 if (cme == NULL) {
129 return TRUE;
130 }
131 else {
132 VM_ASSERT(IMEMO_TYPE_P((VALUE)cme, imemo_ment), "imemo_type:%s", rb_imemo_name(imemo_type((VALUE)cme)));
133
134 if (callable_class_p(cme->defined_class)) {
135 return TRUE;
136 }
137 else {
138 return FALSE;
139 }
140 }
141}
142
143static void
144vm_check_frame_detail(VALUE type, int req_block, int req_me, int req_cref, VALUE specval, VALUE cref_or_me, int is_cframe, const rb_iseq_t *iseq)
145{
146 unsigned int magic = (unsigned int)(type & VM_FRAME_MAGIC_MASK);
147 enum imemo_type cref_or_me_type = imemo_env; /* impossible value */
148
149 if (RB_TYPE_P(cref_or_me, T_IMEMO)) {
150 cref_or_me_type = imemo_type(cref_or_me);
151 }
152 if (type & VM_FRAME_FLAG_BMETHOD) {
153 req_me = TRUE;
154 }
155
156 if (req_block && (type & VM_ENV_FLAG_LOCAL) == 0) {
157 rb_bug("vm_push_frame: specval (%p) should be a block_ptr on %x frame", (void *)specval, magic);
158 }
159 if (!req_block && (type & VM_ENV_FLAG_LOCAL) != 0) {
160 rb_bug("vm_push_frame: specval (%p) should not be a block_ptr on %x frame", (void *)specval, magic);
161 }
162
163 if (req_me) {
164 if (cref_or_me_type != imemo_ment) {
165 rb_bug("vm_push_frame: (%s) should be method entry on %x frame", rb_obj_info(cref_or_me), magic);
166 }
167 }
168 else {
169 if (req_cref && cref_or_me_type != imemo_cref) {
170 rb_bug("vm_push_frame: (%s) should be CREF on %x frame", rb_obj_info(cref_or_me), magic);
171 }
172 else { /* cref or Qfalse */
173 if (cref_or_me != Qfalse && cref_or_me_type != imemo_cref) {
174 if (((type & VM_FRAME_FLAG_LAMBDA) || magic == VM_FRAME_MAGIC_IFUNC || magic == VM_FRAME_MAGIC_DUMMY) && (cref_or_me_type == imemo_ment)) {
175 /* ignore */
176 }
177 else {
178 rb_bug("vm_push_frame: (%s) should be false or cref on %x frame", rb_obj_info(cref_or_me), magic);
179 }
180 }
181 }
182 }
183
184 if (cref_or_me_type == imemo_ment) {
185 const rb_callable_method_entry_t *me = (const rb_callable_method_entry_t *)cref_or_me;
186
187 if (!callable_method_entry_p(me)) {
188 rb_bug("vm_push_frame: ment (%s) should be callable on %x frame.", rb_obj_info(cref_or_me), magic);
189 }
190 }
191
192 if ((type & VM_FRAME_MAGIC_MASK) == VM_FRAME_MAGIC_DUMMY) {
193 VM_ASSERT(iseq == NULL ||
194 RBASIC_CLASS((VALUE)iseq) == 0 || // dummy frame for loading
195 RUBY_VM_NORMAL_ISEQ_P(iseq) //argument error
196 );
197 }
198 else {
199 VM_ASSERT(is_cframe == !RUBY_VM_NORMAL_ISEQ_P(iseq));
200 }
201}
202
203static void
204vm_check_frame(VALUE type,
205 VALUE specval,
206 VALUE cref_or_me,
207 const rb_iseq_t *iseq)
208{
209 VALUE given_magic = type & VM_FRAME_MAGIC_MASK;
210 VM_ASSERT(FIXNUM_P(type));
211
212#define CHECK(magic, req_block, req_me, req_cref, is_cframe) \
213 case magic: \
214 vm_check_frame_detail(type, req_block, req_me, req_cref, \
215 specval, cref_or_me, is_cframe, iseq); \
216 break
217 switch (given_magic) {
218 /* BLK ME CREF CFRAME */
219 CHECK(VM_FRAME_MAGIC_METHOD, TRUE, TRUE, FALSE, FALSE);
220 CHECK(VM_FRAME_MAGIC_CLASS, TRUE, FALSE, TRUE, FALSE);
221 CHECK(VM_FRAME_MAGIC_TOP, TRUE, FALSE, TRUE, FALSE);
222 CHECK(VM_FRAME_MAGIC_CFUNC, TRUE, TRUE, FALSE, TRUE);
223 CHECK(VM_FRAME_MAGIC_BLOCK, FALSE, FALSE, FALSE, FALSE);
224 CHECK(VM_FRAME_MAGIC_IFUNC, FALSE, FALSE, FALSE, TRUE);
225 CHECK(VM_FRAME_MAGIC_EVAL, FALSE, FALSE, FALSE, FALSE);
226 CHECK(VM_FRAME_MAGIC_RESCUE, FALSE, FALSE, FALSE, FALSE);
227 CHECK(VM_FRAME_MAGIC_DUMMY, TRUE, FALSE, FALSE, FALSE);
228 default:
229 rb_bug("vm_push_frame: unknown type (%x)", (unsigned int)given_magic);
230 }
231#undef CHECK
232}
233
234static VALUE vm_stack_canary; /* Initialized later */
235static bool vm_stack_canary_was_born = false;
236
237// Return the index of the instruction right before the given PC.
238// This is needed because insn_entry advances PC before the insn body.
239static unsigned int
240previous_insn_index(const rb_iseq_t *iseq, const VALUE *pc)
241{
242 unsigned int pos = 0;
243 while (pos < ISEQ_BODY(iseq)->iseq_size) {
244 int opcode = rb_vm_insn_addr2opcode((void *)ISEQ_BODY(iseq)->iseq_encoded[pos]);
245 unsigned int next_pos = pos + insn_len(opcode);
246 if (ISEQ_BODY(iseq)->iseq_encoded + next_pos == pc) {
247 return pos;
248 }
249 pos = next_pos;
250 }
251 rb_bug("failed to find the previous insn");
252}
253
254void
255rb_vm_check_canary(const rb_execution_context_t *ec, VALUE *sp)
256{
257 const struct rb_control_frame_struct *reg_cfp = ec->cfp;
258 const struct rb_iseq_struct *iseq;
259
260 if (! LIKELY(vm_stack_canary_was_born)) {
261 return; /* :FIXME: isn't it rather fatal to enter this branch? */
262 }
263 else if ((VALUE *)reg_cfp == ec->vm_stack + ec->vm_stack_size) {
264 /* This is at the very beginning of a thread. cfp does not exist. */
265 return;
266 }
267 else if (! VM_FRAME_RUBYFRAME_P(reg_cfp) || ! (iseq = GET_ISEQ())) {
268 /* The iseq field of an IFUNC frame holds the ifunc. */
269 return;
270 }
271 else if (LIKELY(sp[0] != vm_stack_canary)) {
272 return;
273 }
274 else {
275 /* we are going to call methods below; squash the canary to
276 * prevent infinite loop. */
277 sp[0] = Qundef;
278 }
279
280 const VALUE *orig = rb_iseq_original_iseq(iseq);
281 const VALUE iseqw = rb_iseqw_new(iseq);
282 const VALUE inspection = rb_inspect(iseqw);
283 const char *stri = rb_str_to_cstr(inspection);
284 const VALUE disasm = rb_iseq_disasm(iseq);
285 const char *strd = rb_str_to_cstr(disasm);
286 const ptrdiff_t pos = previous_insn_index(iseq, GET_PC());
287 const enum ruby_vminsn_type insn = (enum ruby_vminsn_type)orig[pos];
288 const char *name = insn_name(insn);
289
290 /* rb_bug() is not capable of outputting this large contents. It
291 is designed to run form a SIGSEGV handler, which tends to be
292 very restricted. */
293 ruby_debug_printf(
294 "We are killing the stack canary set by %s, "
295 "at %s@pc=%"PRIdPTR"\n"
296 "watch out the C stack trace.\n"
297 "%s",
298 name, stri, pos, strd);
299 rb_bug("see above.");
300}
301#define vm_check_canary(ec, sp) rb_vm_check_canary(ec, sp)
302
303#else
304#define vm_check_canary(ec, sp)
305#define vm_check_frame(a, b, c, d)
306#endif /* VM_CHECK_MODE > 0 */
307
308#if USE_DEBUG_COUNTER
309static void
310vm_push_frame_debug_counter_inc(
311 const struct rb_execution_context_struct *ec,
312 const struct rb_control_frame_struct *reg_cfp,
313 VALUE type)
314{
315 const struct rb_control_frame_struct *prev_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(reg_cfp);
316
317 RB_DEBUG_COUNTER_INC(frame_push);
318
319 if (RUBY_VM_END_CONTROL_FRAME(ec) != prev_cfp) {
320 const bool curr = VM_FRAME_RUBYFRAME_P(reg_cfp);
321 const bool prev = VM_FRAME_RUBYFRAME_P(prev_cfp);
322 if (prev) {
323 if (curr) {
324 RB_DEBUG_COUNTER_INC(frame_R2R);
325 }
326 else {
327 RB_DEBUG_COUNTER_INC(frame_R2C);
328 }
329 }
330 else {
331 if (curr) {
332 RB_DEBUG_COUNTER_INC(frame_C2R);
333 }
334 else {
335 RB_DEBUG_COUNTER_INC(frame_C2C);
336 }
337 }
338 }
339
340 switch (type & VM_FRAME_MAGIC_MASK) {
341 case VM_FRAME_MAGIC_METHOD: RB_DEBUG_COUNTER_INC(frame_push_method); return;
342 case VM_FRAME_MAGIC_BLOCK: RB_DEBUG_COUNTER_INC(frame_push_block); return;
343 case VM_FRAME_MAGIC_CLASS: RB_DEBUG_COUNTER_INC(frame_push_class); return;
344 case VM_FRAME_MAGIC_TOP: RB_DEBUG_COUNTER_INC(frame_push_top); return;
345 case VM_FRAME_MAGIC_CFUNC: RB_DEBUG_COUNTER_INC(frame_push_cfunc); return;
346 case VM_FRAME_MAGIC_IFUNC: RB_DEBUG_COUNTER_INC(frame_push_ifunc); return;
347 case VM_FRAME_MAGIC_EVAL: RB_DEBUG_COUNTER_INC(frame_push_eval); return;
348 case VM_FRAME_MAGIC_RESCUE: RB_DEBUG_COUNTER_INC(frame_push_rescue); return;
349 case VM_FRAME_MAGIC_DUMMY: RB_DEBUG_COUNTER_INC(frame_push_dummy); return;
350 }
351
352 rb_bug("unreachable");
353}
354#else
355#define vm_push_frame_debug_counter_inc(ec, cfp, t) /* void */
356#endif
357
358// Return a poison value to be set above the stack top to verify leafness.
359VALUE
360rb_vm_stack_canary(void)
361{
362#if VM_CHECK_MODE > 0
363 return vm_stack_canary;
364#else
365 return 0;
366#endif
367}
368
369STATIC_ASSERT(VM_ENV_DATA_INDEX_ME_CREF, VM_ENV_DATA_INDEX_ME_CREF == -2);
370STATIC_ASSERT(VM_ENV_DATA_INDEX_SPECVAL, VM_ENV_DATA_INDEX_SPECVAL == -1);
371STATIC_ASSERT(VM_ENV_DATA_INDEX_FLAGS, VM_ENV_DATA_INDEX_FLAGS == -0);
372
373static void
374vm_push_frame(rb_execution_context_t *ec,
375 const rb_iseq_t *iseq,
376 VALUE type,
377 VALUE self,
378 VALUE specval,
379 VALUE cref_or_me,
380 const VALUE *pc,
381 VALUE *sp,
382 int local_size,
383 int stack_max)
384{
385 rb_control_frame_t *const cfp = RUBY_VM_NEXT_CONTROL_FRAME(ec->cfp);
386
387 vm_check_frame(type, specval, cref_or_me, iseq);
388 VM_ASSERT(local_size >= 0);
389
390 /* check stack overflow */
391 CHECK_VM_STACK_OVERFLOW0(cfp, sp, local_size + stack_max);
392 vm_check_canary(ec, sp);
393
394 /* setup vm value stack */
395
396 /* initialize local variables */
397 for (int i=0; i < local_size; i++) {
398 *sp++ = Qnil;
399 }
400
401 /* setup ep with managing data */
402 *sp++ = cref_or_me; /* ep[-2] / Qnil or T_IMEMO(cref) or T_IMEMO(ment) */
403 *sp++ = specval /* ep[-1] / block handler or prev env ptr */;
404 *sp++ = type; /* ep[-0] / ENV_FLAGS */
405
406 /* setup new frame */
407 *cfp = (const struct rb_control_frame_struct) {
408 .pc = pc,
409 .sp = sp,
410 ._iseq = iseq,
411 .self = self,
412 .ep = sp - 1,
413 .block_code = NULL,
414#if VM_DEBUG_BP_CHECK
415 .bp_check = sp,
416#endif
417 .jit_return = NULL,
418 };
419
420 /* Ensure the initialization of `*cfp` above never gets reordered with the update of `ec->cfp` below.
421 This is a no-op in all cases we've looked at (https://godbolt.org/z/3oxd1446K), but should guarantee it for all
422 future/untested compilers/platforms. */
423
424 #if defined HAVE_DECL_ATOMIC_SIGNAL_FENCE && HAVE_DECL_ATOMIC_SIGNAL_FENCE
425 atomic_signal_fence(memory_order_seq_cst);
426 #endif
427
428 ec->cfp = cfp;
429
430 if (VMDEBUG == 2) {
431 SDR();
432 }
433 vm_push_frame_debug_counter_inc(ec, cfp, type);
434}
435
436void
437rb_vm_pop_frame_no_int(rb_execution_context_t *ec)
438{
439 rb_control_frame_t *cfp = ec->cfp;
440
441 if (VMDEBUG == 2) SDR();
442
443 ec->cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
444}
445
446/* return TRUE if the frame is finished */
447static inline int
448vm_pop_frame(rb_execution_context_t *ec, rb_control_frame_t *cfp, const VALUE *ep)
449{
450 VALUE flags = ep[VM_ENV_DATA_INDEX_FLAGS];
451
452 if (VMDEBUG == 2) SDR();
453
454 RUBY_VM_CHECK_INTS(ec);
455 ec->cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
456
457 return flags & VM_FRAME_FLAG_FINISH;
458}
459
460void
461rb_vm_pop_frame(rb_execution_context_t *ec)
462{
463 vm_pop_frame(ec, ec->cfp, ec->cfp->ep);
464}
465
466// it pushes pseudo-frame with fname filename.
467void
468rb_vm_push_frame_dummy(rb_execution_context_t *ec, VALUE dmy_iseq)
469{
470 vm_push_frame(ec,
471 (const rb_iseq_t *)dmy_iseq, //const rb_iseq_t *iseq,
472 VM_FRAME_MAGIC_DUMMY | VM_ENV_FLAG_LOCAL | VM_FRAME_FLAG_FINISH, // VALUE type,
473 ec->cfp->self, // VALUE self,
474 VM_BLOCK_HANDLER_NONE, // VALUE specval,
475 Qfalse, // VALUE cref_or_me,
476 NULL, // const VALUE *pc,
477 ec->cfp->sp, // VALUE *sp,
478 0, // int local_size,
479 0); // int stack_max
480}
481
482VALUE
483rb_vm_push_frame_fname(rb_execution_context_t *ec, VALUE fname)
484{
485 rb_iseq_t *rb_iseq_alloc_with_dummy_path(VALUE fname);
486 rb_iseq_t *dmy_iseq = rb_iseq_alloc_with_dummy_path(fname);
487 rb_vm_push_frame_dummy(ec, (VALUE)dmy_iseq);
488 return (VALUE)dmy_iseq;
489}
490
491/* method dispatch */
492static inline VALUE
493rb_arity_error_new(int argc, int min, int max)
494{
495 VALUE err_mess = rb_sprintf("wrong number of arguments (given %d, expected %d", argc, min);
496 if (min == max) {
497 /* max is not needed */
498 }
499 else if (max == UNLIMITED_ARGUMENTS) {
500 rb_str_cat_cstr(err_mess, "+");
501 }
502 else {
503 rb_str_catf(err_mess, "..%d", max);
504 }
505 rb_str_cat_cstr(err_mess, ")");
506 return rb_exc_new3(rb_eArgError, err_mess);
507}
508
509void
510rb_error_arity(int argc, int min, int max)
511{
512 rb_exc_raise(rb_arity_error_new(argc, min, max));
513}
514
515/* lvar */
516
517NOINLINE(static void vm_env_write_slowpath(const VALUE *ep, int index, VALUE v));
518
519static void
520vm_env_write_slowpath(const VALUE *ep, int index, VALUE v)
521{
522 const VALUE envval = VM_ENV_ENVVAL(ep);
523
524 if (RB_FL_TEST_RAW(envval, RUBY_FL_SHAREABLE)) {
525 /* Writing to a SHAREABLE env (an isolated proc) can create a shareable ->
526 * unshareable edge; only a full barrier sets the shref bit keeping v alive
527 * through its owner's local GC. WB_REQUIRED stays: later writes need it too. */
528 if (!SPECIAL_CONST_P(v)) {
529 rb_gc_writebarrier(envval, v);
530 }
531 VM_FORCE_WRITE(&ep[index], v);
532 }
533 else {
534 /* remember env value forcely */
535 rb_gc_writebarrier_remember(envval);
536 VM_FORCE_WRITE(&ep[index], v);
537 VM_ENV_FLAGS_UNSET(ep, VM_ENV_FLAG_WB_REQUIRED);
538 }
539 RB_DEBUG_COUNTER_INC(lvar_set_slowpath);
540}
541
542// YJIT assumes this function never runs GC
543static inline void
544vm_env_write(const VALUE *ep, int index, VALUE v)
545{
546 VALUE flags = ep[VM_ENV_DATA_INDEX_FLAGS];
547 if (LIKELY((flags & VM_ENV_FLAG_WB_REQUIRED) == 0)) {
548 VM_STACK_ENV_WRITE(ep, index, v);
549 }
550 else {
551 vm_env_write_slowpath(ep, index, v);
552 }
553}
554
555void
556rb_vm_env_write(const VALUE *ep, int index, VALUE v)
557{
558 vm_env_write(ep, index, v);
559}
560
561VALUE
562rb_vm_bh_to_procval(const rb_execution_context_t *ec, VALUE block_handler)
563{
564 if (block_handler == VM_BLOCK_HANDLER_NONE) {
565 return Qnil;
566 }
567 else {
568 switch (vm_block_handler_type(block_handler)) {
569 case block_handler_type_iseq:
570 case block_handler_type_ifunc:
571 return rb_vm_make_proc(ec, VM_BH_TO_CAPT_BLOCK(block_handler), rb_cProc);
572 case block_handler_type_symbol:
573 return rb_sym_to_proc(VM_BH_TO_SYMBOL(block_handler));
574 case block_handler_type_proc:
575 return VM_BH_TO_PROC(block_handler);
576 default:
577 VM_UNREACHABLE(rb_vm_bh_to_procval);
578 }
579 }
580}
581
582/* svar */
583
584#if VM_CHECK_MODE > 0
585static int
586vm_svar_valid_p(VALUE svar)
587{
588 if (RB_TYPE_P((VALUE)svar, T_IMEMO)) {
589 switch (imemo_type(svar)) {
590 case imemo_svar:
591 case imemo_cref:
592 case imemo_ment:
593 return TRUE;
594 default:
595 break;
596 }
597 }
598 rb_bug("vm_svar_valid_p: unknown type: %s", rb_obj_info(svar));
599 return FALSE;
600}
601#endif
602
603/* Should this frame's special variables live in the env's svar slot? A SHAREABLE env
604 * (isolated proc) can run in several Ractors at once, making svar shared mutable state
605 * leaking $~/$_ across Ractors: keep them per-EC instead. */
606static inline bool
607lep_svar_in_env_p(const rb_execution_context_t *ec, const VALUE *lep)
608{
609 if (!lep) return false;
610 if (ec == NULL) return true;
611 if (ec->root_lep == lep) return false;
612 /* lep may be a stale on-stack ep of a frame whose env already escaped: lep[0]
613 * still holds the imemo_env, so flags is not a FIXNUM and VM_ENV_ESCAPED_P
614 * asserts. That is not a live shareable proc's env, so fall back to in-env. */
615 if (FIXNUM_P(lep[VM_ENV_DATA_INDEX_FLAGS]) &&
616 VM_ENV_ESCAPED_P(lep) &&
617 RB_FL_TEST_RAW(VM_ENV_ENVVAL(lep), RUBY_FL_SHAREABLE)) {
618 return false;
619 }
620 return true;
621}
622
623static inline struct vm_svar *
624lep_svar(const rb_execution_context_t *ec, const VALUE *lep)
625{
626 VALUE svar;
627
628 if (lep_svar_in_env_p(ec, lep)) {
629 svar = lep[VM_ENV_DATA_INDEX_ME_CREF];
630 }
631 else {
632 svar = ec->root_svar;
633 }
634
635 VM_ASSERT(svar == Qfalse || vm_svar_valid_p(svar));
636
637 return (struct vm_svar *)svar;
638}
639
640static inline void
641lep_svar_write(const rb_execution_context_t *ec, const VALUE *lep, const struct vm_svar *svar)
642{
643 VM_ASSERT(vm_svar_valid_p((VALUE)svar));
644
645 if (lep_svar_in_env_p(ec, lep)) {
646 vm_env_write(lep, VM_ENV_DATA_INDEX_ME_CREF, (VALUE)svar);
647 }
648 else {
649 RB_OBJ_WRITE(rb_ec_thread_ptr(ec)->self, &ec->root_svar, svar);
650 }
651}
652
653static VALUE
654lep_svar_get(const rb_execution_context_t *ec, const VALUE *lep, rb_num_t key)
655{
656 const struct vm_svar *svar = lep_svar(ec, lep);
657
658 if ((VALUE)svar == Qfalse || imemo_type((VALUE)svar) != imemo_svar) return Qnil;
659
660 switch (key) {
661 case VM_SVAR_LASTLINE:
662 return svar->lastline;
663 case VM_SVAR_BACKREF:
664 return svar->backref;
665 default: {
666 const VALUE ary = svar->others;
667
668 if (NIL_P(ary)) {
669 return Qnil;
670 }
671 else {
672 return rb_ary_entry(ary, key - VM_SVAR_EXTRA_START);
673 }
674 }
675 }
676}
677
678static struct vm_svar *
679svar_new(VALUE obj)
680{
681 struct vm_svar *svar = IMEMO_NEW(struct vm_svar, imemo_svar, obj);
682 *((VALUE *)&svar->lastline) = Qnil;
683 *((VALUE *)&svar->backref) = Qnil;
684 *((VALUE *)&svar->others) = Qnil;
685
686 return svar;
687}
688
689static void
690lep_svar_set(const rb_execution_context_t *ec, const VALUE *lep, rb_num_t key, VALUE val)
691{
692 struct vm_svar *svar = lep_svar(ec, lep);
693
694 if ((VALUE)svar == Qfalse || imemo_type((VALUE)svar) != imemo_svar) {
695 lep_svar_write(ec, lep, svar = svar_new((VALUE)svar));
696 }
697
698 switch (key) {
699 case VM_SVAR_LASTLINE:
700 RB_OBJ_WRITE(svar, &svar->lastline, val);
701 return;
702 case VM_SVAR_BACKREF:
703 RB_OBJ_WRITE(svar, &svar->backref, val);
704 return;
705 default: {
706 VALUE ary = svar->others;
707
708 if (NIL_P(ary)) {
709 RB_OBJ_WRITE(svar, &svar->others, ary = rb_ary_new());
710 }
711 rb_ary_store(ary, key - VM_SVAR_EXTRA_START, val);
712 }
713 }
714}
715
716static inline VALUE
717vm_getspecial(const rb_execution_context_t *ec, const VALUE *lep, rb_num_t key, rb_num_t type)
718{
719 VALUE val;
720
721 if (type == 0) {
722 val = lep_svar_get(ec, lep, key);
723 }
724 else {
725 VALUE backref = lep_svar_get(ec, lep, VM_SVAR_BACKREF);
726
727 if (type & 0x01) {
728 switch (type >> 1) {
729 case '&':
730 val = rb_reg_last_match(backref);
731 break;
732 case '`':
733 val = rb_reg_match_pre(backref);
734 break;
735 case '\'':
736 val = rb_reg_match_post(backref);
737 break;
738 case '+':
739 val = rb_reg_match_last(backref);
740 break;
741 default:
742 rb_bug("unexpected back-ref");
743 }
744 }
745 else {
746 val = rb_reg_nth_match((int)(type >> 1), backref);
747 }
748 }
749 return val;
750}
751
752static inline VALUE
753vm_backref_defined(const rb_execution_context_t *ec, const VALUE *lep, rb_num_t type)
754{
755 VALUE backref = lep_svar_get(ec, lep, VM_SVAR_BACKREF);
756 int nth = 0;
757
758 if (type & 0x01) {
759 switch (type >> 1) {
760 case '&':
761 case '`':
762 case '\'':
763 break;
764 case '+':
765 return rb_reg_last_defined(backref);
766 default:
767 rb_bug("unexpected back-ref");
768 }
769 }
770 else {
771 nth = (int)(type >> 1);
772 }
773 return rb_reg_nth_defined(nth, backref);
774}
775
776PUREFUNC(static rb_callable_method_entry_t *check_method_entry(VALUE obj, int can_be_svar));
777static rb_callable_method_entry_t *
778check_method_entry(VALUE obj, int can_be_svar)
779{
780 if (obj == Qfalse) return NULL;
781
782#if VM_CHECK_MODE > 0
783 if (!RB_TYPE_P(obj, T_IMEMO)) rb_bug("check_method_entry: unknown type: %s", rb_obj_info(obj));
784#endif
785
786 switch (imemo_type(obj)) {
787 case imemo_ment:
788 return (rb_callable_method_entry_t *)obj;
789 case imemo_cref:
790 return NULL;
791 case imemo_svar:
792 if (can_be_svar) {
793 return check_method_entry(((struct vm_svar *)obj)->cref_or_me, FALSE);
794 }
795 default:
796#if VM_CHECK_MODE > 0
797 rb_bug("check_method_entry: svar should not be there:");
798#endif
799 return NULL;
800 }
801}
802
803static rb_callable_method_entry_t *
804env_method_entry_unchecked(VALUE obj, int can_be_svar)
805{
806 if (obj == Qfalse) return NULL;
807
808 switch (imemo_type(obj)) {
809 case imemo_ment:
810 return (rb_callable_method_entry_t *)obj;
811 case imemo_cref:
812 return NULL;
813 case imemo_svar:
814 if (can_be_svar) {
815 return env_method_entry_unchecked(((struct vm_svar *)obj)->cref_or_me, FALSE);
816 }
817 default:
818 return NULL;
819 }
820}
821
822const rb_callable_method_entry_t *
823rb_vm_frame_method_entry(const rb_control_frame_t *cfp)
824{
825 const VALUE *ep = cfp->ep;
826 rb_callable_method_entry_t *me;
827
828 while (!VM_ENV_LOCAL_P(ep)) {
829 if ((me = check_method_entry(ep[VM_ENV_DATA_INDEX_ME_CREF], FALSE)) != NULL) return me;
830 ep = VM_ENV_PREV_EP(ep);
831 }
832
833 return check_method_entry(ep[VM_ENV_DATA_INDEX_ME_CREF], TRUE);
834}
835
836const rb_callable_method_entry_t *
837rb_vm_frame_method_entry_unchecked(const rb_control_frame_t *cfp)
838{
839 const VALUE *ep = cfp->ep;
840 rb_callable_method_entry_t *me;
841
842 while (!VM_ENV_LOCAL_P_UNCHECKED(ep)) {
843 if ((me = env_method_entry_unchecked(ep[VM_ENV_DATA_INDEX_ME_CREF], FALSE)) != NULL) return me;
844 ep = VM_ENV_PREV_EP_UNCHECKED(ep);
845 }
846
847 return env_method_entry_unchecked(ep[VM_ENV_DATA_INDEX_ME_CREF], TRUE);
848}
849
850static const rb_iseq_t *
851method_entry_iseqptr(const rb_callable_method_entry_t *me)
852{
853 switch (me->def->type) {
854 case VM_METHOD_TYPE_ISEQ:
855 return me->def->body.iseq.iseqptr;
856 default:
857 return NULL;
858 }
859}
860
861static rb_cref_t *
862method_entry_cref(const rb_callable_method_entry_t *me)
863{
864 switch (me->def->type) {
865 case VM_METHOD_TYPE_ISEQ:
866 return me->def->body.iseq.cref;
867 default:
868 return NULL;
869 }
870}
871
872#if VM_CHECK_MODE == 0
873PUREFUNC(static rb_cref_t *check_cref(VALUE, int));
874#endif
875static rb_cref_t *
876check_cref(VALUE obj, int can_be_svar)
877{
878 if (obj == Qfalse) return NULL;
879
880#if VM_CHECK_MODE > 0
881 if (!RB_TYPE_P(obj, T_IMEMO)) rb_bug("check_cref: unknown type: %s", rb_obj_info(obj));
882#endif
883
884 switch (imemo_type(obj)) {
885 case imemo_ment:
886 return method_entry_cref((rb_callable_method_entry_t *)obj);
887 case imemo_cref:
888 return (rb_cref_t *)obj;
889 case imemo_svar:
890 if (can_be_svar) {
891 return check_cref(((struct vm_svar *)obj)->cref_or_me, FALSE);
892 }
893 default:
894#if VM_CHECK_MODE > 0
895 rb_bug("check_method_entry: svar should not be there:");
896#endif
897 return NULL;
898 }
899}
900
901static inline rb_cref_t *
902vm_env_cref(const VALUE *ep)
903{
904 rb_cref_t *cref;
905
906 while (!VM_ENV_LOCAL_P(ep)) {
907 if ((cref = check_cref(ep[VM_ENV_DATA_INDEX_ME_CREF], FALSE)) != NULL) return cref;
908 ep = VM_ENV_PREV_EP(ep);
909 }
910
911 return check_cref(ep[VM_ENV_DATA_INDEX_ME_CREF], TRUE);
912}
913
914static int
915is_cref(const VALUE v, int can_be_svar)
916{
917 if (RB_TYPE_P(v, T_IMEMO)) {
918 switch (imemo_type(v)) {
919 case imemo_cref:
920 return TRUE;
921 case imemo_svar:
922 if (can_be_svar) return is_cref(((struct vm_svar *)v)->cref_or_me, FALSE);
923 default:
924 break;
925 }
926 }
927 return FALSE;
928}
929
930static int
931vm_env_cref_by_cref(const VALUE *ep)
932{
933 while (!VM_ENV_LOCAL_P(ep)) {
934 if (is_cref(ep[VM_ENV_DATA_INDEX_ME_CREF], FALSE)) return TRUE;
935 ep = VM_ENV_PREV_EP(ep);
936 }
937 return is_cref(ep[VM_ENV_DATA_INDEX_ME_CREF], TRUE);
938}
939
940static rb_cref_t *
941cref_replace_with_duplicated_cref_each_frame(const VALUE *vptr, int can_be_svar, VALUE parent)
942{
943 const VALUE v = *vptr;
944 rb_cref_t *cref, *new_cref;
945
946 if (RB_TYPE_P(v, T_IMEMO)) {
947 switch (imemo_type(v)) {
948 case imemo_cref:
949 cref = (rb_cref_t *)v;
950 new_cref = rb_vm_cref_dup(cref);
951 if (parent) {
952 RB_OBJ_WRITE(parent, vptr, new_cref);
953 }
954 else {
955 VM_FORCE_WRITE(vptr, (VALUE)new_cref);
956 }
957 return (rb_cref_t *)new_cref;
958 case imemo_svar:
959 if (can_be_svar) {
960 return cref_replace_with_duplicated_cref_each_frame(&((struct vm_svar *)v)->cref_or_me, FALSE, v);
961 }
962 /* fall through */
963 case imemo_ment:
964 rb_bug("cref_replace_with_duplicated_cref_each_frame: unreachable");
965 default:
966 break;
967 }
968 }
969 return NULL;
970}
971
972static rb_cref_t *
973vm_cref_replace_with_duplicated_cref(const VALUE *ep)
974{
975 if (vm_env_cref_by_cref(ep)) {
976 rb_cref_t *cref;
977 VALUE envval;
978
979 while (!VM_ENV_LOCAL_P(ep)) {
980 envval = VM_ENV_ESCAPED_P(ep) ? VM_ENV_ENVVAL(ep) : Qfalse;
981 if ((cref = cref_replace_with_duplicated_cref_each_frame(&ep[VM_ENV_DATA_INDEX_ME_CREF], FALSE, envval)) != NULL) {
982 return cref;
983 }
984 ep = VM_ENV_PREV_EP(ep);
985 }
986 envval = VM_ENV_ESCAPED_P(ep) ? VM_ENV_ENVVAL(ep) : Qfalse;
987 return cref_replace_with_duplicated_cref_each_frame(&ep[VM_ENV_DATA_INDEX_ME_CREF], TRUE, envval);
988 }
989 else {
990 rb_bug("vm_cref_dup: unreachable");
991 }
992}
993
994static rb_cref_t *
995vm_get_cref(const VALUE *ep)
996{
997 rb_cref_t *cref = vm_env_cref(ep);
998
999 if (cref != NULL) {
1000 return cref;
1001 }
1002 else {
1003 rb_bug("vm_get_cref: unreachable");
1004 }
1005}
1006
1007rb_cref_t *
1008rb_vm_get_cref(const VALUE *ep)
1009{
1010 return vm_get_cref(ep);
1011}
1012
1013static rb_cref_t *
1014vm_ec_cref(const rb_execution_context_t *ec)
1015{
1016 const rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp);
1017
1018 if (cfp == NULL) {
1019 return NULL;
1020 }
1021 return vm_get_cref(cfp->ep);
1022}
1023
1024static const rb_cref_t *
1025vm_get_const_key_cref(const VALUE *ep)
1026{
1027 const rb_cref_t *cref = vm_get_cref(ep);
1028 const rb_cref_t *key_cref = cref;
1029
1030 while (cref) {
1031 if (CREF_DYNAMIC(cref)) {
1032 return key_cref;
1033 }
1034 cref = CREF_NEXT(cref);
1035 }
1036
1037 /* no dynamic singleton class or cloned class found */
1038 return NULL;
1039}
1040
1041static rb_cref_t *
1042vm_cref_push(const rb_execution_context_t *ec, VALUE klass, const VALUE *ep, int pushed_by_eval, int singleton)
1043{
1044 rb_cref_t *prev_cref = NULL;
1045
1046 if (ep) {
1047 prev_cref = vm_env_cref(ep);
1048 }
1049 else {
1050 rb_control_frame_t *cfp = vm_get_ruby_level_caller_cfp(ec, ec->cfp);
1051
1052 if (cfp) {
1053 prev_cref = vm_env_cref(cfp->ep);
1054 }
1055 }
1056
1057 return vm_cref_new(klass, METHOD_VISI_PUBLIC, FALSE, prev_cref, pushed_by_eval, singleton);
1058}
1059
1060static inline VALUE
1061vm_get_cbase(const VALUE *ep)
1062{
1063 const rb_cref_t *cref = vm_get_cref(ep);
1064
1065 return CREF_CLASS_FOR_DEFINITION(cref);
1066}
1067
1068static inline VALUE
1069vm_get_const_base(const VALUE *ep)
1070{
1071 const rb_cref_t *cref = vm_get_cref(ep);
1072
1073 while (cref) {
1074 if (!CREF_PUSHED_BY_EVAL(cref)) {
1075 return CREF_CLASS_FOR_DEFINITION(cref);
1076 }
1077 cref = CREF_NEXT(cref);
1078 }
1079
1080 return Qundef;
1081}
1082
1083static inline void
1084vm_check_if_namespace(VALUE klass)
1085{
1086 if (!RB_TYPE_P(klass, T_CLASS) && !RB_TYPE_P(klass, T_MODULE)) {
1087 rb_raise(rb_eTypeError, "%+"PRIsVALUE" is not a class/module", klass);
1088 }
1089}
1090
1091static inline void
1092vm_ensure_not_refinement_module(VALUE self)
1093{
1094 if (RB_TYPE_P(self, T_MODULE) && FL_TEST(self, RMODULE_IS_REFINEMENT)) {
1095 rb_warn("not defined at the refinement, but at the outer class/module");
1096 }
1097}
1098
1099static inline VALUE
1100vm_get_iclass(const rb_control_frame_t *cfp, VALUE klass)
1101{
1102 return klass;
1103}
1104
1105static inline VALUE
1106vm_get_ev_const(rb_execution_context_t *ec, VALUE orig_klass, ID id, bool allow_nil, int is_defined)
1107{
1108 void rb_const_warn_if_deprecated(const rb_const_entry_t *ce, VALUE klass, ID id);
1109 VALUE val;
1110
1111 if (NIL_P(orig_klass) && allow_nil) {
1112 /* in current lexical scope */
1113 const rb_cref_t *root_cref = vm_get_cref(ec->cfp->ep);
1114 const rb_cref_t *cref;
1115 VALUE klass = Qnil;
1116
1117 while (root_cref && CREF_PUSHED_BY_EVAL(root_cref)) {
1118 root_cref = CREF_NEXT(root_cref);
1119 }
1120 cref = root_cref;
1121 while (cref && CREF_NEXT(cref)) {
1122 if (CREF_PUSHED_BY_EVAL(cref)) {
1123 klass = Qnil;
1124 }
1125 else {
1126 klass = CREF_CLASS(cref);
1127 }
1128 cref = CREF_NEXT(cref);
1129
1130 if (!NIL_P(klass)) {
1131 VALUE av, am = 0;
1132 rb_const_entry_t entry, *ce = &entry;
1133 search_continue:
1134 if (rb_const_lookup_copy(klass, id, ce)) {
1135 val = ce->value;
1136 // before the warning, which may run Ruby: only this stack holds val until the owner has it
1137 if (!is_defined && !UNDEF_P(val) && UNLIKELY(!rb_class_owned_p(klass)) &&
1138 !rb_class_field_shareable_p(klass, val)) {
1139 rb_const_warn_if_deprecated(ce, klass, id);
1140 rb_const_unshareable_error(klass, id);
1141 }
1142 rb_const_warn_if_deprecated(ce, klass, id);
1143 if (UNDEF_P(val)) {
1144 if (am == klass) break;
1145 am = klass;
1146 if (is_defined) return 1;
1147 if (rb_autoloading_value(klass, id, &av, NULL)) {
1148 if (UNLIKELY(!rb_class_owned_p(klass)) && !rb_class_field_shareable_p(klass, av)) {
1149 rb_const_unshareable_error(klass, id);
1150 }
1151 return av;
1152 }
1153 rb_autoload_load(klass, id);
1154 goto search_continue;
1155 }
1156 else {
1157 if (is_defined) {
1158 return 1;
1159 }
1160 else {
1161 return val;
1162 }
1163 }
1164 }
1165 }
1166 }
1167
1168 /* search self */
1169 if (root_cref && !NIL_P(CREF_CLASS(root_cref))) {
1170 klass = vm_get_iclass(ec->cfp, CREF_CLASS(root_cref));
1171 }
1172 else {
1173 klass = CLASS_OF(ec->cfp->self);
1174 }
1175
1176 if (is_defined) {
1177 return rb_const_defined(klass, id);
1178 }
1179 else {
1180 return rb_const_get(klass, id);
1181 }
1182 }
1183 else {
1184 vm_check_if_namespace(orig_klass);
1185 if (is_defined) {
1186 return rb_public_const_defined_from(orig_klass, id);
1187 }
1188 else {
1189 return rb_public_const_get_from(orig_klass, id);
1190 }
1191 }
1192}
1193
1194VALUE
1195rb_vm_get_ev_const(rb_execution_context_t *ec, VALUE orig_klass, ID id, VALUE allow_nil)
1196{
1197 return vm_get_ev_const(ec, orig_klass, id, allow_nil == Qtrue, 0);
1198}
1199
1200static inline VALUE
1201vm_get_ev_const_chain(rb_execution_context_t *ec, const rb_const_path_t const_path)
1202{
1203 VALUE val = Qnil;
1204 int allow_nil = TRUE;
1205
1206 if (const_path_absolute_p(const_path)) {
1207 val = rb_cObject;
1208 allow_nil = FALSE;
1209 }
1210 size_t i = 0;
1211 ID segment;
1212 while ((segment = const_path_aref(const_path, i))) {
1213 val = vm_get_ev_const(ec, val, segment, allow_nil, 0);
1214 allow_nil = FALSE;
1215 i++;
1216 }
1217 return val;
1218}
1219
1220
1221static inline VALUE
1222vm_get_cvar_base(const rb_cref_t *cref, const rb_control_frame_t *cfp, int top_level_raise)
1223{
1224 VALUE klass;
1225
1226 if (!cref) {
1227 rb_bug("vm_get_cvar_base: no cref");
1228 }
1229
1230 while (CREF_NEXT(cref) &&
1231 (NIL_P(CREF_CLASS(cref)) || RCLASS_SINGLETON_P(CREF_CLASS(cref)) ||
1232 CREF_PUSHED_BY_EVAL(cref) || CREF_SINGLETON(cref))) {
1233 cref = CREF_NEXT(cref);
1234 }
1235 if (top_level_raise && !CREF_NEXT(cref)) {
1236 rb_raise(rb_eRuntimeError, "class variable access from toplevel");
1237 }
1238
1239 klass = vm_get_iclass(cfp, CREF_CLASS(cref));
1240
1241 if (NIL_P(klass)) {
1242 rb_raise(rb_eTypeError, "no class variables available");
1243 }
1244 return klass;
1245}
1246
1247#define ractor_incidental_shareable_p(cond, val) \
1248 (!(cond) || rb_ractor_shareable_p(val))
1249#define ractor_object_incidental_shareable_p(obj, val) \
1250 ractor_incidental_shareable_p(rb_ractor_shareable_p(obj), val)
1251
1252ALWAYS_INLINE(static VALUE vm_getivar(VALUE, ID, const rb_iseq_t *, IVC, const struct rb_callcache *, int, VALUE));
1253static inline VALUE
1254vm_getivar(VALUE obj, ID id, const rb_iseq_t *iseq, IVC ic, const struct rb_callcache *cc, int is_attr, VALUE default_value)
1255{
1256 VALUE fields_obj;
1257#if OPT_IC_FOR_IVAR
1258 if (SPECIAL_CONST_P(obj)) {
1259 return default_value;
1260 }
1261
1262 switch (BUILTIN_TYPE(obj)) {
1263 case T_OBJECT:
1264 fields_obj = ROBJECT_FIELDS_OBJ(obj);
1265 break;
1266 case T_CLASS:
1267 case T_MODULE:
1268 {
1269 if (UNLIKELY(!rb_class_owned_p(obj))) {
1270 // For two reasons we can only use the fast path on the Ractor
1271 // that owns the class.
1272 // First, only the owner Ractor is allowed to set ivars on classes
1273 // and modules. So we can skip locking.
1274 // Second, other ractors need to check the shareability of the
1275 // values returned from the class ivars.
1276
1277 if (default_value == Qundef) { // defined?
1278 return rb_ivar_defined(obj, id) ? Qtrue : Qundef;
1279 }
1280 else {
1281 goto general_path;
1282 }
1283 }
1284
1285 fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
1286 break;
1287 }
1288 default:
1289 fields_obj = rb_obj_fields(obj, id);
1290 }
1291
1292 if (!fields_obj) {
1293 return default_value;
1294 }
1295
1296 VALUE val = Qundef;
1297
1298 shape_id_t shape_id = RBASIC_SHAPE_ID_FOR_READ(fields_obj);
1299 VALUE *ivar_list = rb_imemo_fields_ptr(fields_obj);
1300
1301 rb_getivar_cache cache = rb_getivar_cache_unpack(vm_cache_attr_index_atomic_read(is_attr, ic, cc));
1302
1303 if (LIKELY(cache.shape_offset == shape_id)) {
1304 if (cache.index == ATTR_INDEX_NOT_SET) {
1305 return default_value;
1306 }
1307
1308 val = ivar_list[cache.index];
1309#if USE_DEBUG_COUNTER
1310 RB_DEBUG_COUNTER_INC(ivar_get_ic_hit);
1311
1312 if (RB_TYPE_P(obj, T_OBJECT)) {
1313 RB_DEBUG_COUNTER_INC(ivar_get_obj_hit);
1314 }
1315#endif
1316 RUBY_ASSERT(!UNDEF_P(val));
1317 }
1318 else { // cache miss case
1319#if USE_DEBUG_COUNTER
1320 if (is_attr) {
1321 if (cache.shape_offset != INVALID_SHAPE_ID) {
1322 RB_DEBUG_COUNTER_INC(ivar_get_cc_miss_set);
1323 }
1324 else {
1325 RB_DEBUG_COUNTER_INC(ivar_get_cc_miss_unset);
1326 }
1327 }
1328 else {
1329 if (cache.shape_offset != INVALID_SHAPE_ID) {
1330 RB_DEBUG_COUNTER_INC(ivar_get_ic_miss_set);
1331 }
1332 else {
1333 RB_DEBUG_COUNTER_INC(ivar_get_ic_miss_unset);
1334 }
1335 }
1336 RB_DEBUG_COUNTER_INC(ivar_get_ic_miss);
1337
1338 if (RB_TYPE_P(obj, T_OBJECT)) {
1339 RB_DEBUG_COUNTER_INC(ivar_get_obj_miss);
1340 }
1341#endif
1342
1343 if (UNLIKELY(rb_shape_complex_p(shape_id))) {
1344 st_table *table = (st_table *)ivar_list;
1345
1346 RUBY_ASSERT(table);
1347 RUBY_ASSERT(table == rb_imemo_fields_complex_tbl(fields_obj));
1348
1349 if (!st_lookup(table, id, &val)) {
1350 val = default_value;
1351 }
1352 }
1353 else {
1354 shape_id_t previous_cached_offset = cache.shape_offset;
1355 if (rb_shape_get_iv_index_with_hint(shape_id, id, &cache.index, &cache.shape_offset)) {
1356 if (cache.shape_offset != previous_cached_offset) {
1357 RUBY_ASSERT(!rb_shape_complex_p(cache.shape_offset));
1358 RUBY_ASSERT(cache.shape_offset != INVALID_SHAPE_ID);
1359
1360 uint64_t packed_cache = rb_getivar_cache_pack(cache.shape_offset, cache.index);
1361 vm_cache_attr_index_set(is_attr, ic, cc, packed_cache);
1362 }
1363
1364 if (cache.index == ATTR_INDEX_NOT_SET) {
1365 val = default_value;
1366 }
1367 else {
1368 // We fetched the ivar list above
1369 val = ivar_list[cache.index];
1370 RUBY_ASSERT(!UNDEF_P(val));
1371 }
1372 }
1373 else {
1374 vm_cache_attr_index_set(is_attr, ic, cc, rb_getivar_cache_pack(shape_id, ATTR_INDEX_NOT_SET));
1375 val = default_value;
1376 }
1377 }
1378 }
1379
1380 if (!UNDEF_P(default_value)) {
1381 RUBY_ASSERT(!UNDEF_P(val));
1382 }
1383
1384 return val;
1385
1386general_path:
1387#endif /* OPT_IC_FOR_IVAR */
1388 RB_DEBUG_COUNTER_INC(ivar_get_ic_miss);
1389
1390 if (is_attr) {
1391 return rb_attr_get(obj, id);
1392 }
1393 else {
1394 return rb_ivar_get(obj, id);
1395 }
1396}
1397
1398ALWAYS_INLINE(static VALUE vm_setivar_slowpath(VALUE obj, ID id, VALUE val, const rb_iseq_t *iseq, IVC ic, const struct rb_callcache *cc, int is_attr));
1399NOINLINE(static VALUE vm_setivar_slowpath_ivar(VALUE obj, ID id, VALUE val, const rb_iseq_t *iseq, IVC ic));
1400NOINLINE(static VALUE vm_setivar_slowpath_attr(VALUE obj, ID id, VALUE val, const struct rb_callcache *cc));
1401
1402static VALUE
1403vm_setivar_slowpath(VALUE obj, ID id, VALUE val, const rb_iseq_t *iseq, IVC ic, const struct rb_callcache *cc, int is_attr)
1404{
1405#if OPT_IC_FOR_IVAR
1406 RB_DEBUG_COUNTER_INC(ivar_set_ic_miss);
1407
1408 rb_check_ivar_modifiable(obj);
1409
1410 shape_id_t previous_shape_id = RBASIC_SHAPE_ID(obj);
1411 attr_index_t index = rb_ivar_set_index(obj, id, val);
1412 shape_id_t next_shape_id = RBASIC_SHAPE_ID(obj);
1413
1414 if (!rb_shape_complex_p(next_shape_id)) {
1415 uint64_t packed_cache = rb_setivar_cache_pack(RSHAPE_OFFSET(previous_shape_id), RSHAPE_OFFSET(next_shape_id), index);
1416 vm_cache_attr_index_set(is_attr, ic, cc, packed_cache);
1417 }
1418
1419 RB_DEBUG_COUNTER_INC(ivar_set_obj_miss);
1420 return val;
1421#else
1422 return rb_ivar_set(obj, id, val);
1423#endif
1424}
1425
1426static VALUE
1427vm_setivar_slowpath_ivar(VALUE obj, ID id, VALUE val, const rb_iseq_t *iseq, IVC ic)
1428{
1429 return vm_setivar_slowpath(obj, id, val, iseq, ic, NULL, false);
1430}
1431
1432static VALUE
1433vm_setivar_slowpath_attr(VALUE obj, ID id, VALUE val, const struct rb_callcache *cc)
1434{
1435 return vm_setivar_slowpath(obj, id, val, NULL, NULL, cc, true);
1436}
1437
1438NOINLINE(static VALUE vm_setivar_class(VALUE obj, VALUE val, rb_setivar_cache cache));
1439static VALUE
1440vm_setivar_class(VALUE obj, VALUE val, rb_setivar_cache cache)
1441{
1442 if (UNLIKELY(!rb_class_owned_p(obj))) {
1443 return Qundef;
1444 }
1445
1446 VALUE fields_obj = RCLASS_WRITABLE_FIELDS_OBJ(obj);
1447 if (UNLIKELY(!fields_obj)) {
1448 return Qundef;
1449 }
1450
1451 shape_id_t shape_id = RBASIC_SHAPE_ID(fields_obj);
1452 shape_id_t dest_shape_id = rb_setivar_cache_revalidate(shape_id, RBASIC_SHAPE_ID(fields_obj), cache);
1453 if (UNLIKELY(dest_shape_id == INVALID_SHAPE_ID)) {
1454 return Qundef;
1455 }
1456
1457 RB_OBJ_WRITE(fields_obj, &rb_imemo_fields_ptr(fields_obj)[cache.index], val);
1458
1459 if (shape_id != dest_shape_id) {
1460 RBASIC_SET_SHAPE_ID_ATOMIC(obj, dest_shape_id);
1461 RBASIC_SET_SHAPE_ID(fields_obj, dest_shape_id);
1462 }
1463
1464 RB_DEBUG_COUNTER_INC(ivar_set_ic_hit);
1465
1466 return val;
1467}
1468
1469NOINLINE(static VALUE vm_setivar_default(VALUE obj, ID id, VALUE val, rb_setivar_cache cache));
1470static VALUE
1471vm_setivar_default(VALUE obj, ID id, VALUE val, rb_setivar_cache cache)
1472{
1473 VALUE fields_obj = rb_obj_fields(obj, id);
1474 if (UNLIKELY(!fields_obj)) {
1475 return Qundef;
1476 }
1477
1478 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
1479 shape_id_t dest_shape_id = rb_setivar_cache_revalidate(shape_id, RBASIC_SHAPE_ID(fields_obj), cache);
1480 if (UNLIKELY(dest_shape_id == INVALID_SHAPE_ID)) {
1481 return Qundef;
1482 }
1483
1484 RB_OBJ_WRITE(fields_obj, &rb_imemo_fields_ptr(fields_obj)[cache.index], val);
1485
1486 if (shape_id != dest_shape_id) {
1487 RBASIC_SET_SHAPE_ID(obj, dest_shape_id);
1488 RBASIC_SET_SHAPE_ID(fields_obj, dest_shape_id);
1489 }
1490
1491 RB_DEBUG_COUNTER_INC(ivar_set_ic_hit);
1492
1493 return val;
1494}
1495
1496static inline VALUE
1497vm_setivar(VALUE obj, VALUE val, rb_setivar_cache cache)
1498{
1499#if OPT_IC_FOR_IVAR
1500 switch (BUILTIN_TYPE(obj)) {
1501 case T_OBJECT:
1502 {
1503 VM_ASSERT(!rb_ractor_shareable_p(obj) || rb_obj_frozen_p(obj));
1504
1505 shape_id_t shape_id = RBASIC_SHAPE_ID(obj);
1506 shape_id_t dest_shape_id = rb_setivar_cache_revalidate(shape_id, shape_id, cache);
1507 if (UNLIKELY(dest_shape_id == INVALID_SHAPE_ID)) {
1508 break;
1509 }
1510
1511 VALUE fields_obj = ROBJECT_FIELDS_OBJ(obj);
1512 RB_OBJ_WRITE(fields_obj, &rb_imemo_fields_ptr(fields_obj)[cache.index], val);
1513 if (shape_id != dest_shape_id) {
1514 RBASIC_SET_SHAPE_ID(obj, dest_shape_id);
1515 if (fields_obj != obj) {
1516 RBASIC_SET_SHAPE_ID(fields_obj, dest_shape_id);
1517 }
1518 }
1519
1520 RB_DEBUG_COUNTER_INC(ivar_set_ic_hit);
1521 RB_DEBUG_COUNTER_INC(ivar_set_obj_hit);
1522 return val;
1523 }
1524 break;
1525 case T_CLASS:
1526 case T_MODULE:
1527 RB_DEBUG_COUNTER_INC(ivar_set_ic_miss_noobject);
1528 default:
1529 break;
1530 }
1531
1532 return Qundef;
1533#endif /* OPT_IC_FOR_IVAR */
1534}
1535
1536static VALUE
1537update_classvariable_cache(const rb_iseq_t *iseq, VALUE klass, ID id, const rb_cref_t * cref, ICVARC ic)
1538{
1539 VALUE defined_class = 0;
1540 VALUE cvar_value = rb_cvar_find(klass, id, &defined_class);
1541
1542 if (RB_TYPE_P(defined_class, T_ICLASS)) {
1543 defined_class = RBASIC(defined_class)->klass;
1544 }
1545
1546 VALUE rb_cvc_tbl = RCLASS_CVC_TBL(defined_class);
1547 if (!rb_cvc_tbl) {
1548 rb_bug("the cvc table should be set");
1549 }
1550
1551 VALUE ent_data;
1552 if (!rb_marked_id_table_lookup(rb_cvc_tbl, id, &ent_data)) {
1553 rb_bug("should have cvar cache entry (%s)", rb_id2name(id));
1554 }
1555
1556 struct rb_cvar_class_tbl_entry *ent = (void *)ent_data;
1557
1558 ent->global_cvar_state = GET_GLOBAL_CVAR_STATE();
1559 RB_OBJ_WRITE((VALUE)ent, &ent->cref, cref);
1560 RB_OBJ_WRITE(iseq, &ic->entry, ent);
1561
1562 RUBY_ASSERT(BUILTIN_TYPE((VALUE)cref) == T_IMEMO && IMEMO_TYPE_P(cref, imemo_cref));
1563
1564 return cvar_value;
1565}
1566
1567static inline VALUE
1568vm_getclassvariable(const rb_iseq_t *iseq, const rb_control_frame_t *reg_cfp, ID id, ICVARC ic)
1569{
1570 const rb_cref_t *cref;
1571 cref = vm_get_cref(GET_EP());
1572
1573 // The fast path skips rb_cvar_find's checks, so it is for class_value's owner:
1574 // the sole writer, and the only one allowed to see an unshareable value.
1575 if (ic->entry && ic->entry->global_cvar_state == GET_GLOBAL_CVAR_STATE() && ic->entry->cref == cref &&
1576 LIKELY(rb_class_owned_p(ic->entry->class_value))) {
1577 RB_DEBUG_COUNTER_INC(cvar_read_inline_hit);
1578
1579 VALUE v = rb_ivar_lookup(ic->entry->class_value, id, Qundef);
1580 RUBY_ASSERT(!UNDEF_P(v));
1581
1582 return v;
1583 }
1584
1585 VALUE klass = vm_get_cvar_base(cref, reg_cfp, 1);
1586
1587 return update_classvariable_cache(iseq, klass, id, cref, ic);
1588}
1589
1590VALUE
1591rb_vm_getclassvariable(const rb_iseq_t *iseq, const rb_control_frame_t *cfp, ID id, ICVARC ic)
1592{
1593 return vm_getclassvariable(iseq, cfp, id, ic);
1594}
1595
1596static inline void
1597vm_setclassvariable(const rb_iseq_t *iseq, const rb_control_frame_t *reg_cfp, ID id, VALUE val, ICVARC ic)
1598{
1599 const rb_cref_t *cref;
1600 cref = vm_get_cref(GET_EP());
1601
1602 // as on the read side: the fast path writes straight into class_value
1603 if (ic->entry && ic->entry->global_cvar_state == GET_GLOBAL_CVAR_STATE() && ic->entry->cref == cref &&
1604 LIKELY(rb_class_owned_p(ic->entry->class_value))) {
1605 RB_DEBUG_COUNTER_INC(cvar_write_inline_hit);
1606
1607 rb_class_ivar_set(ic->entry->class_value, id, val);
1608 return;
1609 }
1610
1611 VALUE klass = vm_get_cvar_base(cref, reg_cfp, 1);
1612
1613 rb_cvar_set(klass, id, val);
1614
1615 update_classvariable_cache(iseq, klass, id, cref, ic);
1616}
1617
1618void
1619rb_vm_setclassvariable(const rb_iseq_t *iseq, const rb_control_frame_t *cfp, ID id, VALUE val, ICVARC ic)
1620{
1621 vm_setclassvariable(iseq, cfp, id, val, ic);
1622}
1623
1624ALWAYS_INLINE(static VALUE vm_getinstancevariable(const rb_iseq_t *iseq, VALUE obj, ID id, IVC ic));
1625static inline VALUE
1626vm_getinstancevariable(const rb_iseq_t *iseq, VALUE obj, ID id, IVC ic)
1627{
1628 return vm_getivar(obj, id, iseq, ic, NULL, FALSE, Qnil);
1629}
1630
1631static inline void
1632vm_setinstancevariable(const rb_iseq_t *iseq, VALUE obj, ID id, VALUE val, IVC ic)
1633{
1634 if (RB_SPECIAL_CONST_P(obj)) {
1636 return;
1637 }
1638
1639 rb_setivar_cache cache = rb_setivar_cache_unpack(vm_ic_atomic_cache_read(ic));
1640 if (UNLIKELY(UNDEF_P(vm_setivar(obj, val, cache)))) {
1641 switch (BUILTIN_TYPE(obj)) {
1642 case T_OBJECT:
1643 break;
1644 case T_CLASS:
1645 case T_MODULE:
1646 if (!UNDEF_P(vm_setivar_class(obj, val, cache))) {
1647 return;
1648 }
1649 break;
1650 default:
1651 if (!UNDEF_P(vm_setivar_default(obj, id, val, cache))) {
1652 return;
1653 }
1654 }
1655 vm_setivar_slowpath_ivar(obj, id, val, iseq, ic);
1656 }
1657}
1658
1659void
1660rb_vm_setinstancevariable(const rb_iseq_t *iseq, VALUE obj, ID id, VALUE val, IVC ic)
1661{
1662 vm_setinstancevariable(iseq, obj, id, val, ic);
1663}
1664
1665VALUE
1666rb_vm_getinstancevariable(const rb_iseq_t *iseq, VALUE obj, ID id, IVC ic)
1667{
1668 return vm_getinstancevariable(iseq, obj, id, ic);
1669}
1670
1671static VALUE
1672vm_throw_continue(const rb_execution_context_t *ec, VALUE err)
1673{
1674 /* continue throw */
1675
1676 if (FIXNUM_P(err)) {
1677 ec->tag->state = RUBY_TAG_FATAL;
1678 }
1679 else if (SYMBOL_P(err)) {
1680 ec->tag->state = TAG_THROW;
1681 }
1682 else if (THROW_DATA_P(err)) {
1683 ec->tag->state = THROW_DATA_STATE((struct vm_throw_data *)err);
1684 }
1685 else {
1686 ec->tag->state = TAG_RAISE;
1687 }
1688 return err;
1689}
1690
1691static VALUE
1692vm_throw_start(const rb_execution_context_t *ec, rb_control_frame_t *const reg_cfp, enum ruby_tag_type state,
1693 const int flag, const VALUE throwobj)
1694{
1695 const rb_control_frame_t *escape_cfp = NULL;
1696 const rb_control_frame_t * const eocfp = RUBY_VM_END_CONTROL_FRAME(ec); /* end of control frame pointer */
1697
1698 if (flag != 0) {
1699 /* do nothing */
1700 }
1701 else if (state == TAG_BREAK) {
1702 int is_orphan = 1;
1703 const VALUE *ep = GET_EP();
1704 const rb_iseq_t *base_iseq = GET_ISEQ();
1705 escape_cfp = reg_cfp;
1706
1707 while (ISEQ_BODY(base_iseq)->type != ISEQ_TYPE_BLOCK) {
1708 if (ISEQ_BODY(CFP_ISEQ(escape_cfp))->type == ISEQ_TYPE_CLASS) {
1709 escape_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(escape_cfp);
1710 ep = escape_cfp->ep;
1711 base_iseq = CFP_ISEQ(escape_cfp);
1712 }
1713 else {
1714 ep = VM_ENV_PREV_EP(ep);
1715 base_iseq = ISEQ_BODY(base_iseq)->parent_iseq;
1716 escape_cfp = rb_vm_search_cf_from_ep(ec, escape_cfp, ep);
1717 VM_ASSERT(CFP_ISEQ(escape_cfp) == base_iseq);
1718 }
1719 }
1720
1721 if (VM_FRAME_LAMBDA_P(escape_cfp)) {
1722 /* lambda{... break ...} */
1723 is_orphan = 0;
1724 state = TAG_RETURN;
1725 }
1726 else {
1727 ep = VM_ENV_PREV_EP(ep);
1728
1729 while (escape_cfp < eocfp) {
1730 if (escape_cfp->ep == ep) {
1731 const rb_iseq_t *const iseq = CFP_ISEQ(escape_cfp);
1732 const VALUE epc = CFP_PC(escape_cfp) - ISEQ_BODY(iseq)->iseq_encoded;
1733 const struct iseq_catch_table *const ct = ISEQ_BODY(iseq)->catch_table;
1734 unsigned int i;
1735
1736 if (!ct) break;
1737 for (i=0; i < ct->size; i++) {
1738 const struct iseq_catch_table_entry *const entry =
1739 UNALIGNED_MEMBER_PTR(ct, entries[i]);
1740
1741 if (entry->type == CATCH_TYPE_BREAK &&
1742 entry->iseq == base_iseq &&
1743 entry->start < epc && entry->end >= epc) {
1744 if (entry->cont == epc) { /* found! */
1745 is_orphan = 0;
1746 }
1747 break;
1748 }
1749 }
1750 break;
1751 }
1752
1753 escape_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(escape_cfp);
1754 }
1755 }
1756
1757 if (is_orphan) {
1758 rb_vm_localjump_error("break from proc-closure", throwobj, TAG_BREAK);
1759 }
1760 }
1761 else if (state == TAG_RETRY) {
1762 const VALUE *ep = VM_ENV_PREV_EP(GET_EP());
1763
1764 escape_cfp = rb_vm_search_cf_from_ep(ec, reg_cfp, ep);
1765 }
1766 else if (state == TAG_RETURN) {
1767 const VALUE *current_ep = GET_EP();
1768 const VALUE *target_ep = NULL, *target_lep, *ep = current_ep;
1769 int in_class_frame = 0;
1770 int toplevel = 1;
1771 escape_cfp = reg_cfp;
1772
1773 // find target_lep, target_ep
1774 while (!VM_ENV_LOCAL_P(ep)) {
1775 if (VM_ENV_FLAGS(ep, VM_FRAME_FLAG_LAMBDA) && target_ep == NULL) {
1776 target_ep = ep;
1777 }
1778 ep = VM_ENV_PREV_EP(ep);
1779 }
1780 target_lep = ep;
1781
1782 while (escape_cfp < eocfp) {
1783 const VALUE *lep = VM_CF_LEP(escape_cfp);
1784
1785 if (!target_lep) {
1786 target_lep = lep;
1787 }
1788
1789 if (lep == target_lep &&
1790 VM_FRAME_RUBYFRAME_P(escape_cfp) &&
1791 ISEQ_BODY(CFP_ISEQ(escape_cfp))->type == ISEQ_TYPE_CLASS) {
1792 in_class_frame = 1;
1793 target_lep = 0;
1794 }
1795
1796 if (lep == target_lep) {
1797 if (VM_FRAME_LAMBDA_P(escape_cfp)) {
1798 toplevel = 0;
1799 if (in_class_frame) {
1800 /* lambda {class A; ... return ...; end} */
1801 goto valid_return;
1802 }
1803 else {
1804 const VALUE *tep = current_ep;
1805
1806 while (target_lep != tep) {
1807 if (escape_cfp->ep == tep) {
1808 /* in lambda */
1809 if (tep == target_ep) {
1810 goto valid_return;
1811 }
1812 else {
1813 goto unexpected_return;
1814 }
1815 }
1816 tep = VM_ENV_PREV_EP(tep);
1817 }
1818 }
1819 }
1820 else if (VM_FRAME_RUBYFRAME_P(escape_cfp)) {
1821 switch (ISEQ_BODY(CFP_ISEQ(escape_cfp))->type) {
1822 case ISEQ_TYPE_TOP:
1823 case ISEQ_TYPE_MAIN:
1824 if (toplevel) {
1825 if (in_class_frame) goto unexpected_return;
1826 if (target_ep == NULL) {
1827 goto valid_return;
1828 }
1829 else {
1830 goto unexpected_return;
1831 }
1832 }
1833 break;
1834 case ISEQ_TYPE_EVAL: {
1835 const rb_iseq_t *is = CFP_ISEQ(escape_cfp);
1836 enum rb_iseq_type t = ISEQ_BODY(is)->type;
1837 while (t == ISEQ_TYPE_RESCUE || t == ISEQ_TYPE_ENSURE || t == ISEQ_TYPE_EVAL) {
1838 if (!(is = ISEQ_BODY(is)->parent_iseq)) break;
1839 t = ISEQ_BODY(is)->type;
1840 }
1841 toplevel = t == ISEQ_TYPE_TOP || t == ISEQ_TYPE_MAIN;
1842 break;
1843 }
1844 case ISEQ_TYPE_CLASS:
1845 toplevel = 0;
1846 break;
1847 default:
1848 break;
1849 }
1850 }
1851 }
1852
1853 if (escape_cfp->ep == target_lep && ISEQ_BODY(CFP_ISEQ(escape_cfp))->type == ISEQ_TYPE_METHOD) {
1854 if (target_ep == NULL) {
1855 goto valid_return;
1856 }
1857 else {
1858 goto unexpected_return;
1859 }
1860 }
1861
1862 escape_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(escape_cfp);
1863 }
1864 unexpected_return:;
1865 rb_vm_localjump_error("unexpected return", throwobj, TAG_RETURN);
1866
1867 valid_return:;
1868 /* do nothing */
1869 }
1870 else {
1871 rb_bug("isns(throw): unsupported throw type");
1872 }
1873
1874 ec->tag->state = state;
1875 return (VALUE)THROW_DATA_NEW(throwobj, escape_cfp, state);
1876}
1877
1878static VALUE
1879vm_throw(const rb_execution_context_t *ec, rb_control_frame_t *reg_cfp,
1880 rb_num_t throw_state, VALUE throwobj)
1881{
1882 const int state = (int)(throw_state & VM_THROW_STATE_MASK);
1883 const int flag = (int)(throw_state & VM_THROW_NO_ESCAPE_FLAG);
1884
1885 if (state != 0) {
1886 return vm_throw_start(ec, reg_cfp, state, flag, throwobj);
1887 }
1888 else {
1889 return vm_throw_continue(ec, throwobj);
1890 }
1891}
1892
1893// Fallback for YJIT. Prepare throw data and return it.
1894VALUE
1895rb_vm_throw(const rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, rb_num_t throw_state, VALUE throwobj)
1896{
1897 return vm_throw(ec, reg_cfp, throw_state, throwobj);
1898}
1899
1900NORETURN(VALUE rb_zjit_throw(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, rb_num_t throw_state, VALUE throwobj));
1901
1902// Fallback for ZJIT. Make a longjmp and unwind to the most recent vm_exec().
1903VALUE
1904rb_zjit_throw(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, rb_num_t throw_state, VALUE throwobj)
1905{
1906 VALUE val = vm_throw(ec, reg_cfp, throw_state, throwobj);
1907
1908 // vm_throw() has set ec->tag->state. On the longjmp path, vm_exec() reads the throw data from
1909 // ec->errinfo instead of vm_exec_core()'s return value like THROW_EXCEPTION()'s path does, so
1910 // we need to put it there instead.
1911 enum ruby_tag_type state = ec->tag->state;
1912 ec->errinfo = val;
1913 EC_JUMP_TAG(ec, state);
1914
1916}
1917
1918static inline void
1919vm_expandarray(struct rb_control_frame_struct *cfp, VALUE ary, rb_num_t num, int flag)
1920{
1921 int is_splat = flag & 0x01;
1922 const VALUE *ptr;
1923 rb_num_t len;
1924 const VALUE obj = ary;
1925
1926 if (!RB_TYPE_P(ary, T_ARRAY) && NIL_P(ary = rb_check_array_type(ary))) {
1927 ary = obj;
1928 ptr = &ary;
1929 len = 1;
1930 }
1931 else {
1932 ptr = RARRAY_CONST_PTR(ary);
1933 len = (rb_num_t)RARRAY_LEN(ary);
1934 }
1935
1936 if (num + is_splat == 0) {
1937 /* no space left on stack */
1938 }
1939 else if (flag & 0x02) {
1940 /* post: ..., nil ,ary[-1], ..., ary[0..-num] # top */
1941 rb_num_t i = 0, j;
1942
1943 if (len < num) {
1944 for (i = 0; i < num - len; i++) {
1945 *cfp->sp++ = Qnil;
1946 }
1947 }
1948
1949 for (j = 0; i < num; i++, j++) {
1950 VALUE v = ptr[len - j - 1];
1951 *cfp->sp++ = v;
1952 }
1953
1954 if (is_splat) {
1955 /* Not `*cfp->sp++ = ...`: the compiler may bump sp before the
1956 * call, and a GC run by the allocation would then mark the
1957 * still unwritten slot. */
1958 *cfp->sp = rb_ary_new4(len - j, ptr);
1959 cfp->sp++;
1960 }
1961 }
1962 else {
1963 /* normal: ary[num..-1], ary[num-2], ary[num-3], ..., ary[0] # top */
1964 if (is_splat) {
1965 if (num > len) {
1966 *cfp->sp = rb_ary_new();
1967 }
1968 else {
1969 *cfp->sp = rb_ary_new4(len - num, ptr + num);
1970 }
1971 cfp->sp++;
1972 }
1973
1974 if (num > len) {
1975 rb_num_t i = 0;
1976 for (; i < num - len; i++) {
1977 *cfp->sp++ = Qnil;
1978 }
1979
1980 for (rb_num_t j = 0; i < num; i++, j++) {
1981 *cfp->sp++ = ptr[len - j - 1];
1982 }
1983 }
1984 else {
1985 for (rb_num_t j = 0; j < num; j++) {
1986 *cfp->sp++ = ptr[num - j - 1];
1987 }
1988 }
1989 }
1990
1991 RB_GC_GUARD(ary);
1992}
1993
1994static VALUE vm_call_general(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling);
1995
1996static VALUE vm_mtbl_dump(VALUE klass, ID target_mid);
1997
1998static struct rb_class_cc_entries *
1999vm_ccs_create(VALUE klass, VALUE cc_tbl, ID mid, const rb_callable_method_entry_t *cme)
2000{
2001 int initial_capa = 2;
2002 struct rb_class_cc_entries *ccs = ruby_xmalloc(vm_ccs_alloc_size(initial_capa));
2003#if VM_CHECK_MODE > 0
2004 ccs->debug_sig = ~(VALUE)ccs;
2005#endif
2006 ccs->capa = initial_capa;
2007 ccs->len = 0;
2008 ccs->cme = cme;
2009 METHOD_ENTRY_CACHED_SET((rb_callable_method_entry_t *)cme);
2010
2011 rb_managed_id_table_insert(cc_tbl, mid, (VALUE)ccs);
2012 RB_OBJ_WRITTEN(cc_tbl, Qundef, cme);
2013 return ccs;
2014}
2015
2016static void
2017vm_ccs_push(VALUE cc_tbl, ID mid, struct rb_class_cc_entries *ccs, const struct rb_callinfo *ci, const struct rb_callcache *cc)
2018{
2019 if (! vm_cc_markable(cc)) {
2020 return;
2021 }
2022
2023 if (UNLIKELY(ccs->len == ccs->capa)) {
2024 RUBY_ASSERT(ccs->capa > 0);
2025 ccs->capa *= 2;
2026 ccs = ruby_xrealloc(ccs, vm_ccs_alloc_size(ccs->capa));
2027#if VM_CHECK_MODE > 0
2028 ccs->debug_sig = ~(VALUE)ccs;
2029#endif
2030 // GC?
2031 rb_managed_id_table_insert(cc_tbl, mid, (VALUE)ccs);
2032 }
2033 VM_ASSERT(ccs->len < ccs->capa);
2034
2035 const struct rb_callinfo_kwarg *kwarg = vm_ci_kwarg(ci);
2036 const int pos = ccs->len++;
2037 ccs->entries[pos].argc = vm_ci_argc(ci);
2038 ccs->entries[pos].flag = (unsigned short)vm_ci_flag(ci);
2039 ccs->entries[pos].kw_len = (unsigned short)(kwarg ? kwarg->keyword_len : 0);
2040 RB_OBJ_WRITE(cc_tbl, &ccs->entries[pos].cc, cc);
2041
2042 if (RB_DEBUG_COUNTER_SETMAX(ccs_maxlen, ccs->len)) {
2043 // for tuning
2044 // vm_mtbl_dump(klass, 0);
2045 }
2046}
2047
2048#if VM_CHECK_MODE > 0
2049void
2050rb_vm_ccs_dump(struct rb_class_cc_entries *ccs)
2051{
2052 ruby_debug_printf("ccs:%p (%d,%d)\n", (void *)ccs, ccs->len, ccs->capa);
2053 for (int i=0; i<ccs->len; i++) {
2054 ruby_debug_printf("CCS CI ID:flag:%x argc:%u kw_len:%u\n",
2055 ccs->entries[i].flag,
2056 ccs->entries[i].argc,
2057 ccs->entries[i].kw_len);
2058 rp(ccs->entries[i].cc);
2059 }
2060}
2061
2062static int
2063vm_ccs_verify(struct rb_class_cc_entries *ccs, ID mid, VALUE klass)
2064{
2065 VM_ASSERT(vm_ccs_p(ccs));
2066 VM_ASSERT(ccs->len <= ccs->capa);
2067
2068 for (int i=0; i<ccs->len; i++) {
2069 const struct rb_callcache *cc = ccs->entries[i].cc;
2070
2071 VM_ASSERT(IMEMO_TYPE_P(cc, imemo_callcache));
2072 VM_ASSERT(vm_cc_class_check(cc, klass));
2073 VM_ASSERT(vm_cc_check_cme(cc, ccs->cme));
2074 VM_ASSERT(!vm_cc_super_p(cc));
2075 VM_ASSERT(!vm_cc_refinement_p(cc));
2076 }
2077 return TRUE;
2078}
2079#endif
2080
2081const rb_callable_method_entry_t *rb_check_overloaded_cme(const rb_callable_method_entry_t *cme, const struct rb_callinfo * const ci);
2082
2083static void
2084vm_evict_cc(VALUE klass, VALUE cc_tbl, ID mid)
2085{
2086 ASSERT_vm_locking();
2087
2088 if (rb_multi_ractor_p()) {
2089 if (RCLASS_WRITABLE_CC_TBL(klass) != cc_tbl) {
2090 // Another ractor updated the CC table while we were waiting on the VM lock.
2091 // We have to retry.
2092 return;
2093 }
2094
2095 VALUE ccs_obj = 0;
2096 rb_managed_id_table_lookup(cc_tbl, mid, &ccs_obj);
2097 struct rb_class_cc_entries *ccs = (struct rb_class_cc_entries *)ccs_obj;
2098
2099 if (!ccs || !METHOD_ENTRY_INVALIDATED(ccs->cme)) {
2100 // Another ractor replaced that entry while we were waiting on the VM lock.
2101 return;
2102 }
2103
2104 VALUE new_table = rb_vm_cc_table_dup(cc_tbl);
2105 rb_vm_cc_table_delete(new_table, mid);
2106 RB_OBJ_ATOMIC_WRITE(klass, &RCLASS_WRITABLE_CC_TBL(klass), new_table);
2107 }
2108 else {
2109 rb_vm_cc_table_delete(cc_tbl, mid);
2110 }
2111}
2112
2113static const struct rb_callcache *
2114vm_populate_cc(VALUE klass, const struct rb_callinfo * const ci, ID mid)
2115{
2116 ASSERT_vm_locking();
2117
2118 RB_DEBUG_COUNTER_INC(cc_not_found_in_ccs);
2119
2120 const rb_callable_method_entry_t *cme = rb_callable_method_entry(klass, mid);
2121
2122 VM_ASSERT(cme == NULL || IMEMO_TYPE_P(cme, imemo_ment));
2123
2124 if (cme == NULL) {
2125 // undef or not found: can't cache the information
2126 VM_ASSERT(vm_cc_cme(&rb_vm_empty_cc) == NULL);
2127 return &rb_vm_empty_cc;
2128 }
2129
2130 if (UNLIKELY(cme->def->uncached && !(vm_ci_flag(ci) & VM_CALL_SUPER))) {
2131 // Leaving a cc here would cost a ccs and a cc table entry on klass, which
2132 // is usually a metaclass, so the cost would scale with the number of
2133 // classes. invokesuper is excluded because vm_search_super_method needs a
2134 // cme in the cc it gets back.
2135 return &rb_vm_uncached_cc;
2136 }
2137
2138 VALUE cc_tbl = RCLASS_WRITABLE_CC_TBL(klass);
2139 const VALUE original_cc_table = cc_tbl;
2140 if (!cc_tbl) {
2141 // Is this possible after rb_callable_method_entry ?
2142 cc_tbl = rb_vm_cc_table_create(1);
2143 }
2144 else if (rb_multi_ractor_p()) {
2145 cc_tbl = rb_vm_cc_table_dup(cc_tbl);
2146 }
2147
2148 VM_ASSERT(cme == rb_callable_method_entry(klass, mid));
2149
2150 METHOD_ENTRY_CACHED_SET((struct rb_callable_method_entry_struct *)cme);
2151
2152 VM_ASSERT(cc_tbl);
2153
2154 struct rb_class_cc_entries *ccs = NULL;
2155 {
2156 VALUE ccs_obj;
2157 if (UNLIKELY(rb_managed_id_table_lookup(cc_tbl, mid, &ccs_obj))) {
2158 ccs = (struct rb_class_cc_entries *)ccs_obj;
2159 }
2160 else {
2161 // TODO: required?
2162 ccs = vm_ccs_create(klass, cc_tbl, mid, cme);
2163 }
2164 }
2165
2166 cme = rb_check_overloaded_cme(cme, ci);
2167
2168 const struct rb_callcache *cc = vm_cc_new(klass, cme, vm_call_general, cc_type_normal);
2169 vm_ccs_push(cc_tbl, mid, ccs, ci, cc);
2170
2171 VM_ASSERT(vm_cc_cme(cc) != NULL);
2172 VM_ASSERT(cme->called_id == mid);
2173 VM_ASSERT(vm_cc_cme(cc)->called_id == mid);
2174
2175 if (original_cc_table != cc_tbl) {
2176 RB_OBJ_ATOMIC_WRITE(klass, &RCLASS_WRITABLE_CC_TBL(klass), cc_tbl);
2177 }
2178
2179 return cc;
2180}
2181
2182static const struct rb_callcache *
2183vm_lookup_cc(const VALUE klass, const struct rb_callinfo * const ci, ID mid)
2184{
2185 VALUE cc_tbl;
2186 struct rb_class_cc_entries *ccs;
2187retry:
2188 cc_tbl = RUBY_ATOMIC_VALUE_LOAD(RCLASS_WRITABLE_CC_TBL(klass));
2189 ccs = NULL;
2190
2191 if (cc_tbl) {
2192 // CCS data is keyed on method id, so we don't need the method id
2193 // for doing comparisons in the `for` loop below.
2194
2195 VALUE ccs_obj;
2196 if (rb_managed_id_table_lookup(cc_tbl, mid, &ccs_obj)) {
2197 ccs = (struct rb_class_cc_entries *)ccs_obj;
2198 const int ccs_len = ccs->len;
2199
2200 if (UNLIKELY(METHOD_ENTRY_INVALIDATED(ccs->cme))) {
2201 RB_VM_LOCKING() {
2202 vm_evict_cc(klass, cc_tbl, mid);
2203 }
2204 goto retry;
2205 }
2206 else if (UNDEFINED_METHOD_ENTRY_P(ccs->cme)) {
2207 // vm_populate_cc would return the empty cc for this too
2208 return &rb_vm_empty_cc;
2209 }
2210 else {
2211 VM_ASSERT(vm_ccs_verify(ccs, mid, klass));
2212
2213 // We already know the method id is correct because we had
2214 // to look up the ccs_data by method id. We compare argc and
2215 // flag, plus the keyword argument count: two call sites with
2216 // the same argc and flag can still differ in how many of the
2217 // arguments are keywords (e.g. `m(a: 1, b: 2)` vs `m(1, b: 2)`),
2218 // which selects a different argument setup fastpath.
2219 const struct rb_callinfo_kwarg *kwarg = vm_ci_kwarg(ci);
2220 unsigned int argc = vm_ci_argc(ci);
2221 unsigned int flag = vm_ci_flag(ci);
2222 unsigned int kw_len = kwarg ? kwarg->keyword_len : 0;
2223
2224 for (int i=0; i<ccs_len; i++) {
2225 unsigned int ccs_ci_argc = ccs->entries[i].argc;
2226 unsigned int ccs_ci_flag = ccs->entries[i].flag;
2227 unsigned int ccs_ci_kw_len = ccs->entries[i].kw_len;
2228 const struct rb_callcache *ccs_cc = ccs->entries[i].cc;
2229
2230 VM_ASSERT(IMEMO_TYPE_P(ccs_cc, imemo_callcache));
2231
2232 if (ccs_ci_argc == argc && ccs_ci_flag == flag && ccs_ci_kw_len == kw_len) {
2233 RB_DEBUG_COUNTER_INC(cc_found_in_ccs);
2234
2235 VM_ASSERT(vm_cc_cme(ccs_cc)->called_id == mid);
2236 VM_ASSERT(ccs_cc->klass == klass);
2237 VM_ASSERT(!METHOD_ENTRY_INVALIDATED(vm_cc_cme(ccs_cc)));
2238
2239 return ccs_cc;
2240 }
2241 }
2242 }
2243 }
2244 }
2245
2246 RB_GC_GUARD(cc_tbl);
2247 return NULL;
2248}
2249
2250static const struct rb_callcache *
2251vm_search_cc(const VALUE klass, const struct rb_callinfo * const ci)
2252{
2253 const ID mid = vm_ci_mid(ci);
2254
2255 const struct rb_callcache *cc = vm_lookup_cc(klass, ci, mid);
2256 if (cc) {
2257 return cc;
2258 }
2259
2260 RB_VM_LOCKING() {
2261 if (rb_multi_ractor_p()) {
2262 // The CC may have been populated by another ractor while we were waiting on the lock,
2263 // so we must lookup a second time.
2264 cc = vm_lookup_cc(klass, ci, mid);
2265 }
2266
2267 if (!cc) {
2268 cc = vm_populate_cc(klass, ci, mid);
2269 }
2270 }
2271
2272 return cc;
2273}
2274
2275#if VM_CHECK_MODE > 0
2276static bool
2277vm_cc_resolved_p(const struct rb_callcache *cc)
2278{
2279 return cc != &rb_vm_empty_cc && cc != &rb_vm_uncached_cc;
2280}
2281#endif
2282
2283const struct rb_callcache *
2284rb_vm_search_method_slowpath(const struct rb_callinfo *ci, VALUE klass)
2285{
2286 const struct rb_callcache *cc;
2287
2288 VM_ASSERT(!SPECIAL_CONST_P(klass));
2289
2290 if (RB_BUILTIN_TYPE(klass) == T_NONE) {
2291 // If we find a T_NONE here, it's most likely we called CLASS_OF(obj) on a
2292 // garbage collected object (the freelist is stored in the class pointer),
2293 // but it's possible that just the class was GC'd.
2294 // This message intentionally tries to imply the former, but make an
2295 // accurate statement for either case.
2296 rb_bug("attempted to search method '%s' on a garbage collected object",
2297 rb_id2name(vm_ci_mid(ci)));
2298 }
2299
2300 VM_ASSERT_TYPE2(klass, T_CLASS, T_ICLASS);
2301
2302 cc = vm_search_cc(klass, ci);
2303
2304 VM_ASSERT(cc);
2305 VM_ASSERT(IMEMO_TYPE_P(cc, imemo_callcache));
2306 VM_ASSERT(!vm_cc_resolved_p(cc) || cc->klass == klass);
2307 VM_ASSERT(!vm_cc_resolved_p(cc) || callable_method_entry_p(vm_cc_cme(cc)));
2308 VM_ASSERT(!vm_cc_resolved_p(cc) || !METHOD_ENTRY_INVALIDATED(vm_cc_cme(cc)));
2309 VM_ASSERT(!vm_cc_resolved_p(cc) || vm_cc_cme(cc)->called_id == vm_ci_mid(ci));
2310
2311 return cc;
2312}
2313
2314#if VM_CHECK_MODE > 0
2315static bool
2316vm_cd_owned_by_iseq_p(const struct rb_call_data *cd, const rb_iseq_t *iseq)
2317{
2318 const struct rb_iseq_constant_body *body = ISEQ_BODY(iseq);
2319 return cd >= body->call_data && cd < body->call_data + body->ci_size;
2320}
2321#endif
2322
2323static const struct rb_callcache *
2324vm_search_method_slowpath0(VALUE cd_owner, struct rb_call_data *cd, VALUE klass)
2325{
2326#if USE_DEBUG_COUNTER
2327 const struct rb_callcache *old_cc = cd->cc;
2328 const rb_callable_method_entry_t *const old_cme = old_cc ? old_cc->cme_ : NULL;
2329#endif
2330
2331 const struct rb_callcache *cc = rb_vm_search_method_slowpath(cd->ci, klass);
2332 const rb_callable_method_entry_t *const new_cme = vm_cc_cme(cc);
2333
2334#if OPT_INLINE_METHOD_CACHE
2335 cd->cc = cc;
2336
2337 if (cd_owner && vm_cc_markable(cc)) {
2338 // invokesuper dispatches with a cd on the machine stack, which has no
2339 // owning iseq to remember and keeps its ci out of the GC.
2340 VM_ASSERT(!vm_ci_markable(cd->ci) ||
2341 vm_cd_owned_by_iseq_p(cd, (const rb_iseq_t *)cd_owner));
2342 RB_OBJ_WRITTEN(cd_owner, Qundef, cc);
2343 }
2344
2345#if USE_DEBUG_COUNTER
2346 const struct rb_callcache *empty_cc = &rb_vm_empty_cc;
2347 if (!old_cc || old_cc == empty_cc) {
2348 // empty
2349 RB_DEBUG_COUNTER_INC(mc_inline_miss_empty);
2350 }
2351 else if (old_cc == cc) {
2352 RB_DEBUG_COUNTER_INC(mc_inline_miss_same_cc);
2353 }
2354 else if (old_cme == new_cme) {
2355 RB_DEBUG_COUNTER_INC(mc_inline_miss_same_cme);
2356 }
2357 else if (old_cme && new_cme && old_cme->def == new_cme->def) {
2358 RB_DEBUG_COUNTER_INC(mc_inline_miss_same_def);
2359 }
2360 else {
2361 RB_DEBUG_COUNTER_INC(mc_inline_miss_diff);
2362 }
2363#endif
2364#endif // OPT_INLINE_METHOD_CACHE
2365
2366 if (new_cme) VM_ASSERT(new_cme->called_id == vm_ci_mid(cd->ci));
2367
2368 return cc;
2369}
2370
2371ALWAYS_INLINE(static bool vm_cc_hit_p(const struct rb_callcache *cc, const struct rb_call_data *cd, VALUE klass));
2372static bool
2373vm_cc_hit_p(const struct rb_callcache *cc, const struct rb_call_data *cd, VALUE klass)
2374{
2375 VM_ASSERT_TYPE2(klass, T_CLASS, T_ICLASS);
2376
2377#if OPT_INLINE_METHOD_CACHE
2378 if (LIKELY(vm_cc_class_check(cc, klass))) {
2379 if (LIKELY(!METHOD_ENTRY_INVALIDATED(vm_cc_cme(cc)))) {
2380 VM_ASSERT(callable_method_entry_p(vm_cc_cme(cc)));
2381 RB_DEBUG_COUNTER_INC(mc_inline_hit);
2382 VM_ASSERT(vm_cc_cme(cc) == NULL || // not found
2383 (vm_ci_flag(cd->ci) & VM_CALL_SUPER) || // search_super w/ define_method
2384 vm_cc_cme(cc)->called_id == vm_ci_mid(cd->ci)); // cme->called_id == ci->mid
2385
2386 return true;
2387 }
2388 RB_DEBUG_COUNTER_INC(mc_inline_miss_invalidated);
2389 }
2390 else {
2391 RB_DEBUG_COUNTER_INC(mc_inline_miss_klass);
2392 }
2393#endif
2394
2395 return false;
2396}
2397
2398ALWAYS_INLINE(static const struct rb_callcache *vm_search_method_fastpath(const struct rb_control_frame_struct *reg_cfp, struct rb_call_data *cd, VALUE klass));
2399static const struct rb_callcache *
2400vm_search_method_fastpath(const struct rb_control_frame_struct *reg_cfp, struct rb_call_data *cd, VALUE klass)
2401{
2402 const struct rb_callcache *cc = cd->cc;
2403 if (vm_cc_hit_p(cc, cd, klass)) {
2404 return cc;
2405 }
2406 if (UNLIKELY(cc == &rb_vm_uncached_cc)) {
2407 return cc;
2408 }
2409
2410 return vm_search_method_slowpath0((VALUE)CFP_ISEQ(reg_cfp), cd, klass);
2411}
2412
2413static const struct rb_callable_method_entry_struct *
2414vm_search_method(struct rb_control_frame_struct *reg_cfp, struct rb_call_data *cd, VALUE recv)
2415{
2416 VALUE klass = CLASS_OF(recv);
2417 VM_ASSERT(klass != Qfalse);
2418 VM_ASSERT(RBASIC_CLASS(klass) == 0 || rb_obj_is_kind_of(klass, rb_cClass));
2419
2420 const struct rb_callcache *cc = vm_search_method_fastpath(reg_cfp, cd, klass);
2421 return vm_cc_cme(cc);
2422}
2423
2424static VALUE
2425vm_call_uncached(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling)
2426{
2427 RB_DEBUG_COUNTER_INC(ccf_uncached);
2428
2429 const struct rb_call_data *cd = calling->cd;
2430 const VALUE klass = CLASS_OF(calling->recv);
2431 const rb_callable_method_entry_t *cme = rb_callable_method_entry(klass, vm_ci_mid(cd->ci));
2432
2433 if (UNLIKELY(cme == NULL || !cme->def->uncached)) {
2434 // A site that saw an uncached method is now seeing a receiver whose
2435 // method is cacheable, so let it have a real cc after all.
2436 const struct rb_callcache *cc =
2437 vm_search_method_slowpath0((VALUE)CFP_ISEQ(cfp), (struct rb_call_data *)cd, klass);
2438 calling->cc = cc;
2439 return vm_cc_call(cc)(ec, cfp, calling);
2440 }
2441
2442 calling->cc = &VM_CC_ON_STACK(klass, vm_call_general, {{ 0 }},
2443 rb_check_overloaded_cme(cme, cd->ci));
2444 return vm_call_general(ec, cfp, calling);
2445}
2446
2448rb_zjit_vm_search_method(VALUE cd_owner, struct rb_call_data *cd, VALUE recv)
2449{
2450 // Called from ZJIT with the compile-time iseq, which may differ from
2451 // the iseq on the current CFP.
2452 VALUE klass = CLASS_OF(recv);
2453 const struct rb_callcache *cc = cd->cc;
2454 if (!vm_cc_hit_p(cc, cd, klass)) {
2455 if (UNLIKELY(cc == &rb_vm_uncached_cc)) {
2456 return rb_callable_method_entry(klass, vm_ci_mid(cd->ci));
2457 }
2458 cc = vm_search_method_slowpath0(cd_owner, cd, klass);
2459 }
2460 return vm_cc_cme(cc);
2461}
2462
2463#if __has_attribute(transparent_union)
2464typedef union {
2465 VALUE (*anyargs)(ANYARGS);
2466 VALUE (*f00)(VALUE);
2467 VALUE (*f01)(VALUE, VALUE);
2468 VALUE (*f02)(VALUE, VALUE, VALUE);
2469 VALUE (*f03)(VALUE, VALUE, VALUE, VALUE);
2470 VALUE (*f04)(VALUE, VALUE, VALUE, VALUE, VALUE);
2471 VALUE (*f05)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE);
2472 VALUE (*f06)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE);
2473 VALUE (*f07)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE);
2482 VALUE (*fm1)(int, union { VALUE *x; const VALUE *y; } __attribute__((__transparent_union__)), VALUE);
2483} __attribute__((__transparent_union__)) cfunc_type;
2484# define make_cfunc_type(f) (cfunc_type){.anyargs = (VALUE (*)(ANYARGS))(f)}
2485#else
2486typedef VALUE (*cfunc_type)(ANYARGS);
2487# define make_cfunc_type(f) (cfunc_type)(f)
2488#endif
2489
2490static inline bool
2491cfunc_p(const rb_callable_method_entry_t *me)
2492{
2493 if (! me) {
2494 return false;
2495 }
2496
2497 VM_ASSERT(IMEMO_TYPE_P(me, imemo_ment));
2498 VM_ASSERT(callable_method_entry_p(me));
2499 VM_ASSERT(me->def);
2500
2501 return me->def->type == VM_METHOD_TYPE_CFUNC;
2502}
2503
2504static inline bool
2505cfunc_equal(const rb_callable_method_entry_t *me, cfunc_type func)
2506{
2507 VM_ASSERT(cfunc_p(me));
2508
2509#if __has_attribute(transparent_union)
2510 return me->def->body.cfunc.func == func.anyargs;
2511#else
2512 return me->def->body.cfunc.func == func;
2513#endif
2514}
2515
2516static inline bool
2517check_cfunc(const rb_callable_method_entry_t *me, cfunc_type func)
2518{
2519 return cfunc_p(me) && cfunc_equal(me, func);
2520}
2521
2522static inline int
2523check_method_basic_definition(const rb_callable_method_entry_t *me)
2524{
2525 return me && METHOD_ENTRY_BASIC(me);
2526}
2527
2528static inline int
2529vm_method_cfunc_is(struct rb_control_frame_struct *reg_cfp, CALL_DATA cd, VALUE recv, cfunc_type func)
2530{
2531 VM_ASSERT(reg_cfp != NULL);
2532 const struct rb_callable_method_entry_struct *cme = vm_search_method(reg_cfp, cd, recv);
2533 return check_cfunc(cme, func);
2534}
2535
2536bool
2537rb_zjit_cme_is_cfunc(const rb_callable_method_entry_t *me, const cfunc_type func)
2538{
2539 return check_cfunc(me, func);
2540}
2541
2542int
2543rb_vm_method_cfunc_is(const rb_iseq_t *iseq, CALL_DATA cd, VALUE recv, cfunc_type func)
2544{
2545 const struct rb_callable_method_entry_struct *cme = rb_zjit_vm_search_method((VALUE)iseq, cd, recv);
2546 return check_cfunc(cme, func);
2547}
2548
2549#define check_cfunc(me, func) check_cfunc(me, make_cfunc_type(func))
2550#define vm_method_cfunc_is(reg_cfp, cd, recv, func) vm_method_cfunc_is(reg_cfp, cd, recv, make_cfunc_type(func))
2551
2552#define OP_UNREDEFINED_P(op, t) BASIC_OP_UNREDEFINED_P(BOP_##op, t##_REDEFINED_OP_FLAG)
2553#define EQ_UNREDEFINED_P(t) OP_UNREDEFINED_P(EQ, t)
2554
2555static inline bool
2556FIXNUM_2_P(VALUE a, VALUE b)
2557{
2558 /* FIXNUM_P(a) && FIXNUM_P(b)
2559 * == ((a & 1) && (b & 1))
2560 * == a & b & 1 */
2561 SIGNED_VALUE x = a;
2562 SIGNED_VALUE y = b;
2563 SIGNED_VALUE z = x & y & 1;
2564 return z == 1;
2565}
2566
2567static inline bool
2568FLONUM_2_P(VALUE a, VALUE b)
2569{
2570#if USE_FLONUM
2571 /* FLONUM_P(a) && FLONUM_P(b)
2572 * == ((a & 3) == 2) && ((b & 3) == 2)
2573 * == ! ((a ^ 2) | (b ^ 2) & 3)
2574 */
2575 SIGNED_VALUE x = a;
2576 SIGNED_VALUE y = b;
2577 SIGNED_VALUE z = ((x ^ 2) | (y ^ 2)) & 3;
2578 return !z;
2579#else
2580 return false;
2581#endif
2582}
2583
2584static inline VALUE
2585opt_equality_specialized(VALUE recv, VALUE obj)
2586{
2587 if (recv == obj) {
2588 if (OP_UNREDEFINED_P(EQ, ANY)) {
2589 // Two identical immediate VALUE are always equal
2590 if (SPECIAL_CONST_P(recv)) {
2591 return Qtrue;
2592 }
2593 return Qundef;
2594 }
2595 return Qundef;
2596 }
2597
2598 return opt_equality_specialized_miss(recv, obj);
2599}
2600
2601static VALUE
2602opt_equality(struct rb_control_frame_struct *reg_cfp, VALUE recv, VALUE obj, CALL_DATA cd)
2603{
2604 VM_ASSERT(reg_cfp != NULL);
2605
2606 VALUE val = opt_equality_specialized(recv, obj);
2607 if (!UNDEF_P(val)) return val;
2608
2609 if (!vm_method_cfunc_is(reg_cfp, cd, recv, rb_obj_equal)) {
2610 return Qundef;
2611 }
2612 else {
2613 return RBOOL(recv == obj);
2614 }
2615}
2616
2617static inline const struct rb_callcache *gccct_method_search(rb_execution_context_t *ec, VALUE recv, ID mid, const struct rb_callinfo *ci); // vm_eval.c
2618
2619static inline VALUE
2620opt_equality_by_mid(VALUE recv, VALUE obj, ID mid)
2621{
2622 const struct rb_callcache *cc = gccct_method_search(GET_EC(), recv, mid, &VM_CI_ON_STACK(mid, 0, 1, NULL));
2623
2624 if (cc && check_cfunc(vm_cc_cme(cc), rb_obj_equal)) {
2625 return RBOOL(recv == obj);
2626 }
2627 else {
2628 return RBOOL(RTEST(rb_funcall(recv, mid, 1, obj)));
2629 }
2630}
2631
2632VALUE
2633rb_equal_opt(VALUE obj1, VALUE obj2)
2634{
2635 return opt_equality_by_mid(obj1, obj2, idEq);
2636}
2637
2638VALUE
2639rb_eql_opt(VALUE obj1, VALUE obj2)
2640{
2641 return opt_equality_by_mid(obj1, obj2, idEqlP);
2642}
2643
2644extern VALUE rb_vm_call0(rb_execution_context_t *ec, VALUE, ID, int, const VALUE*, const rb_callable_method_entry_t *, int kw_splat);
2645extern VALUE rb_vm_call_with_refinements(rb_execution_context_t *, VALUE, ID, int, const VALUE *, int);
2646
2647static VALUE
2648check_match(rb_execution_context_t *ec, VALUE pattern, VALUE target, enum vm_check_match_type type)
2649{
2650 switch (type) {
2651 case VM_CHECKMATCH_TYPE_WHEN:
2652 return pattern;
2653 case VM_CHECKMATCH_TYPE_RESCUE:
2654 if (!rb_obj_is_kind_of(pattern, rb_cModule)) {
2655 rb_raise(rb_eTypeError, "class or module required for rescue clause");
2656 }
2657 /* fall through */
2658 case VM_CHECKMATCH_TYPE_CASE: {
2659 return rb_vm_call_with_refinements(ec, pattern, idEqq, 1, &target, RB_NO_KEYWORDS);
2660 }
2661 default:
2662 rb_bug("check_match: unreachable");
2663 }
2664}
2665
2666
2667static inline VALUE
2668double_cmp_lt(double a, double b)
2669{
2670 return RBOOL(a < b);
2671}
2672
2673static inline VALUE
2674double_cmp_le(double a, double b)
2675{
2676 return RBOOL(a <= b);
2677}
2678
2679static inline VALUE
2680double_cmp_gt(double a, double b)
2681{
2682 return RBOOL(a > b);
2683}
2684
2685static inline VALUE
2686double_cmp_ge(double a, double b)
2687{
2688 return RBOOL(a >= b);
2689}
2690
2691// Copied by vm_dump.c
2692static inline VALUE *
2693vm_base_ptr(const rb_control_frame_t *cfp)
2694{
2695 const rb_control_frame_t *prev_cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
2696
2697 if (CFP_ISEQ(cfp) && VM_FRAME_RUBYFRAME_P(cfp)) {
2698 VALUE *bp = prev_cfp->sp + ISEQ_BODY(CFP_ISEQ(cfp))->local_table_size + VM_ENV_DATA_SIZE;
2699
2700 if (ISEQ_BODY(CFP_ISEQ(cfp))->param.flags.forwardable && VM_ENV_LOCAL_P(cfp->ep)) {
2701 int lts = ISEQ_BODY(CFP_ISEQ(cfp))->local_table_size;
2702 int params = ISEQ_BODY(CFP_ISEQ(cfp))->param.size;
2703
2704 CALL_INFO ci = (CALL_INFO)cfp->ep[-(VM_ENV_DATA_SIZE + (lts - params))]; // skip EP stuff, CI should be last local
2705 bp += vm_ci_argc(ci);
2706 }
2707
2708 if (ISEQ_BODY(CFP_ISEQ(cfp))->type == ISEQ_TYPE_METHOD || VM_FRAME_BMETHOD_P(cfp)) {
2709 /* adjust `self' */
2710 bp += 1;
2711 }
2712#if VM_DEBUG_BP_CHECK
2713 if (bp != cfp->bp_check) {
2714 ruby_debug_printf("bp_check: %ld, bp: %ld\n",
2715 (long)(cfp->bp_check - GET_EC()->vm_stack),
2716 (long)(bp - GET_EC()->vm_stack));
2717 rb_bug("vm_base_ptr: unreachable");
2718 }
2719#endif
2720 return bp;
2721 }
2722 else {
2723 return NULL;
2724 }
2725}
2726
2727VALUE *
2728rb_vm_base_ptr(const rb_control_frame_t *cfp)
2729{
2730 return vm_base_ptr(cfp);
2731}
2732
2733/* method call processes with call_info */
2734
2735#include "vm_args.c"
2736
2737static inline VALUE vm_call_iseq_setup_2(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling, int opt_pc, unsigned int param_size, unsigned int local_size);
2738ALWAYS_INLINE(static VALUE vm_call_iseq_setup_normal(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling, const rb_callable_method_entry_t *me, int opt_pc, int param_size, int local_size));
2739static inline VALUE vm_call_iseq_setup_tailcall(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling, int opt_pc, unsigned int param_size, unsigned int local_size);
2740static VALUE vm_call_super_method(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling);
2741static VALUE vm_call_method_nome(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling);
2742static VALUE vm_call_method_each_type(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling);
2743static inline VALUE vm_call_method(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling);
2744
2745static vm_call_handler vm_call_iseq_setup_func(const struct rb_callinfo *ci, const int param_size, const int local_size);
2746
2747static VALUE
2748vm_call_iseq_setup_tailcall_0start(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling)
2749{
2750 RB_DEBUG_COUNTER_INC(ccf_iseq_setup_tailcall_0start);
2751
2752 const struct rb_callcache *cc = calling->cc;
2753 const rb_iseq_t *iseq = def_iseq_ptr(vm_cc_cme(cc)->def);
2754 unsigned int param = ISEQ_BODY(iseq)->param.size;
2755 unsigned int local = ISEQ_BODY(iseq)->local_table_size;
2756 return vm_call_iseq_setup_tailcall(ec, cfp, calling, 0, param, local);
2757}
2758
2759static VALUE
2760vm_call_iseq_setup_normal_0start(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling)
2761{
2762 RB_DEBUG_COUNTER_INC(ccf_iseq_setup_0start);
2763
2764 const struct rb_callcache *cc = calling->cc;
2765 const rb_iseq_t *iseq = def_iseq_ptr(vm_cc_cme(cc)->def);
2766 int param = ISEQ_BODY(iseq)->param.size;
2767 int local = ISEQ_BODY(iseq)->local_table_size;
2768 return vm_call_iseq_setup_normal(ec, cfp, calling, vm_cc_cme(cc), 0, param, local);
2769}
2770
2771bool
2772rb_simple_iseq_p(const rb_iseq_t *iseq)
2773{
2774 return ISEQ_BODY(iseq)->param.flags.has_opt == FALSE &&
2775 ISEQ_BODY(iseq)->param.flags.has_rest == FALSE &&
2776 ISEQ_BODY(iseq)->param.flags.has_post == FALSE &&
2777 ISEQ_BODY(iseq)->param.flags.has_kw == FALSE &&
2778 ISEQ_BODY(iseq)->param.flags.has_kwrest == FALSE &&
2779 ISEQ_BODY(iseq)->param.flags.accepts_no_kwarg == FALSE &&
2780 ISEQ_BODY(iseq)->param.flags.forwardable == FALSE &&
2781 ISEQ_BODY(iseq)->param.flags.has_block == FALSE &&
2782 ISEQ_BODY(iseq)->param.flags.accepts_no_block == FALSE;
2783}
2784
2785bool
2786rb_iseq_only_optparam_p(const rb_iseq_t *iseq)
2787{
2788 return ISEQ_BODY(iseq)->param.flags.has_opt == TRUE &&
2789 ISEQ_BODY(iseq)->param.flags.has_rest == FALSE &&
2790 ISEQ_BODY(iseq)->param.flags.has_post == FALSE &&
2791 ISEQ_BODY(iseq)->param.flags.has_kw == FALSE &&
2792 ISEQ_BODY(iseq)->param.flags.has_kwrest == FALSE &&
2793 ISEQ_BODY(iseq)->param.flags.accepts_no_kwarg == FALSE &&
2794 ISEQ_BODY(iseq)->param.flags.forwardable == FALSE &&
2795 ISEQ_BODY(iseq)->param.flags.has_block == FALSE &&
2796 ISEQ_BODY(iseq)->param.flags.accepts_no_block == FALSE;
2797}
2798
2799bool
2800rb_iseq_only_kwparam_p(const rb_iseq_t *iseq)
2801{
2802 return ISEQ_BODY(iseq)->param.flags.has_opt == FALSE &&
2803 ISEQ_BODY(iseq)->param.flags.has_rest == FALSE &&
2804 ISEQ_BODY(iseq)->param.flags.has_post == FALSE &&
2805 ISEQ_BODY(iseq)->param.flags.has_kw == TRUE &&
2806 ISEQ_BODY(iseq)->param.flags.has_kwrest == FALSE &&
2807 ISEQ_BODY(iseq)->param.flags.forwardable == FALSE &&
2808 ISEQ_BODY(iseq)->param.flags.has_block == FALSE &&
2809 ISEQ_BODY(iseq)->param.flags.accepts_no_block == FALSE;
2810}
2811
2812#define ALLOW_HEAP_ARGV (-2)
2813#define ALLOW_HEAP_ARGV_KEEP_KWSPLAT (-3)
2814
2815static inline bool
2816vm_caller_setup_arg_splat(rb_control_frame_t *cfp, struct rb_calling_info *calling, VALUE ary, int max_args)
2817{
2818 vm_check_canary(GET_EC(), cfp->sp);
2819 bool ret = false;
2820
2821 if (!NIL_P(ary)) {
2822 const VALUE *ptr = RARRAY_CONST_PTR(ary);
2823 rb_len_t len = RARRAY_LEN(ary);
2824 int argc = calling->argc;
2825
2826 if (UNLIKELY(max_args <= ALLOW_HEAP_ARGV && len + argc > VM_ARGC_STACK_MAX)) {
2827 /* Avoid SystemStackError when splatting large arrays by storing arguments in
2828 * a temporary array, instead of trying to keeping arguments on the VM stack.
2829 */
2830 VALUE *argv = cfp->sp - argc;
2831 VALUE argv_ary = rb_ary_hidden_new(len + argc + 1);
2832 rb_ary_cat(argv_ary, argv, argc);
2833 rb_ary_cat(argv_ary, ptr, len);
2834 cfp->sp -= argc - 1;
2835 cfp->sp[-1] = argv_ary;
2836 calling->argc = 1;
2837 calling->heap_argv = argv_ary;
2838 RB_GC_GUARD(ary);
2839 }
2840 else {
2841 long i;
2842
2843 if (max_args >= 0 && len + argc > max_args) {
2844 /* If only a given max_args is allowed, copy up to max args.
2845 * Used by vm_callee_setup_block_arg for non-lambda blocks,
2846 * where additional arguments are ignored.
2847 *
2848 * Also, copy up to one more argument than the maximum,
2849 * in case it is an empty keyword hash that will be removed.
2850 *
2851 * calling->argc still counts the arguments that are not
2852 * copied, so that arity errors report the given number.
2853 */
2854 rb_len_t copy_len = max_args - argc + 1;
2855 if (copy_len < 0) {
2856 /* More than max_args + 1 arguments precede the splat. */
2857 copy_len = 0;
2858 }
2859 calling->argc += len - copy_len;
2860 len = copy_len;
2861 ret = true;
2862 }
2863 else {
2864 /* Unset heap_argv if set originally. Can happen when
2865 * forwarding modified arguments, where heap_argv was used
2866 * originally, but heap_argv not supported by the forwarded
2867 * method in all cases.
2868 */
2869 calling->heap_argv = 0;
2870 }
2871 CHECK_VM_STACK_OVERFLOW(cfp, len);
2872
2873 for (i = 0; i < len; i++) {
2874 *cfp->sp++ = ptr[i];
2875 }
2876 calling->argc += i;
2877 }
2878 }
2879
2880 return ret;
2881}
2882
2883static inline void
2884vm_caller_setup_arg_kw(rb_control_frame_t *cfp, struct rb_calling_info *calling, const struct rb_callinfo *ci)
2885{
2886 const VALUE *const passed_keywords = vm_ci_kwarg(ci)->keywords;
2887 const int kw_len = vm_ci_kwarg(ci)->keyword_len;
2888 const VALUE h = rb_hash_new_capa(kw_len);
2889 VALUE *sp = cfp->sp;
2890 int i;
2891
2892 for (i=0; i<kw_len; i++) {
2893 rb_hash_aset(h, passed_keywords[i], (sp - kw_len)[i]);
2894 }
2895 (sp-kw_len)[0] = h;
2896
2897 cfp->sp -= kw_len - 1;
2898 calling->argc -= kw_len - 1;
2899 calling->kw_splat = 1;
2900}
2901
2902static inline VALUE
2903vm_caller_setup_keyword_hash(const struct rb_callinfo *ci, VALUE keyword_hash)
2904{
2905 if (UNLIKELY(!RB_TYPE_P(keyword_hash, T_HASH))) {
2906 if (keyword_hash != Qnil) {
2907 /* Convert a non-hash keyword splat to a new hash */
2908 keyword_hash = rb_hash_dup(rb_to_hash_type(keyword_hash));
2909 }
2910 }
2911 else if (!IS_ARGS_KW_SPLAT_MUT(ci) && !RHASH_EMPTY_P(keyword_hash)) {
2912 /* Convert a hash keyword splat to a new hash unless
2913 * a mutable keyword splat was passed.
2914 * Skip allocating new hash for empty keyword splat, as empty
2915 * keyword splat will be ignored by both callers.
2916 */
2917 keyword_hash = rb_hash_dup(keyword_hash);
2918 }
2919 return keyword_hash;
2920}
2921
2922static inline void
2923CALLER_SETUP_ARG(struct rb_control_frame_struct *restrict cfp,
2924 struct rb_calling_info *restrict calling,
2925 const struct rb_callinfo *restrict ci, int max_args)
2926{
2927 if (UNLIKELY(IS_ARGS_SPLAT(ci))) {
2928 if (IS_ARGS_KW_SPLAT(ci)) {
2929 // f(*a, **kw)
2930 VM_ASSERT(calling->kw_splat == 1);
2931
2932 cfp->sp -= 2;
2933 calling->argc -= 2;
2934 VALUE ary = cfp->sp[0];
2935 VALUE kwh = vm_caller_setup_keyword_hash(ci, cfp->sp[1]);
2936
2937 // splat a
2938 if (vm_caller_setup_arg_splat(cfp, calling, ary, max_args)) return;
2939
2940 // put kw
2941 if (kwh != Qnil && !RHASH_EMPTY_P(kwh)) {
2942 if (UNLIKELY(calling->heap_argv)) {
2943 rb_ary_push(calling->heap_argv, kwh);
2944 ((struct RHash *)kwh)->basic.flags |= RHASH_PASS_AS_KEYWORDS;
2945 if (max_args != ALLOW_HEAP_ARGV_KEEP_KWSPLAT) {
2946 calling->kw_splat = 0;
2947 }
2948 }
2949 else {
2950 cfp->sp[0] = kwh;
2951 cfp->sp++;
2952 calling->argc++;
2953
2954 VM_ASSERT(calling->kw_splat == 1);
2955 }
2956 }
2957 else {
2958 calling->kw_splat = 0;
2959 }
2960 }
2961 else {
2962 // f(*a)
2963 VM_ASSERT(calling->kw_splat == 0);
2964
2965 cfp->sp -= 1;
2966 calling->argc -= 1;
2967 VALUE ary = cfp->sp[0];
2968
2969 if (vm_caller_setup_arg_splat(cfp, calling, ary, max_args)) {
2970 goto check_keyword;
2971 }
2972
2973 // check the last argument
2974 VALUE last_hash, argv_ary;
2975 if (UNLIKELY(argv_ary = calling->heap_argv)) {
2976 if (!IS_ARGS_KEYWORD(ci) &&
2977 RARRAY_LEN(argv_ary) > 0 &&
2978 RB_TYPE_P((last_hash = rb_ary_last(0, NULL, argv_ary)), T_HASH) &&
2979 (((struct RHash *)last_hash)->basic.flags & RHASH_PASS_AS_KEYWORDS)) {
2980
2981 rb_ary_pop(argv_ary);
2982 if (!RHASH_EMPTY_P(last_hash)) {
2983 rb_ary_push(argv_ary, rb_hash_dup(last_hash));
2984 calling->kw_splat = 1;
2985 }
2986 }
2987 }
2988 else {
2989check_keyword:
2990 if (!IS_ARGS_KEYWORD(ci) &&
2991 calling->argc > 0 &&
2992 RB_TYPE_P((last_hash = cfp->sp[-1]), T_HASH) &&
2993 (((struct RHash *)last_hash)->basic.flags & RHASH_PASS_AS_KEYWORDS)) {
2994
2995 if (RHASH_EMPTY_P(last_hash)) {
2996 calling->argc--;
2997 cfp->sp -= 1;
2998 }
2999 else {
3000 cfp->sp[-1] = rb_hash_dup(last_hash);
3001 calling->kw_splat = 1;
3002 }
3003 }
3004 }
3005 }
3006 }
3007 else if (UNLIKELY(IS_ARGS_KW_SPLAT(ci))) {
3008 // f(**kw)
3009 VM_ASSERT(calling->kw_splat == 1);
3010 VALUE kwh = vm_caller_setup_keyword_hash(ci, cfp->sp[-1]);
3011
3012 if (kwh == Qnil || RHASH_EMPTY_P(kwh)) {
3013 cfp->sp--;
3014 calling->argc--;
3015 calling->kw_splat = 0;
3016 }
3017 else {
3018 cfp->sp[-1] = kwh;
3019 }
3020 }
3021 else if (UNLIKELY(IS_ARGS_KEYWORD(ci))) {
3022 // f(k1:1, k2:2)
3023 VM_ASSERT(calling->kw_splat == 0);
3024
3025 /* This converts VM_CALL_KWARG style to VM_CALL_KW_SPLAT style
3026 * by creating a keyword hash.
3027 * So, vm_ci_flag(ci) & VM_CALL_KWARG is now inconsistent.
3028 */
3029 vm_caller_setup_arg_kw(cfp, calling, ci);
3030 }
3031}
3032
3033#define USE_OPT_HIST 0
3034
3035#if USE_OPT_HIST
3036#define OPT_HIST_MAX 64
3037static int opt_hist[OPT_HIST_MAX+1];
3038
3039__attribute__((destructor))
3040static void
3041opt_hist_show_results_at_exit(void)
3042{
3043 for (int i=0; i<OPT_HIST_MAX; i++) {
3044 ruby_debug_printf("opt_hist\t%d\t%d\n", i, opt_hist[i]);
3045 }
3046}
3047#endif
3048
3049static VALUE
3050vm_call_iseq_setup_normal_opt_start(rb_execution_context_t *ec, rb_control_frame_t *cfp,
3051 struct rb_calling_info *calling)
3052{
3053 const struct rb_callcache *cc = calling->cc;
3054 const rb_iseq_t *iseq = def_iseq_ptr(vm_cc_cme(cc)->def);
3055 const int lead_num = ISEQ_BODY(iseq)->param.lead_num;
3056 const int opt = calling->argc - lead_num;
3057 const int opt_num = ISEQ_BODY(iseq)->param.opt_num;
3058 const int opt_pc = (int)ISEQ_BODY(iseq)->param.opt_table[opt];
3059 const int param = ISEQ_BODY(iseq)->param.size;
3060 const int local = ISEQ_BODY(iseq)->local_table_size;
3061 const int delta = opt_num - opt;
3062
3063 RB_DEBUG_COUNTER_INC(ccf_iseq_opt);
3064
3065#if USE_OPT_HIST
3066 if (opt_pc < OPT_HIST_MAX) {
3067 opt_hist[opt]++;
3068 }
3069 else {
3070 opt_hist[OPT_HIST_MAX]++;
3071 }
3072#endif
3073
3074 return vm_call_iseq_setup_normal(ec, cfp, calling, vm_cc_cme(cc), opt_pc, param - delta, local);
3075}
3076
3077static VALUE
3078vm_call_iseq_setup_tailcall_opt_start(rb_execution_context_t *ec, rb_control_frame_t *cfp,
3079 struct rb_calling_info *calling)
3080{
3081 const struct rb_callcache *cc = calling->cc;
3082 const rb_iseq_t *iseq = def_iseq_ptr(vm_cc_cme(cc)->def);
3083 const int lead_num = ISEQ_BODY(iseq)->param.lead_num;
3084 const int opt = calling->argc - lead_num;
3085 const int opt_pc = (int)ISEQ_BODY(iseq)->param.opt_table[opt];
3086 unsigned const int param = ISEQ_BODY(iseq)->param.size;
3087 unsigned const int local = ISEQ_BODY(iseq)->local_table_size;
3088
3089 RB_DEBUG_COUNTER_INC(ccf_iseq_opt);
3090
3091#if USE_OPT_HIST
3092 if (opt_pc < OPT_HIST_MAX) {
3093 opt_hist[opt]++;
3094 }
3095 else {
3096 opt_hist[OPT_HIST_MAX]++;
3097 }
3098#endif
3099
3100 return vm_call_iseq_setup_tailcall(ec, cfp, calling, opt_pc, param, local);
3101}
3102
3103static void
3104args_setup_kw_parameters(rb_execution_context_t *const ec, const rb_iseq_t *const iseq, const rb_callable_method_entry_t *cme,
3105 VALUE *const passed_values, const int passed_keyword_len, const VALUE *const passed_keywords,
3106 VALUE *const locals);
3107
3108static VALUE
3109vm_call_iseq_forwardable(rb_execution_context_t *ec, rb_control_frame_t *cfp,
3110 struct rb_calling_info *calling)
3111{
3112 const struct rb_callcache *cc = calling->cc;
3113 const rb_iseq_t *iseq = def_iseq_ptr(vm_cc_cme(cc)->def);
3114 int param_size = ISEQ_BODY(iseq)->param.size;
3115 int local_size = ISEQ_BODY(iseq)->local_table_size;
3116
3117 // Setting up local size and param size
3118 VM_ASSERT(ISEQ_BODY(iseq)->param.flags.forwardable);
3119
3120 local_size = local_size + vm_ci_argc(calling->cd->ci);
3121 param_size = param_size + vm_ci_argc(calling->cd->ci);
3122
3123 cfp->sp[0] = (VALUE)calling->cd->ci;
3124
3125 return vm_call_iseq_setup_normal(ec, cfp, calling, vm_cc_cme(cc), 0, param_size, local_size);
3126}
3127
3128static VALUE
3129vm_call_iseq_setup_kwparm_kwarg(rb_execution_context_t *ec, rb_control_frame_t *cfp,
3130 struct rb_calling_info *calling)
3131{
3132 const struct rb_callinfo *ci = calling->cd->ci;
3133 const struct rb_callcache *cc = calling->cc;
3134
3135 VM_ASSERT(vm_ci_flag(ci) & VM_CALL_KWARG);
3136 RB_DEBUG_COUNTER_INC(ccf_iseq_kw1);
3137
3138 const rb_iseq_t *iseq = def_iseq_ptr(vm_cc_cme(cc)->def);
3139 const struct rb_iseq_param_keyword *kw_param = ISEQ_BODY(iseq)->param.keyword;
3140 const struct rb_callinfo_kwarg *kw_arg = vm_ci_kwarg(ci);
3141 const int ci_kw_len = kw_arg->keyword_len;
3142 const VALUE * const ci_keywords = kw_arg->keywords;
3143 VALUE *argv = cfp->sp - calling->argc;
3144 VALUE *const klocals = argv + kw_param->bits_start - kw_param->num;
3145 const int lead_num = ISEQ_BODY(iseq)->param.lead_num;
3146 VALUE * const ci_kws = ALLOCA_N(VALUE, ci_kw_len);
3147 MEMCPY(ci_kws, argv + lead_num, VALUE, ci_kw_len);
3148 args_setup_kw_parameters(ec, iseq, vm_cc_cme(cc), ci_kws, ci_kw_len, ci_keywords, klocals);
3149
3150 int param = ISEQ_BODY(iseq)->param.size;
3151 int local = ISEQ_BODY(iseq)->local_table_size;
3152 return vm_call_iseq_setup_normal(ec, cfp, calling, vm_cc_cme(cc), 0, param, local);
3153}
3154
3155static VALUE
3156vm_call_iseq_setup_kwparm_nokwarg(rb_execution_context_t *ec, rb_control_frame_t *cfp,
3157 struct rb_calling_info *calling)
3158{
3159 const struct rb_callinfo *MAYBE_UNUSED(ci) = calling->cd->ci;
3160 const struct rb_callcache *cc = calling->cc;
3161
3162 VM_ASSERT((vm_ci_flag(ci) & VM_CALL_KWARG) == 0);
3163 RB_DEBUG_COUNTER_INC(ccf_iseq_kw2);
3164
3165 const rb_iseq_t *iseq = def_iseq_ptr(vm_cc_cme(cc)->def);
3166 const struct rb_iseq_param_keyword *kw_param = ISEQ_BODY(iseq)->param.keyword;
3167 VALUE * const argv = cfp->sp - calling->argc;
3168 VALUE * const klocals = argv + kw_param->bits_start - kw_param->num;
3169
3170 int i;
3171 for (i=0; i<kw_param->num; i++) {
3172 klocals[i] = kw_param->default_values[i];
3173 }
3174 klocals[i] = INT2FIX(0); // kw specify flag
3175 // NOTE:
3176 // nobody check this value, but it should be cleared because it can
3177 // points invalid VALUE (T_NONE objects, raw pointer and so on).
3178
3179 int param = ISEQ_BODY(iseq)->param.size;
3180 int local = ISEQ_BODY(iseq)->local_table_size;
3181 return vm_call_iseq_setup_normal(ec, cfp, calling, vm_cc_cme(cc), 0, param, local);
3182}
3183
3184static VALUE builtin_invoker0(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr);
3185
3186static VALUE
3187vm_call_single_noarg_leaf_builtin(rb_execution_context_t *ec, rb_control_frame_t *cfp,
3188 struct rb_calling_info *calling)
3189{
3190 const struct rb_callcache *cc = calling->cc;
3191 // Pairs with the release store in vm_callee_setup_arg so aux_.bf is visible.
3192 vm_call_handler call = (vm_call_handler)(uintptr_t)rbimpl_atomic_ptr_load((void **)&cc->call_, RBIMPL_ATOMIC_ACQUIRE);
3193 if (UNLIKELY(call != vm_call_single_noarg_leaf_builtin)) {
3194 return call(ec, cfp, calling);
3195 }
3196 const struct rb_builtin_function *bf = cc->aux_.bf;
3197 cfp->sp -= (calling->argc + 1);
3198 rb_insn_func_t func_ptr = (rb_insn_func_t)(uintptr_t)bf->func_ptr;
3199 return builtin_invoker0(ec, calling->recv, NULL, func_ptr);
3200}
3201
3202VALUE rb_gen_method_name(VALUE owner, VALUE name); // in vm_backtrace.c
3203
3204static void
3205warn_unused_block(const rb_callable_method_entry_t *cme, const rb_iseq_t *iseq, void *pc)
3206{
3207 rb_vm_t *vm = GET_VM();
3208 set_table *dup_check_table = &vm->unused_block_warning_table;
3209 st_data_t key;
3210 bool strict_unused_block = rb_warning_category_enabled_p(RB_WARN_CATEGORY_STRICT_UNUSED_BLOCK);
3211
3212 union {
3213 VALUE v;
3214 unsigned char b[SIZEOF_VALUE];
3215 } k1 = {
3216 .v = (VALUE)pc,
3217 }, k2 = {
3218 .v = (VALUE)cme->def,
3219 };
3220
3221 // relax check
3222 if (!strict_unused_block) {
3223 key = (st_data_t)cme->def->original_id;
3224
3225 if (set_table_lookup(dup_check_table, key)) {
3226 return;
3227 }
3228 }
3229
3230 // strict check
3231 // make unique key from pc and me->def pointer
3232 key = 0;
3233 for (int i=0; i<SIZEOF_VALUE; i++) {
3234 // fprintf(stderr, "k1:%3d k2:%3d\n", k1.b[i], k2.b[SIZEOF_VALUE-1-i]);
3235 key |= (st_data_t)(k1.b[i] ^ k2.b[SIZEOF_VALUE-1-i]) << (8 * i);
3236 }
3237
3238 if (0) {
3239 fprintf(stderr, "SIZEOF_VALUE:%d\n", SIZEOF_VALUE);
3240 fprintf(stderr, "pc:%p def:%p\n", pc, (void *)cme->def);
3241 fprintf(stderr, "key:%p\n", (void *)key);
3242 }
3243
3244 // duplication check
3245 if (set_insert(dup_check_table, key)) {
3246 // already shown
3247 }
3248 else if (RTEST(ruby_verbose) || strict_unused_block) {
3249 VALUE m_loc = rb_method_entry_location((const rb_method_entry_t *)cme);
3250 VALUE name = rb_gen_method_name(cme->defined_class, rb_iseq_base_label(iseq));
3251
3252 if (!NIL_P(m_loc)) {
3253 rb_warn("the block passed to '%"PRIsVALUE"' defined at %"PRIsVALUE":%"PRIsVALUE" may be ignored",
3254 name, RARRAY_AREF(m_loc, 0), RARRAY_AREF(m_loc, 1));
3255 }
3256 else {
3257 rb_warn("the block may be ignored because '%"PRIsVALUE"' does not use a block", name);
3258 }
3259 }
3260}
3261
3262static inline int
3263vm_callee_setup_arg(rb_execution_context_t *ec, struct rb_calling_info *calling,
3264 const rb_iseq_t *iseq, VALUE *argv, int param_size, int local_size)
3265{
3266 const struct rb_callinfo *ci = calling->cd->ci;
3267 const struct rb_callcache *cc = calling->cc;
3268
3269 VM_ASSERT((vm_ci_argc(ci), 1));
3270 VM_ASSERT(vm_cc_cme(cc) != NULL);
3271
3272 if (UNLIKELY(!ISEQ_BODY(iseq)->param.flags.use_block &&
3273 calling->block_handler != VM_BLOCK_HANDLER_NONE &&
3274 !(vm_ci_flag(calling->cd->ci) & (VM_CALL_OPT_SEND | VM_CALL_SUPER)))) {
3275 warn_unused_block(vm_cc_cme(cc), iseq, (void *)CFP_PC(ec->cfp));
3276 }
3277
3278 if (LIKELY(!(vm_ci_flag(ci) & VM_CALL_KW_SPLAT))) {
3279 if (LIKELY(rb_simple_iseq_p(iseq))) {
3280 rb_control_frame_t *cfp = ec->cfp;
3281 int lead_num = ISEQ_BODY(iseq)->param.lead_num;
3282 CALLER_SETUP_ARG(cfp, calling, ci, lead_num);
3283
3284 if (calling->argc != lead_num) {
3285 argument_arity_error(ec, iseq, vm_cc_cme(cc), calling->argc, lead_num, lead_num);
3286 }
3287
3288 //VM_ASSERT(ci == calling->cd->ci);
3289 VM_ASSERT(cc == calling->cc);
3290
3291 if (vm_call_iseq_optimizable_p(ci, cc)) {
3292 if ((ISEQ_BODY(iseq)->builtin_attrs & BUILTIN_ATTR_SINGLE_NOARG_LEAF) && ruby_vm_c_events_enabled == 0) {
3293 VM_ASSERT(ISEQ_BODY(iseq)->builtin_attrs & BUILTIN_ATTR_LEAF);
3294 vm_cc_bf_set(cc, (void *)ISEQ_BODY(iseq)->iseq_encoded[1]);
3295 rbimpl_atomic_ptr_store((volatile void **)&cc->call_,
3296 (void *)(uintptr_t)vm_call_single_noarg_leaf_builtin,
3297 RBIMPL_ATOMIC_RELEASE);
3298 }
3299 else {
3300 CC_SET_FASTPATH(cc, vm_call_iseq_setup_func(ci, param_size, local_size), true);
3301 }
3302 }
3303 return 0;
3304 }
3305 else if (rb_iseq_only_optparam_p(iseq)) {
3306 rb_control_frame_t *cfp = ec->cfp;
3307
3308 const int lead_num = ISEQ_BODY(iseq)->param.lead_num;
3309 const int opt_num = ISEQ_BODY(iseq)->param.opt_num;
3310
3311 CALLER_SETUP_ARG(cfp, calling, ci, lead_num + opt_num);
3312 const int argc = calling->argc;
3313 const int opt = argc - lead_num;
3314
3315 if (opt < 0 || opt > opt_num) {
3316 argument_arity_error(ec, iseq, vm_cc_cme(cc), argc, lead_num, lead_num + opt_num);
3317 }
3318
3319 if (LIKELY(!(vm_ci_flag(ci) & VM_CALL_TAILCALL))) {
3320 CC_SET_FASTPATH(cc, vm_call_iseq_setup_normal_opt_start,
3321 !IS_ARGS_SPLAT(ci) && !IS_ARGS_KEYWORD(ci) &&
3322 vm_call_cacheable(ci, cc));
3323 }
3324 else {
3325 CC_SET_FASTPATH(cc, vm_call_iseq_setup_tailcall_opt_start,
3326 !IS_ARGS_SPLAT(ci) && !IS_ARGS_KEYWORD(ci) &&
3327 vm_call_cacheable(ci, cc));
3328 }
3329
3330 /* initialize opt vars for self-references */
3331 VM_ASSERT((int)ISEQ_BODY(iseq)->param.size == lead_num + opt_num);
3332 for (int i=argc; i<lead_num + opt_num; i++) {
3333 argv[i] = Qnil;
3334 }
3335 return (int)ISEQ_BODY(iseq)->param.opt_table[opt];
3336 }
3337 else if (rb_iseq_only_kwparam_p(iseq) && !IS_ARGS_SPLAT(ci)) {
3338 const int lead_num = ISEQ_BODY(iseq)->param.lead_num;
3339 const int argc = calling->argc;
3340 const struct rb_iseq_param_keyword *kw_param = ISEQ_BODY(iseq)->param.keyword;
3341
3342 if (vm_ci_flag(ci) & VM_CALL_KWARG) {
3343 const struct rb_callinfo_kwarg *kw_arg = vm_ci_kwarg(ci);
3344
3345 if (argc - kw_arg->keyword_len == lead_num) {
3346 const int ci_kw_len = kw_arg->keyword_len;
3347 const VALUE * const ci_keywords = kw_arg->keywords;
3348 VALUE * const ci_kws = ALLOCA_N(VALUE, ci_kw_len);
3349 MEMCPY(ci_kws, argv + lead_num, VALUE, ci_kw_len);
3350
3351 VALUE *const klocals = argv + kw_param->bits_start - kw_param->num;
3352 args_setup_kw_parameters(ec, iseq, vm_cc_cme(cc), ci_kws, ci_kw_len, ci_keywords, klocals);
3353
3354 CC_SET_FASTPATH(cc, vm_call_iseq_setup_kwparm_kwarg,
3355 vm_call_cacheable(ci, cc));
3356
3357 return 0;
3358 }
3359 }
3360 else if (argc == lead_num) {
3361 /* no kwarg */
3362 VALUE *const klocals = argv + kw_param->bits_start - kw_param->num;
3363 args_setup_kw_parameters(ec, iseq, vm_cc_cme(cc), NULL, 0, NULL, klocals);
3364
3365 if (klocals[kw_param->num] == INT2FIX(0)) {
3366 /* copy from default_values */
3367 CC_SET_FASTPATH(cc, vm_call_iseq_setup_kwparm_nokwarg,
3368 vm_call_cacheable(ci, cc));
3369 }
3370
3371 return 0;
3372 }
3373 }
3374 }
3375
3376 // Called iseq is using ... param
3377 // def foo(...) # <- iseq for foo will have "forwardable"
3378 //
3379 // We want to set the `...` local to the caller's CI
3380 // foo(1, 2) # <- the ci for this should end up as `...`
3381 //
3382 // So hopefully the stack looks like:
3383 //
3384 // => 1
3385 // => 2
3386 // => *
3387 // => **
3388 // => &
3389 // => ... # <- points at `foo`s CI
3390 // => cref_or_me
3391 // => specval
3392 // => type
3393 //
3394 if (ISEQ_BODY(iseq)->param.flags.forwardable) {
3395 bool can_fastpath = true;
3396
3397 if ((vm_ci_flag(ci) & VM_CALL_FORWARDING)) {
3398 struct rb_forwarding_call_data * forward_cd = (struct rb_forwarding_call_data *)calling->cd;
3399 if (vm_ci_argc(ci) != vm_ci_argc(forward_cd->caller_ci)) {
3400 ci = vm_ci_new_runtime(
3401 vm_ci_mid(ci),
3402 vm_ci_flag(ci),
3403 vm_ci_argc(ci),
3404 vm_ci_kwarg(ci));
3405 }
3406 else {
3407 ci = forward_cd->caller_ci;
3408 }
3409 can_fastpath = false;
3410 }
3411 // C functions calling iseqs will stack allocate a CI,
3412 // so we need to convert it to heap allocated
3413 if (!vm_ci_markable(ci)) {
3414 ci = vm_ci_new_runtime(
3415 vm_ci_mid(ci),
3416 vm_ci_flag(ci),
3417 vm_ci_argc(ci),
3418 vm_ci_kwarg(ci));
3419 can_fastpath = false;
3420 }
3421 argv[param_size - 1] = (VALUE)ci;
3422 CC_SET_FASTPATH(cc, vm_call_iseq_forwardable, can_fastpath);
3423 return 0;
3424 }
3425
3426 return setup_parameters_complex(ec, iseq, calling, ci, argv, arg_setup_method);
3427}
3428
3429static void
3430vm_adjust_stack_forwarding(const struct rb_execution_context_struct *ec, struct rb_control_frame_struct *cfp, int argc, VALUE splat)
3431{
3432 // This case is when the caller is using a ... parameter.
3433 // For example `bar(...)`. The call info will have VM_CALL_FORWARDING
3434 // In this case the caller's caller's CI will be on the stack.
3435 //
3436 // For example:
3437 //
3438 // def bar(a, b); a + b; end
3439 // def foo(...); bar(...); end
3440 // foo(1, 2) # <- this CI will be on the stack when we call `bar(...)`
3441 //
3442 // Stack layout will be:
3443 //
3444 // > 1
3445 // > 2
3446 // > CI for foo(1, 2)
3447 // > cref_or_me
3448 // > specval
3449 // > type
3450 // > receiver
3451 // > CI for foo(1, 2), via `getlocal ...`
3452 // > ( SP points here )
3453 const VALUE * lep = VM_CF_LEP(cfp);
3454
3455 const rb_iseq_t *iseq;
3456
3457 // If we're in an escaped environment (lambda for example), get the iseq
3458 // from the captured env.
3459 if (VM_ENV_FLAGS(lep, VM_ENV_FLAG_ESCAPED)) {
3460 rb_env_t * env = (rb_env_t *)lep[VM_ENV_DATA_INDEX_ENV];
3461 iseq = env->iseq;
3462 }
3463 else { // Otherwise use the lep to find the caller
3464 iseq = CFP_ISEQ(rb_vm_search_cf_from_ep(ec, cfp, lep));
3465 }
3466
3467 // Our local storage is below the args we need to copy
3468 int local_size = ISEQ_BODY(iseq)->local_table_size + argc;
3469
3470 const VALUE * from = lep - (local_size + VM_ENV_DATA_SIZE - 1); // 2 for EP values
3471 VALUE * to = cfp->sp - 1; // clobber the CI
3472
3473 if (RTEST(splat)) {
3474 to -= 1; // clobber the splat array
3475 CHECK_VM_STACK_OVERFLOW0(cfp, to, RARRAY_LEN(splat));
3476 MEMCPY(to, RARRAY_CONST_PTR(splat), VALUE, RARRAY_LEN(splat));
3477 to += RARRAY_LEN(splat);
3478 }
3479
3480 CHECK_VM_STACK_OVERFLOW0(cfp, to, argc);
3481 MEMCPY(to, from, VALUE, argc);
3482 cfp->sp = to + argc;
3483
3484 // Stack layout should now be:
3485 //
3486 // > 1
3487 // > 2
3488 // > CI for foo(1, 2)
3489 // > cref_or_me
3490 // > specval
3491 // > type
3492 // > receiver
3493 // > 1
3494 // > 2
3495 // > ( SP points here )
3496}
3497
3498static VALUE
3499vm_call_iseq_setup(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling)
3500{
3501 RB_DEBUG_COUNTER_INC(ccf_iseq_setup);
3502
3503 const struct rb_callcache *cc = calling->cc;
3504 const rb_iseq_t *iseq = def_iseq_ptr(vm_cc_cme(cc)->def);
3505 unsigned int param_size = ISEQ_BODY(iseq)->param.size;
3506 unsigned int local_size = ISEQ_BODY(iseq)->local_table_size;
3507
3508 RUBY_ASSERT(!ISEQ_BODY(iseq)->param.flags.forwardable);
3509
3510 const int opt_pc = vm_callee_setup_arg(ec, calling, iseq, cfp->sp - calling->argc, param_size, local_size);
3511 return vm_call_iseq_setup_2(ec, cfp, calling, opt_pc, param_size, local_size);
3512}
3513
3514static VALUE
3515vm_call_iseq_fwd_setup(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling)
3516{
3517 RB_DEBUG_COUNTER_INC(ccf_iseq_setup);
3518
3519 const struct rb_callcache *cc = calling->cc;
3520 const rb_iseq_t *iseq = def_iseq_ptr(vm_cc_cme(cc)->def);
3521 unsigned int param_size = ISEQ_BODY(iseq)->param.size;
3522 unsigned int local_size = ISEQ_BODY(iseq)->local_table_size;
3523
3524 RUBY_ASSERT(ISEQ_BODY(iseq)->param.flags.forwardable);
3525
3526 // Setting up local size and param size
3527 local_size = local_size + vm_ci_argc(calling->cd->ci);
3528 param_size = param_size + vm_ci_argc(calling->cd->ci);
3529
3530 const int opt_pc = vm_callee_setup_arg(ec, calling, iseq, cfp->sp - calling->argc, param_size, local_size);
3531 return vm_call_iseq_setup_2(ec, cfp, calling, opt_pc, param_size, local_size);
3532}
3533
3534static inline VALUE
3535vm_call_iseq_setup_2(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling,
3536 int opt_pc, unsigned int param_size, unsigned int local_size)
3537{
3538 const struct rb_callinfo *ci = calling->cd->ci;
3539 const struct rb_callcache *cc = calling->cc;
3540
3541 if (LIKELY(!(vm_ci_flag(ci) & VM_CALL_TAILCALL))) {
3542 return vm_call_iseq_setup_normal(ec, cfp, calling, vm_cc_cme(cc), opt_pc, param_size, local_size);
3543 }
3544 else {
3545 return vm_call_iseq_setup_tailcall(ec, cfp, calling, opt_pc, param_size, local_size);
3546 }
3547}
3548
3549static inline VALUE
3550vm_call_iseq_setup_normal(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling, const rb_callable_method_entry_t *me,
3551 int opt_pc, int param_size, int local_size)
3552{
3553 const rb_iseq_t *iseq = def_iseq_ptr(me->def);
3554 VALUE *argv = cfp->sp - calling->argc;
3555 VALUE *sp = argv + param_size;
3556 cfp->sp = argv - 1 /* recv */;
3557
3558 vm_push_frame(ec, iseq, VM_FRAME_MAGIC_METHOD | VM_ENV_FLAG_LOCAL, calling->recv,
3559 calling->block_handler, (VALUE)me,
3560 ISEQ_BODY(iseq)->iseq_encoded + opt_pc, sp,
3561 local_size - param_size,
3562 ISEQ_BODY(iseq)->stack_max);
3563 return Qundef;
3564}
3565
3566static inline VALUE
3567vm_call_iseq_setup_tailcall(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling,
3568 int opt_pc, unsigned int param_size, unsigned int local_size)
3569{
3570 const struct rb_callcache *cc = calling->cc;
3571 VALUE *argv = cfp->sp - calling->argc;
3572 const rb_callable_method_entry_t *me = vm_cc_cme(cc);
3573 const rb_iseq_t *iseq = def_iseq_ptr(me->def);
3574 VALUE *src_argv = argv;
3575 VALUE *sp_orig, *sp;
3576 VALUE finish_flag = VM_FRAME_FINISHED_P(cfp) ? VM_FRAME_FLAG_FINISH : 0;
3577
3578 if (VM_BH_FROM_CFP_P(calling->block_handler, cfp)) {
3579 struct rb_captured_block *dst_captured = VM_CFP_TO_CAPTURED_BLOCK(RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp));
3580 const struct rb_captured_block *src_captured = VM_BH_TO_CAPT_BLOCK(calling->block_handler);
3581 dst_captured->code.val = src_captured->code.val;
3582 if (VM_BH_ISEQ_BLOCK_P(calling->block_handler)) {
3583 calling->block_handler = VM_BH_FROM_ISEQ_BLOCK(dst_captured);
3584 }
3585 else {
3586 calling->block_handler = VM_BH_FROM_IFUNC_BLOCK(dst_captured);
3587 }
3588 }
3589
3590 vm_pop_frame(ec, cfp, cfp->ep);
3591 cfp = ec->cfp;
3592
3593 sp_orig = sp = cfp->sp;
3594
3595 /* push self */
3596 sp[0] = calling->recv;
3597 sp++;
3598
3599 /* copy arguments */
3600 for (unsigned int i = 0; i < param_size; i++) {
3601 *sp++ = src_argv[i];
3602 }
3603
3604 vm_push_frame(ec, iseq, VM_FRAME_MAGIC_METHOD | VM_ENV_FLAG_LOCAL | finish_flag,
3605 calling->recv, calling->block_handler, (VALUE)me,
3606 ISEQ_BODY(iseq)->iseq_encoded + opt_pc, sp,
3607 local_size - param_size,
3608 ISEQ_BODY(iseq)->stack_max);
3609
3610 cfp->sp = sp_orig;
3611
3612 return Qundef;
3613}
3614
3615static void
3616ractor_unsafe_check(void)
3617{
3618 if (!rb_ractor_main_p()) {
3619 rb_raise(rb_eRactorUnsafeError, "ractor unsafe method called from not main ractor");
3620 }
3621}
3622
3623static VALUE
3624call_cfunc_m2(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3625{
3626 ractor_unsafe_check();
3627 VALUE(*f)(VALUE, VALUE) = (VALUE(*)(VALUE, VALUE))func;
3628 return (*f)(recv, rb_ary_new4(argc, argv));
3629}
3630
3631static VALUE
3632call_cfunc_m1(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3633{
3634 ractor_unsafe_check();
3635 VALUE(*f)(int, const VALUE *, VALUE) = (VALUE(*)(int, const VALUE *, VALUE))func;
3636 return (*f)(argc, argv, recv);
3637}
3638
3639static VALUE
3640call_cfunc_0(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3641{
3642 ractor_unsafe_check();
3643 VALUE(*f)(VALUE) = (VALUE(*)(VALUE))func;
3644 return (*f)(recv);
3645}
3646
3647static VALUE
3648call_cfunc_1(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3649{
3650 ractor_unsafe_check();
3651 VALUE(*f)(VALUE, VALUE) = (VALUE(*)(VALUE, VALUE))func;
3652 return (*f)(recv, argv[0]);
3653}
3654
3655static VALUE
3656call_cfunc_2(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3657{
3658 ractor_unsafe_check();
3659 VALUE(*f)(VALUE, VALUE, VALUE) = (VALUE(*)(VALUE, VALUE, VALUE))func;
3660 return (*f)(recv, argv[0], argv[1]);
3661}
3662
3663static VALUE
3664call_cfunc_3(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3665{
3666 ractor_unsafe_check();
3667 VALUE(*f)(VALUE, VALUE, VALUE, VALUE) = (VALUE(*)(VALUE, VALUE, VALUE, VALUE))func;
3668 return (*f)(recv, argv[0], argv[1], argv[2]);
3669}
3670
3671static VALUE
3672call_cfunc_4(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3673{
3674 ractor_unsafe_check();
3675 VALUE(*f)(VALUE, VALUE, VALUE, VALUE, VALUE) = (VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE))func;
3676 return (*f)(recv, argv[0], argv[1], argv[2], argv[3]);
3677}
3678
3679static VALUE
3680call_cfunc_5(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3681{
3682 ractor_unsafe_check();
3683 VALUE(*f)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE) = (VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE))func;
3684 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4]);
3685}
3686
3687static VALUE
3688call_cfunc_6(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3689{
3690 ractor_unsafe_check();
3692 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
3693}
3694
3695static VALUE
3696call_cfunc_7(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3697{
3698 ractor_unsafe_check();
3700 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6]);
3701}
3702
3703static VALUE
3704call_cfunc_8(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3705{
3706 ractor_unsafe_check();
3708 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7]);
3709}
3710
3711static VALUE
3712call_cfunc_9(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3713{
3714 ractor_unsafe_check();
3716 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8]);
3717}
3718
3719static VALUE
3720call_cfunc_10(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3721{
3722 ractor_unsafe_check();
3724 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9]);
3725}
3726
3727static VALUE
3728call_cfunc_11(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3729{
3730 ractor_unsafe_check();
3732 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10]);
3733}
3734
3735static VALUE
3736call_cfunc_12(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3737{
3738 ractor_unsafe_check();
3740 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10], argv[11]);
3741}
3742
3743static VALUE
3744call_cfunc_13(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3745{
3746 ractor_unsafe_check();
3748 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10], argv[11], argv[12]);
3749}
3750
3751static VALUE
3752call_cfunc_14(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3753{
3754 ractor_unsafe_check();
3756 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10], argv[11], argv[12], argv[13]);
3757}
3758
3759static VALUE
3760call_cfunc_15(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3761{
3762 ractor_unsafe_check();
3764 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10], argv[11], argv[12], argv[13], argv[14]);
3765}
3766
3767static VALUE
3768ractor_safe_call_cfunc_m2(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3769{
3770 VALUE(*f)(VALUE, VALUE) = (VALUE(*)(VALUE, VALUE))func;
3771 return (*f)(recv, rb_ary_new4(argc, argv));
3772}
3773
3774static VALUE
3775ractor_safe_call_cfunc_m1(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3776{
3777 VALUE(*f)(int, const VALUE *, VALUE) = (VALUE(*)(int, const VALUE *, VALUE))func;
3778 return (*f)(argc, argv, recv);
3779}
3780
3781static VALUE
3782ractor_safe_call_cfunc_0(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3783{
3784 VALUE(*f)(VALUE) = (VALUE(*)(VALUE))func;
3785 return (*f)(recv);
3786}
3787
3788static VALUE
3789ractor_safe_call_cfunc_1(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3790{
3791 VALUE(*f)(VALUE, VALUE) = (VALUE(*)(VALUE, VALUE))func;
3792 return (*f)(recv, argv[0]);
3793}
3794
3795static VALUE
3796ractor_safe_call_cfunc_2(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3797{
3798 VALUE(*f)(VALUE, VALUE, VALUE) = (VALUE(*)(VALUE, VALUE, VALUE))func;
3799 return (*f)(recv, argv[0], argv[1]);
3800}
3801
3802static VALUE
3803ractor_safe_call_cfunc_3(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3804{
3805 VALUE(*f)(VALUE, VALUE, VALUE, VALUE) = (VALUE(*)(VALUE, VALUE, VALUE, VALUE))func;
3806 return (*f)(recv, argv[0], argv[1], argv[2]);
3807}
3808
3809static VALUE
3810ractor_safe_call_cfunc_4(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3811{
3812 VALUE(*f)(VALUE, VALUE, VALUE, VALUE, VALUE) = (VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE))func;
3813 return (*f)(recv, argv[0], argv[1], argv[2], argv[3]);
3814}
3815
3816static VALUE
3817ractor_safe_call_cfunc_5(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3818{
3819 VALUE(*f)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE) = (VALUE(*)(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE))func;
3820 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4]);
3821}
3822
3823static VALUE
3824ractor_safe_call_cfunc_6(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3825{
3827 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
3828}
3829
3830static VALUE
3831ractor_safe_call_cfunc_7(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3832{
3834 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6]);
3835}
3836
3837static VALUE
3838ractor_safe_call_cfunc_8(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3839{
3841 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7]);
3842}
3843
3844static VALUE
3845ractor_safe_call_cfunc_9(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3846{
3848 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8]);
3849}
3850
3851static VALUE
3852ractor_safe_call_cfunc_10(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3853{
3855 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9]);
3856}
3857
3858static VALUE
3859ractor_safe_call_cfunc_11(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3860{
3862 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10]);
3863}
3864
3865static VALUE
3866ractor_safe_call_cfunc_12(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3867{
3869 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10], argv[11]);
3870}
3871
3872static VALUE
3873ractor_safe_call_cfunc_13(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3874{
3876 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10], argv[11], argv[12]);
3877}
3878
3879static VALUE
3880ractor_safe_call_cfunc_14(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3881{
3883 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10], argv[11], argv[12], argv[13]);
3884}
3885
3886static VALUE
3887ractor_safe_call_cfunc_15(VALUE recv, int argc, const VALUE *argv, VALUE (*func)(ANYARGS))
3888{
3890 return (*f)(recv, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10], argv[11], argv[12], argv[13], argv[14]);
3891}
3892
3893static inline int
3894vm_cfp_consistent_p(rb_execution_context_t *ec, const rb_control_frame_t *reg_cfp)
3895{
3896 const int ov_flags = RAISED_STACKOVERFLOW;
3897 if (LIKELY(reg_cfp == ec->cfp + 1)) return TRUE;
3898 if (rb_ec_raised_p(ec, ov_flags)) {
3899 rb_ec_raised_reset(ec, ov_flags);
3900 return TRUE;
3901 }
3902 return FALSE;
3903}
3904
3905#define CHECK_CFP_CONSISTENCY(func) \
3906 (LIKELY(vm_cfp_consistent_p(ec, reg_cfp)) ? (void)0 : \
3907 rb_bug(func ": cfp consistency error (%p, %p)", (void *)reg_cfp, (void *)(ec->cfp+1)))
3908
3909static inline
3910const rb_method_cfunc_t *
3911vm_method_cfunc_entry(const rb_callable_method_entry_t *me)
3912{
3913#if VM_DEBUG_VERIFY_METHOD_CACHE
3914 switch (me->def->type) {
3915 case VM_METHOD_TYPE_CFUNC:
3916 case VM_METHOD_TYPE_NOTIMPLEMENTED:
3917 break;
3918# define METHOD_BUG(t) case VM_METHOD_TYPE_##t: rb_bug("wrong method type: " #t)
3919 METHOD_BUG(ISEQ);
3920 METHOD_BUG(ATTRSET);
3921 METHOD_BUG(IVAR);
3922 METHOD_BUG(BMETHOD);
3923 METHOD_BUG(ZSUPER);
3924 METHOD_BUG(UNDEF);
3925 METHOD_BUG(OPTIMIZED);
3926 METHOD_BUG(MISSING);
3927 METHOD_BUG(REFINED);
3928 METHOD_BUG(ALIAS);
3929# undef METHOD_BUG
3930 default:
3931 rb_bug("wrong method type: %d", me->def->type);
3932 }
3933#endif
3934 return UNALIGNED_MEMBER_PTR(me->def, body.cfunc);
3935}
3936
3937static VALUE
3938vm_call_cfunc_with_frame_(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling,
3939 int argc, VALUE *argv, VALUE *stack_bottom)
3940{
3941 RB_DEBUG_COUNTER_INC(ccf_cfunc_with_frame);
3942 const struct rb_callinfo *ci = calling->cd->ci;
3943 const struct rb_callcache *cc = calling->cc;
3944 VALUE val;
3945 const rb_callable_method_entry_t *me = vm_cc_cme(cc);
3946 const rb_method_cfunc_t *cfunc = vm_method_cfunc_entry(me);
3947
3948 VALUE recv = calling->recv;
3949 VALUE block_handler = calling->block_handler;
3950 VALUE frame_type = VM_FRAME_MAGIC_CFUNC | VM_FRAME_FLAG_CFRAME | VM_ENV_FLAG_LOCAL;
3951
3952 if (UNLIKELY(calling->kw_splat)) {
3953 frame_type |= VM_FRAME_FLAG_CFRAME_KW;
3954 }
3955
3956 VM_ASSERT(reg_cfp == ec->cfp);
3957
3958 RUBY_DTRACE_CMETHOD_ENTRY_HOOK(ec, me->owner, me->def->original_id);
3959 EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_CALL, recv, me->def->original_id, vm_ci_mid(ci), me->owner, Qundef);
3960
3961 vm_push_frame(ec, NULL, frame_type, recv,
3962 block_handler, (VALUE)me,
3963 0, ec->cfp->sp, 0, 0);
3964
3965 int len = cfunc->argc;
3966 if (len >= 0) rb_check_arity(argc, len, len);
3967
3968 reg_cfp->sp = stack_bottom;
3969 val = (*cfunc->invoker)(recv, argc, argv, cfunc->func);
3970
3971 CHECK_CFP_CONSISTENCY("vm_call_cfunc");
3972
3973 rb_vm_pop_frame(ec);
3974
3975 VM_ASSERT(ec->cfp->sp == stack_bottom);
3976
3977 EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_RETURN, recv, me->def->original_id, vm_ci_mid(ci), me->owner, val);
3978 RUBY_DTRACE_CMETHOD_RETURN_HOOK(ec, me->owner, me->def->original_id);
3979
3980 return val;
3981}
3982
3983// Push a C method frame for a given cme. This is called when JIT code skipped
3984// pushing a frame but the C method reached a point where a frame is needed.
3985void
3986rb_vm_push_cfunc_frame(const rb_callable_method_entry_t *cme, int recv_idx)
3987{
3988 VM_ASSERT(cme->def->type == VM_METHOD_TYPE_CFUNC);
3989 rb_execution_context_t *ec = GET_EC();
3990 VALUE *sp = ec->cfp->sp;
3991 VALUE recv = *(sp - recv_idx - 1);
3992 VALUE frame_type = VM_FRAME_MAGIC_CFUNC | VM_FRAME_FLAG_CFRAME | VM_ENV_FLAG_LOCAL;
3993 VALUE block_handler = VM_BLOCK_HANDLER_NONE;
3994#if VM_CHECK_MODE > 0
3995 // Clean up the stack canary since we're about to satisfy the "leaf or lazy push" assumption
3996 *(GET_EC()->cfp->sp) = Qfalse;
3997#endif
3998 vm_push_frame(ec, NULL, frame_type, recv, block_handler, (VALUE)cme, 0, ec->cfp->sp, 0, 0);
3999}
4000
4001// If true, cc->call needs to include `CALLER_SETUP_ARG` (i.e. can't be skipped in fastpath)
4002bool
4003rb_splat_or_kwargs_p(const struct rb_callinfo *restrict ci)
4004{
4005 return IS_ARGS_SPLAT(ci) || IS_ARGS_KW_OR_KW_SPLAT(ci);
4006}
4007
4008static VALUE
4009vm_call_get_kwarg(rb_control_frame_t *reg_cfp, CALL_DATA cd, ID kw)
4010{
4011
4012 VALUE sym = ID2SYM(kw);
4013 if (vm_ci_flag(cd->ci) & VM_CALL_KW_SPLAT) {
4014 VALUE keywords = TOPN(0);
4015 if (UNLIKELY(!RB_TYPE_P(keywords, T_HASH))) {
4016 TOPN(0) = keywords = rb_to_hash_type(keywords);
4017 }
4018 return rb_hash_lookup2(keywords, sym, Qundef);
4019 }
4020 else {
4021 const struct rb_callinfo_kwarg *kwarg = vm_ci_kwarg(cd->ci);
4022 if (kwarg) {
4023 for (int index = 0; index < kwarg->keyword_len; index++) {
4024 if (kwarg->keywords[index] == sym) {
4025 return TOPN(kwarg->keyword_len - index - 1);
4026 }
4027 }
4028 }
4029 }
4030 return Qundef;
4031}
4032
4033static VALUE
4034vm_call_cfunc_with_frame(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling)
4035{
4036 int argc = calling->argc;
4037 VALUE *stack_bottom = reg_cfp->sp - argc - 1;
4038 VALUE *argv = &stack_bottom[1];
4039
4040 return vm_call_cfunc_with_frame_(ec, reg_cfp, calling, argc, argv, stack_bottom);
4041}
4042
4043static VALUE
4044vm_call_cfunc_other(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling)
4045{
4046 const struct rb_callinfo *ci = calling->cd->ci;
4047 RB_DEBUG_COUNTER_INC(ccf_cfunc_other);
4048
4049 CALLER_SETUP_ARG(reg_cfp, calling, ci, ALLOW_HEAP_ARGV_KEEP_KWSPLAT);
4050 VALUE argv_ary;
4051 if (UNLIKELY(argv_ary = calling->heap_argv)) {
4052 VM_ASSERT(!IS_ARGS_KEYWORD(ci));
4053 int argc = RARRAY_LENINT(argv_ary);
4054 VALUE *argv = (VALUE *)RARRAY_CONST_PTR(argv_ary);
4055 VALUE *stack_bottom = reg_cfp->sp - 2;
4056
4057 VM_ASSERT(calling->argc == 1);
4058 VM_ASSERT(RB_TYPE_P(argv_ary, T_ARRAY));
4059 VM_ASSERT(RBASIC_CLASS(argv_ary) == 0); // hidden ary
4060
4061 return vm_call_cfunc_with_frame_(ec, reg_cfp, calling, argc, argv, stack_bottom);
4062 }
4063 else {
4064 CC_SET_FASTPATH(calling->cc, vm_call_cfunc_with_frame, !rb_splat_or_kwargs_p(ci) && !calling->kw_splat && !(vm_ci_flag(ci) & VM_CALL_FORWARDING));
4065
4066 return vm_call_cfunc_with_frame(ec, reg_cfp, calling);
4067 }
4068}
4069
4070static inline VALUE
4071vm_call_cfunc_array_argv(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling, int stack_offset, int argc_offset)
4072{
4073 VALUE argv_ary = reg_cfp->sp[-1 - stack_offset];
4074 int argc = RARRAY_LENINT(argv_ary) - argc_offset;
4075
4076 if (UNLIKELY(argc > VM_ARGC_STACK_MAX)) {
4077 return vm_call_cfunc_other(ec, reg_cfp, calling);
4078 }
4079
4080 VALUE *argv = (VALUE *)RARRAY_CONST_PTR(argv_ary);
4081 calling->kw_splat = 0;
4082 int i;
4083 VALUE *stack_bottom = reg_cfp->sp - 2 - stack_offset;
4084 VALUE *sp = stack_bottom;
4085 CHECK_VM_STACK_OVERFLOW(reg_cfp, argc);
4086 for(i = 0; i < argc; i++) {
4087 *++sp = argv[i];
4088 }
4089 reg_cfp->sp = sp+1;
4090
4091 return vm_call_cfunc_with_frame_(ec, reg_cfp, calling, argc, stack_bottom+1, stack_bottom);
4092}
4093
4094static inline VALUE
4095vm_call_cfunc_only_splat(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling)
4096{
4097 RB_DEBUG_COUNTER_INC(ccf_cfunc_only_splat);
4098 VALUE argv_ary = reg_cfp->sp[-1];
4099 int argc = RARRAY_LENINT(argv_ary);
4100 VALUE *argv = (VALUE *)RARRAY_CONST_PTR(argv_ary);
4101 VALUE last_hash;
4102 int argc_offset = 0;
4103
4104 if (UNLIKELY(argc > 0 &&
4105 RB_TYPE_P((last_hash = argv[argc-1]), T_HASH) &&
4106 (((struct RHash *)last_hash)->basic.flags & RHASH_PASS_AS_KEYWORDS))) {
4107 if (!RHASH_EMPTY_P(last_hash)) {
4108 return vm_call_cfunc_other(ec, reg_cfp, calling);
4109 }
4110 argc_offset++;
4111 }
4112 return vm_call_cfunc_array_argv(ec, reg_cfp, calling, 0, argc_offset);
4113}
4114
4115static inline VALUE
4116vm_call_cfunc_only_splat_kw(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling)
4117{
4118 RB_DEBUG_COUNTER_INC(ccf_cfunc_only_splat_kw);
4119 VALUE keyword_hash = reg_cfp->sp[-1];
4120
4121 if (keyword_hash == Qnil || (RB_TYPE_P(keyword_hash, T_HASH) && RHASH_EMPTY_P(keyword_hash))) {
4122 return vm_call_cfunc_array_argv(ec, reg_cfp, calling, 1, 0);
4123 }
4124
4125 return vm_call_cfunc_other(ec, reg_cfp, calling);
4126}
4127
4128static VALUE
4129vm_call_cfunc(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling)
4130{
4131 const struct rb_callinfo *ci = calling->cd->ci;
4132 RB_DEBUG_COUNTER_INC(ccf_cfunc);
4133
4134 if (IS_ARGS_SPLAT(ci) && !(vm_ci_flag(ci) & VM_CALL_FORWARDING)) {
4135 if (!IS_ARGS_KW_SPLAT(ci) && vm_ci_argc(ci) == 1) {
4136 // f(*a)
4137 CC_SET_FASTPATH(calling->cc, vm_call_cfunc_only_splat, TRUE);
4138 return vm_call_cfunc_only_splat(ec, reg_cfp, calling);
4139 }
4140 if (IS_ARGS_KW_SPLAT(ci) && vm_ci_argc(ci) == 2) {
4141 // f(*a, **kw)
4142 CC_SET_FASTPATH(calling->cc, vm_call_cfunc_only_splat_kw, TRUE);
4143 return vm_call_cfunc_only_splat_kw(ec, reg_cfp, calling);
4144 }
4145 }
4146
4147 CC_SET_FASTPATH(calling->cc, vm_call_cfunc_other, TRUE);
4148 return vm_call_cfunc_other(ec, reg_cfp, calling);
4149}
4150
4151static VALUE
4152vm_call_ivar(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling)
4153{
4154 const struct rb_callcache *cc = calling->cc;
4155 RB_DEBUG_COUNTER_INC(ccf_ivar);
4156 cfp->sp -= 1;
4157 VALUE ivar = vm_getivar(calling->recv, vm_cc_cme(cc)->def->body.attr.id, NULL, NULL, cc, TRUE, Qnil);
4158 return ivar;
4159}
4160
4161static VALUE
4162vm_call_attrset_direct(rb_execution_context_t *ec, rb_control_frame_t *cfp, const struct rb_callcache *cc, VALUE obj)
4163{
4164 RB_DEBUG_COUNTER_INC(ccf_attrset);
4165 VALUE val = *(cfp->sp - 1);
4166 cfp->sp -= 2;
4167 rb_setivar_cache cache = rb_setivar_cache_unpack(vm_cc_atomic_cache_read(cc));
4168 ID id = vm_cc_cme(cc)->def->body.attr.id;
4169 rb_check_frozen(obj);
4170 VALUE res = vm_setivar(obj, val, cache);
4171 if (UNDEF_P(res)) {
4172 switch (BUILTIN_TYPE(obj)) {
4173 case T_OBJECT:
4174 break;
4175 case T_CLASS:
4176 case T_MODULE:
4177 {
4178 res = vm_setivar_class(obj, val, cache);
4179 if (!UNDEF_P(res)) {
4180 return res;
4181 }
4182 }
4183 break;
4184 default:
4185 {
4186 res = vm_setivar_default(obj, id, val, cache);
4187 if (!UNDEF_P(res)) {
4188 return res;
4189 }
4190 }
4191 }
4192 res = vm_setivar_slowpath_attr(obj, id, val, cc);
4193 }
4194 return res;
4195}
4196
4197static VALUE
4198vm_call_attrset(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling)
4199{
4200 return vm_call_attrset_direct(ec, cfp, calling->cc, calling->recv);
4201}
4202
4203static inline VALUE
4204vm_call_bmethod_body(rb_execution_context_t *ec, struct rb_calling_info *calling, const VALUE *argv)
4205{
4206 rb_proc_t *proc;
4207 VALUE val;
4208 const struct rb_callcache *cc = calling->cc;
4209 const rb_callable_method_entry_t *cme = vm_cc_cme(cc);
4210 VALUE procv = cme->def->body.bmethod.proc;
4211
4212 if (!RB_OBJ_SHAREABLE_P(procv) &&
4213 cme->def->body.bmethod.defined_ractor_id != rb_ec_ractor_id(ec)) {
4214 rb_raise(rb_eRuntimeError, "defined with an un-shareable Proc in a different Ractor");
4215 }
4216
4217 /* control block frame */
4218 GetProcPtr(procv, proc);
4219 val = vm_invoke_bmethod(ec, proc, calling->recv, CALLING_ARGC(calling), argv, calling->kw_splat, calling->block_handler, vm_cc_cme(cc));
4220
4221 return val;
4222}
4223
4224static int vm_callee_setup_block_arg(rb_execution_context_t *ec, struct rb_calling_info *calling, const struct rb_callinfo *ci, const rb_iseq_t *iseq, VALUE *argv, const enum arg_setup_type arg_setup_type);
4225
4226static VALUE
4227vm_call_iseq_bmethod(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling)
4228{
4229 RB_DEBUG_COUNTER_INC(ccf_iseq_bmethod);
4230
4231 const struct rb_callcache *cc = calling->cc;
4232 const rb_callable_method_entry_t *cme = vm_cc_cme(cc);
4233 VALUE procv = cme->def->body.bmethod.proc;
4234
4235 if (!RB_OBJ_SHAREABLE_P(procv) &&
4236 cme->def->body.bmethod.defined_ractor_id != rb_ec_ractor_id(ec)) {
4237 rb_raise(rb_eRuntimeError, "defined with an un-shareable Proc in a different Ractor");
4238 }
4239
4240 rb_proc_t *proc;
4241 GetProcPtr(procv, proc);
4242 const struct rb_block *block = &proc->block;
4243
4244 while (vm_block_type(block) == block_type_proc) {
4245 block = vm_proc_block(block->as.proc);
4246 }
4247 VM_ASSERT(vm_block_type(block) == block_type_iseq);
4248
4249 const struct rb_captured_block *captured = &block->as.captured;
4250 const rb_iseq_t *iseq = rb_iseq_check(captured->code.iseq);
4251 VALUE * const argv = cfp->sp - calling->argc;
4252 const int arg_size = ISEQ_BODY(iseq)->param.size;
4253
4254 int opt_pc;
4255 if (vm_ci_flag(calling->cd->ci) & VM_CALL_ARGS_SIMPLE) {
4256 opt_pc = vm_callee_setup_block_arg(ec, calling, calling->cd->ci, iseq, argv, arg_setup_method);
4257 }
4258 else {
4259 opt_pc = setup_parameters_complex(ec, iseq, calling, calling->cd->ci, argv, arg_setup_method);
4260 }
4261
4262 cfp->sp = argv - 1; // -1 for the receiver
4263
4264 vm_push_frame(ec, iseq,
4265 VM_FRAME_MAGIC_BLOCK | VM_FRAME_FLAG_BMETHOD | VM_FRAME_FLAG_LAMBDA,
4266 calling->recv,
4267 VM_GUARDED_PREV_EP(captured->ep),
4268 (VALUE)cme,
4269 ISEQ_BODY(iseq)->iseq_encoded + opt_pc,
4270 argv + arg_size,
4271 ISEQ_BODY(iseq)->local_table_size - arg_size,
4272 ISEQ_BODY(iseq)->stack_max);
4273
4274 return Qundef;
4275}
4276
4277static VALUE
4278vm_call_noniseq_bmethod(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling)
4279{
4280 RB_DEBUG_COUNTER_INC(ccf_noniseq_bmethod);
4281
4282 VALUE *argv;
4283 int argc;
4284 CALLER_SETUP_ARG(cfp, calling, calling->cd->ci, ALLOW_HEAP_ARGV);
4285 if (UNLIKELY(calling->heap_argv)) {
4286 argv = RARRAY_PTR(calling->heap_argv);
4287 cfp->sp -= 2;
4288 }
4289 else {
4290 argc = calling->argc;
4291 argv = ALLOCA_N(VALUE, argc);
4292 MEMCPY(argv, cfp->sp - argc, VALUE, argc);
4293 cfp->sp += - argc - 1;
4294 }
4295
4296 return vm_call_bmethod_body(ec, calling, argv);
4297}
4298
4299static VALUE
4300vm_call_bmethod(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling)
4301{
4302 RB_DEBUG_COUNTER_INC(ccf_bmethod);
4303
4304 const struct rb_callcache *cc = calling->cc;
4305 const rb_callable_method_entry_t *cme = vm_cc_cme(cc);
4306 VALUE procv = cme->def->body.bmethod.proc;
4307 rb_proc_t *proc;
4308 GetProcPtr(procv, proc);
4309 const struct rb_block *block = &proc->block;
4310
4311 while (vm_block_type(block) == block_type_proc) {
4312 block = vm_proc_block(block->as.proc);
4313 }
4314 if (vm_block_type(block) == block_type_iseq) {
4315 CC_SET_FASTPATH(cc, vm_call_iseq_bmethod, TRUE);
4316 return vm_call_iseq_bmethod(ec, cfp, calling);
4317 }
4318
4319 CC_SET_FASTPATH(cc, vm_call_noniseq_bmethod, TRUE);
4320 return vm_call_noniseq_bmethod(ec, cfp, calling);
4321}
4322
4323VALUE
4324rb_find_defined_class_by_owner(VALUE current_class, VALUE target_owner)
4325{
4326 VALUE klass = current_class;
4327
4328 /* for prepended Module, then start from cover class */
4329 if (RB_TYPE_P(klass, T_ICLASS) && RICLASS_IS_ORIGIN_P(klass) &&
4330 RB_TYPE_P(RBASIC_CLASS(klass), T_CLASS)) {
4331 klass = RBASIC_CLASS(klass);
4332 }
4333
4334 while (RTEST(klass)) {
4335 VALUE owner = RB_TYPE_P(klass, T_ICLASS) ? RBASIC_CLASS(klass) : klass;
4336 if (owner == target_owner) {
4337 return klass;
4338 }
4339 klass = RCLASS_SUPER(klass);
4340 }
4341
4342 return current_class; /* maybe module function */
4343}
4344
4345static const rb_callable_method_entry_t *
4346aliased_callable_method_entry(const rb_callable_method_entry_t *me)
4347{
4348 const rb_method_entry_t *orig_me =
4349 rb_method_alias_original_me(rb_method_entry_def_acquire((const rb_method_entry_t *)me));
4350 const rb_callable_method_entry_t *cme = NULL;
4351
4352 if (orig_me->defined_class == 0) { // only true on first resolution
4353 // Resolving the alias mutates `me` (and may replace me->def, dropping a
4354 // reference to the shared definition), so it has to be serialized. Two
4355 // ractors calling the same aliased method would otherwise both release
4356 // the same definition which could result in a UAF.
4357 RB_VM_LOCKING() {
4358 orig_me = me->def->body.alias.original_me;
4359 // me is the ALIAS me. It has a def that's different from orig_me->def.
4360 if (orig_me->defined_class == 0) {
4361 // orig_me is the unresolved me clone that rb_add_alias stored.
4362 VALUE defined_class = rb_find_defined_class_by_owner(me->defined_class, orig_me->owner);
4363 VM_ASSERT_TYPE(orig_me->owner, T_MODULE);
4364 cme = rb_method_entry_complement_defined_class(orig_me, me->called_id, defined_class);
4365
4366 if (me->def->reference_count == 1) {
4367 rbimpl_atomic_ptr_store((volatile void **)&me->def->body.alias.original_me,
4368 (void *)cme, RBIMPL_ATOMIC_RELEASE);
4369 RB_OBJ_WRITTEN(me, Qundef, cme);
4370 }
4371 else {
4372 rb_method_definition_t *def =
4373 rb_method_definition_create(VM_METHOD_TYPE_ALIAS, me->def->original_id);
4374 def->body.alias.original_me = (rb_method_entry_t *)cme;
4375 def->original_module = cme->def->original_module;
4376 rb_method_definition_set((rb_method_entry_t *)me, def, NULL);
4377 RB_OBJ_WRITTEN(me, Qundef, cme);
4378 RB_OBJ_WRITTEN(me, Qundef, def->original_module);
4379 }
4380 }
4381 else {
4382 cme = (const rb_callable_method_entry_t *)orig_me;
4383 }
4384 }
4385 }
4386 else {
4387 cme = (const rb_callable_method_entry_t *)orig_me;
4388 }
4389
4390 VM_ASSERT(callable_method_entry_p(cme));
4391 return cme;
4392}
4393
4394const rb_callable_method_entry_t *
4395rb_aliased_callable_method_entry(const rb_callable_method_entry_t *me)
4396{
4397 return aliased_callable_method_entry(me);
4398}
4399
4400static VALUE
4401vm_call_alias(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling)
4402{
4403 calling->cc = &VM_CC_ON_STACK(Qundef,
4404 vm_call_general,
4405 {{0}},
4406 aliased_callable_method_entry(vm_cc_cme(calling->cc)));
4407
4408 return vm_call_method_each_type(ec, cfp, calling);
4409}
4410
4411static enum method_missing_reason
4412ci_missing_reason(const struct rb_callinfo *ci)
4413{
4414 enum method_missing_reason stat = MISSING_NOENTRY;
4415 if (vm_ci_flag(ci) & VM_CALL_VCALL && !(vm_ci_flag(ci) & VM_CALL_FORWARDING)) stat |= MISSING_VCALL;
4416 if (vm_ci_flag(ci) & VM_CALL_FCALL) stat |= MISSING_FCALL;
4417 if (vm_ci_flag(ci) & VM_CALL_SUPER) stat |= MISSING_SUPER;
4418 return stat;
4419}
4420
4421static VALUE vm_call_method_missing(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling);
4422
4423static VALUE
4424vm_call_symbol(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp,
4425 struct rb_calling_info *calling, const struct rb_callinfo *ci, VALUE symbol, int flags)
4426{
4427 ASSUME(calling->argc >= 0);
4428
4429 enum method_missing_reason missing_reason = MISSING_NOENTRY;
4430 int argc = calling->argc;
4431 VALUE recv = calling->recv;
4432 VALUE klass = CLASS_OF(recv);
4433 ID mid = rb_check_id(&symbol);
4434 flags |= VM_CALL_OPT_SEND;
4435
4436 if (UNLIKELY(! mid)) {
4437 mid = idMethodMissing;
4438 missing_reason = ci_missing_reason(ci);
4439 ec->method_missing_reason = missing_reason;
4440
4441 VALUE argv_ary;
4442 if (UNLIKELY(argv_ary = calling->heap_argv)) {
4443 if (rb_method_basic_definition_p(klass, idMethodMissing)) {
4444 rb_ary_unshift(argv_ary, symbol);
4445
4446 /* Inadvertent symbol creation shall be forbidden, see [Feature #5112] */
4447 int priv = vm_ci_flag(ci) & (VM_CALL_FCALL | VM_CALL_VCALL);
4448 VALUE exc = rb_make_no_method_exception(
4449 rb_eNoMethodError, 0, recv, RARRAY_LENINT(argv_ary), RARRAY_CONST_PTR(argv_ary), priv);
4450
4451 rb_exc_raise(exc);
4452 }
4453 rb_ary_unshift(argv_ary, rb_str_intern(symbol));
4454 }
4455 else {
4456 /* E.g. when argc == 2
4457 *
4458 * | | | | TOPN
4459 * | | +------+
4460 * | | +---> | arg1 | 0
4461 * +------+ | +------+
4462 * | arg1 | -+ +-> | arg0 | 1
4463 * +------+ | +------+
4464 * | arg0 | ---+ | sym | 2
4465 * +------+ +------+
4466 * | recv | | recv | 3
4467 * --+------+--------+------+------
4468 */
4469 int i = argc;
4470 CHECK_VM_STACK_OVERFLOW(reg_cfp, 1);
4471 INC_SP(1);
4472 MEMMOVE(&TOPN(i - 1), &TOPN(i), VALUE, i);
4473 argc = ++calling->argc;
4474
4475 if (rb_method_basic_definition_p(klass, idMethodMissing)) {
4476 /* Inadvertent symbol creation shall be forbidden, see [Feature #5112] */
4477 TOPN(i) = symbol;
4478 int priv = vm_ci_flag(ci) & (VM_CALL_FCALL | VM_CALL_VCALL);
4479 const VALUE *argv = STACK_ADDR_FROM_TOP(argc);
4480 VALUE exc = rb_make_no_method_exception(
4481 rb_eNoMethodError, 0, recv, argc, argv, priv);
4482
4483 rb_exc_raise(exc);
4484 }
4485 else {
4486 TOPN(i) = rb_str_intern(symbol);
4487 }
4488 }
4489 }
4490
4491 struct rb_forwarding_call_data new_fcd = {
4492 .cd = {
4493 .ci = &VM_CI_ON_STACK(mid, flags, argc, vm_ci_kwarg(ci)),
4494 .cc = NULL,
4495 },
4496 .caller_ci = NULL,
4497 };
4498
4499 if (!(vm_ci_flag(ci) & VM_CALL_FORWARDING)) {
4500 calling->cd = &new_fcd.cd;
4501 }
4502 else {
4503 const struct rb_callinfo *caller_ci = ((struct rb_forwarding_call_data *)calling->cd)->caller_ci;
4504 VM_ASSERT((vm_ci_argc(caller_ci), 1));
4505 new_fcd.caller_ci = caller_ci;
4506 calling->cd = (struct rb_call_data *)&new_fcd;
4507 }
4508 calling->cc = &VM_CC_ON_STACK(klass,
4509 vm_call_general,
4510 { .method_missing_reason = missing_reason },
4511 rb_callable_method_entry_with_refinements(klass, mid, NULL));
4512
4513 if (flags & VM_CALL_FCALL) {
4514 return vm_call_method(ec, reg_cfp, calling);
4515 }
4516
4517 const struct rb_callcache *cc = calling->cc;
4518 VM_ASSERT(callable_method_entry_p(vm_cc_cme(cc)));
4519
4520 if (vm_cc_cme(cc) != NULL) {
4521 switch (METHOD_ENTRY_VISI(vm_cc_cme(cc))) {
4522 case METHOD_VISI_PUBLIC: /* likely */
4523 return vm_call_method_each_type(ec, reg_cfp, calling);
4524 case METHOD_VISI_PRIVATE:
4525 vm_cc_method_missing_reason_set(cc, MISSING_PRIVATE);
4526 break;
4527 case METHOD_VISI_PROTECTED:
4528 vm_cc_method_missing_reason_set(cc, MISSING_PROTECTED);
4529 break;
4530 default:
4531 VM_UNREACHABLE(vm_call_method);
4532 }
4533 return vm_call_method_missing(ec, reg_cfp, calling);
4534 }
4535
4536 return vm_call_method_nome(ec, reg_cfp, calling);
4537}
4538
4539static VALUE
4540vm_call_opt_send0(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling, int flags)
4541{
4542 const struct rb_callinfo *ci = calling->cd->ci;
4543 int i;
4544 VALUE sym;
4545
4546 i = calling->argc - 1;
4547
4548 if (calling->argc == 0) {
4549 rb_raise(rb_eArgError, "no method name given");
4550 }
4551
4552 sym = TOPN(i);
4553 /* E.g. when i == 2
4554 *
4555 * | | | | TOPN
4556 * +------+ | |
4557 * | arg1 | ---+ | | 0
4558 * +------+ | +------+
4559 * | arg0 | -+ +-> | arg1 | 1
4560 * +------+ | +------+
4561 * | sym | +---> | arg0 | 2
4562 * +------+ +------+
4563 * | recv | | recv | 3
4564 * --+------+--------+------+------
4565 */
4566 /* shift arguments */
4567 if (i > 0) {
4568 MEMMOVE(&TOPN(i), &TOPN(i-1), VALUE, i);
4569 }
4570 calling->argc -= 1;
4571 DEC_SP(1);
4572
4573 return vm_call_symbol(ec, reg_cfp, calling, ci, sym, flags);
4574}
4575
4576static VALUE
4577vm_call_opt_send_complex(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling)
4578{
4579 RB_DEBUG_COUNTER_INC(ccf_opt_send_complex);
4580 const struct rb_callinfo *ci = calling->cd->ci;
4581 int flags = VM_CALL_FCALL;
4582 VALUE sym;
4583
4584 VALUE argv_ary;
4585 CALLER_SETUP_ARG(reg_cfp, calling, ci, ALLOW_HEAP_ARGV);
4586 if (UNLIKELY(argv_ary = calling->heap_argv)) {
4587 sym = rb_ary_shift(argv_ary);
4588 flags |= VM_CALL_ARGS_SPLAT;
4589 if (calling->kw_splat) {
4590 VALUE last_hash = rb_ary_last(0, NULL, argv_ary);
4591 ((struct RHash *)last_hash)->basic.flags |= RHASH_PASS_AS_KEYWORDS;
4592 calling->kw_splat = 0;
4593 }
4594 return vm_call_symbol(ec, reg_cfp, calling, ci, sym, flags);
4595 }
4596
4597 if (calling->kw_splat) flags |= VM_CALL_KW_SPLAT;
4598 return vm_call_opt_send0(ec, reg_cfp, calling, flags);
4599}
4600
4601static VALUE
4602vm_call_opt_send_simple(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling)
4603{
4604 RB_DEBUG_COUNTER_INC(ccf_opt_send_simple);
4605 return vm_call_opt_send0(ec, reg_cfp, calling, vm_ci_flag(calling->cd->ci) | VM_CALL_FCALL);
4606}
4607
4608static VALUE
4609vm_call_opt_send(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling)
4610{
4611 RB_DEBUG_COUNTER_INC(ccf_opt_send);
4612
4613 const struct rb_callinfo *ci = calling->cd->ci;
4614 int flags = vm_ci_flag(ci);
4615
4616 if (UNLIKELY((flags & VM_CALL_FORWARDING) || (!(flags & VM_CALL_ARGS_SIMPLE) &&
4617 ((calling->argc == 1 && (flags & (VM_CALL_ARGS_SPLAT | VM_CALL_KW_SPLAT))) ||
4618 (calling->argc == 2 && (flags & VM_CALL_ARGS_SPLAT) && (flags & VM_CALL_KW_SPLAT)) ||
4619 ((flags & VM_CALL_KWARG) && (vm_ci_kwarg(ci)->keyword_len == calling->argc)))))) {
4620 CC_SET_FASTPATH(calling->cc, vm_call_opt_send_complex, TRUE);
4621 return vm_call_opt_send_complex(ec, reg_cfp, calling);
4622 }
4623
4624 CC_SET_FASTPATH(calling->cc, vm_call_opt_send_simple, TRUE);
4625 return vm_call_opt_send_simple(ec, reg_cfp, calling);
4626}
4627
4628static VALUE
4629vm_call_method_missing_body(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling,
4630 const struct rb_callinfo *orig_ci, enum method_missing_reason reason)
4631{
4632 RB_DEBUG_COUNTER_INC(ccf_method_missing);
4633
4634 VALUE *argv = STACK_ADDR_FROM_TOP(calling->argc);
4635 unsigned int argc, flag;
4636
4637 flag = VM_CALL_FCALL | VM_CALL_OPT_SEND | vm_ci_flag(orig_ci);
4638 argc = ++calling->argc;
4639
4640 /* shift arguments: m(a, b, c) #=> method_missing(:m, a, b, c) */
4641 CHECK_VM_STACK_OVERFLOW(reg_cfp, 1);
4642 vm_check_canary(ec, reg_cfp->sp);
4643 if (argc > 1) {
4644 MEMMOVE(argv+1, argv, VALUE, argc-1);
4645 }
4646 argv[0] = ID2SYM(vm_ci_mid(orig_ci));
4647 INC_SP(1);
4648
4649 ec->method_missing_reason = reason;
4650
4651 struct rb_forwarding_call_data new_fcd = {
4652 .cd = {
4653 .ci = &VM_CI_ON_STACK(idMethodMissing, flag, argc, vm_ci_kwarg(orig_ci)),
4654 .cc = NULL,
4655 },
4656 .caller_ci = NULL,
4657 };
4658
4659 if (!(flag & VM_CALL_FORWARDING)) {
4660 calling->cd = &new_fcd.cd;
4661 }
4662 else {
4663 const struct rb_callinfo *caller_ci = ((struct rb_forwarding_call_data *)calling->cd)->caller_ci;
4664 VM_ASSERT((vm_ci_argc(caller_ci), 1));
4665 new_fcd.caller_ci = caller_ci;
4666 calling->cd = (struct rb_call_data *)&new_fcd;
4667 }
4668
4669 calling->cc = &VM_CC_ON_STACK(Qundef, vm_call_general, {{ 0 }},
4670 rb_callable_method_entry_without_refinements(CLASS_OF(calling->recv), idMethodMissing, NULL));
4671 return vm_call_method(ec, reg_cfp, calling);
4672}
4673
4674static VALUE
4675vm_call_method_missing(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling)
4676{
4677 return vm_call_method_missing_body(ec, reg_cfp, calling, calling->cd->ci, vm_cc_cmethod_missing_reason(calling->cc));
4678}
4679
4680static const rb_callable_method_entry_t *refined_method_callable_without_refinement(const rb_callable_method_entry_t *me);
4681static VALUE
4682vm_call_zsuper(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling, VALUE klass)
4683{
4684 klass = RCLASS_SUPER(klass);
4685
4686 const rb_callable_method_entry_t *cme = klass ? rb_callable_method_entry(klass, vm_ci_mid(calling->cd->ci)) : NULL;
4687 if (cme == NULL) {
4688 return vm_call_method_nome(ec, cfp, calling);
4689 }
4690 if (cme->def->type == VM_METHOD_TYPE_REFINED &&
4691 cme->def->body.refined.orig_me) {
4692 cme = refined_method_callable_without_refinement(cme);
4693 }
4694
4695 calling->cc = &VM_CC_ON_STACK(Qundef, vm_call_general, {{ 0 }}, cme);
4696
4697 return vm_call_method_each_type(ec, cfp, calling);
4698}
4699
4700static inline VALUE
4701find_refinement(VALUE refinements, VALUE klass)
4702{
4703 if (NIL_P(refinements)) {
4704 return Qnil;
4705 }
4706 return rb_hash_lookup(refinements, klass);
4707}
4708
4709PUREFUNC(static rb_control_frame_t * current_method_entry(const rb_execution_context_t *ec, rb_control_frame_t *cfp));
4710static rb_control_frame_t *
4711current_method_entry(const rb_execution_context_t *ec, rb_control_frame_t *cfp)
4712{
4713 rb_control_frame_t *top_cfp = cfp;
4714
4715 if (CFP_ISEQ(cfp) && !VM_FRAME_BMETHOD_P(cfp) && ISEQ_BODY(CFP_ISEQ(cfp))->type == ISEQ_TYPE_BLOCK) {
4716 const rb_iseq_t *local_iseq = ISEQ_BODY(CFP_ISEQ(cfp))->local_iseq;
4717
4718 do {
4719 cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp);
4720 if (RUBY_VM_CONTROL_FRAME_STACK_OVERFLOW_P(ec, cfp)) {
4721 /* TODO: orphan block */
4722 return top_cfp;
4723 }
4724 } while (CFP_ISEQ(cfp) != local_iseq && !VM_FRAME_BMETHOD_P(cfp));
4725 }
4726 return cfp;
4727}
4728
4729static const rb_callable_method_entry_t *
4730refined_method_callable_without_refinement(const rb_callable_method_entry_t *me)
4731{
4732 const rb_method_entry_t *orig_me = me->def->body.refined.orig_me;
4733 const rb_callable_method_entry_t *cme;
4734
4735 if (orig_me->defined_class == 0) {
4736 cme = NULL;
4738 }
4739 else {
4740 cme = (const rb_callable_method_entry_t *)orig_me;
4741 }
4742
4743 VM_ASSERT(callable_method_entry_p(cme));
4744
4745 if (UNDEFINED_METHOD_ENTRY_P(cme)) {
4746 cme = NULL;
4747 }
4748
4749 return cme;
4750}
4751
4752// Construct correct super chain for module refinements.
4753// Each class including/prepending a module has a weak map mapping refinement
4754// iclasses to refinement module iclasses with the correct super. Like
4755// singleton classes, these are lazily initialized (both the map and
4756// the refinement module iclasses).
4757static VALUE
4758module_refinement_iclass(VALUE refinement_iclass, VALUE defined_class)
4759{
4760 VALUE module_ref_iclass = Qundef;
4761
4762 RB_VM_LOCKING() {
4763 VALUE cache = RCLASS_MODULE_REFINEMENT_ICLASSES(defined_class);
4764
4765 if (LIKELY(cache)) {
4766 module_ref_iclass = rb_wmap_lookup(cache, refinement_iclass);
4767 }
4768 else {
4769 cache = rb_wmap_new_hidden();
4770 RCLASS_SET_MODULE_REFINEMENT_ICLASSES(defined_class, cache);
4771 }
4772
4773 if (UNDEF_P(module_ref_iclass)) {
4774 VALUE super;
4775 VALUE refinement_iclass_super = RCLASS_SUPER(refinement_iclass);
4776
4777 if (RICLASS_FOR_REFINEMENT_P(refinement_iclass_super)) {
4778 super = module_refinement_iclass(refinement_iclass_super, defined_class);
4779 }
4780 else {
4781 super = defined_class;
4782 }
4783
4784 module_ref_iclass = rb_include_class_new(RBASIC(refinement_iclass)->klass, super);
4785 RCLASS_SET_REFINED_CLASS(module_ref_iclass, RCLASS_REFINED_CLASS(refinement_iclass));
4786 rb_class_subclass_add(RCLASS_REFINED_CLASS(refinement_iclass), module_ref_iclass);
4787 rb_wmap_aset(cache, refinement_iclass, module_ref_iclass);
4788 }
4789 }
4790
4791 return module_ref_iclass;
4792}
4793
4794VALUE
4795rb_vm_module_refinement_iclass(VALUE refinement_iclass, VALUE defined_class)
4796{
4797 return module_refinement_iclass(refinement_iclass, defined_class);
4798}
4799
4800static VALUE
4801refinement_iclass_for_cme(VALUE refinement_iclass, const rb_callable_method_entry_t *cme)
4802{
4803 if (RB_TYPE_P(cme->owner, T_MODULE) && RB_TYPE_P(cme->defined_class, T_ICLASS)) {
4804 refinement_iclass = module_refinement_iclass(refinement_iclass, cme->defined_class);
4805 }
4806 return refinement_iclass;
4807}
4808
4809VALUE
4810rb_vm_refinement_iclass_for_cme(VALUE refinement_iclass, const rb_callable_method_entry_t *cme)
4811{
4812 return refinement_iclass_for_cme(refinement_iclass, cme);
4813}
4814
4815static const rb_callable_method_entry_t *
4816search_refined_method(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling)
4817{
4818 const struct rb_callinfo *ci = calling->cd->ci;
4819 ID mid = vm_ci_mid(ci);
4820 // The initialize call of opt_new must behave like Class#new, which does not see the caller's refinements. [Bug #22501]
4821 const rb_cref_t *top_cref = (vm_ci_flag(ci) & VM_CALL_IGNORE_REFINEMENTS) ? NULL : vm_get_cref(cfp->ep);
4822 const struct rb_callcache * const cc = calling->cc;
4823 const rb_callable_method_entry_t *refined_cme = vm_cc_cme(cc);
4824 const rb_callable_method_entry_t *cme;
4825 bool skip_current_method = vm_cc_call(cc) == vm_call_super_method;
4826
4827 retry:
4828 cme = refined_cme;
4829
4830 for (const rb_cref_t *cref = top_cref; cref; cref = CREF_NEXT(cref)) {
4831 VALUE refinement = find_refinement(CREF_REFINEMENTS(cref), refined_cme->owner);
4832 if (NIL_P(refinement)) continue;
4833
4834 refinement = refinement_iclass_for_cme(refinement, refined_cme);
4835
4836 const rb_callable_method_entry_t *const ref_me =
4837 rb_callable_method_entry(refinement, mid);
4838
4839 if (ref_me) {
4840 if (skip_current_method) {
4841 const rb_control_frame_t *top_cfp = current_method_entry(ec, cfp);
4842 const rb_callable_method_entry_t *top_me = rb_vm_frame_method_entry(top_cfp);
4843 if (top_me && rb_method_definition_eq(ref_me->def, top_me->def)) {
4844 continue;
4845 }
4846 }
4847
4848 if (cme->def->type != VM_METHOD_TYPE_REFINED ||
4849 cme->def != ref_me->def) {
4850 cme = ref_me;
4851 }
4852 if (ref_me->def->type != VM_METHOD_TYPE_REFINED) {
4853 return cme;
4854 }
4855 }
4856 else {
4857 return NULL;
4858 }
4859 }
4860
4861 if (refined_cme->def->body.refined.orig_me) {
4862 return refined_method_callable_without_refinement(refined_cme);
4863 }
4864 else {
4865 VALUE klass = RCLASS_SUPER(refined_cme->defined_class);
4866 cme = klass ? rb_callable_method_entry(klass, mid) : NULL;
4867 if (cme && cme->def->type == VM_METHOD_TYPE_REFINED) {
4868 // Resolve it here; a second pass of vm_call_refined would cache
4869 // the result for this entry's iclass.
4870 refined_cme = cme;
4871 skip_current_method = false;
4872 goto retry;
4873 }
4874 return cme;
4875 }
4876}
4877
4878static VALUE
4879vm_call_refined(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling)
4880{
4881 const rb_callable_method_entry_t *ref_cme = search_refined_method(ec, cfp, calling);
4882
4883 if (ref_cme) {
4884 if (calling->cd->cc) {
4885 const struct rb_callcache *cc = calling->cc = vm_cc_new(vm_cc_cme(calling->cc)->defined_class, ref_cme, vm_call_general, cc_type_refinement);
4886 RB_OBJ_WRITE(CFP_ISEQ(cfp), &calling->cd->cc, cc);
4887 return vm_call_method(ec, cfp, calling);
4888 }
4889 else {
4890 struct rb_callcache *ref_cc = &VM_CC_ON_STACK(Qundef, vm_call_general, {{ 0 }}, ref_cme);
4891 calling->cc= ref_cc;
4892 return vm_call_method(ec, cfp, calling);
4893 }
4894 }
4895 else {
4896 return vm_call_method_nome(ec, cfp, calling);
4897 }
4898}
4899
4900static inline VALUE vm_invoke_block(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling, const struct rb_callinfo *ci, bool is_lambda, VALUE block_handler);
4901
4902NOINLINE(static VALUE
4903 vm_invoke_block_opt_call(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp,
4904 struct rb_calling_info *calling, const struct rb_callinfo *ci, VALUE block_handler));
4905
4906static VALUE
4907vm_invoke_block_opt_call(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp,
4908 struct rb_calling_info *calling, const struct rb_callinfo *ci, VALUE block_handler)
4909{
4910 int argc = calling->argc;
4911
4912 /* remove self */
4913 if (argc > 0) MEMMOVE(&TOPN(argc), &TOPN(argc-1), VALUE, argc);
4914 DEC_SP(1);
4915
4916 return vm_invoke_block(ec, reg_cfp, calling, ci, false, block_handler);
4917}
4918
4919static VALUE
4920vm_call_opt_call(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling)
4921{
4922 RB_DEBUG_COUNTER_INC(ccf_opt_call);
4923
4924 const struct rb_callinfo *ci = calling->cd->ci;
4925 VALUE procval = calling->recv;
4926 return vm_invoke_block_opt_call(ec, reg_cfp, calling, ci, VM_BH_FROM_PROC(procval));
4927}
4928
4929static VALUE
4930vm_call_opt_block_call(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling)
4931{
4932 RB_DEBUG_COUNTER_INC(ccf_opt_block_call);
4933
4934 VALUE block_handler = VM_ENV_BLOCK_HANDLER(VM_CF_LEP(reg_cfp));
4935 const struct rb_callinfo *ci = calling->cd->ci;
4936
4937 if (UNLIKELY(block_handler == VM_BLOCK_HANDLER_NONE)) {
4938 rb_vm_localjump_error("no block given (yield)", Qnil, 0);
4939 }
4940
4941 enum ruby_basic_operators bop;
4942 switch (vm_ci_mid(ci)) {
4943 case idAREF: bop = BOP_AREF; break;
4944 case idYield: bop = BOP_YIELD; break;
4945 case idEqq: bop = BOP_EQQ; break;
4946 default: bop = BOP_CALL; break;
4947 }
4948
4949 if (BASIC_OP_UNREDEFINED_P(bop, PROC_REDEFINED_OP_FLAG)) {
4950 return vm_invoke_block_opt_call(ec, reg_cfp, calling, ci, block_handler);
4951 }
4952 else {
4953 calling->recv = rb_vm_bh_to_procval(ec, block_handler);
4954 calling->cc = rb_vm_search_method_slowpath(ci, CLASS_OF(calling->recv));
4955 return vm_call_general(ec, reg_cfp, calling);
4956 }
4957}
4958
4959static VALUE
4960vm_call_opt_struct_aref0(rb_execution_context_t *ec, struct rb_calling_info *calling)
4961{
4962 VALUE recv = calling->recv;
4963
4964 VM_ASSERT(RB_TYPE_P(recv, T_STRUCT));
4965 VM_ASSERT(vm_cc_cme(calling->cc)->def->type == VM_METHOD_TYPE_OPTIMIZED);
4966 VM_ASSERT(vm_cc_cme(calling->cc)->def->body.optimized.type == OPTIMIZED_METHOD_TYPE_STRUCT_AREF);
4967
4968 const unsigned int off = vm_cc_cme(calling->cc)->def->body.optimized.index;
4969 return RSTRUCT_GET_RAW(recv, off);
4970}
4971
4972static VALUE
4973vm_call_opt_struct_aref(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling)
4974{
4975 RB_DEBUG_COUNTER_INC(ccf_opt_struct_aref);
4976
4977 VALUE ret = vm_call_opt_struct_aref0(ec, calling);
4978 reg_cfp->sp -= 1;
4979 return ret;
4980}
4981
4982static VALUE
4983vm_call_opt_struct_aset0(rb_execution_context_t *ec, struct rb_calling_info *calling, VALUE val)
4984{
4985 VALUE recv = calling->recv;
4986
4987 VM_ASSERT(RB_TYPE_P(recv, T_STRUCT));
4988 VM_ASSERT(vm_cc_cme(calling->cc)->def->type == VM_METHOD_TYPE_OPTIMIZED);
4989 VM_ASSERT(vm_cc_cme(calling->cc)->def->body.optimized.type == OPTIMIZED_METHOD_TYPE_STRUCT_ASET);
4990
4991 rb_check_frozen(recv);
4992
4993 const unsigned int off = vm_cc_cme(calling->cc)->def->body.optimized.index;
4994 RSTRUCT_SET_RAW(recv, off, val);
4995
4996 return val;
4997}
4998
4999static VALUE
5000vm_call_opt_struct_aset(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling)
5001{
5002 RB_DEBUG_COUNTER_INC(ccf_opt_struct_aset);
5003
5004 VALUE ret = vm_call_opt_struct_aset0(ec, calling, *(reg_cfp->sp - 1));
5005 reg_cfp->sp -= 2;
5006 return ret;
5007}
5008
5009NOINLINE(static VALUE vm_call_optimized(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling,
5010 const struct rb_callinfo *ci, const struct rb_callcache *cc));
5011
5012#define VM_CALL_METHOD_ATTR(var, func, nohook) \
5013 if (UNLIKELY(ruby_vm_c_events_enabled > 0)) { \
5014 EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_CALL, calling->recv, vm_cc_cme(cc)->def->original_id, \
5015 vm_ci_mid(ci), vm_cc_cme(cc)->owner, Qundef); \
5016 var = func; \
5017 EXEC_EVENT_HOOK(ec, RUBY_EVENT_C_RETURN, calling->recv, vm_cc_cme(cc)->def->original_id, \
5018 vm_ci_mid(ci), vm_cc_cme(cc)->owner, (var)); \
5019 } \
5020 else { \
5021 nohook; \
5022 var = func; \
5023 }
5024
5025static VALUE
5026vm_call_optimized(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling,
5027 const struct rb_callinfo *ci, const struct rb_callcache *cc)
5028{
5029 switch (vm_cc_cme(cc)->def->body.optimized.type) {
5030 case OPTIMIZED_METHOD_TYPE_SEND:
5031 CC_SET_FASTPATH(cc, vm_call_opt_send, TRUE);
5032 return vm_call_opt_send(ec, cfp, calling);
5033 case OPTIMIZED_METHOD_TYPE_CALL:
5034 CC_SET_FASTPATH(cc, vm_call_opt_call, TRUE);
5035 return vm_call_opt_call(ec, cfp, calling);
5036 case OPTIMIZED_METHOD_TYPE_BLOCK_CALL:
5037 CC_SET_FASTPATH(cc, vm_call_opt_block_call, TRUE);
5038 return vm_call_opt_block_call(ec, cfp, calling);
5039 case OPTIMIZED_METHOD_TYPE_STRUCT_AREF: {
5040 CALLER_SETUP_ARG(cfp, calling, ci, 0);
5041 rb_check_arity(calling->argc, 0, 0);
5042
5043 VALUE v;
5044 VM_CALL_METHOD_ATTR(v,
5045 vm_call_opt_struct_aref(ec, cfp, calling),
5046 set_vm_cc_ivar(cc); \
5047 CC_SET_FASTPATH(cc, vm_call_opt_struct_aref, (vm_ci_flag(ci) & VM_CALL_ARGS_SIMPLE)))
5048 return v;
5049 }
5050 case OPTIMIZED_METHOD_TYPE_STRUCT_ASET: {
5051 CALLER_SETUP_ARG(cfp, calling, ci, 1);
5052 rb_check_arity(calling->argc, 1, 1);
5053
5054 VALUE v;
5055 VM_CALL_METHOD_ATTR(v,
5056 vm_call_opt_struct_aset(ec, cfp, calling),
5057 set_vm_cc_ivar(cc); \
5058 CC_SET_FASTPATH(cc, vm_call_opt_struct_aset, (vm_ci_flag(ci) & VM_CALL_ARGS_SIMPLE)))
5059 return v;
5060 }
5061 default:
5062 rb_bug("vm_call_method: unsupported optimized method type (%d)", vm_cc_cme(cc)->def->body.optimized.type);
5063 }
5064}
5065
5066static VALUE
5067vm_call_method_each_type(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling)
5068{
5069 const struct rb_callinfo *ci = calling->cd->ci;
5070 const struct rb_callcache *cc = calling->cc;
5071 const rb_callable_method_entry_t *cme = vm_cc_cme(cc);
5072 VALUE v;
5073
5074 VM_ASSERT(! METHOD_ENTRY_INVALIDATED(cme));
5075
5076 switch (cme->def->type) {
5077 case VM_METHOD_TYPE_ISEQ:
5078 if (ISEQ_BODY(def_iseq_ptr(cme->def))->param.flags.forwardable) {
5079 CC_SET_FASTPATH(cc, vm_call_iseq_fwd_setup, TRUE);
5080 return vm_call_iseq_fwd_setup(ec, cfp, calling);
5081 }
5082 else {
5083 CC_SET_FASTPATH(cc, vm_call_iseq_setup, TRUE);
5084 return vm_call_iseq_setup(ec, cfp, calling);
5085 }
5086
5087 case VM_METHOD_TYPE_NOTIMPLEMENTED:
5088 case VM_METHOD_TYPE_CFUNC:
5089 CC_SET_FASTPATH(cc, vm_call_cfunc, TRUE);
5090 return vm_call_cfunc(ec, cfp, calling);
5091
5092 case VM_METHOD_TYPE_ATTRSET:
5093 CALLER_SETUP_ARG(cfp, calling, ci, 1);
5094
5095 rb_check_arity(calling->argc, 1, 1);
5096
5097 const unsigned int aset_mask = (VM_CALL_ARGS_SPLAT | VM_CALL_KW_SPLAT | VM_CALL_KWARG | VM_CALL_FORWARDING);
5098
5099 if (vm_cc_markable(cc)) {
5100 vm_cc_attr_index_set(cc, IVAR_CACHE_INIT);
5101 VM_CALL_METHOD_ATTR(v,
5102 vm_call_attrset_direct(ec, cfp, cc, calling->recv),
5103 CC_SET_FASTPATH(cc, vm_call_attrset, !(vm_ci_flag(ci) & aset_mask)));
5104 }
5105 else {
5106 cc = &((struct rb_callcache) {
5107 .flags = T_IMEMO |
5108 (imemo_callcache << FL_USHIFT) |
5109 VM_CALLCACHE_UNMARKABLE |
5110 VM_CALLCACHE_ON_STACK,
5111 .klass = cc->klass,
5112 .cme_ = cc->cme_,
5113 .call_ = cc->call_,
5114 .aux_ = {
5115 .attr = {
5116 .value = IVAR_CACHE_INIT,
5117 }
5118 },
5119 });
5120
5121 VM_CALL_METHOD_ATTR(v,
5122 vm_call_attrset_direct(ec, cfp, cc, calling->recv),
5123 CC_SET_FASTPATH(cc, vm_call_attrset, !(vm_ci_flag(ci) & aset_mask)));
5124 }
5125 return v;
5126
5127 case VM_METHOD_TYPE_IVAR:
5128 CALLER_SETUP_ARG(cfp, calling, ci, 0);
5129 rb_check_arity(calling->argc, 0, 0);
5130 vm_cc_attr_index_set(cc, rb_getivar_cache_pack(ROOT_SHAPE_ID, ATTR_INDEX_NOT_SET));
5131 const unsigned int ivar_mask = (VM_CALL_ARGS_SPLAT | VM_CALL_KW_SPLAT | VM_CALL_FORWARDING);
5132 VM_CALL_METHOD_ATTR(v,
5133 vm_call_ivar(ec, cfp, calling),
5134 CC_SET_FASTPATH(cc, vm_call_ivar, !(vm_ci_flag(ci) & ivar_mask)));
5135 return v;
5136
5137 case VM_METHOD_TYPE_MISSING:
5138 vm_cc_method_missing_reason_set(cc, 0);
5139 CC_SET_FASTPATH(cc, vm_call_method_missing, TRUE);
5140 return vm_call_method_missing(ec, cfp, calling);
5141
5142 case VM_METHOD_TYPE_BMETHOD:
5143 CC_SET_FASTPATH(cc, vm_call_bmethod, TRUE);
5144 return vm_call_bmethod(ec, cfp, calling);
5145
5146 case VM_METHOD_TYPE_ALIAS:
5147 CC_SET_FASTPATH(cc, vm_call_alias, TRUE);
5148 return vm_call_alias(ec, cfp, calling);
5149
5150 case VM_METHOD_TYPE_OPTIMIZED:
5151 return vm_call_optimized(ec, cfp, calling, ci, cc);
5152
5153 case VM_METHOD_TYPE_UNDEF:
5154 break;
5155
5156 case VM_METHOD_TYPE_ZSUPER:
5157 return vm_call_zsuper(ec, cfp, calling, RCLASS_ORIGIN(vm_cc_cme(cc)->defined_class));
5158
5159 case VM_METHOD_TYPE_REFINED:
5160 // CC_SET_FASTPATH(cc, vm_call_refined, TRUE);
5161 // should not set FASTPATH since vm_call_refined assumes cc->call is vm_call_super_method on invokesuper.
5162 return vm_call_refined(ec, cfp, calling);
5163 }
5164
5165 rb_bug("vm_call_method: unsupported method type (%d)", vm_cc_cme(cc)->def->type);
5166}
5167
5168NORETURN(static void vm_raise_method_missing(rb_execution_context_t *ec, int argc, const VALUE *argv, VALUE obj, int call_status));
5169
5170static VALUE
5171vm_call_method_nome(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling)
5172{
5173 /* method missing */
5174 const struct rb_callinfo *ci = calling->cd->ci;
5175 const int stat = ci_missing_reason(ci);
5176
5177 if (vm_ci_mid(ci) == idMethodMissing) {
5178 if (UNLIKELY(calling->heap_argv)) {
5179 vm_raise_method_missing(ec, RARRAY_LENINT(calling->heap_argv), RARRAY_CONST_PTR(calling->heap_argv), calling->recv, stat);
5180 }
5181 else {
5182 rb_control_frame_t *reg_cfp = cfp;
5183 VALUE *argv = STACK_ADDR_FROM_TOP(calling->argc);
5184 vm_raise_method_missing(ec, calling->argc, argv, calling->recv, stat);
5185 }
5186 }
5187 else {
5188 return vm_call_method_missing_body(ec, cfp, calling, ci, stat);
5189 }
5190}
5191
5192/* Protected method calls and super invocations need to check that the receiver
5193 * (self for super) inherits the module on which the method is defined.
5194 * In the case of refinements, it should consider the original class not the
5195 * refinement.
5196 */
5197static VALUE
5198vm_defined_class_for_protected_call(const rb_callable_method_entry_t *me)
5199{
5200 VALUE defined_class = me->defined_class;
5201 VALUE refined_class = RCLASS_REFINED_CLASS(defined_class);
5202 return NIL_P(refined_class) ? defined_class : refined_class;
5203}
5204
5205static inline VALUE
5206vm_call_method(rb_execution_context_t *ec, rb_control_frame_t *cfp, struct rb_calling_info *calling)
5207{
5208 const struct rb_callinfo *ci = calling->cd->ci;
5209 const struct rb_callcache *cc = calling->cc;
5210
5211 VM_ASSERT(callable_method_entry_p(vm_cc_cme(cc)));
5212
5213 if (vm_cc_cme(cc) != NULL) {
5214 switch (METHOD_ENTRY_VISI(vm_cc_cme(cc))) {
5215 case METHOD_VISI_PUBLIC: /* likely */
5216 return vm_call_method_each_type(ec, cfp, calling);
5217
5218 case METHOD_VISI_PRIVATE:
5219 if (!(vm_ci_flag(ci) & VM_CALL_FCALL)) {
5220 enum method_missing_reason stat = MISSING_PRIVATE;
5221 if (vm_ci_flag(ci) & VM_CALL_VCALL) stat |= MISSING_VCALL;
5222
5223 vm_cc_method_missing_reason_set(cc, stat);
5224 CC_SET_FASTPATH(cc, vm_call_method_missing, TRUE);
5225 return vm_call_method_missing(ec, cfp, calling);
5226 }
5227 return vm_call_method_each_type(ec, cfp, calling);
5228
5229 case METHOD_VISI_PROTECTED:
5230 if (!(vm_ci_flag(ci) & (VM_CALL_OPT_SEND | VM_CALL_FCALL))) {
5231 VALUE defined_class = vm_defined_class_for_protected_call(vm_cc_cme(cc));
5232 if (!rb_obj_is_kind_of(cfp->self, defined_class)) {
5233 vm_cc_method_missing_reason_set(cc, MISSING_PROTECTED);
5234 return vm_call_method_missing(ec, cfp, calling);
5235 }
5236 else {
5237 /* caching method info to dummy cc */
5238 VM_ASSERT(vm_cc_cme(cc) != NULL);
5239 struct rb_callcache cc_on_stack = *cc;
5240 FL_SET_RAW((VALUE)&cc_on_stack, VM_CALLCACHE_UNMARKABLE);
5241 calling->cc = &cc_on_stack;
5242 return vm_call_method_each_type(ec, cfp, calling);
5243 }
5244 }
5245 return vm_call_method_each_type(ec, cfp, calling);
5246
5247 default:
5248 rb_bug("unreachable");
5249 }
5250 }
5251 else {
5252 return vm_call_method_nome(ec, cfp, calling);
5253 }
5254}
5255
5256static VALUE
5257vm_call_general(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling)
5258{
5259 RB_DEBUG_COUNTER_INC(ccf_general);
5260 return vm_call_method(ec, reg_cfp, calling);
5261}
5262
5263void
5264rb_vm_cc_general(const struct rb_callcache *cc)
5265{
5266 VM_ASSERT(IMEMO_TYPE_P(cc, imemo_callcache));
5267 VM_ASSERT(cc != vm_cc_empty());
5268
5269 *(vm_call_handler *)&cc->call_ = vm_call_general;
5270}
5271
5272static VALUE
5273vm_call_super_method(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, struct rb_calling_info *calling)
5274{
5275 RB_DEBUG_COUNTER_INC(ccf_super_method);
5276
5277 // This line is introduced to make different from `vm_call_general` because some compilers (VC we found)
5278 // can merge the function and the address of the function becomes same.
5279 // The address of `vm_call_super_method` is used in `search_refined_method`, so it should be different.
5280 if (ec == NULL) rb_bug("unreachable");
5281
5282 /* this check is required to distinguish with other functions. */
5283 VM_ASSERT(vm_cc_call(calling->cc) == vm_call_super_method);
5284 return vm_call_method(ec, reg_cfp, calling);
5285}
5286
5287/* super */
5288
5289static inline VALUE
5290vm_search_normal_superclass(VALUE klass)
5291{
5292 if (RICLASS_FOR_REFINEMENT_P(klass)) {
5293 if (RB_TYPE_P(RCLASS_REFINED_CLASS(klass), T_MODULE)) {
5294 do {
5295 klass = RCLASS_SUPER(klass);
5296 } while (RICLASS_FOR_REFINEMENT_P(klass));
5297
5298 return klass;
5299 }
5300
5301 klass = RBASIC(klass)->klass;
5302 }
5303 klass = RCLASS_ORIGIN(klass);
5304 return RCLASS_SUPER(klass);
5305}
5306
5307NORETURN(static void vm_super_outside(void));
5308
5309static void
5310vm_super_outside(void)
5311{
5312 rb_raise(rb_eNoMethodError, "super called outside of method");
5313}
5314
5315static const struct rb_callcache *
5316empty_cc_for_super(void)
5317{
5318 return &rb_vm_empty_cc_for_super;
5319}
5320
5321static const struct rb_callcache *
5322vm_search_super_method(const rb_control_frame_t *reg_cfp, struct rb_call_data *cd, VALUE recv)
5323{
5324 VALUE current_defined_class;
5325 const rb_iseq_t *iseq = CFP_ISEQ(reg_cfp);
5326 const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(reg_cfp);
5327
5328 if (!me) {
5329 vm_super_outside();
5330 }
5331
5332 current_defined_class = vm_defined_class_for_protected_call(me);
5333
5334 if (BUILTIN_TYPE(current_defined_class) != T_MODULE &&
5335 iseq != method_entry_iseqptr(me) &&
5336 !rb_obj_is_kind_of(recv, current_defined_class)) {
5337 VALUE m = RB_TYPE_P(current_defined_class, T_ICLASS) ?
5338 RCLASS_INCLUDER(current_defined_class) : current_defined_class;
5339
5340 if (m) { /* not bound UnboundMethod */
5341 rb_raise(rb_eTypeError,
5342 "self has wrong type to call super in this context: "
5343 "%"PRIsVALUE" (expected %"PRIsVALUE")",
5344 rb_obj_class(recv), m);
5345 }
5346 }
5347
5348 if (me->def->type == VM_METHOD_TYPE_BMETHOD && (vm_ci_flag(cd->ci) & VM_CALL_ZSUPER)) {
5349 rb_raise(rb_eRuntimeError,
5350 "implicit argument passing of super from method defined"
5351 " by define_method() is not supported."
5352 " Specify all arguments explicitly.");
5353 }
5354
5355 ID mid = me->def->original_id;
5356
5357 if (!vm_ci_markable(cd->ci)) {
5358 VM_FORCE_WRITE((const VALUE *)&cd->ci->mid, (VALUE)mid);
5359 }
5360 else {
5361 // update iseq. really? (TODO)
5362 cd->ci = vm_ci_new_runtime(mid,
5363 vm_ci_flag(cd->ci),
5364 vm_ci_argc(cd->ci),
5365 vm_ci_kwarg(cd->ci));
5366
5367 RB_OBJ_WRITTEN(iseq, Qundef, cd->ci);
5368 }
5369
5370 const struct rb_callcache *cc;
5371
5372 VALUE klass = vm_search_normal_superclass(me->defined_class);
5373
5374 if (!klass) {
5375 /* bound instance method of module */
5376 cc = vm_cc_new(Qundef, NULL, vm_call_method_missing, cc_type_super);
5377 vm_cc_method_missing_reason_set(cc, ci_missing_reason(cd->ci));
5378 RB_OBJ_WRITE(iseq, &cd->cc, cc);
5379 }
5380 else {
5381 cc = vm_search_method_fastpath(reg_cfp, cd, klass);
5382 VM_ASSERT(cc != &rb_vm_uncached_cc);
5383 const rb_callable_method_entry_t *cached_cme = vm_cc_cme(cc);
5384
5385 // define_method can cache for different method id
5386 if (cached_cme == NULL) {
5387 // empty_cc_for_super is not markable object
5388 cd->cc = empty_cc_for_super();
5389 }
5390 else if (cached_cme->called_id != mid) {
5391 const rb_callable_method_entry_t *cme = rb_callable_method_entry(klass, mid);
5392 if (cme) {
5393 cc = vm_cc_new(klass, cme, vm_call_super_method, cc_type_super);
5394 RB_OBJ_WRITE(iseq, &cd->cc, cc);
5395 }
5396 else {
5397 cd->cc = cc = empty_cc_for_super();
5398 }
5399 }
5400 else {
5401 switch (cached_cme->def->type) {
5402 // vm_call_refined (search_refined_method) assumes cc->call is vm_call_super_method on invokesuper
5403 case VM_METHOD_TYPE_REFINED:
5404 // cc->klass is superclass of receiver class. Checking cc->klass is not enough to invalidate IVC for the receiver class.
5405 case VM_METHOD_TYPE_ATTRSET:
5406 case VM_METHOD_TYPE_IVAR:
5407 vm_cc_call_set(cc, vm_call_super_method); // invalidate fastpath
5408 break;
5409 default:
5410 break; // use fastpath
5411 }
5412 }
5413 }
5414
5415 VM_ASSERT((vm_cc_cme(cc), true));
5416
5417 return cc;
5418}
5419
5420/* yield */
5421
5422static inline int
5423block_proc_is_lambda(const VALUE procval)
5424{
5425 rb_proc_t *proc;
5426
5427 if (procval) {
5428 GetProcPtr(procval, proc);
5429 return proc->header.is_lambda;
5430 }
5431 else {
5432 return 0;
5433 }
5434}
5435
5436static VALUE
5437vm_yield_with_cfunc(rb_execution_context_t *ec,
5438 const struct rb_captured_block *captured,
5439 VALUE self, int argc, const VALUE *argv, int kw_splat, VALUE block_handler,
5440 const rb_callable_method_entry_t *me, int stack_argc)
5441{
5442 int is_lambda = FALSE; /* TODO */
5443 VALUE val, arg, blockarg;
5444 int frame_flag;
5445 const struct vm_ifunc *ifunc = captured->code.ifunc;
5446
5447 if (is_lambda) {
5448 arg = rb_ary_new4(argc, argv);
5449 }
5450 else if (argc == 0) {
5451 arg = Qnil;
5452 }
5453 else {
5454 arg = argv[0];
5455 }
5456
5457 blockarg = rb_vm_bh_to_procval(ec, block_handler);
5458
5459 frame_flag = VM_FRAME_MAGIC_IFUNC | VM_FRAME_FLAG_CFRAME | (me ? VM_FRAME_FLAG_BMETHOD : 0);
5460 if (kw_splat) {
5461 frame_flag |= VM_FRAME_FLAG_CFRAME_KW;
5462 }
5463
5464 rb_control_frame_t *cfp = ec->cfp;
5465 vm_push_frame(ec, (const rb_iseq_t *)captured->code.ifunc,
5466 frame_flag,
5467 self,
5468 VM_GUARDED_PREV_EP(captured->ep),
5469 (VALUE)me,
5470 0, cfp->sp, 0, 0);
5471 /* The new frame keeps the arguments live. Pop them from the caller
5472 * before the callback can exit via break. */
5473 cfp->sp -= stack_argc;
5474 val = (*ifunc->func)(arg, (VALUE)ifunc->data, argc, argv, blockarg);
5475 rb_vm_pop_frame(ec);
5476
5477 return val;
5478}
5479
5480VALUE
5481rb_vm_yield_with_cfunc(rb_execution_context_t *ec, const struct rb_captured_block *captured, int argc, const VALUE *argv)
5482{
5483 return vm_yield_with_cfunc(ec, captured, captured->self, argc, argv, 0, VM_BLOCK_HANDLER_NONE, NULL, 0);
5484}
5485
5486static VALUE
5487vm_yield_with_symbol(rb_execution_context_t *ec, VALUE symbol, int argc, const VALUE *argv, int kw_splat, VALUE block_handler)
5488{
5489 VALUE passed_proc = rb_vm_bh_to_procval(ec, block_handler);
5490
5491 if (!rb_box_available()) {
5492 return rb_sym_proc_call(SYM2ID(symbol), argc, argv, kw_splat, passed_proc);
5493 }
5494
5495 const rb_control_frame_t *reg_cfp = ec->cfp;
5496 const rb_control_frame_t *ruby_cfp = rb_vm_get_ruby_level_next_cfp(ec, reg_cfp);
5497 const rb_box_t *box = NULL;
5498
5499 /*
5500 * Traverse the frames until a user box (Main or Optional Box) is found.
5501 * Frames for built-in methods like <internal:xxx> run in the Root or Master Box,
5502 */
5503 while (ruby_cfp) {
5504 box = current_box_on_cfp(ec, ruby_cfp);
5505 if (BOX_USER_P(box)) {
5506 break;
5507 }
5508 ruby_cfp = rb_vm_get_ruby_level_next_cfp(ec, RUBY_VM_PREVIOUS_CONTROL_FRAME(ruby_cfp));
5509 }
5510
5511 // Fallback to the normal call if no user box is found
5512 if (!ruby_cfp || !box) {
5513 return rb_sym_proc_call(SYM2ID(symbol), argc, argv, kw_splat, passed_proc);
5514 }
5515
5516 /*
5517 * Push a dummy block frame whose outer env is `ruby_cfp` so that the
5518 * method resolves in the caller's box (via the ep chain) and the
5519 * backtrace reads like a usual block invocation at the caller's site.
5520 */
5521 const rb_iseq_t *caller_iseq = CFP_ISEQ(ruby_cfp);
5522 VALUE name = rb_sprintf("block in %"PRIsVALUE, rb_iseq_label(caller_iseq));
5523 const rb_iseq_t *iseq = rb_iseq_new_with_opt(Qnil, name,
5524 rb_iseq_path(caller_iseq), rb_iseq_realpath(caller_iseq),
5525 rb_vm_get_sourceline(ruby_cfp), caller_iseq, 0,
5526 ISEQ_TYPE_BLOCK, NULL, Qnil);
5527 volatile VALUE val = Qnil;
5528 enum ruby_tag_type state;
5529
5530 vm_push_frame(ec, iseq, VM_FRAME_MAGIC_BLOCK | VM_FRAME_FLAG_FINISH,
5531 ruby_cfp->self, VM_GUARDED_PREV_EP(ruby_cfp->ep),
5532 Qfalse, /* cref or me */
5533 ISEQ_BODY(iseq)->iseq_encoded, reg_cfp->sp,
5534 ISEQ_BODY(iseq)->local_table_size, ISEQ_BODY(iseq)->stack_max);
5535
5536 /*
5537 * The pushed frame is finished (owned by no vm_exec loop), so catch the
5538 * non-local exit here, pop the frame, and let the caller's handlers see
5539 * the exception.
5540 */
5541 EC_PUSH_TAG(ec);
5542 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
5543 val = rb_sym_proc_call(SYM2ID(symbol), argc, argv, kw_splat, passed_proc);
5544 }
5545 EC_POP_TAG();
5546
5547 if (state != TAG_NONE) {
5548 rb_vm_rewind_cfp(ec, (rb_control_frame_t *)reg_cfp);
5549 EC_JUMP_TAG(ec, state);
5550 }
5551
5552 rb_vm_pop_frame(ec);
5553
5554 return val;
5555}
5556
5557static inline int
5558vm_callee_setup_block_arg_arg0_splat(rb_control_frame_t *cfp, const rb_iseq_t *iseq, VALUE *argv, VALUE ary)
5559{
5560 int i;
5561 rb_len_t len = RARRAY_LEN(ary);
5562
5563 CHECK_VM_STACK_OVERFLOW(cfp, ISEQ_BODY(iseq)->param.lead_num);
5564
5565 for (i=0; i<len && i<ISEQ_BODY(iseq)->param.lead_num; i++) {
5566 argv[i] = RARRAY_AREF(ary, i);
5567 }
5568
5569 return i;
5570}
5571
5572static inline VALUE
5573vm_callee_setup_block_arg_arg0_check(VALUE *argv)
5574{
5575 VALUE ary, arg0 = argv[0];
5576 ary = rb_check_array_type(arg0);
5577#if 0
5578 argv[0] = arg0;
5579#else
5580 VM_ASSERT(argv[0] == arg0);
5581#endif
5582 return ary;
5583}
5584
5585static int
5586vm_callee_setup_block_arg(rb_execution_context_t *ec, struct rb_calling_info *calling, const struct rb_callinfo *ci, const rb_iseq_t *iseq, VALUE *argv, const enum arg_setup_type arg_setup_type)
5587{
5588 if (rb_simple_iseq_p(iseq)) {
5589 rb_control_frame_t *cfp = ec->cfp;
5590 VALUE arg0;
5591
5592 CALLER_SETUP_ARG(cfp, calling, ci, ISEQ_BODY(iseq)->param.lead_num);
5593
5594 if (arg_setup_type == arg_setup_block &&
5595 calling->argc == 1 &&
5596 ISEQ_BODY(iseq)->param.flags.has_lead &&
5597 !ISEQ_BODY(iseq)->param.flags.ambiguous_param0 &&
5598 !NIL_P(arg0 = vm_callee_setup_block_arg_arg0_check(argv))) {
5599 calling->argc = vm_callee_setup_block_arg_arg0_splat(cfp, iseq, argv, arg0);
5600 }
5601
5602 if (calling->argc != ISEQ_BODY(iseq)->param.lead_num) {
5603 if (arg_setup_type == arg_setup_block) {
5604 if (calling->argc < ISEQ_BODY(iseq)->param.lead_num) {
5605 int i;
5606 CHECK_VM_STACK_OVERFLOW(cfp, ISEQ_BODY(iseq)->param.lead_num);
5607 for (i=calling->argc; i<ISEQ_BODY(iseq)->param.lead_num; i++) argv[i] = Qnil;
5608 calling->argc = ISEQ_BODY(iseq)->param.lead_num; /* fill rest parameters */
5609 }
5610 else if (calling->argc > ISEQ_BODY(iseq)->param.lead_num) {
5611 calling->argc = ISEQ_BODY(iseq)->param.lead_num; /* simply truncate arguments */
5612 }
5613 }
5614 else {
5615 argument_arity_error(ec, iseq, NULL, calling->argc, ISEQ_BODY(iseq)->param.lead_num, ISEQ_BODY(iseq)->param.lead_num);
5616 }
5617 }
5618
5619 return 0;
5620 }
5621 else {
5622 return setup_parameters_complex(ec, iseq, calling, ci, argv, arg_setup_type);
5623 }
5624}
5625
5626static int
5627vm_yield_setup_args(rb_execution_context_t *ec, const rb_iseq_t *iseq, const int argc, VALUE *argv, int flags, VALUE block_handler, enum arg_setup_type arg_setup_type)
5628{
5629 struct rb_calling_info calling_entry, *calling;
5630
5631 calling = &calling_entry;
5632 calling->argc = argc;
5633 calling->block_handler = block_handler;
5634 calling->kw_splat = (flags & VM_CALL_KW_SPLAT) ? 1 : 0;
5635 calling->recv = Qundef;
5636 calling->heap_argv = 0;
5637 calling->cc = NULL;
5638 struct rb_callinfo dummy_ci = VM_CI_ON_STACK(0, flags, 0, 0);
5639
5640 return vm_callee_setup_block_arg(ec, calling, &dummy_ci, iseq, argv, arg_setup_type);
5641}
5642
5643/* ruby iseq -> ruby block */
5644
5645static VALUE
5646vm_invoke_iseq_block_with_cref(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp,
5647 struct rb_calling_info *calling, const struct rb_callinfo *ci,
5648 bool is_lambda, VALUE block_handler, const rb_cref_t *cref)
5649{
5650 const struct rb_captured_block *captured = VM_BH_TO_ISEQ_BLOCK(block_handler);
5651 const rb_iseq_t *iseq = rb_iseq_check(captured->code.iseq);
5652 const int arg_size = ISEQ_BODY(iseq)->param.size;
5653 VALUE * const rsp = GET_SP() - calling->argc;
5654 VALUE * const argv = rsp;
5655 int opt_pc = vm_callee_setup_block_arg(ec, calling, ci, iseq, argv, is_lambda ? arg_setup_method : arg_setup_block);
5656 int frame_flag = VM_FRAME_MAGIC_BLOCK | (is_lambda ? VM_FRAME_FLAG_LAMBDA : 0);
5657
5658 SET_SP(rsp);
5659
5660 /* cref is normally 0; Proc#refined supplies a refinement cref */
5661 vm_push_frame(ec, iseq,
5662 frame_flag,
5663 captured->self,
5664 VM_GUARDED_PREV_EP(captured->ep), (VALUE)cref,
5665 ISEQ_BODY(iseq)->iseq_encoded + opt_pc,
5666 rsp + arg_size,
5667 ISEQ_BODY(iseq)->local_table_size - arg_size, ISEQ_BODY(iseq)->stack_max);
5668
5669 return Qundef;
5670}
5671
5672static VALUE
5673vm_invoke_iseq_block(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp,
5674 struct rb_calling_info *calling, const struct rb_callinfo *ci,
5675 bool is_lambda, VALUE block_handler)
5676{
5677 return vm_invoke_iseq_block_with_cref(ec, reg_cfp, calling, ci, is_lambda, block_handler, NULL);
5678}
5679
5680static VALUE
5681vm_invoke_symbol_block(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp,
5682 struct rb_calling_info *calling, const struct rb_callinfo *ci,
5683 MAYBE_UNUSED(bool is_lambda), VALUE block_handler)
5684{
5685 VALUE symbol = VM_BH_TO_SYMBOL(block_handler);
5686 int flags = vm_ci_flag(ci);
5687
5688 if (UNLIKELY(!(flags & VM_CALL_ARGS_SIMPLE) &&
5689 ((calling->argc == 0) ||
5690 (calling->argc == 1 && (flags & (VM_CALL_ARGS_SPLAT | VM_CALL_KW_SPLAT))) ||
5691 (calling->argc == 2 && (flags & VM_CALL_ARGS_SPLAT) && (flags & VM_CALL_KW_SPLAT)) ||
5692 ((flags & VM_CALL_KWARG) && (vm_ci_kwarg(ci)->keyword_len == calling->argc))))) {
5693 CALLER_SETUP_ARG(reg_cfp, calling, ci, ALLOW_HEAP_ARGV);
5694 flags = 0;
5695 if (UNLIKELY(calling->heap_argv)) {
5696#if VM_ARGC_STACK_MAX < 0
5697 if (RARRAY_LEN(calling->heap_argv) < 1) {
5698 rb_raise(rb_eArgError, "no receiver given");
5699 }
5700#endif
5701 calling->recv = rb_ary_shift(calling->heap_argv);
5702 // Modify stack to avoid cfp consistency error
5703 reg_cfp->sp++;
5704 reg_cfp->sp[-1] = reg_cfp->sp[-2];
5705 reg_cfp->sp[-2] = calling->recv;
5706 flags |= VM_CALL_ARGS_SPLAT;
5707 }
5708 else {
5709 if (calling->argc < 1) {
5710 rb_raise(rb_eArgError, "no receiver given");
5711 }
5712 calling->recv = TOPN(--calling->argc);
5713 }
5714 if (calling->kw_splat) {
5715 flags |= VM_CALL_KW_SPLAT;
5716 }
5717 }
5718 else {
5719 if (calling->argc < 1) {
5720 rb_raise(rb_eArgError, "no receiver given");
5721 }
5722 calling->recv = TOPN(--calling->argc);
5723 }
5724
5725 return vm_call_symbol(ec, reg_cfp, calling, ci, symbol, flags);
5726}
5727
5728static VALUE
5729vm_invoke_ifunc_block(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp,
5730 struct rb_calling_info *calling, const struct rb_callinfo *ci,
5731 MAYBE_UNUSED(bool is_lambda), VALUE block_handler)
5732{
5733 const struct rb_captured_block *captured = VM_BH_TO_IFUNC_BLOCK(block_handler);
5734 CALLER_SETUP_ARG(reg_cfp, calling, ci, ALLOW_HEAP_ARGV_KEEP_KWSPLAT);
5735 const VALUE *argv = calling->heap_argv ? RARRAY_CONST_PTR(calling->heap_argv) : STACK_ADDR_FROM_TOP(calling->argc);
5736 return vm_yield_with_cfunc(ec, captured, captured->self, CALLING_ARGC(calling), argv,
5737 calling->kw_splat, calling->block_handler, NULL, calling->argc);
5738}
5739
5740static inline VALUE
5741vm_block_to_block_handler(const struct rb_block *block)
5742{
5743 switch (vm_block_type(block)) {
5744 case block_type_iseq:
5745 return VM_BH_FROM_ISEQ_BLOCK(&block->as.captured);
5746 case block_type_ifunc:
5747 return VM_BH_FROM_IFUNC_BLOCK(&block->as.captured);
5748 case block_type_symbol:
5749 return VM_BH_FROM_SYMBOL(block->as.symbol);
5750 case block_type_proc:
5751 return VM_BH_FROM_PROC(block->as.proc);
5752 }
5753 VM_UNREACHABLE(vm_yield_with_proc);
5754 return Qundef;
5755}
5756
5757static VALUE
5758vm_proc_to_block_handler(VALUE procval)
5759{
5760 return vm_block_to_block_handler(vm_proc_block(procval));
5761}
5762
5763NOINLINE(static VALUE
5764vm_invoke_proc_block_with_cref(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp,
5765 struct rb_calling_info *calling, const struct rb_callinfo *ci,
5766 bool is_lambda, VALUE block_handler, VALUE refined_procval));
5767static VALUE
5768vm_invoke_proc_block_with_cref(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp,
5769 struct rb_calling_info *calling, const struct rb_callinfo *ci,
5770 bool is_lambda, VALUE block_handler, VALUE refined_procval)
5771{
5772 const rb_cref_t *cref = rb_proc_refinements_cref_for_call(refined_procval);
5773 return vm_invoke_iseq_block_with_cref(ec, reg_cfp, calling, ci, is_lambda, block_handler, cref);
5774}
5775
5776static VALUE
5777vm_invoke_proc_block(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp,
5778 struct rb_calling_info *calling, const struct rb_callinfo *ci,
5779 bool is_lambda, VALUE block_handler)
5780{
5781 VALUE refined_procval = 0;
5782
5783 while (vm_block_handler_type(block_handler) == block_handler_type_proc) {
5784 VALUE procval = VM_BH_TO_PROC(block_handler);
5785 rb_proc_t *po;
5786 GetProcPtr(procval, po);
5787 if (po->header.is_refined) refined_procval = procval;
5788 is_lambda = po->header.is_lambda;
5789 block_handler = vm_block_to_block_handler(&po->block);
5790 }
5791
5792 if (UNLIKELY(refined_procval) && vm_block_handler_type(block_handler) == block_handler_type_iseq) {
5793 /* should not be inlined so that vm_invoke_proc_block stays leaf/frameless. */
5794 return vm_invoke_proc_block_with_cref(ec, reg_cfp, calling, ci, is_lambda, block_handler,
5795 refined_procval);
5796 }
5797
5798 return vm_invoke_block(ec, reg_cfp, calling, ci, is_lambda, block_handler);
5799}
5800
5801static inline VALUE
5802vm_invoke_block(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp,
5803 struct rb_calling_info *calling, const struct rb_callinfo *ci,
5804 bool is_lambda, VALUE block_handler)
5805{
5806 VALUE (*func)(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp,
5807 struct rb_calling_info *calling, const struct rb_callinfo *ci,
5808 bool is_lambda, VALUE block_handler);
5809
5810 switch (vm_block_handler_type(block_handler)) {
5811 case block_handler_type_iseq: func = vm_invoke_iseq_block; break;
5812 case block_handler_type_ifunc: func = vm_invoke_ifunc_block; break;
5813 case block_handler_type_proc: func = vm_invoke_proc_block; break;
5814 case block_handler_type_symbol: func = vm_invoke_symbol_block; break;
5815 default: rb_bug("vm_invoke_block: unreachable");
5816 }
5817
5818 return func(ec, reg_cfp, calling, ci, is_lambda, block_handler);
5819}
5820
5821static VALUE
5822vm_make_proc_with_iseq(const rb_iseq_t *blockiseq)
5823{
5824 const rb_execution_context_t *ec = GET_EC();
5825 const rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp);
5826 struct rb_captured_block *captured;
5827
5828 if (cfp == 0) {
5829 rb_bug("vm_make_proc_with_iseq: unreachable");
5830 }
5831
5832 captured = VM_CFP_TO_CAPTURED_BLOCK(cfp);
5833 captured->code.iseq = blockiseq;
5834
5835 return rb_vm_make_proc(ec, captured, rb_cProc);
5836}
5837
5838static VALUE
5839vm_once_exec(VALUE iseq)
5840{
5841 VALUE proc = vm_make_proc_with_iseq((rb_iseq_t *)iseq);
5842 return rb_proc_call_with_block(proc, 0, 0, Qnil);
5843}
5844
5845#define RUNNING_THREAD_ONCE_DONE ((rb_thread_t *)0x1)
5846
5848 rb_vm_t *vm;
5849 struct rb_imemo_once_storage *storage;
5850};
5851
5852static void
5853vm_once_broadcast(rb_vm_t *vm)
5854{
5855 rb_native_mutex_lock(&vm->once_lock);
5856 rb_native_cond_broadcast(&vm->once_cond);
5857 rb_native_mutex_unlock(&vm->once_lock);
5858}
5859
5860static void *
5861vm_once_wait_no_gvl(void *ptr)
5862{
5863 struct vm_once_wait_arg *arg = (struct vm_once_wait_arg *)ptr;
5864 rb_vm_t *vm = arg->vm;
5865 rb_thread_t *running_th;
5866
5867 rb_native_mutex_lock(&vm->once_lock);
5868 running_th = rbimpl_atomic_ptr_load((void **)&arg->storage->running_thread, RBIMPL_ATOMIC_ACQUIRE);
5869 if (running_th != NULL && running_th != RUNNING_THREAD_ONCE_DONE) {
5870 rb_native_cond_wait(&vm->once_cond, &vm->once_lock);
5871 }
5872 rb_native_mutex_unlock(&vm->once_lock);
5873 return NULL;
5874}
5875
5876static void
5877vm_once_wait_ubf(void *ptr)
5878{
5879 vm_once_broadcast((rb_vm_t *)ptr);
5880}
5881
5882static VALUE
5883vm_once_clear(VALUE data)
5884{
5885 struct rb_imemo_once_storage *storage = (struct rb_imemo_once_storage *)data;
5886 rbimpl_atomic_ptr_store((volatile void **)&storage->running_thread, NULL, RBIMPL_ATOMIC_RELEASE);
5887 vm_once_broadcast(GET_VM());
5888 return Qnil;
5889}
5890
5891/* defined insn */
5892
5893static bool
5894check_respond_to_missing(VALUE obj, VALUE v)
5895{
5896 VALUE args[2];
5897 VALUE r;
5898
5899 args[0] = obj; args[1] = Qfalse;
5900 r = rb_check_funcall(v, idRespond_to_missing, 2, args);
5901 if (!UNDEF_P(r) && RTEST(r)) {
5902 return true;
5903 }
5904 else {
5905 return false;
5906 }
5907}
5908
5909static bool
5910vm_defined(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, rb_num_t op_type, VALUE obj, VALUE v)
5911{
5912 VALUE klass;
5913 enum defined_type type = (enum defined_type)op_type;
5914
5915 switch (type) {
5916 case DEFINED_IVAR:
5917 return rb_ivar_defined(GET_SELF(), SYM2ID(obj));
5918 break;
5919 case DEFINED_GVAR:
5920 return rb_gvar_defined(SYM2ID(obj));
5921 break;
5922 case DEFINED_CVAR: {
5923 const rb_cref_t *cref = vm_get_cref(GET_EP());
5924 klass = vm_get_cvar_base(cref, GET_CFP(), 0);
5925 return rb_cvar_defined(klass, SYM2ID(obj));
5926 break;
5927 }
5928 case DEFINED_CONST:
5929 case DEFINED_CONST_FROM: {
5930 bool allow_nil = type == DEFINED_CONST;
5931 klass = v;
5932 return vm_get_ev_const(ec, klass, SYM2ID(obj), allow_nil, true);
5933 break;
5934 }
5935 case DEFINED_FUNC:
5936 klass = CLASS_OF(v);
5937 return rb_ec_obj_respond_to(ec, v, SYM2ID(obj), TRUE);
5938 break;
5939 case DEFINED_METHOD:{
5940 VALUE klass = CLASS_OF(v);
5941 const rb_callable_method_entry_t *cme = rb_callable_method_entry_with_refinements(klass, SYM2ID(obj), NULL);
5942
5943 if (cme) {
5944 switch (METHOD_ENTRY_VISI(cme)) {
5945 case METHOD_VISI_PRIVATE:
5946 break;
5947 case METHOD_VISI_PROTECTED:
5948 if (!rb_obj_is_kind_of(GET_SELF(), vm_defined_class_for_protected_call(cme))) {
5949 break;
5950 }
5951 case METHOD_VISI_PUBLIC:
5952 return true;
5953 break;
5954 default:
5955 rb_bug("vm_defined: unreachable: %u", (unsigned int)METHOD_ENTRY_VISI(cme));
5956 }
5957 }
5958 else {
5959 return check_respond_to_missing(obj, v);
5960 }
5961 break;
5962 }
5963 case DEFINED_YIELD:
5964 if (GET_BLOCK_HANDLER() != VM_BLOCK_HANDLER_NONE) {
5965 return true;
5966 }
5967 break;
5968 case DEFINED_ZSUPER:
5969 {
5970 const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(GET_CFP());
5971
5972 if (me) {
5973 VALUE klass = vm_search_normal_superclass(me->defined_class);
5974 if (!klass) return false;
5975
5976 ID id = me->def->original_id;
5977
5978 return rb_method_boundp(klass, id, 0);
5979 }
5980 }
5981 break;
5982 case DEFINED_REF:
5983 return RTEST(vm_backref_defined(ec, GET_LEP(), FIX2INT(obj)));
5984 default:
5985 rb_bug("unimplemented defined? type (VM)");
5986 break;
5987 }
5988
5989 return false;
5990}
5991
5992bool
5993rb_vm_defined(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, rb_num_t op_type, VALUE obj, VALUE v)
5994{
5995 return vm_defined(ec, reg_cfp, op_type, obj, v);
5996}
5997
5998static const VALUE *
5999vm_get_ep(const VALUE *const reg_ep, rb_num_t lv)
6000{
6001 rb_num_t i;
6002 const VALUE *ep = reg_ep;
6003 for (i = 0; i < lv; i++) {
6004 ep = GET_PREV_EP(ep);
6005 }
6006 return ep;
6007}
6008
6009static VALUE
6010vm_get_special_object(const VALUE *const reg_ep,
6011 enum vm_special_object_type type)
6012{
6013 switch (type) {
6014 case VM_SPECIAL_OBJECT_VMCORE:
6015 return rb_mRubyVMFrozenCore;
6016 case VM_SPECIAL_OBJECT_CBASE:
6017 return vm_get_cbase(reg_ep);
6018 case VM_SPECIAL_OBJECT_CONST_BASE:
6019 return vm_get_const_base(reg_ep);
6020 case VM_SPECIAL_OBJECT_UNSET:
6021 return rb_builtin_unset;
6022 default:
6023 rb_bug("putspecialobject insn: unknown value_type %d", type);
6024 }
6025}
6026
6027// ZJIT implementation is using the C function
6028// and needs to call a non-static function
6029VALUE
6030rb_vm_get_special_object(const VALUE *reg_ep, enum vm_special_object_type type)
6031{
6032 return vm_get_special_object(reg_ep, type);
6033}
6034
6035static VALUE
6036vm_concat_array(VALUE ary1, VALUE ary2st)
6037{
6038 const VALUE ary2 = ary2st;
6039 VALUE tmp1 = rb_check_to_array(ary1);
6040 VALUE tmp2 = rb_check_to_array(ary2);
6041
6042 if (NIL_P(tmp1)) {
6043 tmp1 = rb_ary_new3(1, ary1);
6044 }
6045 if (tmp1 == ary1) {
6046 tmp1 = rb_ary_dup(ary1);
6047 }
6048
6049 if (NIL_P(tmp2)) {
6050 return rb_ary_push(tmp1, ary2);
6051 }
6052 else {
6053 return rb_ary_concat(tmp1, tmp2);
6054 }
6055}
6056
6057static VALUE
6058vm_concat_to_array(VALUE ary1, VALUE ary2st)
6059{
6060 /* ary1 must be a newly created array */
6061 const VALUE ary2 = ary2st;
6062
6063 if (NIL_P(ary2)) return ary1;
6064
6065 VALUE tmp2 = rb_check_to_array(ary2);
6066
6067 if (NIL_P(tmp2)) {
6068 return rb_ary_push(ary1, ary2);
6069 }
6070 else {
6071 return rb_ary_concat(ary1, tmp2);
6072 }
6073}
6074
6075// YJIT implementation is using the C function
6076// and needs to call a non-static function
6077VALUE
6078rb_vm_concat_array(VALUE ary1, VALUE ary2st)
6079{
6080 return vm_concat_array(ary1, ary2st);
6081}
6082
6083VALUE
6084rb_vm_concat_to_array(VALUE ary1, VALUE ary2st)
6085{
6086 return vm_concat_to_array(ary1, ary2st);
6087}
6088
6089static VALUE
6090vm_splat_array(VALUE flag, VALUE ary)
6091{
6092 if (NIL_P(ary)) {
6093 return RTEST(flag) ? rb_ary_new() : rb_cArray_empty_frozen;
6094 }
6095 VALUE tmp = rb_check_to_array(ary);
6096 if (NIL_P(tmp)) {
6097 return rb_ary_new3(1, ary);
6098 }
6099 else if (RTEST(flag)) {
6100 return rb_ary_dup(tmp);
6101 }
6102 else {
6103 return tmp;
6104 }
6105}
6106
6107// YJIT implementation is using the C function
6108// and needs to call a non-static function
6109VALUE
6110rb_vm_splat_array(VALUE flag, VALUE ary)
6111{
6112 return vm_splat_array(flag, ary);
6113}
6114
6115static VALUE
6116vm_check_match(rb_execution_context_t *ec, VALUE target, VALUE pattern, rb_num_t flag)
6117{
6118 enum vm_check_match_type type = ((int)flag) & VM_CHECKMATCH_TYPE_MASK;
6119
6120 if (flag & VM_CHECKMATCH_ARRAY) {
6121 rb_len_t i;
6122 const rb_len_t n = RARRAY_LEN(pattern);
6123
6124 for (i = 0; i < n; i++) {
6125 VALUE v = RARRAY_AREF(pattern, i);
6126 VALUE c = check_match(ec, v, target, type);
6127
6128 if (RTEST(c)) {
6129 return c;
6130 }
6131 }
6132 return Qfalse;
6133 }
6134 else {
6135 return check_match(ec, pattern, target, type);
6136 }
6137}
6138
6139VALUE
6140rb_vm_check_match(rb_execution_context_t *ec, VALUE target, VALUE pattern, rb_num_t flag)
6141{
6142 return vm_check_match(ec, target, pattern, flag);
6143}
6144
6145static VALUE
6146vm_check_keyword(lindex_t bits, lindex_t idx, const VALUE *ep)
6147{
6148 const VALUE kw_bits = *(ep - bits);
6149
6150 if (FIXNUM_P(kw_bits)) {
6151 unsigned int b = (unsigned int)FIX2ULONG(kw_bits);
6152 if ((idx < VM_KW_SPECIFIED_BITS_MAX) && (b & (0x01 << idx)))
6153 return Qfalse;
6154 }
6155 else {
6156 VM_ASSERT(rb_set_p(kw_bits), "%s", rb_obj_info(kw_bits));
6157 if (rb_set_lookup(kw_bits, INT2FIX(idx))) return Qfalse;
6158 }
6159 return Qtrue;
6160}
6161
6162static void
6163vm_dtrace(rb_event_flag_t flag, rb_execution_context_t *ec)
6164{
6165 if (RUBY_DTRACE_METHOD_ENTRY_ENABLED() ||
6166 RUBY_DTRACE_METHOD_RETURN_ENABLED() ||
6167 RUBY_DTRACE_CMETHOD_ENTRY_ENABLED() ||
6168 RUBY_DTRACE_CMETHOD_RETURN_ENABLED()) {
6169
6170 switch (flag) {
6171 case RUBY_EVENT_CALL:
6172 RUBY_DTRACE_METHOD_ENTRY_HOOK(ec, 0, 0);
6173 return;
6174 case RUBY_EVENT_C_CALL:
6175 RUBY_DTRACE_CMETHOD_ENTRY_HOOK(ec, 0, 0);
6176 return;
6177 case RUBY_EVENT_RETURN:
6178 RUBY_DTRACE_METHOD_RETURN_HOOK(ec, 0, 0);
6179 return;
6181 RUBY_DTRACE_CMETHOD_RETURN_HOOK(ec, 0, 0);
6182 return;
6183 }
6184 }
6185}
6186
6187static VALUE
6188vm_const_get_under(ID id, rb_num_t flags, VALUE cbase)
6189{
6190 if (!rb_const_defined_at(cbase, id)) {
6191 return 0;
6192 }
6193 else if (VM_DEFINECLASS_SCOPED_P(flags)) {
6194 return rb_public_const_get_at(cbase, id);
6195 }
6196 else {
6197 return rb_const_get_at(cbase, id);
6198 }
6199}
6200
6201static VALUE
6202vm_check_if_class(ID id, rb_num_t flags, VALUE super, VALUE klass)
6203{
6204 if (!RB_TYPE_P(klass, T_CLASS)) {
6205 return 0;
6206 }
6207 else if (VM_DEFINECLASS_HAS_SUPERCLASS_P(flags)) {
6208 VALUE tmp = rb_class_real(RCLASS_SUPER(klass));
6209
6210 if (tmp != super) {
6211 rb_raise(rb_eTypeError,
6212 "superclass mismatch for class %"PRIsVALUE"",
6213 rb_id2str(id));
6214 }
6215 else {
6216 return klass;
6217 }
6218 }
6219 else {
6220 return klass;
6221 }
6222}
6223
6224static VALUE
6225vm_check_if_module(ID id, VALUE mod)
6226{
6227 if (!RB_TYPE_P(mod, T_MODULE)) {
6228 return 0;
6229 }
6230 else {
6231 return mod;
6232 }
6233}
6234
6235static VALUE
6236declare_under(ID id, VALUE cbase, VALUE c)
6237{
6238 rb_set_class_path_string(c, cbase, rb_id2str(id));
6239 rb_const_set(cbase, id, c);
6240 return c;
6241}
6242
6243static VALUE
6244vm_declare_class(ID id, rb_num_t flags, VALUE cbase, VALUE super)
6245{
6246 /* new class declaration */
6247 VALUE s = VM_DEFINECLASS_HAS_SUPERCLASS_P(flags) ? super : rb_cObject;
6248 VALUE c = declare_under(id, cbase, rb_define_class_id(id, s));
6249 rb_class_inherited(s, c);
6250 return c;
6251}
6252
6253static VALUE
6254vm_declare_module(ID id, VALUE cbase)
6255{
6256 /* new module declaration */
6257 return declare_under(id, cbase, rb_module_new());
6258}
6259
6260NORETURN(static void unmatched_redefinition(const char *type, VALUE cbase, ID id, VALUE old));
6261static void
6262unmatched_redefinition(const char *type, VALUE cbase, ID id, VALUE old)
6263{
6264 VALUE name = rb_id2str(id);
6265 VALUE message = rb_sprintf("%"PRIsVALUE" is not a %s",
6266 name, type);
6267 VALUE location = rb_const_source_location_at(cbase, id);
6268 if (!NIL_P(location)) {
6269 rb_str_catf(message, "\n%"PRIsVALUE":%"PRIsVALUE":"
6270 " previous definition of %"PRIsVALUE" was here",
6271 rb_ary_entry(location, 0), rb_ary_entry(location, 1), name);
6272 }
6274}
6275
6276static VALUE
6277vm_define_class(ID id, rb_num_t flags, VALUE cbase, VALUE super)
6278{
6279 VALUE klass;
6280
6281 if (VM_DEFINECLASS_HAS_SUPERCLASS_P(flags) && !RB_TYPE_P(super, T_CLASS)) {
6282 rb_raise(rb_eTypeError,
6283 "superclass must be an instance of Class (given an instance of %"PRIsVALUE")",
6284 rb_obj_class(super));
6285 }
6286
6287 vm_check_if_namespace(cbase);
6288
6289 /* find klass */
6290 rb_autoload_load(cbase, id);
6291
6292 if ((klass = vm_const_get_under(id, flags, cbase)) != 0) {
6293 if (!vm_check_if_class(id, flags, super, klass))
6294 unmatched_redefinition("class", cbase, id, klass);
6295 return klass;
6296 }
6297 else {
6298 return vm_declare_class(id, flags, cbase, super);
6299 }
6300}
6301
6302static VALUE
6303vm_define_module(ID id, rb_num_t flags, VALUE cbase)
6304{
6305 VALUE mod;
6306
6307 vm_check_if_namespace(cbase);
6308 if ((mod = vm_const_get_under(id, flags, cbase)) != 0) {
6309 if (!vm_check_if_module(id, mod))
6310 unmatched_redefinition("module", cbase, id, mod);
6311 return mod;
6312 }
6313 else {
6314 return vm_declare_module(id, cbase);
6315 }
6316}
6317
6318static VALUE
6319vm_find_or_create_class_by_id(ID id,
6320 rb_num_t flags,
6321 VALUE cbase,
6322 VALUE super)
6323{
6324 rb_vm_defineclass_type_t type = VM_DEFINECLASS_TYPE(flags);
6325
6326 switch (type) {
6327 case VM_DEFINECLASS_TYPE_CLASS:
6328 /* classdef returns class scope value */
6329 return vm_define_class(id, flags, cbase, super);
6330
6331 case VM_DEFINECLASS_TYPE_SINGLETON_CLASS:
6332 /* classdef returns class scope value */
6333 return rb_singleton_class(cbase);
6334
6335 case VM_DEFINECLASS_TYPE_MODULE:
6336 /* classdef returns class scope value */
6337 return vm_define_module(id, flags, cbase);
6338
6339 default:
6340 rb_bug("unknown defineclass type: %d", (int)type);
6341 }
6342}
6343
6344static rb_method_visibility_t
6345vm_scope_visibility_get(const rb_execution_context_t *ec)
6346{
6347 const rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp);
6348
6349 if (!vm_env_cref_by_cref(cfp->ep)) {
6350 return METHOD_VISI_PUBLIC;
6351 }
6352 else {
6353 return CREF_SCOPE_VISI(vm_ec_cref(ec))->method_visi;
6354 }
6355}
6356
6357static int
6358vm_scope_module_func_check(const rb_execution_context_t *ec)
6359{
6360 const rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(ec, ec->cfp);
6361
6362 if (!vm_env_cref_by_cref(cfp->ep)) {
6363 return FALSE;
6364 }
6365 else {
6366 return CREF_SCOPE_VISI(vm_ec_cref(ec))->module_func;
6367 }
6368}
6369
6370static void
6371vm_define_method(const rb_execution_context_t *ec, VALUE obj, ID id, VALUE iseqval, int is_singleton)
6372{
6373 VALUE klass;
6374 rb_method_visibility_t visi;
6375 rb_cref_t *cref = vm_ec_cref(ec);
6376
6377 if (is_singleton) {
6378 klass = rb_singleton_class(obj); /* class and frozen checked in this API */
6379 visi = METHOD_VISI_PUBLIC;
6380 }
6381 else {
6382 klass = CREF_CLASS_FOR_DEFINITION(cref);
6383 visi = vm_scope_visibility_get(ec);
6384 }
6385
6386 if (NIL_P(klass)) {
6387 rb_raise(rb_eTypeError, "no class/module to add method");
6388 }
6389
6390 rb_add_method_iseq(klass, id, (const rb_iseq_t *)iseqval, cref, visi);
6391 // Set max_iv_count on klasses based on number of ivar sets that are in the initialize method
6392 if (id == idInitialize && RB_TYPE_P(klass, T_CLASS) &&
6393 !RCLASS_SINGLETON_P(klass) && !RCLASS_EXPECT_NO_IVAR(klass) &&
6394 (rb_get_alloc_func(klass) == rb_class_allocate_instance)) {
6395 RCLASS_SET_MAX_IV_COUNT(klass, rb_estimate_iv_count(klass, (const rb_iseq_t *)iseqval));
6396 }
6397
6398 if (!is_singleton && vm_scope_module_func_check(ec)) {
6399 klass = rb_singleton_class(klass);
6400 rb_add_method_iseq(klass, id, (const rb_iseq_t *)iseqval, cref, METHOD_VISI_PUBLIC);
6401 }
6402}
6403
6404// Return the untagged block handler:
6405// * If it's VM_BLOCK_HANDLER_NONE, return nil
6406// * If it's an ISEQ or an IFUNC, fetch it from its rb_captured_block
6407// * If it's a PROC or SYMBOL, return it as is
6408VALUE
6409rb_vm_untag_block_handler(VALUE block_handler)
6410{
6411 if (VM_BLOCK_HANDLER_NONE == block_handler) return Qnil;
6412
6413 switch (vm_block_handler_type(block_handler)) {
6414 case block_handler_type_iseq:
6415 case block_handler_type_ifunc: {
6416 struct rb_captured_block *captured = VM_TAGGED_PTR_REF(block_handler, 0x03);
6417 return captured->code.val;
6418 }
6419 case block_handler_type_proc:
6420 case block_handler_type_symbol:
6421 return block_handler;
6422 default:
6423 rb_bug("rb_vm_untag_block_handler: unreachable");
6424 }
6425}
6426
6427VALUE
6428rb_vm_get_untagged_block_handler(rb_control_frame_t *reg_cfp)
6429{
6430 return rb_vm_untag_block_handler(VM_CF_BLOCK_HANDLER(reg_cfp));
6431}
6432
6433static VALUE
6434vm_invokeblock_i(struct rb_execution_context_struct *ec,
6435 struct rb_control_frame_struct *reg_cfp,
6436 struct rb_calling_info *calling)
6437{
6438 const struct rb_callinfo *ci = calling->cd->ci;
6439 VALUE block_handler = VM_CF_BLOCK_HANDLER(GET_CFP());
6440
6441 if (block_handler == VM_BLOCK_HANDLER_NONE) {
6442 rb_vm_localjump_error("no block given (yield)", Qnil, 0);
6443 }
6444 else {
6445 return vm_invoke_block(ec, GET_CFP(), calling, ci, false, block_handler);
6446 }
6447}
6448
6449enum method_explorer_type {
6450 mexp_search_method,
6451 mexp_search_invokeblock,
6452 mexp_search_super,
6453};
6454
6455ALWAYS_INLINE(static VALUE vm_sendish(struct rb_execution_context_struct *ec,
6456 struct rb_control_frame_struct *reg_cfp,
6457 struct rb_call_data *cd, VALUE block_handler,
6458 enum method_explorer_type method_explorer));
6459static inline VALUE
6460vm_sendish(
6461 struct rb_execution_context_struct *ec,
6462 struct rb_control_frame_struct *reg_cfp,
6463 struct rb_call_data *cd,
6464 VALUE block_handler,
6465 enum method_explorer_type method_explorer
6466) {
6467 VALUE val = Qundef;
6468 const struct rb_callinfo *ci = cd->ci;
6469 const struct rb_callcache *cc;
6470 int argc = vm_ci_argc(ci);
6471 VALUE recv = TOPN(argc);
6472 struct rb_calling_info calling = {
6473 .block_handler = block_handler,
6474 .kw_splat = IS_ARGS_KW_SPLAT(ci) > 0,
6475 .recv = recv,
6476 .argc = argc,
6477 .cd = cd,
6478 };
6479
6480 switch (method_explorer) {
6481 case mexp_search_method:
6482 calling.cc = cc = vm_search_method_fastpath(reg_cfp, cd, CLASS_OF(recv));
6483 val = vm_cc_call(cc)(ec, GET_CFP(), &calling);
6484 break;
6485 case mexp_search_super:
6486 calling.cc = cc = vm_search_super_method(reg_cfp, cd, recv);
6487 val = vm_cc_call(cc)(ec, GET_CFP(), &calling);
6488 break;
6489 case mexp_search_invokeblock:
6490 val = vm_invokeblock_i(ec, GET_CFP(), &calling);
6491 break;
6492 }
6493 return val;
6494}
6495
6496VALUE
6497rb_vm_send(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, CALL_DATA cd, ISEQ blockiseq)
6498{
6499 stack_check(ec);
6500 VALUE bh = vm_caller_setup_arg_block(ec, GET_CFP(), cd->ci, blockiseq, false);
6501 VALUE val = vm_sendish(ec, GET_CFP(), cd, bh, mexp_search_method);
6502 VM_EXEC(ec, val);
6503 return val;
6504}
6505
6506// Fallback for YJIT/ZJIT, not used by the interpreter
6507VALUE
6508rb_vm_sendforward(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, CALL_DATA cd, ISEQ blockiseq)
6509{
6510 stack_check(ec);
6511
6512 struct rb_forwarding_call_data adjusted_cd;
6513 struct rb_callinfo adjusted_ci;
6514
6515 VALUE bh = vm_caller_setup_fwd_args(GET_EC(), GET_CFP(), cd, blockiseq, false, &adjusted_cd, &adjusted_ci);
6516
6517 VALUE val = vm_sendish(ec, GET_CFP(), &adjusted_cd.cd, bh, mexp_search_method);
6518
6519 if (cd->cc != adjusted_cd.cd.cc && vm_cc_markable(adjusted_cd.cd.cc)) {
6520 RB_OBJ_WRITE(CFP_ISEQ(GET_CFP()), &cd->cc, adjusted_cd.cd.cc);
6521 }
6522
6523 VM_EXEC(ec, val);
6524 return val;
6525}
6526
6527VALUE
6528rb_vm_opt_send_without_block(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, CALL_DATA cd)
6529{
6530 stack_check(ec);
6531 VALUE bh = VM_BLOCK_HANDLER_NONE;
6532 VALUE val = vm_sendish(ec, GET_CFP(), cd, bh, mexp_search_method);
6533 VM_EXEC(ec, val);
6534 return val;
6535}
6536
6537VALUE
6538rb_vm_invokesuper(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, CALL_DATA cd, ISEQ blockiseq)
6539{
6540 stack_check(ec);
6541
6542 struct rb_callinfo adjusted_ci = VM_CI_ON_STACK(vm_ci_mid(cd->ci),
6543 vm_ci_flag(cd->ci),
6544 vm_ci_argc(cd->ci),
6545 vm_ci_kwarg(cd->ci));
6546 const struct rb_callcache *original_cc = rbimpl_atomic_ptr_load((void **)&cd->cc, RBIMPL_ATOMIC_ACQUIRE);
6547 struct rb_call_data adjusted_cd = {
6548 .ci = &adjusted_ci,
6549 .cc = original_cc,
6550 };
6551
6552 VALUE bh = vm_caller_setup_arg_block(ec, GET_CFP(), adjusted_cd.ci, blockiseq, true);
6553 VALUE val = vm_sendish(ec, GET_CFP(), &adjusted_cd, bh, mexp_search_super);
6554
6555 if (original_cc != adjusted_cd.cc && vm_cc_markable(adjusted_cd.cc)) {
6556 rbimpl_atomic_ptr_store((volatile void **)&cd->cc, (void *)adjusted_cd.cc, RBIMPL_ATOMIC_RELEASE);
6557 RB_OBJ_WRITTEN(CFP_ISEQ(GET_CFP()), Qundef, adjusted_cd.cc);
6558 }
6559
6560 VM_EXEC(ec, val);
6561 return val;
6562}
6563
6564// Fallback for YJIT/ZJIT, not used by the interpreter
6565VALUE
6566rb_vm_invokesuperforward(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, CALL_DATA cd, ISEQ blockiseq)
6567{
6568 stack_check(ec);
6569 struct rb_forwarding_call_data adjusted_cd;
6570 struct rb_callinfo adjusted_ci;
6571
6572 VALUE bh = vm_caller_setup_fwd_args(GET_EC(), GET_CFP(), cd, blockiseq, true, &adjusted_cd, &adjusted_ci);
6573
6574 VALUE val = vm_sendish(ec, GET_CFP(), &adjusted_cd.cd, bh, mexp_search_super);
6575
6576 if (cd->cc != adjusted_cd.cd.cc && vm_cc_markable(adjusted_cd.cd.cc)) {
6577 RB_OBJ_WRITE(CFP_ISEQ(GET_CFP()), &cd->cc, adjusted_cd.cd.cc);
6578 }
6579
6580 VM_EXEC(ec, val);
6581 return val;
6582}
6583
6584VALUE
6585rb_vm_invokeblock(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, CALL_DATA cd)
6586{
6587 stack_check(ec);
6588 VALUE bh = VM_BLOCK_HANDLER_NONE;
6589 VALUE val = vm_sendish(ec, GET_CFP(), cd, bh, mexp_search_invokeblock);
6590 VM_EXEC(ec, val);
6591 return val;
6592}
6593
6594/* object.c */
6595VALUE rb_nil_to_s(VALUE);
6596VALUE rb_true_to_s(VALUE);
6597VALUE rb_false_to_s(VALUE);
6598/* numeric.c */
6599VALUE rb_int_to_s(int argc, VALUE *argv, VALUE x);
6600VALUE rb_fix_to_s(VALUE);
6601/* variable.c */
6602VALUE rb_mod_to_s(VALUE);
6604
6605static VALUE
6606vm_objtostring(struct rb_control_frame_struct *reg_cfp, VALUE recv, CALL_DATA cd)
6607{
6608 int type = TYPE(recv);
6609 if (type == T_STRING) {
6610 return recv;
6611 }
6612
6613 const struct rb_callable_method_entry_struct *cme = vm_search_method(reg_cfp, cd, recv);
6614
6615 switch (type) {
6616 case T_SYMBOL:
6617 if (check_method_basic_definition(cme)) {
6618 return rb_sym2str(recv);
6619 }
6620 break;
6621 case T_MODULE:
6622 case T_CLASS:
6623 if (check_cfunc(cme, rb_mod_to_s)) {
6624 // rb_mod_to_s() allocates a mutable string, but since we are only
6625 // going to use this string for interpolation, it's fine to use the
6626 // frozen string.
6627 VALUE val = rb_mod_name(recv);
6628 if (NIL_P(val)) {
6629 val = rb_mod_to_s(recv);
6630 }
6631 return val;
6632 }
6633 break;
6634 case T_NIL:
6635 if (check_cfunc(cme, rb_nil_to_s)) {
6636 return rb_nil_to_s(recv);
6637 }
6638 break;
6639 case T_TRUE:
6640 if (check_cfunc(cme, rb_true_to_s)) {
6641 return rb_true_to_s(recv);
6642 }
6643 break;
6644 case T_FALSE:
6645 if (check_cfunc(cme, rb_false_to_s)) {
6646 return rb_false_to_s(recv);
6647 }
6648 break;
6649 case T_FIXNUM:
6650 if (check_cfunc(cme, rb_int_to_s)) {
6651 return rb_fix_to_s(recv);
6652 }
6653 break;
6654 }
6655 return Qundef;
6656}
6657
6658// ZJIT implementation is using the C function
6659// and needs to call a non-static function
6660VALUE
6661rb_vm_objtostring(struct rb_control_frame_struct *reg_cfp, VALUE recv, CALL_DATA cd)
6662{
6663 return vm_objtostring(reg_cfp, recv, cd);
6664}
6665
6666static VALUE
6667vm_opt_ary_freeze(VALUE ary, int bop, ID id)
6668{
6669 if (BASIC_OP_UNREDEFINED_P(bop, ARRAY_REDEFINED_OP_FLAG)) {
6670 return ary;
6671 }
6672 else {
6673 return Qundef;
6674 }
6675}
6676
6677static VALUE
6678vm_opt_hash_freeze(VALUE hash, int bop, ID id)
6679{
6680 if (BASIC_OP_UNREDEFINED_P(bop, HASH_REDEFINED_OP_FLAG)) {
6681 return hash;
6682 }
6683 else {
6684 return Qundef;
6685 }
6686}
6687
6688static VALUE
6689vm_opt_str_freeze(VALUE str, int bop, ID id)
6690{
6691 if (BASIC_OP_UNREDEFINED_P(bop, STRING_REDEFINED_OP_FLAG)) {
6692 return str;
6693 }
6694 else {
6695 return Qundef;
6696 }
6697}
6698
6699/* this macro is mandatory to use OPTIMIZED_CMP. What a design! */
6700#define id_cmp idCmp
6701
6702static VALUE
6703vm_opt_duparray_include_p(rb_execution_context_t *ec, const VALUE ary, VALUE target)
6704{
6705 if (OP_UNREDEFINED_P(INCLUDE_P, ARRAY)) {
6706 return rb_ary_includes(ary, target);
6707 }
6708 else {
6709 VALUE args[1] = {target};
6710
6711 // duparray
6712 RUBY_DTRACE_CREATE_HOOK(ARRAY, RARRAY_LEN(ary));
6713 VALUE dupary = rb_ary_resurrect(ary);
6714
6715 return rb_vm_call_with_refinements(ec, dupary, idIncludeP, 1, args, RB_NO_KEYWORDS);
6716 }
6717}
6718
6719VALUE
6720rb_vm_opt_duparray_include_p(rb_execution_context_t *ec, const VALUE ary, VALUE target)
6721{
6722 return vm_opt_duparray_include_p(ec, ary, target);
6723}
6724
6725static VALUE
6726vm_opt_newarray_max(rb_execution_context_t *ec, rb_num_t array_len, const VALUE *ptr)
6727{
6728 if (OP_UNREDEFINED_P(MAX, ARRAY)) {
6729 if (array_len == 0) {
6730 return Qnil;
6731 }
6732 else {
6733 VALUE result = *ptr;
6734 rb_snum_t i = array_len - 1;
6735 while (i-- > 0) {
6736 const VALUE v = *++ptr;
6737 if (OPTIMIZED_CMP(v, result) > 0) {
6738 result = v;
6739 }
6740 }
6741 return result;
6742 }
6743 }
6744 else {
6745 return rb_vm_call_with_refinements(ec, rb_ary_new4(array_len, ptr), idMax, 0, NULL, RB_NO_KEYWORDS);
6746 }
6747}
6748
6749VALUE
6750rb_vm_opt_newarray_max(rb_execution_context_t *ec, rb_num_t array_len, const VALUE *ptr)
6751{
6752 return vm_opt_newarray_max(ec, array_len, ptr);
6753}
6754
6755static VALUE
6756vm_opt_newarray_min(rb_execution_context_t *ec, rb_num_t array_len, const VALUE *ptr)
6757{
6758 if (OP_UNREDEFINED_P(MIN, ARRAY)) {
6759 if (array_len == 0) {
6760 return Qnil;
6761 }
6762 else {
6763 VALUE result = *ptr;
6764 rb_snum_t i = array_len - 1;
6765 while (i-- > 0) {
6766 const VALUE v = *++ptr;
6767 if (OPTIMIZED_CMP(v, result) < 0) {
6768 result = v;
6769 }
6770 }
6771 return result;
6772 }
6773 }
6774 else {
6775 return rb_vm_call_with_refinements(ec, rb_ary_new4(array_len, ptr), idMin, 0, NULL, RB_NO_KEYWORDS);
6776 }
6777}
6778
6779VALUE
6780rb_vm_opt_newarray_min(rb_execution_context_t *ec, rb_num_t array_len, const VALUE *ptr)
6781{
6782 return vm_opt_newarray_min(ec, array_len, ptr);
6783}
6784
6785static VALUE
6786vm_opt_newarray_hash(rb_execution_context_t *ec, rb_num_t array_len, const VALUE *ptr)
6787{
6788 // If Array#hash is _not_ monkeypatched, use the optimized call
6789 if (OP_UNREDEFINED_P(HASH, ARRAY)) {
6790 return rb_ary_hash_values(array_len, ptr);
6791 }
6792 else {
6793 return rb_vm_call_with_refinements(ec, rb_ary_new4(array_len, ptr), idHash, 0, NULL, RB_NO_KEYWORDS);
6794 }
6795}
6796
6797VALUE
6798rb_vm_opt_newarray_hash(rb_execution_context_t *ec, rb_num_t array_len, const VALUE *ptr)
6799{
6800 return vm_opt_newarray_hash(ec, array_len, ptr);
6801}
6802
6803VALUE rb_setup_fake_ary(struct RArray *fake_ary, const VALUE *list, rb_len_t len);
6804VALUE rb_ec_pack_ary(rb_execution_context_t *ec, VALUE ary, VALUE fmt, VALUE buffer);
6805
6806static VALUE
6807vm_opt_newarray_include_p(rb_execution_context_t *ec, rb_num_t array_len, const VALUE *ptr, VALUE target)
6808{
6809 if (OP_UNREDEFINED_P(INCLUDE_P, ARRAY)) {
6810 struct RArray fake_ary = {RBASIC_INIT};
6811 VALUE ary = rb_setup_fake_ary(&fake_ary, ptr, array_len);
6812 return rb_ary_includes(ary, target);
6813 }
6814 else {
6815 VALUE args[1] = {target};
6816 return rb_vm_call_with_refinements(ec, rb_ary_new4(array_len, ptr), idIncludeP, 1, args, RB_NO_KEYWORDS);
6817 }
6818}
6819
6820VALUE
6821rb_vm_opt_newarray_include_p(rb_execution_context_t *ec, rb_num_t array_len, const VALUE *ptr, VALUE target)
6822{
6823 return vm_opt_newarray_include_p(ec, array_len, ptr, target);
6824}
6825
6826static VALUE
6827vm_opt_newarray_pack_buffer(rb_execution_context_t *ec, rb_num_t array_len, const VALUE *ptr, VALUE fmt, VALUE buffer)
6828{
6829 if (OP_UNREDEFINED_P(PACK, ARRAY)) {
6830 struct RArray fake_ary = {RBASIC_INIT};
6831 VALUE ary = rb_setup_fake_ary(&fake_ary, ptr, array_len);
6832 return rb_ec_pack_ary(ec, ary, fmt, (UNDEF_P(buffer) ? Qnil : buffer));
6833 }
6834 else {
6835 // The opt_newarray_send insn drops the keyword args so we need to rebuild them.
6836 // Setup an array with room for keyword hash.
6837 VALUE args[2];
6838 args[0] = fmt;
6839 int kw_splat = RB_NO_KEYWORDS;
6840 int argc = 1;
6841
6842 if (!UNDEF_P(buffer)) {
6843 args[1] = rb_hash_new_capa(1);
6844 rb_hash_aset(args[1], ID2SYM(idBuffer), buffer);
6845 kw_splat = RB_PASS_KEYWORDS;
6846 argc++;
6847 }
6848
6849 return rb_vm_call_with_refinements(ec, rb_ary_new4(array_len, ptr), idPack, argc, args, kw_splat);
6850 }
6851}
6852
6853VALUE
6854rb_vm_opt_newarray_pack_buffer(rb_execution_context_t *ec, rb_num_t array_len, const VALUE *ptr, VALUE fmt, VALUE buffer)
6855{
6856 return vm_opt_newarray_pack_buffer(ec, array_len, ptr, fmt, buffer);
6857}
6858
6859
6860#undef id_cmp
6861
6862static void
6863vm_track_constant_cache(ID id, void *ic)
6864{
6865 rb_vm_t *vm = GET_VM();
6866 struct rb_id_table *const_cache = &vm->constant_cache;
6867 VALUE lookup_result;
6868 set_table *ics;
6869
6870 if (rb_id_table_lookup(const_cache, id, &lookup_result)) {
6871 ics = (set_table *)lookup_result;
6872 }
6873 else {
6874 ics = set_init_numtable();
6875 rb_id_table_insert(const_cache, id, (VALUE)ics);
6876 }
6877
6878 /* The call below to st_insert could allocate which could trigger a GC.
6879 * If it triggers a GC, it may free an iseq that also holds a cache to this
6880 * constant. If that iseq is the last iseq with a cache to this constant, then
6881 * it will free this ST table, which would cause an use-after-free during this
6882 * st_insert.
6883 *
6884 * So to fix this issue, we store the ID that is currently being inserted
6885 * and, in remove_from_constant_cache, we don't free the ST table for ID
6886 * equal to this one.
6887 *
6888 * See [Bug #20921].
6889 */
6890 vm->inserting_constant_cache_id = id;
6891
6892 set_insert(ics, (st_data_t)ic);
6893
6894 vm->inserting_constant_cache_id = (ID)0;
6895}
6896
6897static void
6898vm_ic_track_const_chain(rb_control_frame_t *cfp, IC ic, const rb_const_path_t const_path)
6899{
6900 RB_VM_LOCKING() {
6901 size_t i = 0;
6902 ID segment;
6903 while (((segment = const_path_aref(const_path, i)))) {
6904 vm_track_constant_cache(segment, ic);
6905 i++;
6906 }
6907 }
6908}
6909
6910// For JIT inlining
6911static inline bool
6912vm_inlined_ic_hit_p(VALUE flags, VALUE value, const rb_cref_t *ic_cref, rb_serial_t ractor_id, const VALUE *reg_ep)
6913{
6914 // Not rb_ractor_main_p(): an owner Ractor may now cache an unshareable constant
6915 // of its own class, and only it may be handed that value back.
6916 if ((flags & IMEMO_CONST_CACHE_SHAREABLE) || ractor_id == rb_ractor_id(GET_RACTOR())) {
6917 VM_ASSERT(ractor_incidental_shareable_p(flags & IMEMO_CONST_CACHE_SHAREABLE, value));
6918
6919 return (ic_cref == NULL || // no need to check CREF
6920 ic_cref == vm_get_cref(reg_ep));
6921 }
6922 return false;
6923}
6924
6925static bool
6926vm_ic_hit_p(const struct iseq_inline_constant_cache_entry *ice, const VALUE *reg_ep)
6927{
6928 VM_ASSERT(IMEMO_TYPE_P(ice, imemo_constcache));
6929 return vm_inlined_ic_hit_p(ice->flags, ice->value, ice->ic_cref, ice->ractor_id, reg_ep);
6930}
6931
6932// YJIT needs this function to never allocate and never raise
6933bool
6934rb_vm_ic_hit_p(IC ic, const VALUE *reg_ep)
6935{
6936 return ic->entry && vm_ic_hit_p(ic->entry, reg_ep);
6937}
6938
6939static void
6940vm_ic_update(const rb_execution_context_t *ec, const rb_iseq_t *iseq, IC ic, VALUE val, const VALUE *reg_ep)
6941{
6942 if (ruby_vm_const_missing_count > 0) {
6943 ruby_vm_const_missing_count = 0;
6944 ic->entry = NULL;
6945 return;
6946 }
6947
6948 struct iseq_inline_constant_cache_entry *ice = SHAREABLE_IMEMO_NEW(struct iseq_inline_constant_cache_entry, imemo_constcache, 0);
6949 RB_OBJ_WRITE(ice, &ice->value, val);
6950 ice->ic_cref = vm_get_const_key_cref(reg_ep);
6951 ice->ractor_id = rb_ractor_id(rb_ec_ractor_ptr(ec));
6952
6953 if (rb_ractor_shareable_p(val)) {
6954 RUBY_ASSERT((rb_gc_verify_shareable(val), 1));
6955 ice->flags |= IMEMO_CONST_CACHE_SHAREABLE;
6956 }
6957 RB_OBJ_WRITE(iseq, &ic->entry, ice);
6958
6959#if USE_YJIT
6960 if (rb_yjit_enabled_p && ISEQ_BODY(iseq)->jit_payload) {
6961 // Multiple `opt_getconstant_path` instructions may share the same IC,
6962 // we must call `rb_yjit_constant_ic_update` for each of them.
6963 const VALUE *encoded = ISEQ_BODY(iseq)->iseq_encoded;
6964 unsigned int size = ISEQ_BODY(iseq)->iseq_size;
6965 for (unsigned int pos = 0; pos < size;) {
6966 int insn = rb_vm_insn_decode(encoded[pos]);
6967 if (insn == BIN(opt_getconstant_path) && (IC)encoded[pos + 1] == ic) {
6968 rb_yjit_constant_ic_update(iseq, ic, pos);
6969 }
6970 pos += insn_len(insn);
6971 }
6972 }
6973#endif
6974}
6975
6976VALUE
6977rb_vm_opt_getconstant_path(rb_execution_context_t *ec, rb_control_frame_t *const reg_cfp, IC ic)
6978{
6979 VALUE val;
6980 const rb_const_path_t const_path = ic->const_path;
6981 struct iseq_inline_constant_cache_entry *ice = ic->entry;
6982
6983 if (ice && vm_ic_hit_p(ice, GET_EP())) {
6984 val = ice->value;
6985
6986 // On a non-main ractor another ractor can concurrently reassign a
6987 // shareable constant (which invalidates ICs asynchronously), so the
6988 // cached-but-still-shareable value may legitimately differ from a
6989 // freshly recomputed chain. Only assert equality when single-ractor.
6990 VM_ASSERT(val == vm_get_ev_const_chain(ec, const_path) || rb_multi_ractor_p());
6991 }
6992 else {
6993 ruby_vm_constant_cache_misses++;
6994 val = vm_get_ev_const_chain(ec, const_path);
6995 vm_ic_track_const_chain(GET_CFP(), ic, const_path);
6996 vm_ic_update(ec, CFP_ISEQ(GET_CFP()), ic, val, GET_EP());
6997 }
6998 return val;
6999}
7000
7001// Return true if the once value is already computed and set *result to the value.
7002// Otherwise, return false.
7003// Used for ZJIT. Keep in sync with `vm_once_dispatch` below.
7004bool
7005rb_vm_once_done_value(VALUE once_storage, VALUE *result)
7006{
7007 struct rb_imemo_once_storage *storage = (struct rb_imemo_once_storage *)once_storage;
7008 rb_thread_t *running_th = rbimpl_atomic_ptr_load((void **)&storage->running_thread, RBIMPL_ATOMIC_ACQUIRE);
7009 if (running_th == RUNNING_THREAD_ONCE_DONE) {
7010 *result = storage->value;
7011 return true;
7012 }
7013 return false;
7014}
7015
7016static VALUE
7017vm_once_dispatch(rb_execution_context_t *ec, ISEQ iseq, VALUE once_storage)
7018{
7019 struct rb_imemo_once_storage *storage = (struct rb_imemo_once_storage *)once_storage;
7020 rb_thread_t *th = rb_ec_thread_ptr(ec);
7021 rb_thread_t *running_th;
7022
7023 again:
7024 running_th = rbimpl_atomic_ptr_load((void **)&storage->running_thread, RBIMPL_ATOMIC_ACQUIRE);
7025 if (running_th == RUNNING_THREAD_ONCE_DONE) {
7026 return storage->value;
7027 }
7028 else if (running_th == NULL) {
7029 VALUE val = Qundef;
7030 enum ruby_tag_type state;
7031 if (rbimpl_atomic_ptr_cas((void **)&storage->running_thread, running_th, th, RBIMPL_ATOMIC_RELEASE, RBIMPL_ATOMIC_RELAXED) != running_th) {
7032 goto again;
7033 }
7034 EC_PUSH_TAG(ec);
7035 if ((state = EC_EXEC_TAG()) == TAG_NONE) {
7036 val = vm_once_exec((VALUE)iseq);
7037 }
7038 EC_POP_TAG();
7039 if (state != TAG_NONE) {
7040 vm_once_clear((VALUE)storage);
7041 EC_JUMP_TAG(ec, state);
7042 }
7043
7044 // TODO: confirm that it is shareable
7045 if (RB_FL_ABLE(val)) {
7047 }
7048
7049 RB_OBJ_WRITE((VALUE)storage, &storage->value, val);
7050
7051 rbimpl_atomic_ptr_store((volatile void**)&storage->running_thread, RUNNING_THREAD_ONCE_DONE, RBIMPL_ATOMIC_RELEASE); /* success */
7052 vm_once_broadcast(rb_ec_vm_ptr(ec));
7053 return val;
7054 }
7055 else if (running_th == th) {
7056 /* recursive once */
7057 return vm_once_exec((VALUE)iseq);
7058 }
7059 else {
7060 /* wait for the winner to finish */
7061 struct vm_once_wait_arg arg = { .vm = rb_ec_vm_ptr(ec), .storage = storage };
7062 rb_nogvl(vm_once_wait_no_gvl, &arg, vm_once_wait_ubf, arg.vm,
7064 RUBY_VM_CHECK_INTS(ec);
7065 goto again;
7066 }
7067}
7068
7069static OFFSET
7070vm_case_dispatch(CDHASH hash, OFFSET else_offset, VALUE key)
7071{
7072 switch (OBJ_BUILTIN_TYPE(key)) {
7073 case -1:
7074 case T_FLOAT:
7075 case T_SYMBOL:
7076 case T_BIGNUM:
7077 case T_STRING:
7078 if (BASIC_OP_UNREDEFINED_P(BOP_EQQ,
7079 SYMBOL_REDEFINED_OP_FLAG |
7080 INTEGER_REDEFINED_OP_FLAG |
7081 FLOAT_REDEFINED_OP_FLAG |
7082 NIL_REDEFINED_OP_FLAG |
7083 TRUE_REDEFINED_OP_FLAG |
7084 FALSE_REDEFINED_OP_FLAG |
7085 STRING_REDEFINED_OP_FLAG)) {
7086 st_data_t val;
7087 if (RB_FLOAT_TYPE_P(key)) {
7088 double kval = RFLOAT_VALUE(key);
7089 if (!isinf(kval) && modf(kval, &kval) == 0.0) {
7090 key = FIXABLE(kval) ? LONG2FIX((long)kval) : rb_dbl2big(kval);
7091 }
7092 }
7093 if (st_lookup(rb_imemo_cdhash_tbl(hash), key, &val)) {
7094 return (VALUE)val;
7095 }
7096 else {
7097 return else_offset;
7098 }
7099 }
7100 }
7101 return 0;
7102}
7103
7104NORETURN(static void
7105 vm_stack_consistency_error(const rb_execution_context_t *ec,
7106 const rb_control_frame_t *,
7107 const VALUE *));
7108static void
7109vm_stack_consistency_error(const rb_execution_context_t *ec,
7110 const rb_control_frame_t *cfp,
7111 const VALUE *bp)
7112{
7113 const ptrdiff_t nsp = VM_SP_CNT(ec, cfp->sp);
7114 const ptrdiff_t nbp = VM_SP_CNT(ec, bp);
7115 static const char stack_consistency_error[] =
7116 "Stack consistency error (sp: %"PRIdPTRDIFF", bp: %"PRIdPTRDIFF")";
7117#if defined RUBY_DEVEL
7118 VALUE mesg = rb_sprintf(stack_consistency_error, nsp, nbp);
7119 rb_str_cat_cstr(mesg, "\n");
7120 rb_str_append(mesg, rb_iseq_disasm(CFP_ISEQ(cfp)));
7122#else
7123 rb_bug(stack_consistency_error, nsp, nbp);
7124#endif
7125}
7126
7127static VALUE
7128vm_opt_plus(VALUE recv, VALUE obj)
7129{
7130 if (FIXNUM_2_P(recv, obj) &&
7131 OP_UNREDEFINED_P(PLUS, INTEGER)) {
7132 return rb_fix_plus_fix(recv, obj);
7133 }
7134 else if (FLONUM_2_P(recv, obj) &&
7135 OP_UNREDEFINED_P(PLUS, FLOAT)) {
7136 return DBL2NUM(RFLOAT_VALUE(recv) + RFLOAT_VALUE(obj));
7137 }
7138 else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) {
7139 return Qundef;
7140 }
7141 else if (RBASIC_CLASS(recv) == rb_cFloat &&
7142 RBASIC_CLASS(obj) == rb_cFloat &&
7143 OP_UNREDEFINED_P(PLUS, FLOAT)) {
7144 return DBL2NUM(RFLOAT_VALUE(recv) + RFLOAT_VALUE(obj));
7145 }
7146 else if (RBASIC_CLASS(recv) == rb_cString &&
7147 RBASIC_CLASS(obj) == rb_cString &&
7148 OP_UNREDEFINED_P(PLUS, STRING)) {
7149 return rb_str_opt_plus(recv, obj);
7150 }
7151 else if (RBASIC_CLASS(recv) == rb_cArray &&
7152 RBASIC_CLASS(obj) == rb_cArray &&
7153 OP_UNREDEFINED_P(PLUS, ARRAY)) {
7154 return rb_ary_plus(recv, obj);
7155 }
7156 else {
7157 return Qundef;
7158 }
7159}
7160
7161static VALUE
7162vm_opt_minus(VALUE recv, VALUE obj)
7163{
7164 if (FIXNUM_2_P(recv, obj) &&
7165 OP_UNREDEFINED_P(MINUS, INTEGER)) {
7166 return rb_fix_minus_fix(recv, obj);
7167 }
7168 else if (FLONUM_2_P(recv, obj) &&
7169 OP_UNREDEFINED_P(MINUS, FLOAT)) {
7170 return DBL2NUM(RFLOAT_VALUE(recv) - RFLOAT_VALUE(obj));
7171 }
7172 else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) {
7173 return Qundef;
7174 }
7175 else if (RBASIC_CLASS(recv) == rb_cFloat &&
7176 RBASIC_CLASS(obj) == rb_cFloat &&
7177 OP_UNREDEFINED_P(MINUS, FLOAT)) {
7178 return DBL2NUM(RFLOAT_VALUE(recv) - RFLOAT_VALUE(obj));
7179 }
7180 else {
7181 return Qundef;
7182 }
7183}
7184
7185static VALUE
7186vm_opt_mult(VALUE recv, VALUE obj)
7187{
7188 if (FIXNUM_2_P(recv, obj) &&
7189 OP_UNREDEFINED_P(MULT, INTEGER)) {
7190 return rb_fix_mul_fix(recv, obj);
7191 }
7192 else if (FLONUM_2_P(recv, obj) &&
7193 OP_UNREDEFINED_P(MULT, FLOAT)) {
7194 return DBL2NUM(RFLOAT_VALUE(recv) * RFLOAT_VALUE(obj));
7195 }
7196 else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) {
7197 return Qundef;
7198 }
7199 else if (RBASIC_CLASS(recv) == rb_cFloat &&
7200 RBASIC_CLASS(obj) == rb_cFloat &&
7201 OP_UNREDEFINED_P(MULT, FLOAT)) {
7202 return DBL2NUM(RFLOAT_VALUE(recv) * RFLOAT_VALUE(obj));
7203 }
7204 else {
7205 return Qundef;
7206 }
7207}
7208
7209static VALUE
7210vm_opt_div(VALUE recv, VALUE obj)
7211{
7212 if (FIXNUM_2_P(recv, obj) &&
7213 OP_UNREDEFINED_P(DIV, INTEGER)) {
7214 return (FIX2LONG(obj) == 0) ? Qundef : rb_fix_div_fix(recv, obj);
7215 }
7216 else if (FLONUM_2_P(recv, obj) &&
7217 OP_UNREDEFINED_P(DIV, FLOAT)) {
7218 return rb_flo_div_flo(recv, obj);
7219 }
7220 else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) {
7221 return Qundef;
7222 }
7223 else if (RBASIC_CLASS(recv) == rb_cFloat &&
7224 RBASIC_CLASS(obj) == rb_cFloat &&
7225 OP_UNREDEFINED_P(DIV, FLOAT)) {
7226 return rb_flo_div_flo(recv, obj);
7227 }
7228 else {
7229 return Qundef;
7230 }
7231}
7232
7233static VALUE
7234vm_opt_mod(VALUE recv, VALUE obj)
7235{
7236 if (FIXNUM_2_P(recv, obj) &&
7237 OP_UNREDEFINED_P(MOD, INTEGER)) {
7238 return (FIX2LONG(obj) == 0) ? Qundef : rb_fix_mod_fix(recv, obj);
7239 }
7240 else if (FLONUM_2_P(recv, obj) &&
7241 OP_UNREDEFINED_P(MOD, FLOAT)) {
7242 return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(recv), RFLOAT_VALUE(obj)));
7243 }
7244 else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) {
7245 return Qundef;
7246 }
7247 else if (RBASIC_CLASS(recv) == rb_cFloat &&
7248 RBASIC_CLASS(obj) == rb_cFloat &&
7249 OP_UNREDEFINED_P(MOD, FLOAT)) {
7250 return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(recv), RFLOAT_VALUE(obj)));
7251 }
7252 else {
7253 return Qundef;
7254 }
7255}
7256
7257static VALUE
7258vm_opt_neq(struct rb_control_frame_struct *reg_cfp, CALL_DATA cd, CALL_DATA cd_eq, VALUE recv, VALUE obj)
7259{
7260 if (vm_method_cfunc_is(reg_cfp, cd, recv, rb_obj_not_equal)) {
7261 VALUE val = opt_equality(reg_cfp, recv, obj, cd_eq);
7262
7263 if (!UNDEF_P(val)) {
7264 return RBOOL(!RTEST(val));
7265 }
7266 }
7267
7268 return Qundef;
7269}
7270
7271static VALUE
7272vm_opt_lt(VALUE recv, VALUE obj)
7273{
7274 if (FIXNUM_2_P(recv, obj) &&
7275 OP_UNREDEFINED_P(LT, INTEGER)) {
7276 return RBOOL((SIGNED_VALUE)recv < (SIGNED_VALUE)obj);
7277 }
7278 else if (FLONUM_2_P(recv, obj) &&
7279 OP_UNREDEFINED_P(LT, FLOAT)) {
7280 return RBOOL(RFLOAT_VALUE(recv) < RFLOAT_VALUE(obj));
7281 }
7282 else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) {
7283 return Qundef;
7284 }
7285 else if (RBASIC_CLASS(recv) == rb_cFloat &&
7286 RBASIC_CLASS(obj) == rb_cFloat &&
7287 OP_UNREDEFINED_P(LT, FLOAT)) {
7288 return RBOOL(RFLOAT_VALUE(recv) < RFLOAT_VALUE(obj));
7289 }
7290 else {
7291 return Qundef;
7292 }
7293}
7294
7295static VALUE
7296vm_opt_le(VALUE recv, VALUE obj)
7297{
7298 if (FIXNUM_2_P(recv, obj) &&
7299 OP_UNREDEFINED_P(LE, INTEGER)) {
7300 return RBOOL((SIGNED_VALUE)recv <= (SIGNED_VALUE)obj);
7301 }
7302 else if (FLONUM_2_P(recv, obj) &&
7303 OP_UNREDEFINED_P(LE, FLOAT)) {
7304 return RBOOL(RFLOAT_VALUE(recv) <= RFLOAT_VALUE(obj));
7305 }
7306 else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) {
7307 return Qundef;
7308 }
7309 else if (RBASIC_CLASS(recv) == rb_cFloat &&
7310 RBASIC_CLASS(obj) == rb_cFloat &&
7311 OP_UNREDEFINED_P(LE, FLOAT)) {
7312 return RBOOL(RFLOAT_VALUE(recv) <= RFLOAT_VALUE(obj));
7313 }
7314 else {
7315 return Qundef;
7316 }
7317}
7318
7319static VALUE
7320vm_opt_gt(VALUE recv, VALUE obj)
7321{
7322 if (FIXNUM_2_P(recv, obj) &&
7323 OP_UNREDEFINED_P(GT, INTEGER)) {
7324 return RBOOL((SIGNED_VALUE)recv > (SIGNED_VALUE)obj);
7325 }
7326 else if (FLONUM_2_P(recv, obj) &&
7327 OP_UNREDEFINED_P(GT, FLOAT)) {
7328 return RBOOL(RFLOAT_VALUE(recv) > RFLOAT_VALUE(obj));
7329 }
7330 else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) {
7331 return Qundef;
7332 }
7333 else if (RBASIC_CLASS(recv) == rb_cFloat &&
7334 RBASIC_CLASS(obj) == rb_cFloat &&
7335 OP_UNREDEFINED_P(GT, FLOAT)) {
7336 return RBOOL(RFLOAT_VALUE(recv) > RFLOAT_VALUE(obj));
7337 }
7338 else {
7339 return Qundef;
7340 }
7341}
7342
7343static VALUE
7344vm_opt_ge(VALUE recv, VALUE obj)
7345{
7346 if (FIXNUM_2_P(recv, obj) &&
7347 OP_UNREDEFINED_P(GE, INTEGER)) {
7348 return RBOOL((SIGNED_VALUE)recv >= (SIGNED_VALUE)obj);
7349 }
7350 else if (FLONUM_2_P(recv, obj) &&
7351 OP_UNREDEFINED_P(GE, FLOAT)) {
7352 return RBOOL(RFLOAT_VALUE(recv) >= RFLOAT_VALUE(obj));
7353 }
7354 else if (SPECIAL_CONST_P(recv) || SPECIAL_CONST_P(obj)) {
7355 return Qundef;
7356 }
7357 else if (RBASIC_CLASS(recv) == rb_cFloat &&
7358 RBASIC_CLASS(obj) == rb_cFloat &&
7359 OP_UNREDEFINED_P(GE, FLOAT)) {
7360 return RBOOL(RFLOAT_VALUE(recv) >= RFLOAT_VALUE(obj));
7361 }
7362 else {
7363 return Qundef;
7364 }
7365}
7366
7367
7368static VALUE
7369vm_opt_ltlt(VALUE recv, VALUE obj)
7370{
7371 if (SPECIAL_CONST_P(recv)) {
7372 return Qundef;
7373 }
7374 else if (RBASIC_CLASS(recv) == rb_cString &&
7375 OP_UNREDEFINED_P(LTLT, STRING)) {
7376 if (LIKELY(RB_TYPE_P(obj, T_STRING))) {
7377 return rb_str_buf_append(recv, obj);
7378 }
7379 else {
7380 return rb_str_concat(recv, obj);
7381 }
7382 }
7383 else if (RBASIC_CLASS(recv) == rb_cArray &&
7384 OP_UNREDEFINED_P(LTLT, ARRAY)) {
7385 return rb_ary_push(recv, obj);
7386 }
7387 else {
7388 return Qundef;
7389 }
7390}
7391
7392static VALUE
7393vm_opt_and(VALUE recv, VALUE obj)
7394{
7395 // If recv and obj are both fixnums, then the bottom tag bit
7396 // will be 1 on both. 1 & 1 == 1, so the result value will also
7397 // be a fixnum. If either side is *not* a fixnum, then the tag bit
7398 // will be 0, and we return Qundef.
7399 VALUE ret = ((SIGNED_VALUE) recv) & ((SIGNED_VALUE) obj);
7400
7401 if (FIXNUM_P(ret) &&
7402 OP_UNREDEFINED_P(AND, INTEGER)) {
7403 return ret;
7404 }
7405 else {
7406 return Qundef;
7407 }
7408}
7409
7410static VALUE
7411vm_opt_or(VALUE recv, VALUE obj)
7412{
7413 if (FIXNUM_2_P(recv, obj) &&
7414 OP_UNREDEFINED_P(OR, INTEGER)) {
7415 return recv | obj;
7416 }
7417 else {
7418 return Qundef;
7419 }
7420}
7421
7422static VALUE
7423vm_opt_aref(VALUE recv, VALUE obj)
7424{
7425 if (SPECIAL_CONST_P(recv)) {
7426 if (FIXNUM_2_P(recv, obj) &&
7427 OP_UNREDEFINED_P(AREF, INTEGER)) {
7428 return rb_fix_aref(recv, obj);
7429 }
7430 return Qundef;
7431 }
7432 else if (RBASIC_CLASS(recv) == rb_cArray &&
7433 OP_UNREDEFINED_P(AREF, ARRAY)) {
7434 if (FIXNUM_P(obj)) {
7435 return rb_ary_entry_internal(recv, FIX2LONG(obj));
7436 }
7437 else {
7438 return rb_ary_aref1(recv, obj);
7439 }
7440 }
7441 else if (RBASIC_CLASS(recv) == rb_cHash &&
7442 OP_UNREDEFINED_P(AREF, HASH)) {
7443 return rb_hash_aref(recv, obj);
7444 }
7445 else {
7446 return Qundef;
7447 }
7448}
7449
7450static VALUE
7451vm_opt_aset(VALUE recv, VALUE obj, VALUE set)
7452{
7453 if (SPECIAL_CONST_P(recv)) {
7454 return Qundef;
7455 }
7456 else if (RBASIC_CLASS(recv) == rb_cArray &&
7457 OP_UNREDEFINED_P(ASET, ARRAY) &&
7458 FIXNUM_P(obj)) {
7459 rb_ary_store(recv, FIX2LONG(obj), set);
7460 return set;
7461 }
7462 else if (RBASIC_CLASS(recv) == rb_cHash &&
7463 OP_UNREDEFINED_P(ASET, HASH)) {
7464 rb_hash_aset(recv, obj, set);
7465 return set;
7466 }
7467 else {
7468 return Qundef;
7469 }
7470}
7471
7472static VALUE
7473vm_opt_length(VALUE recv, int bop)
7474{
7475 if (SPECIAL_CONST_P(recv)) {
7476 return Qundef;
7477 }
7478 else if (RBASIC_CLASS(recv) == rb_cString &&
7479 BASIC_OP_UNREDEFINED_P(bop, STRING_REDEFINED_OP_FLAG)) {
7480 if (bop == BOP_EMPTY_P) {
7481 return LEN2NUM(RSTRING_LEN(recv));
7482 }
7483 else {
7484 return rb_str_length(recv);
7485 }
7486 }
7487 else if (RBASIC_CLASS(recv) == rb_cArray &&
7488 BASIC_OP_UNREDEFINED_P(bop, ARRAY_REDEFINED_OP_FLAG)) {
7489 return LEN2NUM(RARRAY_LEN(recv));
7490 }
7491 else if (RBASIC_CLASS(recv) == rb_cHash &&
7492 BASIC_OP_UNREDEFINED_P(bop, HASH_REDEFINED_OP_FLAG)) {
7493 return INT2FIX(RHASH_SIZE(recv));
7494 }
7495 else {
7496 return Qundef;
7497 }
7498}
7499
7500static VALUE
7501vm_opt_empty_p(VALUE recv)
7502{
7503 switch (vm_opt_length(recv, BOP_EMPTY_P)) {
7504 case Qundef: return Qundef;
7505 case INT2FIX(0): return Qtrue;
7506 default: return Qfalse;
7507 }
7508}
7509
7510VALUE rb_false(VALUE obj);
7511
7512static VALUE
7513vm_opt_nil_p(struct rb_control_frame_struct *reg_cfp, CALL_DATA cd, VALUE recv)
7514{
7515 if (NIL_P(recv) &&
7516 OP_UNREDEFINED_P(NIL_P, NIL)) {
7517 return Qtrue;
7518 }
7519 else if (vm_method_cfunc_is(reg_cfp, cd, recv, rb_false)) {
7520 return Qfalse;
7521 }
7522 else {
7523 return Qundef;
7524 }
7525}
7526
7527static VALUE
7528fix_succ(VALUE x)
7529{
7530 switch (x) {
7531 case ~0UL:
7532 /* 0xFFFF_FFFF == INT2FIX(-1)
7533 * `-1.succ` is of course 0. */
7534 return INT2FIX(0);
7535 case RSHIFT(~0UL, 1):
7536 /* 0x7FFF_FFFF == LONG2FIX(0x3FFF_FFFF)
7537 * 0x3FFF_FFFF + 1 == 0x4000_0000, which is a Bignum. */
7538 return rb_uint2big(1UL << (SIZEOF_LONG * CHAR_BIT - 2));
7539 default:
7540 /* LONG2FIX(FIX2LONG(x)+FIX2LONG(y))
7541 * == ((lx*2+1)/2 + (ly*2+1)/2)*2+1
7542 * == lx*2 + ly*2 + 1
7543 * == (lx*2+1) + (ly*2+1) - 1
7544 * == x + y - 1
7545 *
7546 * Here, if we put y := INT2FIX(1):
7547 *
7548 * == x + INT2FIX(1) - 1
7549 * == x + 2 .
7550 */
7551 return x + 2;
7552 }
7553}
7554
7555static VALUE
7556vm_opt_succ(VALUE recv)
7557{
7558 if (FIXNUM_P(recv) &&
7559 OP_UNREDEFINED_P(SUCC, INTEGER)) {
7560 return fix_succ(recv);
7561 }
7562 else if (SPECIAL_CONST_P(recv)) {
7563 return Qundef;
7564 }
7565 else if (RBASIC_CLASS(recv) == rb_cString &&
7566 OP_UNREDEFINED_P(SUCC, STRING)) {
7567 return rb_str_succ(recv);
7568 }
7569 else {
7570 return Qundef;
7571 }
7572}
7573
7574static VALUE
7575vm_opt_not(struct rb_control_frame_struct *reg_cfp, CALL_DATA cd, VALUE recv)
7576{
7577 if (vm_method_cfunc_is(reg_cfp, cd, recv, rb_obj_not)) {
7578 return RBOOL(!RTEST(recv));
7579 }
7580 else {
7581 return Qundef;
7582 }
7583}
7584
7585static VALUE
7586vm_opt_regexpmatch2(VALUE recv, VALUE obj)
7587{
7588 if (SPECIAL_CONST_P(recv)) {
7589 return Qundef;
7590 }
7591 else if (RBASIC_CLASS(recv) == rb_cString &&
7592 CLASS_OF(obj) == rb_cRegexp &&
7593 OP_UNREDEFINED_P(MATCH, STRING)) {
7594 return rb_reg_match(obj, recv);
7595 }
7596 else if (RBASIC_CLASS(recv) == rb_cRegexp &&
7597 OP_UNREDEFINED_P(MATCH, REGEXP)) {
7598 return rb_reg_match(recv, obj);
7599 }
7600 else {
7601 return Qundef;
7602 }
7603}
7604
7605#undef EQ_UNREDEFINED_P
7606#undef OP_UNREDEFINED_P
7607
7608NOINLINE(static void vm_trace(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp));
7609
7610static inline void
7611vm_trace_hook(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, const VALUE *pc, size_t pc_len,
7612 rb_event_flag_t pc_events, rb_event_flag_t target_event,
7613 rb_hook_list_t *global_hooks, st_data_t local_hooks_key, VALUE val)
7614{
7615 rb_event_flag_t event = pc_events & target_event;
7616 VALUE self = GET_SELF();
7617
7618 VM_ASSERT(rb_popcount64((uint64_t)event) == 1);
7619
7620 if (event & global_hooks->events) {
7621 /* point PC to the next instruction, like during execution, for the source line */
7622 reg_cfp->pc += pc_len;
7623 vm_dtrace(event, ec);
7624 rb_exec_event_hook_orig(ec, global_hooks, event, self, 0, 0, 0 , val, 0);
7625 reg_cfp->pc -= pc_len;
7626 }
7627
7628 st_data_t local_hooks_data;
7629 if (local_hooks_key && st_lookup(rb_ractor_targeted_hooks(rb_ec_ractor_ptr(ec)), local_hooks_key, &local_hooks_data)) {
7630 rb_hook_list_t *local_hooks = (rb_hook_list_t *)local_hooks_data;
7631 if (event & local_hooks->events) {
7632 /* point PC to the next instruction, like during execution, for the source line */
7633 reg_cfp->pc += pc_len;
7634 rb_exec_event_hook_orig(ec, local_hooks, event, self, 0, 0, 0 , val, 0);
7635 reg_cfp->pc -= pc_len;
7636 }
7637 }
7638}
7639
7640#define VM_TRACE_HOOK(target_event, val) do { \
7641 if ((pc_events & (target_event)) & enabled_flags) { \
7642 vm_trace_hook(ec, reg_cfp, pc, pc_len, pc_events, (target_event), global_hooks, iseq_local_hooks_key, (val)); \
7643 } \
7644} while (0)
7645
7646static VALUE
7647rescue_errinfo(rb_execution_context_t *ec, rb_control_frame_t *cfp)
7648{
7649 VM_ASSERT(VM_FRAME_RUBYFRAME_P(cfp));
7650 VM_ASSERT(ISEQ_BODY(CFP_ISEQ(cfp))->type == ISEQ_TYPE_RESCUE);
7651 return cfp->ep[VM_ENV_INDEX_LAST_LVAR];
7652}
7653
7654static void
7655vm_trace(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp)
7656{
7657 const VALUE *pc = reg_cfp->pc;
7658 rb_ractor_t *r = rb_ec_ractor_ptr(ec);
7659 rb_event_flag_t enabled_flags = r->pub.hooks.events & ISEQ_TRACE_EVENTS;
7660 rb_event_flag_t ractor_events = enabled_flags;
7661
7662 if (enabled_flags == 0 && rb_ractor_targeted_hooks_cnt(r) == 0) {
7663 return;
7664 }
7665 else {
7666 const rb_iseq_t *iseq = CFP_ISEQ(reg_cfp);
7667 size_t pos = pc - ISEQ_BODY(iseq)->iseq_encoded;
7668 rb_iseq_events_t pc_events = rb_iseq_events(iseq, pos);
7669 st_data_t iseq_local_hooks_key = 0;
7670 rb_event_flag_t iseq_local_events = 0;
7671 if (RB_UNLIKELY(iseq->aux.exec.local_hooks_cnt > 0)) {
7672 st_data_t val;
7673 iseq_local_hooks_key = (st_data_t)iseq;
7674 if (st_lookup(rb_ractor_targeted_hooks(r), iseq_local_hooks_key, &val)) {
7675 iseq_local_events = ((rb_hook_list_t *)val)->events;
7676 }
7677 }
7678
7679 st_data_t bmethod_local_hooks_key = 0;
7680 rb_event_flag_t bmethod_local_events = 0;
7681 const bool bmethod_frame = VM_FRAME_BMETHOD_P(reg_cfp);
7682 enabled_flags |= iseq_local_events;
7683
7684 VM_ASSERT((iseq_local_events & ~ISEQ_TRACE_EVENTS) == 0);
7685
7686 if (bmethod_frame) {
7687 const rb_callable_method_entry_t *me = rb_vm_frame_method_entry(reg_cfp);
7688 VM_ASSERT(me->def->type == VM_METHOD_TYPE_BMETHOD);
7689 if (RB_UNLIKELY(me->def->body.bmethod.local_hooks_cnt > 0)) {
7690 st_data_t val;
7691 bmethod_local_hooks_key = (st_data_t)me->def;
7692 if (st_lookup(rb_ractor_targeted_hooks(r), bmethod_local_hooks_key, &val)) {
7693 bmethod_local_events = ((rb_hook_list_t *)val)->events;
7694 }
7695 }
7696 }
7697
7698 if ((pc_events & enabled_flags) == 0 && !bmethod_frame) {
7699#if 0
7700 /* disable trace */
7701 /* TODO: incomplete */
7702 rb_iseq_trace_set(iseq, vm_event_flags & ISEQ_TRACE_EVENTS);
7703#else
7704 /* do not disable trace because of performance problem
7705 * (re-enable overhead)
7706 */
7707#endif
7708 return;
7709 }
7710 else if (ec->trace_arg != NULL) {
7711 /* already tracing */
7712 return;
7713 }
7714 else {
7715 rb_hook_list_t *global_hooks = rb_ec_ractor_hooks(ec);
7716 /* Note, not considering iseq local events here since the same
7717 * iseq could be used in multiple bmethods. */
7718 rb_event_flag_t bmethod_events = ractor_events | bmethod_local_events;
7719 const size_t pc_len = (size_t)insn_len(rb_vm_insn_decode(*pc));
7720
7721 if (0) {
7722 VALUE path = rb_iseq_path(iseq);
7723 VALUE label = rb_iseq_label(iseq);
7724 ruby_debug_printf("vm_trace>>%4d (%4x) - %.*s:%d %.*s\n",
7725 (int)pos,
7726 (int)pc_events,
7727 RSTRING_LENINT(path), RSTRING_PTR(path),
7728 rb_iseq_line_no(iseq, pos),
7729 RSTRING_LENINT(label), RSTRING_PTR(label));
7730 }
7731 VM_ASSERT(reg_cfp->pc == pc);
7732 VM_ASSERT(pc_events != 0);
7733
7734 /* check traces */
7735 if ((pc_events & RUBY_EVENT_B_CALL) && bmethod_frame && (bmethod_events & RUBY_EVENT_CALL)) {
7736 /* b_call instruction running as a method. Fire call event. */
7737 vm_trace_hook(ec, reg_cfp, pc, pc_len, RUBY_EVENT_CALL, RUBY_EVENT_CALL, global_hooks, bmethod_local_hooks_key, Qundef);
7738 }
7740 VM_TRACE_HOOK(RUBY_EVENT_RESCUE, rescue_errinfo(ec, reg_cfp));
7741 VM_TRACE_HOOK(RUBY_EVENT_LINE, Qundef);
7742 VM_TRACE_HOOK(RUBY_EVENT_COVERAGE_LINE, LONG2FIX(pos));
7743 VM_TRACE_HOOK(RUBY_EVENT_COVERAGE_BRANCH, Qundef);
7744 VM_TRACE_HOOK(RUBY_EVENT_END | RUBY_EVENT_RETURN | RUBY_EVENT_B_RETURN, TOPN(0));
7745 if ((pc_events & RUBY_EVENT_B_RETURN) && bmethod_frame && (bmethod_events & RUBY_EVENT_RETURN)) {
7746 /* b_return instruction running as a method. Fire return event. */
7747 vm_trace_hook(ec, reg_cfp, pc, pc_len, RUBY_EVENT_RETURN, RUBY_EVENT_RETURN, global_hooks, bmethod_local_hooks_key, TOPN(0));
7748 }
7749 }
7750 }
7751}
7752#undef VM_TRACE_HOOK
7753
7754#if VM_CHECK_MODE > 0
7755NORETURN( NOINLINE( COLDFUNC
7756void rb_vm_canary_is_found_dead(enum ruby_vminsn_type i, VALUE c)));
7757
7758void
7759Init_vm_stack_canary(void)
7760{
7761 /* This has to be called _after_ our PRNG is properly set up. */
7762 int n = ruby_fill_random_bytes(&vm_stack_canary, sizeof vm_stack_canary, false);
7763 /* Make it a large positive Fixnum. Arguments a block does not take
7764 * stay at the stack top, where vm_push_frame checks the canary. */
7765 vm_stack_canary >>= 2;
7766 vm_stack_canary |= (VALUE)1 << (SIZEOF_VALUE * CHAR_BIT - 2);
7767 vm_stack_canary |= 0x01; // valid VALUE (Fixnum)
7768
7769 vm_stack_canary_was_born = true;
7770 VM_ASSERT(n == 0);
7771}
7772
7773void
7774rb_vm_canary_is_found_dead(enum ruby_vminsn_type i, VALUE c)
7775{
7776 /* Because a method has already been called, why not call
7777 * another one. */
7778 const char *insn = rb_insns_name(i);
7779 VALUE inspection = rb_inspect(c);
7780 const char *str = StringValueCStr(inspection);
7781
7782 rb_bug("dead canary found at %s: %s", insn, str);
7783}
7784
7785#else
7786void Init_vm_stack_canary(void) { /* nothing to do */ }
7787#endif
7788
7789
7790/* a part of the following code is generated by this ruby script:
7791
779216.times{|i|
7793 typedef_args = (0...i).map{|j| "VALUE v#{j+1}"}.join(", ")
7794 typedef_args.prepend(", ") if i != 0
7795 call_args = (0...i).map{|j| "argv[#{j}]"}.join(", ")
7796 call_args.prepend(", ") if i != 0
7797 puts %Q{
7798static VALUE
7799builtin_invoker#{i}(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr)
7800{
7801 typedef VALUE (*rb_invoke_funcptr#{i}_t)(rb_execution_context_t *ec, VALUE self#{typedef_args});
7802 return (*(rb_invoke_funcptr#{i}_t)funcptr)(ec, self#{call_args});
7803}}
7804}
7805
7806puts
7807puts "static VALUE (* const cfunc_invokers[])(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr) = {"
780816.times{|i|
7809 puts " builtin_invoker#{i},"
7810}
7811puts "};"
7812*/
7813
7814static VALUE
7815builtin_invoker0(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr)
7816{
7817 typedef VALUE (*rb_invoke_funcptr0_t)(rb_execution_context_t *ec, VALUE self);
7818 return (*(rb_invoke_funcptr0_t)funcptr)(ec, self);
7819}
7820
7821static VALUE
7822builtin_invoker1(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr)
7823{
7824 typedef VALUE (*rb_invoke_funcptr1_t)(rb_execution_context_t *ec, VALUE self, VALUE v1);
7825 return (*(rb_invoke_funcptr1_t)funcptr)(ec, self, argv[0]);
7826}
7827
7828static VALUE
7829builtin_invoker2(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr)
7830{
7831 typedef VALUE (*rb_invoke_funcptr2_t)(rb_execution_context_t *ec, VALUE self, VALUE v1, VALUE v2);
7832 return (*(rb_invoke_funcptr2_t)funcptr)(ec, self, argv[0], argv[1]);
7833}
7834
7835static VALUE
7836builtin_invoker3(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr)
7837{
7838 typedef VALUE (*rb_invoke_funcptr3_t)(rb_execution_context_t *ec, VALUE self, VALUE v1, VALUE v2, VALUE v3);
7839 return (*(rb_invoke_funcptr3_t)funcptr)(ec, self, argv[0], argv[1], argv[2]);
7840}
7841
7842static VALUE
7843builtin_invoker4(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr)
7844{
7845 typedef VALUE (*rb_invoke_funcptr4_t)(rb_execution_context_t *ec, VALUE self, VALUE v1, VALUE v2, VALUE v3, VALUE v4);
7846 return (*(rb_invoke_funcptr4_t)funcptr)(ec, self, argv[0], argv[1], argv[2], argv[3]);
7847}
7848
7849static VALUE
7850builtin_invoker5(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr)
7851{
7852 typedef VALUE (*rb_invoke_funcptr5_t)(rb_execution_context_t *ec, VALUE self, VALUE v1, VALUE v2, VALUE v3, VALUE v4, VALUE v5);
7853 return (*(rb_invoke_funcptr5_t)funcptr)(ec, self, argv[0], argv[1], argv[2], argv[3], argv[4]);
7854}
7855
7856static VALUE
7857builtin_invoker6(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr)
7858{
7859 typedef VALUE (*rb_invoke_funcptr6_t)(rb_execution_context_t *ec, VALUE self, VALUE v1, VALUE v2, VALUE v3, VALUE v4, VALUE v5, VALUE v6);
7860 return (*(rb_invoke_funcptr6_t)funcptr)(ec, self, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
7861}
7862
7863static VALUE
7864builtin_invoker7(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr)
7865{
7866 typedef VALUE (*rb_invoke_funcptr7_t)(rb_execution_context_t *ec, VALUE self, VALUE v1, VALUE v2, VALUE v3, VALUE v4, VALUE v5, VALUE v6, VALUE v7);
7867 return (*(rb_invoke_funcptr7_t)funcptr)(ec, self, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6]);
7868}
7869
7870static VALUE
7871builtin_invoker8(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr)
7872{
7873 typedef VALUE (*rb_invoke_funcptr8_t)(rb_execution_context_t *ec, VALUE self, VALUE v1, VALUE v2, VALUE v3, VALUE v4, VALUE v5, VALUE v6, VALUE v7, VALUE v8);
7874 return (*(rb_invoke_funcptr8_t)funcptr)(ec, self, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7]);
7875}
7876
7877static VALUE
7878builtin_invoker9(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr)
7879{
7880 typedef VALUE (*rb_invoke_funcptr9_t)(rb_execution_context_t *ec, VALUE self, VALUE v1, VALUE v2, VALUE v3, VALUE v4, VALUE v5, VALUE v6, VALUE v7, VALUE v8, VALUE v9);
7881 return (*(rb_invoke_funcptr9_t)funcptr)(ec, self, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8]);
7882}
7883
7884static VALUE
7885builtin_invoker10(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr)
7886{
7887 typedef VALUE (*rb_invoke_funcptr10_t)(rb_execution_context_t *ec, VALUE self, VALUE v1, VALUE v2, VALUE v3, VALUE v4, VALUE v5, VALUE v6, VALUE v7, VALUE v8, VALUE v9, VALUE v10);
7888 return (*(rb_invoke_funcptr10_t)funcptr)(ec, self, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9]);
7889}
7890
7891static VALUE
7892builtin_invoker11(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr)
7893{
7894 typedef VALUE (*rb_invoke_funcptr11_t)(rb_execution_context_t *ec, VALUE self, VALUE v1, VALUE v2, VALUE v3, VALUE v4, VALUE v5, VALUE v6, VALUE v7, VALUE v8, VALUE v9, VALUE v10, VALUE v11);
7895 return (*(rb_invoke_funcptr11_t)funcptr)(ec, self, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10]);
7896}
7897
7898static VALUE
7899builtin_invoker12(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr)
7900{
7901 typedef VALUE (*rb_invoke_funcptr12_t)(rb_execution_context_t *ec, VALUE self, VALUE v1, VALUE v2, VALUE v3, VALUE v4, VALUE v5, VALUE v6, VALUE v7, VALUE v8, VALUE v9, VALUE v10, VALUE v11, VALUE v12);
7902 return (*(rb_invoke_funcptr12_t)funcptr)(ec, self, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10], argv[11]);
7903}
7904
7905static VALUE
7906builtin_invoker13(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr)
7907{
7908 typedef VALUE (*rb_invoke_funcptr13_t)(rb_execution_context_t *ec, VALUE self, VALUE v1, VALUE v2, VALUE v3, VALUE v4, VALUE v5, VALUE v6, VALUE v7, VALUE v8, VALUE v9, VALUE v10, VALUE v11, VALUE v12, VALUE v13);
7909 return (*(rb_invoke_funcptr13_t)funcptr)(ec, self, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10], argv[11], argv[12]);
7910}
7911
7912static VALUE
7913builtin_invoker14(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr)
7914{
7915 typedef VALUE (*rb_invoke_funcptr14_t)(rb_execution_context_t *ec, VALUE self, VALUE v1, VALUE v2, VALUE v3, VALUE v4, VALUE v5, VALUE v6, VALUE v7, VALUE v8, VALUE v9, VALUE v10, VALUE v11, VALUE v12, VALUE v13, VALUE v14);
7916 return (*(rb_invoke_funcptr14_t)funcptr)(ec, self, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10], argv[11], argv[12], argv[13]);
7917}
7918
7919static VALUE
7920builtin_invoker15(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr)
7921{
7922 typedef VALUE (*rb_invoke_funcptr15_t)(rb_execution_context_t *ec, VALUE self, VALUE v1, VALUE v2, VALUE v3, VALUE v4, VALUE v5, VALUE v6, VALUE v7, VALUE v8, VALUE v9, VALUE v10, VALUE v11, VALUE v12, VALUE v13, VALUE v14, VALUE v15);
7923 return (*(rb_invoke_funcptr15_t)funcptr)(ec, self, argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10], argv[11], argv[12], argv[13], argv[14]);
7924}
7925
7926typedef VALUE (*builtin_invoker)(rb_execution_context_t *ec, VALUE self, const VALUE *argv, rb_insn_func_t funcptr);
7927
7928static builtin_invoker
7929lookup_builtin_invoker(int argc)
7930{
7931 static const builtin_invoker invokers[] = {
7932 builtin_invoker0,
7933 builtin_invoker1,
7934 builtin_invoker2,
7935 builtin_invoker3,
7936 builtin_invoker4,
7937 builtin_invoker5,
7938 builtin_invoker6,
7939 builtin_invoker7,
7940 builtin_invoker8,
7941 builtin_invoker9,
7942 builtin_invoker10,
7943 builtin_invoker11,
7944 builtin_invoker12,
7945 builtin_invoker13,
7946 builtin_invoker14,
7947 builtin_invoker15,
7948 };
7949
7950 return invokers[argc];
7951}
7952
7953static inline VALUE
7954invoke_bf(rb_execution_context_t *ec, rb_control_frame_t *reg_cfp, const struct rb_builtin_function* bf, const VALUE *argv)
7955{
7956 const bool canary_p = ISEQ_BODY(CFP_ISEQ(reg_cfp))->builtin_attrs & BUILTIN_ATTR_LEAF; // Verify an assumption of `Primitive.attr! :leaf`
7957 SETUP_CANARY(canary_p);
7958 rb_insn_func_t func_ptr = (rb_insn_func_t)(uintptr_t)bf->func_ptr;
7959 VALUE ret = (*lookup_builtin_invoker(bf->argc))(ec, reg_cfp->self, argv, func_ptr);
7960 CHECK_CANARY(canary_p, BIN(invokebuiltin));
7961 return ret;
7962}
7963
7964static VALUE
7965vm_invoke_builtin(rb_execution_context_t *ec, rb_control_frame_t *cfp, const struct rb_builtin_function* bf, const VALUE *argv)
7966{
7967 return invoke_bf(ec, cfp, bf, argv);
7968}
7969
7970static VALUE
7971vm_invoke_builtin_delegate(rb_execution_context_t *ec, rb_control_frame_t *cfp, const struct rb_builtin_function *bf, unsigned int start_index)
7972{
7973 if (0) { // debug print
7974 fputs("vm_invoke_builtin_delegate: passing -> ", stderr);
7975 for (int i=0; i<bf->argc; i++) {
7976 ruby_debug_printf(":%s ", rb_id2name(ISEQ_BODY(CFP_ISEQ(cfp))->local_table[i+start_index]));
7977 }
7978 ruby_debug_printf("\n" "%s %s(%d):%p\n", RUBY_FUNCTION_NAME_STRING, bf->name, bf->argc,
7979 (void *)(uintptr_t)bf->func_ptr);
7980 }
7981
7982 if (bf->argc == 0) {
7983 return invoke_bf(ec, cfp, bf, NULL);
7984 }
7985 else {
7986 const VALUE *argv = cfp->ep - ISEQ_BODY(CFP_ISEQ(cfp))->local_table_size - VM_ENV_DATA_SIZE + 1 + start_index;
7987 return invoke_bf(ec, cfp, bf, argv);
7988 }
7989}
7990
7991// for __builtin_inline!()
7992
7993VALUE
7994rb_vm_lvar_exposed(rb_execution_context_t *ec, int index)
7995{
7996 const rb_control_frame_t *cfp = ec->cfp;
7997 return cfp->ep[index];
7998}
#define RUBY_EVENT_END
Encountered an end of a class clause.
Definition event.h:40
#define RUBY_EVENT_C_CALL
A method, written in C, is called.
Definition event.h:43
#define RUBY_EVENT_B_RETURN
Encountered a next statement.
Definition event.h:74
#define RUBY_EVENT_CLASS
Encountered a new class.
Definition event.h:39
#define RUBY_EVENT_LINE
Encountered a new line.
Definition event.h:38
#define RUBY_EVENT_RETURN
Encountered a return statement.
Definition event.h:42
#define RUBY_EVENT_C_RETURN
Return from a method, written in C.
Definition event.h:44
#define RUBY_EVENT_B_CALL
Encountered an yield statement.
Definition event.h:73
uint32_t rb_event_flag_t
Represents event(s).
Definition event.h:115
#define RUBY_EVENT_CALL
A method, written in Ruby, is called.
Definition event.h:41
#define RUBY_EVENT_RESCUE
Encountered a rescue statement.
Definition event.h:75
static VALUE RB_FL_TEST_RAW(VALUE obj, VALUE flags)
This is an implementation detail of RB_FL_TEST().
Definition fl_type.h:407
static bool RB_FL_ABLE(VALUE obj)
Checks if the object is flaggable.
Definition fl_type.h:384
@ RUBY_FL_SHAREABLE
This flag has something to do with Ractor.
Definition fl_type.h:253
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:3074
VALUE rb_module_new(void)
Creates a new, anonymous module.
Definition class.c:1678
VALUE rb_class_inherited(VALUE super, VALUE klass)
Calls Class::inherited.
Definition class.c:1578
VALUE rb_define_class_id(ID id, VALUE super)
This is a very badly designed API that creates an anonymous class.
Definition class.c:1557
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define LEN2NUM
Old name of RB_LEN2NUM.
Definition len_t.h:33
#define T_NIL
Old name of RUBY_T_NIL.
Definition value_type.h:72
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
#define T_IMEMO
Old name of RUBY_T_IMEMO.
Definition value_type.h:67
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define T_STRUCT
Old name of RUBY_T_STRUCT.
Definition value_type.h:79
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition value_type.h:63
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define SYM2ID
Old name of RB_SYM2ID.
Definition symbol.h:45
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define T_NONE
Old name of RUBY_T_NONE.
Definition value_type.h:74
#define rb_ary_new4
Old name of rb_ary_new_from_values.
Definition array.h:659
#define FIXABLE
Old name of RB_FIXABLE.
Definition fixnum.h:25
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define T_MODULE
Old name of RUBY_T_MODULE.
Definition value_type.h:70
#define ASSUME
Old name of RBIMPL_ASSUME.
Definition assume.h:27
#define FIX2ULONG
Old name of RB_FIX2ULONG.
Definition long.h:47
#define T_TRUE
Old name of RUBY_T_TRUE.
Definition value_type.h:81
#define T_ICLASS
Old name of RUBY_T_ICLASS.
Definition value_type.h:66
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
#define rb_exc_new3
Old name of rb_exc_new_str.
Definition error.h:38
#define T_FALSE
Old name of RUBY_T_FALSE.
Definition value_type.h:61
#define Qtrue
Old name of RUBY_Qtrue.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define T_OBJECT
Old name of RUBY_T_OBJECT.
Definition value_type.h:75
#define NIL_P
Old name of RB_NIL_P.
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define T_CLASS
Old name of RUBY_T_CLASS.
Definition value_type.h:58
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define FL_TEST
Old name of RB_FL_TEST.
Definition fl_type.h:127
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define FL_USHIFT
Old name of RUBY_FL_USHIFT.
Definition fl_type.h:67
#define FL_SET_RAW
Old name of RB_FL_SET_RAW.
Definition fl_type.h:126
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:679
#define rb_notimplement()
Definition flock.c:3
#define ruby_verbose
This variable controls whether the interpreter is in debug mode.
Definition error.h:476
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
VALUE rb_eFatal
fatal exception.
Definition error.c:1453
VALUE rb_eNoMethodError
NoMethodError exception.
Definition error.c:1465
void rb_exc_fatal(VALUE mesg)
Raises a fatal error in the current thread.
Definition eval.c:692
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1455
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:464
void rb_error_frozen_object(VALUE frozen_obj)
Identical to rb_error_frozen(), except it takes arbitrary Ruby object instead of C's string.
Definition error.c:4305
VALUE rb_exc_new_str(VALUE etype, VALUE str)
Identical to rb_exc_new_cstr(), except it takes a Ruby's string instead of C's.
Definition error.c:1508
@ RB_WARN_CATEGORY_STRICT_UNUSED_BLOCK
Warning is for checking unused block strictly.
Definition error.h:57
VALUE rb_cClass
Class class.
Definition object.c:62
VALUE rb_cArray
Array class.
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
Definition object.c:2264
VALUE rb_cRegexp
Regexp class.
Definition re.c:3635
VALUE rb_obj_frozen_p(VALUE obj)
Same as RB_OBJ_FROZEN(), but returns Qtrue/Qfalse instead of bool.
Definition object.c:1312
VALUE rb_cHash
Hash class.
Definition hash.c:123
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:230
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:665
VALUE rb_cBasicObject
BasicObject class.
Definition object.c:58
VALUE rb_cModule
Module class.
Definition object.c:61
VALUE rb_class_real(VALUE klass)
Finds a "real" class.
Definition object.c:221
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:902
VALUE rb_cFloat
Float class.
Definition numeric.c:201
VALUE rb_cProc
Proc class.
Definition proc.c:46
VALUE rb_cString
String class.
Definition string.c:86
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition gc.h:504
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:492
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1162
int rb_during_gc(void)
Queries if the GC is busy.
Definition gc.c:5718
VALUE rb_ary_concat(VALUE lhs, VALUE rhs)
Destructively appends the contents of latter into the end of former.
VALUE rb_ary_shift(VALUE ary)
Destructively deletes an element from the beginning of the passed array and returns what was deleted.
VALUE rb_ary_resurrect(VALUE ary)
I guess there is no use case of this function in extension libraries, but this is a routine identical...
VALUE rb_ary_entry(VALUE ary, rb_len_t off)
Queries an element of an array.
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
VALUE rb_ary_includes(VALUE ary, VALUE elem)
Queries if the passed array has the passed entry.
void rb_ary_store(VALUE ary, rb_len_t key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
VALUE rb_ary_plus(VALUE lhs, VALUE rhs)
Creates a new array, concatenating the former to the latter.
VALUE rb_check_array_type(VALUE obj)
Try converting an object to its array representation using its to_ary method, if any.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_pop(VALUE ary)
Destructively deletes an element from the end of the passed array and returns what was deleted.
VALUE rb_ary_hidden_new(rb_len_t capa)
Allocates a hidden (no class) empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_cat(VALUE ary, const VALUE *train, rb_len_t len)
Destructively appends multiple elements at the end of the array.
#define UNLIMITED_ARGUMENTS
This macro is used in conjunction with rb_check_arity().
Definition error.h:35
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
VALUE rb_proc_call_with_block(VALUE recv, int argc, const VALUE *argv, VALUE proc)
Identical to rb_proc_call(), except you can additionally pass another proc object,...
Definition proc.c:1776
VALUE rb_reg_last_match(VALUE md)
This just returns the argument, stringified.
Definition re.c:2740
VALUE rb_reg_match(VALUE re, VALUE str)
This is the match operator.
Definition re.c:4829
VALUE rb_reg_nth_match(int n, VALUE md)
Queries the nth captured substring.
Definition re.c:2716
VALUE rb_reg_match_post(VALUE md)
The portion of the original string after the given match.
Definition re.c:2798
VALUE rb_reg_nth_defined(int n, VALUE md)
Identical to rb_reg_nth_match(), except it just returns Boolean.
Definition re.c:2700
VALUE rb_reg_match_pre(VALUE md)
The portion of the original string before the given match.
Definition re.c:2766
VALUE rb_reg_match_last(VALUE md)
The portion of the original string that captured at the very last.
Definition re.c:2827
bool rb_set_lookup(VALUE set, VALUE element)
Whether the set contains the given element.
Definition set.c:2396
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:4027
VALUE rb_str_succ(VALUE orig)
Searches for the "successor" of a string.
Definition string.c:5767
VALUE rb_str_buf_append(VALUE dst, VALUE src)
Identical to rb_str_cat_cstr(), except it takes Ruby's string instead of C's.
Definition string.c:3991
VALUE rb_str_concat(VALUE dst, VALUE src)
Identical to rb_str_append(), except it also accepts an integer as a codepoint.
Definition string.c:4276
#define rb_str_cat_cstr(buf, str)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1681
VALUE rb_str_length(VALUE)
Identical to rb_str_strlen(), except it returns the value in rb_cInteger.
Definition string.c:2543
VALUE rb_str_intern(VALUE str)
Identical to rb_to_symbol(), except it assumes the receiver being an instance of RString.
Definition symbol.c:1120
VALUE rb_const_get(VALUE space, ID name)
Identical to rb_const_defined(), except it returns the actual defined value.
Definition variable.c:3553
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2186
void rb_cvar_set(VALUE klass, ID name, VALUE val)
Assigns a value to a class variable.
Definition variable.c:4347
VALUE rb_cvar_find(VALUE klass, ID name, VALUE *front)
Identical to rb_cvar_get(), except it takes additional "front" pointer.
Definition variable.c:4408
VALUE rb_ivar_get(VALUE obj, ID name)
Identical to rb_iv_get(), except it accepts the name as an ID instead of a C string.
Definition variable.c:1665
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
Definition variable.c:4036
VALUE rb_autoload_load(VALUE space, ID name)
Kicks the autoload procedure as if it was "touched".
Definition variable.c:3374
VALUE rb_mod_name(VALUE mod)
Queries the name of a module.
Definition variable.c:151
VALUE rb_const_get_at(VALUE space, ID name)
Identical to rb_const_defined_at(), except it returns the actual defined value.
Definition variable.c:3559
void rb_set_class_path_string(VALUE klass, VALUE space, VALUE name)
Identical to rb_set_class_path(), except it accepts the name as Ruby's string instead of C's.
Definition variable.c:440
VALUE rb_ivar_defined(VALUE obj, ID name)
Queries if the instance variable is defined at the object.
Definition variable.c:2246
int rb_const_defined_at(VALUE space, ID name)
Identical to rb_const_defined(), except it doesn't look for parent classes.
Definition variable.c:3894
VALUE rb_cvar_defined(VALUE klass, ID name)
Queries if the given class has the given class variable.
Definition variable.c:4433
int rb_const_defined(VALUE space, ID name)
Queries if the constant is defined at the namespace.
Definition variable.c:3888
int rb_method_basic_definition_p(VALUE klass, ID mid)
Well... Let us hesitate from describing what a "basic definition" is.
Definition vm_method.c:3650
VALUE rb_check_funcall(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv(), except it returns RUBY_Qundef instead of raising rb_eNoMethodError.
Definition vm_eval.c:729
rb_alloc_func_t rb_get_alloc_func(VALUE klass)
Queries the allocator function of a class.
Definition vm_method.c:1920
int rb_method_boundp(VALUE klass, ID id, int ex)
Queries if the klass has this method.
Definition vm_method.c:2542
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition symbol.c:1334
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1191
int off
Offset inside of ptr.
Definition io.h:5
int len
Length of the buffer.
Definition io.h:8
#define RB_OBJ_SET_SHAREABLE(obj)
Wrapper of rb_obj_set_shareable().
Definition ractor.h:290
static bool rb_ractor_shareable_p(VALUE obj)
Queries if multiple Ractors can share the passed object or not.
Definition ractor.h:269
#define RB_OBJ_SHAREABLE_P(obj)
Queries if the passed object has previously classified as shareable or not.
Definition ractor.h:255
#define RB_NOGVL_UBF_ASYNC_SAFE
Passing this flag to rb_nogvl() indicates that the passed UBF is async-signal-safe.
Definition thread.h:71
#define RB_NOGVL_INTR_FAIL
Passing this flag to rb_nogvl() prevents it from processing interrupts after the given function retur...
Definition thread.h:50
void * rb_nogvl(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2, int flags)
Identical to rb_thread_call_without_gvl(), except it additionally takes "flags" that change the behav...
Definition thread.c:1775
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:375
#define ALLOCA_N(type, n)
Definition memory.h:295
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
#define MEMMOVE(p1, p2, type, n)
Handy macro to call memmove.
Definition memory.h:387
VALUE type(ANYARGS)
ANYARGS-ed function type.
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition rarray.h:256
static VALUE * RARRAY_PTR(VALUE ary)
Wild use of a C pointer.
Definition rarray.h:341
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:398
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:52
static VALUE RBASIC_CLASS(VALUE obj)
Queries the class of an object.
Definition rbasic.h:166
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
#define RCLASS_SUPER
Just another name of rb_class_get_superclass.
Definition rclass.h:44
#define RHASH_SIZE(h)
Queries the size of the hash.
Definition rhash.h:57
#define RHASH_EMPTY_P(h)
Checks if the hash is empty.
Definition rhash.h:67
static int RSTRING_LENINT(VALUE str)
Identical to RSTRING_LEN(), except it differs for the return type.
Definition rstring.h:438
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
#define RB_PASS_KEYWORDS
Pass keywords, final argument must be a hash of keywords.
Definition scan_args.h:72
#define RB_NO_KEYWORDS
Do not pass keywords.
Definition scan_args.h:69
static bool RB_SPECIAL_CONST_P(VALUE obj)
Checks if the given object is of enum ruby_special_consts.
#define RTEST
This is an old name of RB_TEST.
#define ANYARGS
Functions declared using this macro take arbitrary arguments, including void.
Definition stdarg.h:64
Ruby's array.
Definition rarray.h:128
const VALUE ary[1]
Embedded elements.
Definition rarray.h:188
Definition hash.h:54
Definition iseq.h:402
Definition vm_core.h:250
Definition method.h:63
Internal header for Class.
Definition class.h:31
Storage for the once instruction (see vm_once_dispatch).
Definition imemo.h:112
rb_cref_t * cref
class reference, should be marked
Definition method.h:144
const rb_iseq_t * iseqptr
iseq pointer, should be separated from iseqval
Definition method.h:143
IFUNC (Internal FUNCtion).
Definition imemo.h:90
SVAR (Special VARiable).
Definition imemo.h:55
const VALUE cref_or_me
class reference or rb_method_entry_t
Definition imemo.h:57
THROW_DATA.
Definition imemo.h:64
void rb_native_mutex_lock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_lock.
void rb_native_cond_broadcast(rb_nativethread_cond_t *cond)
Signals a condition variable.
void rb_native_mutex_unlock(rb_nativethread_lock_t *lock)
Just another name of rb_nativethread_lock_unlock.
void rb_native_cond_wait(rb_nativethread_cond_t *cond, rb_nativethread_lock_t *mutex)
Waits for the passed condition variable to be signalled.
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition value.h:63
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
#define SIZEOF_VALUE
Identical to sizeof(VALUE), except it is a macro that can also be used inside of preprocessor directi...
Definition value.h:69
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static enum ruby_value_type RB_BUILTIN_TYPE(VALUE obj)
Queries the type of the object.
Definition value_type.h:182
static bool RB_FLOAT_TYPE_P(VALUE obj)
Queries if the object is an instance of rb_cFloat.
Definition value_type.h:264
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376