Ruby 4.1.0dev (2026-12-03 revision 39488c9c9b56a23d09320ec4d0e742983e2bbe61)
compile.c (39488c9c9b56a23d09320ec4d0e742983e2bbe61)
1/**********************************************************************
2
3 compile.c - ruby node tree -> VM instruction sequence
4
5 $Author$
6 created at: 04/01/01 03:42:15 JST
7
8 Copyright (C) 2004-2007 Koichi Sasada
9
10**********************************************************************/
11
12#include "ruby/internal/config.h"
13#include <math.h>
14
15#ifdef HAVE_DLADDR
16# include <dlfcn.h>
17#endif
18
19#include "encindex.h"
20#include "id_table.h"
21#include "internal.h"
22#include "internal/array.h"
23#include "internal/compile.h"
24#include "internal/coverage.h"
25#include "internal/complex.h"
26#include "internal/encoding.h"
27#include "internal/error.h"
28#include "internal/gc.h"
29#include "internal/hash.h"
30#include "internal/io.h"
31#include "internal/numeric.h"
32#include "internal/object.h"
33#include "internal/rational.h"
34#include "internal/re.h"
35#include "internal/ruby_parser.h"
36#include "internal/st.h"
37#include "internal/symbol.h"
38#include "internal/thread.h"
39#include "internal/variable.h"
40#include "iseq.h"
41#include "ruby/ractor.h"
42#include "ruby/re.h"
43#include "ruby/util.h"
44#include "vm_core.h"
45#include "vm_callinfo.h"
46#include "vm_debug.h"
47#include "yjit.h"
48
49#include "builtin.h"
50#include "insns.inc"
51#include "insns_info.inc"
52
53#define FIXNUM_INC(n, i) ((n)+(INT2FIX(i)&~FIXNUM_FLAG))
54
55typedef struct iseq_link_element {
56 enum {
57 ISEQ_ELEMENT_ANCHOR,
58 ISEQ_ELEMENT_LABEL,
59 ISEQ_ELEMENT_INSN,
60 ISEQ_ELEMENT_ADJUST,
61 ISEQ_ELEMENT_TRACE,
62 } type;
63 struct iseq_link_element *next;
64 struct iseq_link_element *prev;
65} LINK_ELEMENT;
66
67typedef struct iseq_link_anchor {
68 LINK_ELEMENT anchor;
69 LINK_ELEMENT *last;
70} LINK_ANCHOR;
71
72typedef enum {
73 LABEL_RESCUE_NONE,
74 LABEL_RESCUE_BEG,
75 LABEL_RESCUE_END,
76 LABEL_RESCUE_TYPE_MAX
77} LABEL_RESCUE_TYPE;
78
79typedef struct iseq_label_data {
80 LINK_ELEMENT link;
81 int label_no;
82 int position;
83 int sc_state;
84 int sp;
85 int refcnt;
86 unsigned int set: 1;
87 unsigned int rescued: 2;
88 unsigned int unremovable: 1;
89} LABEL;
90
91typedef struct iseq_insn_data {
92 LINK_ELEMENT link;
93 enum ruby_vminsn_type insn_id;
94 int operand_size;
95 int sc_state;
96 VALUE *operands;
97 struct {
98 int line_no;
99 int node_id;
100 rb_iseq_events_t events;
101 } insn_info;
102} INSN;
103
104typedef struct iseq_adjust_data {
105 LINK_ELEMENT link;
106 LABEL *label;
107 int line_no;
108} ADJUST;
109
110typedef struct iseq_trace_data {
111 LINK_ELEMENT link;
112 rb_iseq_events_t event;
113 long data;
114} TRACE;
115
117 LABEL *begin;
118 LABEL *end;
119 struct ensure_range *next;
120};
121
123 const void *ensure_node;
125 struct ensure_range *erange;
126};
127
128const ID rb_iseq_shared_exc_local_tbl[] = {idERROR_INFO};
129
142
143#ifndef CPDEBUG
144#define CPDEBUG 0
145#endif
146
147#if CPDEBUG >= 0
148#define compile_debug CPDEBUG
149#else
150#define compile_debug ISEQ_COMPILE_DATA(iseq)->option->debug_level
151#endif
152
153#if CPDEBUG
154
155#define compile_debug_print_indent(level) \
156 ruby_debug_print_indent((level), compile_debug, gl_node_level * 2)
157
158#define debugp(header, value) (void) \
159 (compile_debug_print_indent(1) && \
160 ruby_debug_print_value(1, compile_debug, (header), (value)))
161
162#define debugi(header, id) (void) \
163 (compile_debug_print_indent(1) && \
164 ruby_debug_print_id(1, compile_debug, (header), (id)))
165
166#define debugp_param(header, value) (void) \
167 (compile_debug_print_indent(1) && \
168 ruby_debug_print_value(1, compile_debug, (header), (value)))
169
170#define debugp_verbose(header, value) (void) \
171 (compile_debug_print_indent(2) && \
172 ruby_debug_print_value(2, compile_debug, (header), (value)))
173
174#define debugp_verbose_node(header, value) (void) \
175 (compile_debug_print_indent(10) && \
176 ruby_debug_print_value(10, compile_debug, (header), (value)))
177
178#define debug_node_start(node) ((void) \
179 (compile_debug_print_indent(1) && \
180 (ruby_debug_print_node(1, CPDEBUG, "", (const NODE *)(node)), gl_node_level)), \
181 gl_node_level++)
182
183#define debug_node_end() gl_node_level --
184
185#else
186
187#define debugi(header, id) ((void)0)
188#define debugp(header, value) ((void)0)
189#define debugp_verbose(header, value) ((void)0)
190#define debugp_verbose_node(header, value) ((void)0)
191#define debugp_param(header, value) ((void)0)
192#define debug_node_start(node) ((void)0)
193#define debug_node_end() ((void)0)
194#endif
195
196#if CPDEBUG > 1 || CPDEBUG < 0
197#undef printf
198#define printf ruby_debug_printf
199#define debugs if (compile_debug_print_indent(1)) ruby_debug_printf
200#define debug_compile(msg, v) ((void)(compile_debug_print_indent(1) && fputs((msg), stderr)), (v))
201#else
202#define debugs if(0)printf
203#define debug_compile(msg, v) (v)
204#endif
205
206#define LVAR_ERRINFO (1)
207
208/* create new label */
209#define NEW_LABEL(l) new_label_body(iseq, (l))
210#define LABEL_FORMAT "<L%03d>"
211
212#define NEW_ISEQ(node, name, type, line_no) \
213 new_child_iseq(iseq, (node), rb_fstring(name), 0, (type), (line_no))
214
215#define NEW_CHILD_ISEQ(node, name, type, line_no) \
216 new_child_iseq(iseq, (node), rb_fstring(name), iseq, (type), (line_no))
217
218#define NEW_CHILD_ISEQ_WITH_CALLBACK(callback_func, name, type, line_no) \
219 new_child_iseq_with_callback(iseq, (callback_func), (name), iseq, (type), (line_no))
220
221/* add instructions */
222#define ADD_SEQ(seq1, seq2) \
223 APPEND_LIST((seq1), (seq2))
224
225/* add an instruction */
226#define ADD_INSN(seq, line_node, insn) \
227 ADD_ELEM((seq), (LINK_ELEMENT *) new_insn_body(iseq, nd_line(line_node), nd_node_id(line_node), BIN(insn), 0))
228
229/* add an instruction with the given line number and node id */
230#define ADD_SYNTHETIC_INSN(seq, line_no, node_id, insn) \
231 ADD_ELEM((seq), (LINK_ELEMENT *) new_insn_body(iseq, (line_no), (node_id), BIN(insn), 0))
232
233/* insert an instruction before next */
234#define INSERT_BEFORE_INSN(next, line_no, node_id, insn) \
235 ELEM_INSERT_PREV(&(next)->link, (LINK_ELEMENT *) new_insn_body(iseq, line_no, node_id, BIN(insn), 0))
236
237/* insert an instruction after prev */
238#define INSERT_AFTER_INSN(prev, line_no, node_id, insn) \
239 ELEM_INSERT_NEXT(&(prev)->link, (LINK_ELEMENT *) new_insn_body(iseq, line_no, node_id, BIN(insn), 0))
240
241/* add an instruction with some operands (1, 2, 3, 5) */
242#define ADD_INSN1(seq, line_node, insn, op1) \
243 ADD_ELEM((seq), (LINK_ELEMENT *) \
244 new_insn_body(iseq, nd_line(line_node), nd_node_id(line_node), BIN(insn), 1, (VALUE)(op1)))
245
246/* insert an instruction with some operands (1, 2, 3, 5) before next */
247#define INSERT_BEFORE_INSN1(next, line_no, node_id, insn, op1) \
248 ELEM_INSERT_PREV(&(next)->link, (LINK_ELEMENT *) \
249 new_insn_body(iseq, line_no, node_id, BIN(insn), 1, (VALUE)(op1)))
250
251/* insert an instruction with some operands (1, 2, 3, 5) after prev */
252#define INSERT_AFTER_INSN1(prev, line_no, node_id, insn, op1) \
253 ELEM_INSERT_NEXT(&(prev)->link, (LINK_ELEMENT *) \
254 new_insn_body(iseq, line_no, node_id, BIN(insn), 1, (VALUE)(op1)))
255
256#define LABEL_REF(label) ((label)->refcnt++)
257
258/* add an instruction with label operand (alias of ADD_INSN1) */
259#define ADD_INSNL(seq, line_node, insn, label) (ADD_INSN1(seq, line_node, insn, label), LABEL_REF(label))
260
261#define ADD_INSN2(seq, line_node, insn, op1, op2) \
262 ADD_ELEM((seq), (LINK_ELEMENT *) \
263 new_insn_body(iseq, nd_line(line_node), nd_node_id(line_node), BIN(insn), 2, (VALUE)(op1), (VALUE)(op2)))
264
265#define ADD_INSN3(seq, line_node, insn, op1, op2, op3) \
266 ADD_ELEM((seq), (LINK_ELEMENT *) \
267 new_insn_body(iseq, nd_line(line_node), nd_node_id(line_node), BIN(insn), 3, (VALUE)(op1), (VALUE)(op2), (VALUE)(op3)))
268
269/* Specific Insn factory */
270#define ADD_SEND(seq, line_node, id, argc) \
271 ADD_SEND_R((seq), (line_node), (id), (argc), NULL, (VALUE)INT2FIX(0), NULL)
272
273#define ADD_SEND_WITH_FLAG(seq, line_node, id, argc, flag) \
274 ADD_SEND_R((seq), (line_node), (id), (argc), NULL, (VALUE)(flag), NULL)
275
276#define ADD_SEND_WITH_BLOCK(seq, line_node, id, argc, block) \
277 ADD_SEND_R((seq), (line_node), (id), (argc), (block), (VALUE)INT2FIX(0), NULL)
278
279#define ADD_CALL_RECEIVER(seq, line_node) \
280 ADD_INSN((seq), (line_node), putself)
281
282#define ADD_CALL(seq, line_node, id, argc) \
283 ADD_SEND_R((seq), (line_node), (id), (argc), NULL, (VALUE)INT2FIX(VM_CALL_FCALL), NULL)
284
285#define ADD_CALL_WITH_BLOCK(seq, line_node, id, argc, block) \
286 ADD_SEND_R((seq), (line_node), (id), (argc), (block), (VALUE)INT2FIX(VM_CALL_FCALL), NULL)
287
288#define ADD_SEND_R(seq, line_node, id, argc, block, flag, keywords) \
289 ADD_ELEM((seq), (LINK_ELEMENT *) new_insn_send(iseq, nd_line(line_node), nd_node_id(line_node), (id), (VALUE)(argc), (block), (VALUE)(flag), (keywords)))
290
291#define ADD_TRACE(seq, event) \
292 ADD_ELEM((seq), (LINK_ELEMENT *)new_trace_body(iseq, (event), 0))
293#define ADD_TRACE_WITH_DATA(seq, event, data) \
294 ADD_ELEM((seq), (LINK_ELEMENT *)new_trace_body(iseq, (event), (data)))
295
296static void iseq_add_getlocal(rb_iseq_t *iseq, LINK_ANCHOR *const seq, const NODE *const line_node, int idx, int level);
297static void iseq_add_setlocal(rb_iseq_t *iseq, LINK_ANCHOR *const seq, const NODE *const line_node, int idx, int level);
298
299#define ADD_GETLOCAL(seq, line_node, idx, level) iseq_add_getlocal(iseq, (seq), (line_node), (idx), (level))
300#define ADD_SETLOCAL(seq, line_node, idx, level) iseq_add_setlocal(iseq, (seq), (line_node), (idx), (level))
301
302/* add label */
303#define ADD_LABEL(seq, label) \
304 ADD_ELEM((seq), (LINK_ELEMENT *) (label))
305
306#define APPEND_LABEL(seq, before, label) \
307 APPEND_ELEM((seq), (before), (LINK_ELEMENT *) (label))
308
309#define ADD_ADJUST(seq, line_node, label) \
310 ADD_ELEM((seq), (LINK_ELEMENT *) new_adjust_body(iseq, (label), nd_line(line_node)))
311
312#define ADD_ADJUST_RESTORE(seq, label) \
313 ADD_ELEM((seq), (LINK_ELEMENT *) new_adjust_body(iseq, (label), -1))
314
315#define LABEL_UNREMOVABLE(label) \
316 ((label) ? (LABEL_REF(label), (label)->unremovable=1) : 0)
317#define ADD_CATCH_ENTRY(type, ls, le, iseqv, lc) do { \
318 VALUE _e = rb_ary_new3(5, (type), \
319 (VALUE)(ls) | 1, (VALUE)(le) | 1, \
320 (VALUE)(iseqv), (VALUE)(lc) | 1); \
321 LABEL_UNREMOVABLE(ls); \
322 LABEL_REF(le); \
323 LABEL_REF(lc); \
324 if (NIL_P(ISEQ_COMPILE_DATA(iseq)->catch_table_ary)) \
325 RB_OBJ_WRITE(iseq, &ISEQ_COMPILE_DATA(iseq)->catch_table_ary, rb_ary_hidden_new(3)); \
326 rb_ary_push(ISEQ_COMPILE_DATA(iseq)->catch_table_ary, freeze_hide_obj(_e)); \
327} while (0)
328
329/* compile node */
330#define COMPILE(anchor, desc, node) \
331 (debug_compile("== " desc "\n", \
332 iseq_compile_each(iseq, (anchor), (node), 0)))
333
334/* compile node, this node's value will be popped */
335#define COMPILE_POPPED(anchor, desc, node) \
336 (debug_compile("== " desc "\n", \
337 iseq_compile_each(iseq, (anchor), (node), 1)))
338
339/* compile node, which is popped when 'popped' is true */
340#define COMPILE_(anchor, desc, node, popped) \
341 (debug_compile("== " desc "\n", \
342 iseq_compile_each(iseq, (anchor), (node), (popped))))
343
344#define COMPILE_RECV(anchor, desc, node, recv) \
345 (private_recv_p(node) ? \
346 (ADD_INSN(anchor, node, putself), VM_CALL_FCALL) : \
347 COMPILE(anchor, desc, recv) ? 0 : -1)
348
349#define OPERAND_AT(insn, idx) \
350 (((INSN*)(insn))->operands[(idx)])
351
352#define INSN_OF(insn) \
353 (((INSN*)(insn))->insn_id)
354
355#define IS_INSN(link) ((link)->type == ISEQ_ELEMENT_INSN)
356#define IS_LABEL(link) ((link)->type == ISEQ_ELEMENT_LABEL)
357#define IS_ADJUST(link) ((link)->type == ISEQ_ELEMENT_ADJUST)
358#define IS_TRACE(link) ((link)->type == ISEQ_ELEMENT_TRACE)
359#define IS_INSN_ID(iobj, insn) (INSN_OF(iobj) == BIN(insn))
360#define IS_NEXT_INSN_ID(link, insn) \
361 ((link)->next && IS_INSN((link)->next) && IS_INSN_ID((link)->next, insn))
362
363static inline bool
364IS_INDEPENDENT_INSN(LINK_ELEMENT *link)
365{
366 if (!IS_INSN(link)) {
367 return false;
368 }
369
370 enum ruby_vminsn_type type = INSN_OF(link);
371
372 return (
373 type == BIN(putobject) ||
374 type == BIN(putspecialobject) ||
375 type == BIN(putnil) ||
376 type == BIN(putself) ||
377 type == BIN(duphash) ||
378 type == BIN(getinstancevariable) ||
379 type == BIN(getlocal) ||
380 type == BIN(getlocal_WC_0) ||
381 type == BIN(getlocal_WC_1) ||
382 type == BIN(putobject_INT2FIX_0_) ||
383 type == BIN(putobject_INT2FIX_1_) ||
384 type == BIN(opt_getconstant_path)
385 );
386}
387
388/* error */
389#if CPDEBUG > 0
391#endif
392RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 3, 4)
393static void
394append_compile_error(const rb_iseq_t *iseq, int line, const char *fmt, ...)
395{
396 VALUE err_info = ISEQ_COMPILE_DATA(iseq)->err_info;
397 VALUE file = rb_iseq_path(iseq);
398 VALUE err = err_info == Qtrue ? Qfalse : err_info;
399 va_list args;
400
401 va_start(args, fmt);
402 err = rb_syntax_error_append(err, file, line, -1, NULL, fmt, args);
403 va_end(args);
404 if (NIL_P(err_info)) {
405 RB_OBJ_WRITE(iseq, &ISEQ_COMPILE_DATA(iseq)->err_info, err);
406 rb_set_errinfo(err);
407 }
408 else if (!err_info) {
409 RB_OBJ_WRITE(iseq, &ISEQ_COMPILE_DATA(iseq)->err_info, Qtrue);
410 }
411 if (compile_debug) {
412 if (SPECIAL_CONST_P(err)) err = rb_eSyntaxError;
413 rb_exc_fatal(err);
414 }
415}
416
417#if 0
418static void
419compile_bug(rb_iseq_t *iseq, int line, const char *fmt, ...)
420{
421 va_list args;
422 va_start(args, fmt);
423 rb_report_bug_valist(rb_iseq_path(iseq), line, fmt, args);
424 va_end(args);
425 abort();
426}
427#endif
428
429#define COMPILE_ERROR append_compile_error
430
431#define ERROR_ARGS_AT(n) iseq, nd_line(n),
432#define ERROR_ARGS ERROR_ARGS_AT(node)
433
434#define EXPECT_NODE(prefix, node, ndtype, errval) \
435do { \
436 const NODE *error_node = (node); \
437 enum node_type error_type = nd_type(error_node); \
438 if (error_type != (ndtype)) { \
439 COMPILE_ERROR(ERROR_ARGS_AT(error_node) \
440 prefix ": " #ndtype " is expected, but %s", \
441 ruby_node_name(error_type)); \
442 return errval; \
443 } \
444} while (0)
445
446#define EXPECT_NODE_NONULL(prefix, parent, ndtype, errval) \
447do { \
448 COMPILE_ERROR(ERROR_ARGS_AT(parent) \
449 prefix ": must be " #ndtype ", but 0"); \
450 return errval; \
451} while (0)
452
453#define UNKNOWN_NODE(prefix, node, errval) \
454do { \
455 const NODE *error_node = (node); \
456 COMPILE_ERROR(ERROR_ARGS_AT(error_node) prefix ": unknown node (%s)", \
457 ruby_node_name(nd_type(error_node))); \
458 return errval; \
459} while (0)
460
461#define COMPILE_OK 1
462#define COMPILE_NG 0
463
464#define CHECK(sub) if (!(sub)) {BEFORE_RETURN;return COMPILE_NG;}
465#define NO_CHECK(sub) (void)(sub)
466#define BEFORE_RETURN
467
468#define DECL_ANCHOR(name) \
469 LINK_ANCHOR name[1] = {{{ISEQ_ELEMENT_ANCHOR,},&name[0].anchor}}
470#define INIT_ANCHOR(name) \
471 ((name->last = &name->anchor)->next = NULL) /* re-initialize */
472
473static inline VALUE
474freeze_hide_obj(VALUE obj)
475{
476 OBJ_FREEZE(obj);
477 RBASIC_CLEAR_CLASS(obj);
478 return obj;
479}
480
481#include "optinsn.inc"
482#if OPT_INSTRUCTIONS_UNIFICATION
483#include "optunifs.inc"
484#endif
485
486/* for debug */
487#if CPDEBUG < 0
488#define ISEQ_ARG iseq,
489#define ISEQ_ARG_DECLARE rb_iseq_t *iseq,
490#else
491#define ISEQ_ARG
492#define ISEQ_ARG_DECLARE
493#endif
494
495#if CPDEBUG
496#define gl_node_level ISEQ_COMPILE_DATA(iseq)->node_level
497#endif
498
499static void dump_disasm_list_with_cursor(const LINK_ELEMENT *link, const LINK_ELEMENT *curr, const LABEL *dest);
500static void dump_disasm_list(const LINK_ELEMENT *elem);
501
502static int insn_data_length(INSN *iobj);
503static int calc_sp_depth(int depth, INSN *iobj);
504
505static INSN *new_insn_body(rb_iseq_t *iseq, int line_no, int node_id, enum ruby_vminsn_type insn_id, int argc, ...);
506static LABEL *new_label_body(rb_iseq_t *iseq, long line);
507static ADJUST *new_adjust_body(rb_iseq_t *iseq, LABEL *label, int line);
508static TRACE *new_trace_body(rb_iseq_t *iseq, rb_iseq_events_t event, long data);
509
510
511static int iseq_compile_each(rb_iseq_t *iseq, LINK_ANCHOR *anchor, const NODE *n, int);
512static int iseq_setup(rb_iseq_t *iseq, LINK_ANCHOR *const anchor);
513static int iseq_setup_insn(rb_iseq_t *iseq, LINK_ANCHOR *const anchor);
514static int iseq_optimize(rb_iseq_t *iseq, LINK_ANCHOR *const anchor);
515static int iseq_insns_unification(rb_iseq_t *iseq, LINK_ANCHOR *const anchor);
516
517static int iseq_set_local_table(rb_iseq_t *iseq, const rb_ast_id_table_t *tbl, const NODE *const node_args);
518static int iseq_set_exception_local_table(rb_iseq_t *iseq);
519static int iseq_set_arguments(rb_iseq_t *iseq, LINK_ANCHOR *const anchor, const NODE *const node);
520
521static int iseq_set_sequence(rb_iseq_t *iseq, LINK_ANCHOR *const anchor);
522static int iseq_set_exception_table(rb_iseq_t *iseq);
523static int iseq_set_optargs_table(rb_iseq_t *iseq);
524static int iseq_set_parameters_lvar_state(const rb_iseq_t *iseq);
525
526static int compile_defined_expr(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, VALUE needstr, bool ignore);
527static int compile_hash(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *node, int method_call_keywords, int popped);
528
529/*
530 * To make Array to LinkedList, use link_anchor
531 */
532
533static void
534verify_list(ISEQ_ARG_DECLARE const char *info, LINK_ANCHOR *const anchor)
535{
536#if CPDEBUG
537 int flag = 0;
538 LINK_ELEMENT *list, *plist;
539
540 if (!compile_debug) return;
541
542 list = anchor->anchor.next;
543 plist = &anchor->anchor;
544 while (list) {
545 if (plist != list->prev) {
546 flag += 1;
547 }
548 plist = list;
549 list = list->next;
550 }
551
552 if (anchor->last != plist && anchor->last != 0) {
553 flag |= 0x70000;
554 }
555
556 if (flag != 0) {
557 rb_bug("list verify error: %08x (%s)", flag, info);
558 }
559#endif
560}
561#if CPDEBUG < 0
562#define verify_list(info, anchor) verify_list(iseq, (info), (anchor))
563#endif
564
565static void
566verify_call_cache(rb_iseq_t *iseq)
567{
568#if CPDEBUG
569 VALUE *original = rb_iseq_original_iseq(iseq);
570 size_t i = 0;
571 while (i < ISEQ_BODY(iseq)->iseq_size) {
572 VALUE insn = original[i];
573 const char *types = insn_op_types(insn);
574
575 for (int j=0; types[j]; j++) {
576 if (types[j] == TS_CALLDATA) {
577 struct rb_call_data *cd = (struct rb_call_data *)original[i+j+1];
578 const struct rb_callinfo *ci = cd->ci;
579 const struct rb_callcache *cc = cd->cc;
580 if (cc != vm_cc_empty()) {
581 vm_ci_dump(ci);
582 rb_bug("call cache is not initialized by vm_cc_empty()");
583 }
584 }
585 }
586 i += insn_len(insn);
587 }
588
589 for (unsigned int i=0; i<ISEQ_BODY(iseq)->ci_size; i++) {
590 struct rb_call_data *cd = &ISEQ_BODY(iseq)->call_data[i];
591 const struct rb_callinfo *ci = cd->ci;
592 const struct rb_callcache *cc = cd->cc;
593 if (cc != NULL && cc != vm_cc_empty()) {
594 vm_ci_dump(ci);
595 rb_bug("call cache is not initialized by vm_cc_empty()");
596 }
597 }
598#endif
599}
600
601/*
602 * elem1, elem2 => elem1, elem2, elem
603 */
604static void
605ADD_ELEM(ISEQ_ARG_DECLARE LINK_ANCHOR *const anchor, LINK_ELEMENT *elem)
606{
607 elem->prev = anchor->last;
608 anchor->last->next = elem;
609 anchor->last = elem;
610 verify_list("add", anchor);
611}
612
613/*
614 * elem1, before, elem2 => elem1, before, elem, elem2
615 */
616static void
617APPEND_ELEM(ISEQ_ARG_DECLARE LINK_ANCHOR *const anchor, LINK_ELEMENT *before, LINK_ELEMENT *elem)
618{
619 elem->prev = before;
620 elem->next = before->next;
621 elem->next->prev = elem;
622 before->next = elem;
623 if (before == anchor->last) anchor->last = elem;
624 verify_list("add", anchor);
625}
626#if CPDEBUG < 0
627#define ADD_ELEM(anchor, elem) ADD_ELEM(iseq, (anchor), (elem))
628#define APPEND_ELEM(anchor, before, elem) APPEND_ELEM(iseq, (anchor), (before), (elem))
629#endif
630
631static int
632branch_coverage_valid_p(rb_iseq_t *iseq, int first_line)
633{
634 if (!ISEQ_COVERAGE(iseq)) return 0;
635 if (!ISEQ_BRANCH_COVERAGE(iseq)) return 0;
636 if (first_line <= 0) return 0;
637 return 1;
638}
639
640static VALUE
641setup_branch(const rb_code_location_t *loc, const char *type, VALUE structure, VALUE key)
642{
643 const int first_lineno = loc->beg_pos.lineno, first_column = loc->beg_pos.column;
644 const int last_lineno = loc->end_pos.lineno, last_column = loc->end_pos.column;
645 VALUE branch = rb_ary_hidden_new(6);
646
647 rb_hash_aset(structure, key, branch);
648 rb_ary_push(branch, ID2SYM(rb_intern(type)));
649 rb_ary_push(branch, INT2NUM(first_lineno));
650 rb_ary_push(branch, INT2NUM(first_column));
651 rb_ary_push(branch, INT2NUM(last_lineno));
652 rb_ary_push(branch, INT2NUM(last_column));
653 return branch;
654}
655
656static VALUE
657decl_branch_base(rb_iseq_t *iseq, int node_id, const rb_code_location_t *loc, const char *type)
658{
659 if (!branch_coverage_valid_p(iseq, loc->beg_pos.lineno)) return Qundef;
660
661 /*
662 * A branch base is keyed by [source_hash (in two halves), node_id, first_lineno],
663 * which identifies the branch node stably even across (re-)evals against
664 * the same path.
665 *
666 * if !structure[key]
667 * structure[key] = [type, first_lineno, first_column, last_lineno, last_column, branches = {}]
668 * else
669 * branches = structure[key][5]
670 * end
671 */
672 uint64_t source_hash = ISEQ_BODY(iseq)->source_hash;
673 VALUE key = rb_ary_new_from_args(4,
674 ULONG2NUM((unsigned long)(source_hash >> 32)),
675 ULONG2NUM((unsigned long)(source_hash & 0xffffffff)),
676 INT2FIX(node_id),
677 INT2NUM(loc->beg_pos.lineno));
678 rb_ary_freeze(key);
679
680 VALUE structure = RARRAY_AREF(ISEQ_BRANCH_COVERAGE(iseq), 0);
681 VALUE branch_base = rb_hash_aref(structure, key);
682 VALUE branches;
683
684 if (NIL_P(branch_base)) {
685 branch_base = setup_branch(loc, type, structure, key);
686 branches = rb_hash_new();
687 rb_obj_hide(branches);
688 rb_ary_push(branch_base, branches);
689 }
690 else {
691 branches = RARRAY_AREF(branch_base, 5);
692 }
693
694 return branches;
695}
696
697static NODE
698generate_dummy_line_node(int lineno, int node_id)
699{
700 NODE dummy = { 0 };
701 nd_set_line(&dummy, lineno);
702 nd_set_node_id(&dummy, node_id);
703 return dummy;
704}
705
706static void
707add_trace_branch_coverage(rb_iseq_t *iseq, LINK_ANCHOR *const seq, const rb_code_location_t *loc, int node_id, int branch_id, const char *type, VALUE branches)
708{
709 if (!branch_coverage_valid_p(iseq, loc->beg_pos.lineno)) return;
710
711 /*
712 * if !branches[branch_id]
713 * branches[branch_id] = [type, first_lineno, first_column, last_lineno, last_column, counter_idx]
714 * else
715 * counter_idx= branches[branch_id][5]
716 * end
717 */
718
719 VALUE key = INT2FIX(branch_id);
720 VALUE branch = rb_hash_aref(branches, key);
721 long counter_idx;
722
723 if (NIL_P(branch)) {
724 branch = setup_branch(loc, type, branches, key);
725 VALUE counters = RARRAY_AREF(ISEQ_BRANCH_COVERAGE(iseq), 1);
726 counter_idx = RARRAY_LEN(counters);
727 rb_ary_push(branch, LONG2FIX(counter_idx));
728 rb_ary_push(counters, INT2FIX(0));
729 }
730 else {
731 counter_idx = FIX2LONG(RARRAY_AREF(branch, 5));
732 }
733
734 ADD_TRACE_WITH_DATA(seq, RUBY_EVENT_COVERAGE_BRANCH, counter_idx);
735 ADD_SYNTHETIC_INSN(seq, loc->end_pos.lineno, node_id, nop);
736}
737
738#define ISEQ_LAST_LINE(iseq) (ISEQ_COMPILE_DATA(iseq)->last_line)
739
740// last_line is 0 until the first line event, e.g. in an empty body.
741static int
742iseq_synthetic_lineno(const rb_iseq_t *iseq)
743{
744 int lineno = ISEQ_LAST_LINE(iseq);
745 return lineno ? lineno : ISEQ_BODY(iseq)->location.first_lineno;
746}
747
748static int
749validate_label(st_data_t name, st_data_t label, st_data_t arg)
750{
751 rb_iseq_t *iseq = (rb_iseq_t *)arg;
752 LABEL *lobj = (LABEL *)label;
753 if (!lobj->link.next) {
754 do {
755 COMPILE_ERROR(iseq, lobj->position,
756 "%"PRIsVALUE": undefined label",
757 rb_sym2str((VALUE)name));
758 } while (0);
759 }
760 return ST_CONTINUE;
761}
762
763static void
764validate_labels(rb_iseq_t *iseq, st_table *labels_table)
765{
766 st_foreach(labels_table, validate_label, (st_data_t)iseq);
767 st_free_table(labels_table);
768}
769
770static NODE *
771get_nd_recv(const NODE *node)
772{
773 switch (nd_type(node)) {
774 case NODE_CALL:
775 return RNODE_CALL(node)->nd_recv;
776 case NODE_OPCALL:
777 return RNODE_OPCALL(node)->nd_recv;
778 case NODE_FCALL:
779 return 0;
780 case NODE_QCALL:
781 return RNODE_QCALL(node)->nd_recv;
782 case NODE_VCALL:
783 return 0;
784 case NODE_ATTRASGN:
785 return RNODE_ATTRASGN(node)->nd_recv;
786 case NODE_OP_ASGN1:
787 return RNODE_OP_ASGN1(node)->nd_recv;
788 case NODE_OP_ASGN2:
789 return RNODE_OP_ASGN2(node)->nd_recv;
790 default:
791 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
792 }
793}
794
795static ID
796get_node_call_nd_mid(const NODE *node)
797{
798 switch (nd_type(node)) {
799 case NODE_CALL:
800 return RNODE_CALL(node)->nd_mid;
801 case NODE_OPCALL:
802 return RNODE_OPCALL(node)->nd_mid;
803 case NODE_FCALL:
804 return RNODE_FCALL(node)->nd_mid;
805 case NODE_QCALL:
806 return RNODE_QCALL(node)->nd_mid;
807 case NODE_VCALL:
808 return RNODE_VCALL(node)->nd_mid;
809 case NODE_ATTRASGN:
810 return RNODE_ATTRASGN(node)->nd_mid;
811 default:
812 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
813 }
814}
815
816static NODE *
817get_nd_args(const NODE *node)
818{
819 switch (nd_type(node)) {
820 case NODE_CALL:
821 return RNODE_CALL(node)->nd_args;
822 case NODE_OPCALL:
823 return RNODE_OPCALL(node)->nd_args;
824 case NODE_FCALL:
825 return RNODE_FCALL(node)->nd_args;
826 case NODE_QCALL:
827 return RNODE_QCALL(node)->nd_args;
828 case NODE_VCALL:
829 return 0;
830 case NODE_ATTRASGN:
831 return RNODE_ATTRASGN(node)->nd_args;
832 default:
833 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
834 }
835}
836
837static ID
838get_node_colon_nd_mid(const NODE *node)
839{
840 switch (nd_type(node)) {
841 case NODE_COLON2:
842 return RNODE_COLON2(node)->nd_mid;
843 case NODE_COLON3:
844 return RNODE_COLON3(node)->nd_mid;
845 default:
846 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
847 }
848}
849
850static ID
851get_nd_vid(const NODE *node)
852{
853 switch (nd_type(node)) {
854 case NODE_LASGN:
855 return RNODE_LASGN(node)->nd_vid;
856 case NODE_DASGN:
857 return RNODE_DASGN(node)->nd_vid;
858 case NODE_IASGN:
859 return RNODE_IASGN(node)->nd_vid;
860 case NODE_CVASGN:
861 return RNODE_CVASGN(node)->nd_vid;
862 default:
863 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
864 }
865}
866
867static NODE *
868get_nd_value(const NODE *node)
869{
870 switch (nd_type(node)) {
871 case NODE_LASGN:
872 return RNODE_LASGN(node)->nd_value;
873 case NODE_DASGN:
874 return RNODE_DASGN(node)->nd_value;
875 default:
876 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
877 }
878}
879
880static VALUE
881get_string_value(const NODE *node)
882{
883 switch (nd_type(node)) {
884 case NODE_STR:
885 return RB_OBJ_SET_SHAREABLE(rb_node_str_string_val(node));
886 case NODE_FILE:
887 return RB_OBJ_SET_SHAREABLE(rb_node_file_path_val(node));
888 default:
889 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
890 }
891}
892
893VALUE
894rb_iseq_compile_callback(rb_iseq_t *iseq, const struct rb_iseq_new_with_callback_callback_func * ifunc)
895{
896 DECL_ANCHOR(ret);
897 INIT_ANCHOR(ret);
898
899 (*ifunc->func)(iseq, ret, ifunc->data);
900
901 ADD_SYNTHETIC_INSN(ret, iseq_synthetic_lineno(iseq), -1, leave);
902
903 CHECK(iseq_setup_insn(iseq, ret));
904 return iseq_setup(iseq, ret);
905}
906
907static bool drop_unreachable_return(LINK_ANCHOR *ret);
908
909VALUE
910rb_iseq_compile_node(rb_iseq_t *iseq, const NODE *node)
911{
912 DECL_ANCHOR(ret);
913 INIT_ANCHOR(ret);
914
915 if (node == 0) {
916 NO_CHECK(COMPILE(ret, "nil", node));
917 iseq_set_local_table(iseq, 0, 0);
918 }
919 /* assume node is T_NODE */
920 else if (nd_type_p(node, NODE_SCOPE)) {
921 /* iseq type of top, method, class, block */
922 iseq_set_local_table(iseq, RNODE_SCOPE(node)->nd_tbl, (NODE *)RNODE_SCOPE(node)->nd_args);
923 iseq_set_arguments(iseq, ret, (NODE *)RNODE_SCOPE(node)->nd_args);
924 iseq_set_parameters_lvar_state(iseq);
925
926 switch (ISEQ_BODY(iseq)->type) {
927 case ISEQ_TYPE_BLOCK:
928 {
929 LABEL *start = ISEQ_COMPILE_DATA(iseq)->start_label = NEW_LABEL(0);
930 LABEL *end = ISEQ_COMPILE_DATA(iseq)->end_label = NEW_LABEL(0);
931
932 start->rescued = LABEL_RESCUE_BEG;
933 end->rescued = LABEL_RESCUE_END;
934
935 ADD_TRACE(ret, RUBY_EVENT_B_CALL);
936 ADD_SYNTHETIC_INSN(ret, ISEQ_BODY(iseq)->location.first_lineno, -1, nop);
937 ADD_LABEL(ret, start);
938 CHECK(COMPILE(ret, "block body", RNODE_SCOPE(node)->nd_body));
939 ADD_LABEL(ret, end);
940 ADD_TRACE(ret, RUBY_EVENT_B_RETURN);
941 ISEQ_COMPILE_DATA(iseq)->last_line = ISEQ_BODY(iseq)->location.code_location.end_pos.lineno;
942
943 /* wide range catch handler must put at last */
944 ADD_CATCH_ENTRY(CATCH_TYPE_REDO, start, end, NULL, start);
945 ADD_CATCH_ENTRY(CATCH_TYPE_NEXT, start, end, NULL, end);
946 break;
947 }
948 case ISEQ_TYPE_CLASS:
949 {
950 ADD_TRACE(ret, RUBY_EVENT_CLASS);
951 CHECK(COMPILE(ret, "scoped node", RNODE_SCOPE(node)->nd_body));
952 ADD_TRACE(ret, RUBY_EVENT_END);
953 ISEQ_COMPILE_DATA(iseq)->last_line = nd_line(node);
954 break;
955 }
956 case ISEQ_TYPE_METHOD:
957 {
958 ISEQ_COMPILE_DATA(iseq)->root_node = RNODE_SCOPE(node)->nd_body;
959 ADD_TRACE(ret, RUBY_EVENT_CALL);
960 CHECK(COMPILE(ret, "scoped node", RNODE_SCOPE(node)->nd_body));
961 ISEQ_COMPILE_DATA(iseq)->root_node = RNODE_SCOPE(node)->nd_body;
962 ADD_TRACE(ret, RUBY_EVENT_RETURN);
963 ISEQ_COMPILE_DATA(iseq)->last_line = nd_line(node);
964 break;
965 }
966 default: {
967 CHECK(COMPILE(ret, "scoped node", RNODE_SCOPE(node)->nd_body));
968 break;
969 }
970 }
971 }
972 else {
973 const char *m;
974#define INVALID_ISEQ_TYPE(type) \
975 ISEQ_TYPE_##type: m = #type; goto invalid_iseq_type
976 switch (ISEQ_BODY(iseq)->type) {
977 case INVALID_ISEQ_TYPE(METHOD);
978 case INVALID_ISEQ_TYPE(CLASS);
979 case INVALID_ISEQ_TYPE(BLOCK);
980 case INVALID_ISEQ_TYPE(EVAL);
981 case INVALID_ISEQ_TYPE(MAIN);
982 case INVALID_ISEQ_TYPE(TOP);
983#undef INVALID_ISEQ_TYPE /* invalid iseq types end */
984 case ISEQ_TYPE_RESCUE:
985 iseq_set_exception_local_table(iseq);
986 CHECK(COMPILE(ret, "rescue", node));
987 break;
988 case ISEQ_TYPE_ENSURE:
989 iseq_set_exception_local_table(iseq);
990 CHECK(COMPILE_POPPED(ret, "ensure", node));
991 break;
992 case ISEQ_TYPE_PLAIN:
993 CHECK(COMPILE(ret, "ensure", node));
994 break;
995 default:
996 COMPILE_ERROR(ERROR_ARGS "unknown scope: %d", ISEQ_BODY(iseq)->type);
997 return COMPILE_NG;
998 invalid_iseq_type:
999 COMPILE_ERROR(ERROR_ARGS "compile/ISEQ_TYPE_%s should not be reached", m);
1000 return COMPILE_NG;
1001 }
1002 }
1003
1004 if (ISEQ_BODY(iseq)->type == ISEQ_TYPE_RESCUE || ISEQ_BODY(iseq)->type == ISEQ_TYPE_ENSURE) {
1005 NODE dummy_line_node = generate_dummy_line_node(ISEQ_BODY(iseq)->location.first_lineno, -1);
1006 ADD_GETLOCAL(ret, &dummy_line_node, LVAR_ERRINFO, 0);
1007 ADD_INSN1(ret, &dummy_line_node, throw, INT2FIX(0) /* continue throw */ );
1008 }
1009 else if (!drop_unreachable_return(ret)) {
1010 ADD_SYNTHETIC_INSN(ret, iseq_synthetic_lineno(iseq), -1, leave);
1011 }
1012
1013#if OPT_SUPPORT_JOKE
1014 if (ISEQ_COMPILE_DATA(iseq)->labels_table) {
1015 st_table *labels_table = ISEQ_COMPILE_DATA(iseq)->labels_table;
1016 ISEQ_COMPILE_DATA(iseq)->labels_table = 0;
1017 validate_labels(iseq, labels_table);
1018 }
1019#endif
1020 CHECK(iseq_setup_insn(iseq, ret));
1021 return iseq_setup(iseq, ret);
1022}
1023
1024static int
1025rb_iseq_translate_threaded_code(rb_iseq_t *iseq)
1026{
1027#if OPT_DIRECT_THREADED_CODE || OPT_CALL_THREADED_CODE
1028 const void * const *table = rb_vm_get_insns_address_table();
1029 unsigned int i;
1030 VALUE *encoded = (VALUE *)ISEQ_BODY(iseq)->iseq_encoded;
1031
1032 for (i = 0; i < ISEQ_BODY(iseq)->iseq_size; /* */ ) {
1033 int insn = (int)vm_insn_unpack_insn(encoded[i]);
1034 int len = insn_len(insn);
1035 encoded[i] = vm_insn_repack_insn(encoded[i], (VALUE)table[insn]);
1036 i += len;
1037 }
1038#endif
1039 FL_SET((VALUE)iseq, ISEQ_TRANSLATED);
1040
1041#if USE_YJIT
1042 rb_yjit_live_iseq_count++;
1043 rb_yjit_iseq_alloc_count++;
1044#endif
1045
1046 return COMPILE_OK;
1047}
1048
1049VALUE *
1050rb_iseq_original_iseq(const rb_iseq_t *iseq) /* cold path */
1051{
1052 struct rb_iseq_variable *v = ISEQ_VARIABLE(iseq);
1053 VALUE *original_code = v ? RUBY_ATOMIC_PTR_LOAD(v->original_iseq) : NULL;
1054
1055 if (original_code) return original_code;
1056 original_code = ALLOC_N(VALUE, ISEQ_BODY(iseq)->iseq_size);
1057 MEMCPY(original_code, ISEQ_BODY(iseq)->iseq_encoded, VALUE, ISEQ_BODY(iseq)->iseq_size);
1058
1059 {
1060 unsigned int i;
1061
1062 for (i = 0; i < ISEQ_BODY(iseq)->iseq_size; /* */ ) {
1063 const void *addr = (const void *)original_code[i];
1064 const int insn = rb_vm_insn_addr2insn(addr);
1065
1066 original_code[i] = insn;
1067 i += insn_len(insn);
1068 }
1069 }
1070
1071 /* Concurrent callers can each build a copy; publish only fully
1072 * translated code and keep the first one. */
1073 v = rb_iseq_variable_ensure((rb_iseq_t *)iseq);
1074 VALUE *prev = ATOMIC_PTR_CAS(v->original_iseq,
1075 NULL, original_code);
1076 if (prev) {
1077 SIZED_FREE_N(original_code, ISEQ_BODY(iseq)->iseq_size);
1078 return prev;
1079 }
1080 return original_code;
1081}
1082
1083/*********************************************/
1084/* definition of data structure for compiler */
1085/*********************************************/
1086
1087#if defined(HAVE_TRUE_LONG_LONG) && SIZEOF_LONG_LONG > SIZEOF_VALUE
1088# define ALIGNMENT_SIZE SIZEOF_LONG_LONG
1089#else
1090# define ALIGNMENT_SIZE SIZEOF_VALUE
1091#endif
1092#define PADDING_SIZE_MAX ((size_t)((ALIGNMENT_SIZE) - 1))
1093
1094#define ALIGNMENT_SIZE_OF(type) alignment_size_assert(RUBY_ALIGNOF(type), #type)
1095
1096static inline size_t
1097alignment_size_assert(size_t align, const char *type)
1098{
1099 RUBY_ASSERT((align & (align - 1)) == 0,
1100 "ALIGNMENT_SIZE_OF(%s):%zd == (2 ** N) is expected", type, align);
1101 return align;
1102}
1103
1104/* calculate padding size for aligned memory access */
1105static inline size_t
1106calc_padding(void *ptr, size_t align)
1107{
1108 size_t mis;
1109 size_t padding = 0;
1110
1111 mis = (size_t)ptr & (align - 1);
1112 if (mis > 0) {
1113 padding = align - mis;
1114 }
1115
1116 return padding;
1117}
1118
1119static void *
1120compile_data_alloc_with_arena(struct iseq_compile_data_storage **arena, size_t size, size_t align)
1121{
1122 void *ptr = 0;
1123 struct iseq_compile_data_storage *storage = *arena;
1124 size_t padding = calc_padding((void *)&storage->buff[storage->pos], align);
1125
1126 if (size >= INT_MAX - padding) rb_memerror();
1127 if (storage->pos + size + padding > storage->size) {
1128 unsigned int alloc_size = storage->size;
1129
1130 while (alloc_size < size + PADDING_SIZE_MAX) {
1131 if (alloc_size >= INT_MAX / 2) rb_memerror();
1132 alloc_size *= 2;
1133 }
1134 storage->next = (void *)ALLOC_N(char, alloc_size +
1135 offsetof(struct iseq_compile_data_storage, buff));
1136 storage = *arena = storage->next;
1137 storage->next = 0;
1138 storage->pos = 0;
1139 storage->size = alloc_size;
1140 padding = calc_padding((void *)&storage->buff[storage->pos], align);
1141 }
1142
1143 storage->pos += (int)padding;
1144
1145 ptr = (void *)&storage->buff[storage->pos];
1146 storage->pos += (int)size;
1147 return ptr;
1148}
1149
1150static void *
1151compile_data_alloc(rb_iseq_t *iseq, size_t size, size_t align)
1152{
1153 struct iseq_compile_data_storage ** arena = &ISEQ_COMPILE_DATA(iseq)->node.storage_current;
1154 return compile_data_alloc_with_arena(arena, size, align);
1155}
1156
1157#define compile_data_alloc_type(iseq, type) \
1158 (type *)compile_data_alloc(iseq, sizeof(type), ALIGNMENT_SIZE_OF(type))
1159
1160static inline void *
1161compile_data_alloc2(rb_iseq_t *iseq, size_t elsize, size_t num, size_t align)
1162{
1163 size_t size = rb_size_mul_or_raise(elsize, num, rb_eRuntimeError);
1164 return compile_data_alloc(iseq, size, align);
1165}
1166
1167#define compile_data_alloc2_type(iseq, type, num) \
1168 (type *)compile_data_alloc2(iseq, sizeof(type), num, ALIGNMENT_SIZE_OF(type))
1169
1170static inline void *
1171compile_data_calloc2(rb_iseq_t *iseq, size_t elsize, size_t num, size_t align)
1172{
1173 size_t size = rb_size_mul_or_raise(elsize, num, rb_eRuntimeError);
1174 void *p = compile_data_alloc(iseq, size, align);
1175 memset(p, 0, size);
1176 return p;
1177}
1178
1179#define compile_data_calloc2_type(iseq, type, num) \
1180 (type *)compile_data_calloc2(iseq, sizeof(type), num, ALIGNMENT_SIZE_OF(type))
1181
1182static INSN *
1183compile_data_alloc_insn(rb_iseq_t *iseq)
1184{
1185 struct iseq_compile_data_storage ** arena = &ISEQ_COMPILE_DATA(iseq)->insn.storage_current;
1186 return (INSN *)compile_data_alloc_with_arena(arena, sizeof(INSN), ALIGNMENT_SIZE_OF(INSN));
1187}
1188
1189static LABEL *
1190compile_data_alloc_label(rb_iseq_t *iseq)
1191{
1192 return compile_data_alloc_type(iseq, LABEL);
1193}
1194
1195static ADJUST *
1196compile_data_alloc_adjust(rb_iseq_t *iseq)
1197{
1198 return compile_data_alloc_type(iseq, ADJUST);
1199}
1200
1201static TRACE *
1202compile_data_alloc_trace(rb_iseq_t *iseq)
1203{
1204 return compile_data_alloc_type(iseq, TRACE);
1205}
1206
1207/*
1208 * elem1, elemX => elem1, elem2, elemX
1209 */
1210static void
1211ELEM_INSERT_NEXT(LINK_ELEMENT *elem1, LINK_ELEMENT *elem2)
1212{
1213 elem2->next = elem1->next;
1214 elem2->prev = elem1;
1215 elem1->next = elem2;
1216 if (elem2->next) {
1217 elem2->next->prev = elem2;
1218 }
1219}
1220
1221/*
1222 * elem1, elemX => elemX, elem2, elem1
1223 */
1224static void
1225ELEM_INSERT_PREV(LINK_ELEMENT *elem1, LINK_ELEMENT *elem2)
1226{
1227 elem2->prev = elem1->prev;
1228 elem2->next = elem1;
1229 elem1->prev = elem2;
1230 if (elem2->prev) {
1231 elem2->prev->next = elem2;
1232 }
1233}
1234
1235/*
1236 * elemX, elem1, elemY => elemX, elem2, elemY
1237 */
1238static void
1239ELEM_REPLACE(LINK_ELEMENT *elem1, LINK_ELEMENT *elem2)
1240{
1241 elem2->prev = elem1->prev;
1242 elem2->next = elem1->next;
1243 if (elem1->prev) {
1244 elem1->prev->next = elem2;
1245 }
1246 if (elem1->next) {
1247 elem1->next->prev = elem2;
1248 }
1249}
1250
1251static void
1252ELEM_REMOVE(LINK_ELEMENT *elem)
1253{
1254 elem->prev->next = elem->next;
1255 if (elem->next) {
1256 elem->next->prev = elem->prev;
1257 }
1258}
1259
1260/*
1261 * elem1, elem2 => elem2, elem1
1262 */
1263static void
1264ELEM_SWAP(LINK_ELEMENT *first, LINK_ELEMENT *second)
1265{
1266 RUBY_ASSERT(first->next == second);
1267 RUBY_ASSERT(first == second->prev);
1268
1269 first->prev->next = second;
1270 second->next->prev = first;
1271
1272 first->next = second->next;
1273 second->next = first;
1274
1275 second->prev = first->prev;
1276 first->prev = second;
1277
1278 if (IS_INSN(first) && IS_INSN(second)) {
1279 INSN *first_insn = (INSN*)first;
1280 INSN *second_insn = (INSN*)second;
1281
1282 // [Bug #22299] If both instructions are on the same line and the first one carries
1283 // a line event we need to swap the event as well.
1284 if (first_insn->insn_info.line_no == second_insn->insn_info.line_no) {
1285 rb_iseq_events_t mask = (RUBY_EVENT_LINE | RUBY_EVENT_COVERAGE_LINE);
1286 rb_iseq_events_t first_events = first_insn->insn_info.events & mask;
1287 rb_iseq_events_t second_events = second_insn->insn_info.events & mask;
1288 first_insn->insn_info.events = (first_insn->insn_info.events & ~mask) | second_events;
1289 second_insn->insn_info.events = (second_insn->insn_info.events & ~mask) | first_events;
1290 }
1291 }
1292}
1293
1294static LINK_ELEMENT *
1295FIRST_ELEMENT(const LINK_ANCHOR *const anchor)
1296{
1297 return anchor->anchor.next;
1298}
1299
1300static LINK_ELEMENT *
1301LAST_ELEMENT(LINK_ANCHOR *const anchor)
1302{
1303 return anchor->last;
1304}
1305
1306static LINK_ELEMENT *
1307ELEM_FIRST_INSN(LINK_ELEMENT *elem)
1308{
1309 while (elem) {
1310 switch (elem->type) {
1311 case ISEQ_ELEMENT_INSN:
1312 case ISEQ_ELEMENT_ADJUST:
1313 return elem;
1314 default:
1315 elem = elem->next;
1316 }
1317 }
1318 return NULL;
1319}
1320
1321static int
1322LIST_INSN_SIZE_ONE(const LINK_ANCHOR *const anchor)
1323{
1324 LINK_ELEMENT *first_insn = ELEM_FIRST_INSN(FIRST_ELEMENT(anchor));
1325 if (first_insn != NULL &&
1326 ELEM_FIRST_INSN(first_insn->next) == NULL) {
1327 return TRUE;
1328 }
1329 else {
1330 return FALSE;
1331 }
1332}
1333
1334static int
1335LIST_INSN_SIZE_ZERO(const LINK_ANCHOR *const anchor)
1336{
1337 if (ELEM_FIRST_INSN(FIRST_ELEMENT(anchor)) == NULL) {
1338 return TRUE;
1339 }
1340 else {
1341 return FALSE;
1342 }
1343}
1344
1345/*
1346 * anc1: e1, e2, e3
1347 * anc2: e4, e5
1348 *#=>
1349 * anc1: e1, e2, e3, e4, e5
1350 * anc2: e4, e5 (broken)
1351 */
1352static void
1353APPEND_LIST(ISEQ_ARG_DECLARE LINK_ANCHOR *const anc1, LINK_ANCHOR *const anc2)
1354{
1355 if (anc2->anchor.next) {
1356 /* LINK_ANCHOR must not loop */
1357 RUBY_ASSERT(anc2->last != &anc2->anchor);
1358 anc1->last->next = anc2->anchor.next;
1359 anc2->anchor.next->prev = anc1->last;
1360 anc1->last = anc2->last;
1361 }
1362 else {
1363 RUBY_ASSERT(anc2->last == &anc2->anchor);
1364 }
1365 verify_list("append", anc1);
1366}
1367#if CPDEBUG < 0
1368#define APPEND_LIST(anc1, anc2) APPEND_LIST(iseq, (anc1), (anc2))
1369#endif
1370
1371#if CPDEBUG && 0
1372static void
1373debug_list(ISEQ_ARG_DECLARE LINK_ANCHOR *const anchor, LINK_ELEMENT *cur)
1374{
1375 LINK_ELEMENT *list = FIRST_ELEMENT(anchor);
1376 printf("----\n");
1377 printf("anch: %p, frst: %p, last: %p\n", (void *)&anchor->anchor,
1378 (void *)anchor->anchor.next, (void *)anchor->last);
1379 while (list) {
1380 printf("curr: %p, next: %p, prev: %p, type: %d\n", (void *)list, (void *)list->next,
1381 (void *)list->prev, (int)list->type);
1382 list = list->next;
1383 }
1384 printf("----\n");
1385
1386 dump_disasm_list_with_cursor(anchor->anchor.next, cur, 0);
1387 verify_list("debug list", anchor);
1388}
1389#if CPDEBUG < 0
1390#define debug_list(anc, cur) debug_list(iseq, (anc), (cur))
1391#endif
1392#else
1393#define debug_list(anc, cur) ((void)0)
1394#endif
1395
1396static TRACE *
1397new_trace_body(rb_iseq_t *iseq, rb_iseq_events_t event, long data)
1398{
1399 TRACE *trace = compile_data_alloc_trace(iseq);
1400
1401 trace->link.type = ISEQ_ELEMENT_TRACE;
1402 trace->link.next = NULL;
1403 trace->event = event;
1404 trace->data = data;
1405
1406 return trace;
1407}
1408
1409static LABEL *
1410new_label_body(rb_iseq_t *iseq, long line)
1411{
1412 LABEL *labelobj = compile_data_alloc_label(iseq);
1413
1414 labelobj->link.type = ISEQ_ELEMENT_LABEL;
1415 labelobj->link.next = 0;
1416
1417 labelobj->label_no = ISEQ_COMPILE_DATA(iseq)->label_no++;
1418 labelobj->sc_state = 0;
1419 labelobj->sp = -1;
1420 labelobj->refcnt = 0;
1421 labelobj->set = 0;
1422 labelobj->rescued = LABEL_RESCUE_NONE;
1423 labelobj->unremovable = 0;
1424 labelobj->position = -1;
1425 return labelobj;
1426}
1427
1428static ADJUST *
1429new_adjust_body(rb_iseq_t *iseq, LABEL *label, int line)
1430{
1431 ADJUST *adjust = compile_data_alloc_adjust(iseq);
1432 adjust->link.type = ISEQ_ELEMENT_ADJUST;
1433 adjust->link.next = 0;
1434 adjust->label = label;
1435 adjust->line_no = line;
1436 LABEL_UNREMOVABLE(label);
1437 return adjust;
1438}
1439
1440static void
1441iseq_insn_each_markable_object(INSN *insn, void (*func)(VALUE *, VALUE), VALUE data)
1442{
1443 const char *types = insn_op_types(insn->insn_id);
1444 for (int j = 0; types[j]; j++) {
1445 char type = types[j];
1446 switch (type) {
1447 case TS_CDHASH:
1448 case TS_ISEQ:
1449 case TS_VALUE:
1450 case TS_CALLDATA: // ci is stored.
1451 func(&OPERAND_AT(insn, j), data);
1452 break;
1453 default:
1454 break;
1455 }
1456 }
1457}
1458
1459static void
1460iseq_insn_each_object_write_barrier(VALUE * obj, VALUE iseq)
1461{
1462 RB_OBJ_WRITTEN(iseq, Qundef, *obj);
1464 RBASIC_CLASS(*obj) == 0 || // hidden
1465 RB_OBJ_SHAREABLE_P(*obj));
1466}
1467
1468static INSN *
1469new_insn_core(rb_iseq_t *iseq, int line_no, int node_id, int insn_id, int argc, VALUE *argv)
1470{
1471 INSN *iobj = compile_data_alloc_insn(iseq);
1472
1473 /* printf("insn_id: %d, line: %d\n", insn_id, nd_line(line_node)); */
1474
1475 iobj->link.type = ISEQ_ELEMENT_INSN;
1476 iobj->link.next = 0;
1477 iobj->insn_id = insn_id;
1478 iobj->insn_info.line_no = line_no;
1479 iobj->insn_info.node_id = node_id;
1480 iobj->insn_info.events = 0;
1481 iobj->operands = argv;
1482 iobj->operand_size = argc;
1483 iobj->sc_state = 0;
1484
1485 iseq_insn_each_markable_object(iobj, iseq_insn_each_object_write_barrier, (VALUE)iseq);
1486
1487 return iobj;
1488}
1489
1490static INSN *
1491new_insn_body(rb_iseq_t *iseq, int line_no, int node_id, enum ruby_vminsn_type insn_id, int argc, ...)
1492{
1493 VALUE *operands = 0;
1494 va_list argv;
1495 if (argc > 0) {
1496 int i;
1497 va_start(argv, argc);
1498 operands = compile_data_alloc2_type(iseq, VALUE, argc);
1499 for (i = 0; i < argc; i++) {
1500 VALUE v = va_arg(argv, VALUE);
1501 operands[i] = v;
1502 }
1503 va_end(argv);
1504 }
1505 return new_insn_core(iseq, line_no, node_id, insn_id, argc, operands);
1506}
1507
1508static INSN *
1509insn_replace_with_operands(rb_iseq_t *iseq, INSN *iobj, enum ruby_vminsn_type insn_id, int argc, ...)
1510{
1511 VALUE *operands = 0;
1512 va_list argv;
1513 if (argc > 0) {
1514 int i;
1515 va_start(argv, argc);
1516 operands = compile_data_alloc2_type(iseq, VALUE, argc);
1517 for (i = 0; i < argc; i++) {
1518 VALUE v = va_arg(argv, VALUE);
1519 operands[i] = v;
1520 }
1521 va_end(argv);
1522 }
1523
1524 iobj->insn_id = insn_id;
1525 iobj->operand_size = argc;
1526 iobj->operands = operands;
1527 iseq_insn_each_markable_object(iobj, iseq_insn_each_object_write_barrier, (VALUE)iseq);
1528
1529 return iobj;
1530}
1531
1532static const struct rb_callinfo *
1533new_callinfo(rb_iseq_t *iseq, ID mid, int argc, unsigned int flag, struct rb_callinfo_kwarg *kw_arg, int has_blockiseq)
1534{
1535 VM_ASSERT(argc >= 0);
1536
1537 if (kw_arg) {
1538 flag |= VM_CALL_KWARG;
1539 argc += kw_arg->keyword_len;
1540 }
1541
1542 if (!(flag & (VM_CALL_ARGS_SPLAT | VM_CALL_ARGS_BLOCKARG | VM_CALL_KWARG | VM_CALL_KW_SPLAT | VM_CALL_FORWARDING))
1543 && !has_blockiseq) {
1544 flag |= VM_CALL_ARGS_SIMPLE;
1545 }
1546
1547 ISEQ_BODY(iseq)->ci_size++;
1548 const struct rb_callinfo *ci = vm_ci_new(mid, flag, argc, kw_arg);
1549 RB_OBJ_WRITTEN(iseq, Qundef, ci);
1550 return ci;
1551}
1552
1553static INSN *
1554new_insn_send(rb_iseq_t *iseq, int line_no, int node_id, ID id, VALUE argc, const rb_iseq_t *blockiseq, VALUE flag, struct rb_callinfo_kwarg *keywords)
1555{
1556 VALUE *operands = compile_data_calloc2_type(iseq, VALUE, 2);
1557 VALUE ci = (VALUE)new_callinfo(iseq, id, FIX2INT(argc), FIX2INT(flag), keywords, blockiseq != NULL);
1558 operands[0] = ci;
1559 operands[1] = (VALUE)blockiseq;
1560 if (blockiseq) {
1561 RB_OBJ_WRITTEN(iseq, Qundef, blockiseq);
1562 }
1563
1564 INSN *insn;
1565
1566 if (vm_ci_flag((struct rb_callinfo *)ci) & VM_CALL_FORWARDING) {
1567 insn = new_insn_core(iseq, line_no, node_id, BIN(sendforward), 2, operands);
1568 }
1569 else {
1570 insn = new_insn_core(iseq, line_no, node_id, BIN(send), 2, operands);
1571 }
1572
1573 RB_OBJ_WRITTEN(iseq, Qundef, ci);
1574 RB_GC_GUARD(ci);
1575 return insn;
1576}
1577
1578static rb_iseq_t *
1579new_child_iseq(rb_iseq_t *iseq, const NODE *const node,
1580 VALUE name, const rb_iseq_t *parent, enum rb_iseq_type type, int line_no)
1581{
1582 rb_iseq_t *ret_iseq;
1583 VALUE ast_value = rb_ruby_ast_new(node);
1584
1585 // The child AST wrapper does not carry the source hash, so copy it from
1586 // the enclosing iseq before compiling, for grandchildren to inherit it.
1587 if (ISEQ_BODY(iseq)->source_hash) {
1588 rb_ast_t *child_ast = rb_ruby_ast_data_get(ast_value);
1589 child_ast->body.source_hash = ISEQ_BODY(iseq)->source_hash;
1590 child_ast->body.has_source_hash = 1;
1591 }
1592
1593 debugs("[new_child_iseq]> ---------------------------------------\n");
1594 int isolated_depth = ISEQ_COMPILE_DATA(iseq)->isolated_depth;
1595 ret_iseq = rb_iseq_new_with_opt(ast_value, name,
1596 ISEQ_BODY(iseq)->location.pathobj, rb_iseq_realpath(iseq),
1597 line_no, parent,
1598 isolated_depth ? isolated_depth + 1 : 0,
1599 type, ISEQ_COMPILE_DATA(iseq)->option,
1600 ISEQ_SCRIPT_LINES(iseq));
1601 debugs("[new_child_iseq]< ---------------------------------------\n");
1602 return ret_iseq;
1603}
1604
1605static rb_iseq_t *
1606new_child_iseq_with_callback(rb_iseq_t *iseq, const struct rb_iseq_new_with_callback_callback_func *ifunc,
1607 VALUE name, const rb_iseq_t *parent, enum rb_iseq_type type, int line_no)
1608{
1609 rb_iseq_t *ret_iseq;
1610
1611 debugs("[new_child_iseq_with_callback]> ---------------------------------------\n");
1612 ret_iseq = rb_iseq_new_with_callback(ifunc, name,
1613 ISEQ_BODY(iseq)->location.pathobj, rb_iseq_realpath(iseq),
1614 line_no, parent, type, ISEQ_COMPILE_DATA(iseq)->option);
1615 debugs("[new_child_iseq_with_callback]< ---------------------------------------\n");
1616 return ret_iseq;
1617}
1618
1619static void
1620set_catch_except_p(rb_iseq_t *iseq)
1621{
1622 RUBY_ASSERT(ISEQ_COMPILE_DATA(iseq));
1623 ISEQ_COMPILE_DATA(iseq)->catch_except_p = true;
1624 if (ISEQ_BODY(iseq)->parent_iseq != NULL) {
1625 if (ISEQ_COMPILE_DATA(ISEQ_BODY(iseq)->parent_iseq)) {
1626 set_catch_except_p((rb_iseq_t *) ISEQ_BODY(iseq)->parent_iseq);
1627 }
1628 }
1629}
1630
1631/* Set body->catch_except_p to true if the ISeq may catch an exception. If it is false,
1632 JIT-ed code may be optimized. If we are extremely conservative, we should set true
1633 if catch table exists. But we want to optimize while loop, which always has catch
1634 table entries for break/next/redo.
1635
1636 So this function sets true for limited ISeqs with break/next/redo catch table entries
1637 whose child ISeq would really raise an exception. */
1638static void
1639update_catch_except_flags(rb_iseq_t *iseq, struct rb_iseq_constant_body *body)
1640{
1641 unsigned int pos;
1642 size_t i;
1643 int insn;
1644 const struct iseq_catch_table *ct = body->catch_table;
1645
1646 /* This assumes that a block has parent_iseq which may catch an exception from the block, and that
1647 BREAK/NEXT/REDO catch table entries are used only when `throw` insn is used in the block. */
1648 pos = 0;
1649 while (pos < body->iseq_size) {
1650 insn = rb_vm_insn_decode(body->iseq_encoded[pos]);
1651 if (insn == BIN(throw)) {
1652 set_catch_except_p(iseq);
1653 break;
1654 }
1655 pos += insn_len(insn);
1656 }
1657
1658 if (ct == NULL)
1659 return;
1660
1661 for (i = 0; i < ct->size; i++) {
1662 const struct iseq_catch_table_entry *entry =
1663 UNALIGNED_MEMBER_PTR(ct, entries[i]);
1664 if (entry->type != CATCH_TYPE_BREAK
1665 && entry->type != CATCH_TYPE_NEXT
1666 && entry->type != CATCH_TYPE_REDO) {
1667 RUBY_ASSERT(ISEQ_COMPILE_DATA(iseq));
1668 ISEQ_COMPILE_DATA(iseq)->catch_except_p = true;
1669 break;
1670 }
1671 }
1672}
1673
1674static void
1675iseq_insert_nop_between_end_and_cont(rb_iseq_t *iseq)
1676{
1677 VALUE catch_table_ary = ISEQ_COMPILE_DATA(iseq)->catch_table_ary;
1678 if (NIL_P(catch_table_ary)) return;
1679 unsigned int i, tlen = (unsigned int)RARRAY_LEN(catch_table_ary);
1680 const VALUE *tptr = RARRAY_CONST_PTR(catch_table_ary);
1681 for (i = 0; i < tlen; i++) {
1682 const VALUE *ptr = RARRAY_CONST_PTR(tptr[i]);
1683 LINK_ELEMENT *end = (LINK_ELEMENT *)(ptr[2] & ~1);
1684 LINK_ELEMENT *cont = (LINK_ELEMENT *)(ptr[4] & ~1);
1685 LINK_ELEMENT *e;
1686
1687 enum rb_catch_type ct = (enum rb_catch_type)(ptr[0] & 0xffff);
1688
1689 if (ct != CATCH_TYPE_BREAK
1690 && ct != CATCH_TYPE_NEXT
1691 && ct != CATCH_TYPE_REDO) {
1692
1693 for (e = end; e && (IS_LABEL(e) || IS_TRACE(e)); e = e->next) {
1694 if (e == cont) {
1695 int lineno = ISEQ_BODY(iseq)->location.first_lineno;
1696 for (LINK_ELEMENT *prev = end; prev; prev = prev->prev) {
1697 if (IS_INSN(prev)) {
1698 lineno = ((INSN *)prev)->insn_info.line_no;
1699 break;
1700 }
1701 }
1702 INSN *nop = new_insn_core(iseq, lineno, -1, BIN(nop), 0, 0);
1703 ELEM_INSERT_NEXT(end, &nop->link);
1704 break;
1705 }
1706 }
1707 }
1708 }
1709
1710 RB_GC_GUARD(catch_table_ary);
1711}
1712
1713static int
1714iseq_setup_insn(rb_iseq_t *iseq, LINK_ANCHOR *const anchor)
1715{
1716 if (RTEST(ISEQ_COMPILE_DATA(iseq)->err_info))
1717 return COMPILE_NG;
1718
1719 /* debugs("[compile step 2] (iseq_array_to_linkedlist)\n"); */
1720
1721 if (compile_debug > 5)
1722 dump_disasm_list(FIRST_ELEMENT(anchor));
1723
1724 debugs("[compile step 3.1 (iseq_optimize)]\n");
1725 iseq_optimize(iseq, anchor);
1726
1727 if (compile_debug > 5)
1728 dump_disasm_list(FIRST_ELEMENT(anchor));
1729
1730 if (ISEQ_COMPILE_DATA(iseq)->option->instructions_unification) {
1731 debugs("[compile step 3.2 (iseq_insns_unification)]\n");
1732 iseq_insns_unification(iseq, anchor);
1733 if (compile_debug > 5)
1734 dump_disasm_list(FIRST_ELEMENT(anchor));
1735 }
1736
1737 debugs("[compile step 3.4 (iseq_insert_nop_between_end_and_cont)]\n");
1738 iseq_insert_nop_between_end_and_cont(iseq);
1739 if (compile_debug > 5)
1740 dump_disasm_list(FIRST_ELEMENT(anchor));
1741
1742 return COMPILE_OK;
1743}
1744
1745static int
1746iseq_setup(rb_iseq_t *iseq, LINK_ANCHOR *const anchor)
1747{
1748 if (RTEST(ISEQ_COMPILE_DATA(iseq)->err_info))
1749 return COMPILE_NG;
1750
1751 debugs("[compile step 4.1 (iseq_set_sequence)]\n");
1752 if (!iseq_set_sequence(iseq, anchor)) return COMPILE_NG;
1753 if (compile_debug > 5)
1754 dump_disasm_list(FIRST_ELEMENT(anchor));
1755
1756 debugs("[compile step 4.2 (iseq_set_exception_table)]\n");
1757 if (!iseq_set_exception_table(iseq)) return COMPILE_NG;
1758
1759 debugs("[compile step 4.3 (set_optargs_table)] \n");
1760 if (!iseq_set_optargs_table(iseq)) return COMPILE_NG;
1761
1762 debugs("[compile step 5 (iseq_translate_threaded_code)] \n");
1763 if (!rb_iseq_translate_threaded_code(iseq)) return COMPILE_NG;
1764
1765 debugs("[compile step 6 (update_catch_except_flags)] \n");
1766 RUBY_ASSERT(ISEQ_COMPILE_DATA(iseq));
1767 update_catch_except_flags(iseq, ISEQ_BODY(iseq));
1768
1769 debugs("[compile step 6.1 (remove unused catch tables)] \n");
1770 RUBY_ASSERT(ISEQ_COMPILE_DATA(iseq));
1771 if (!ISEQ_COMPILE_DATA(iseq)->catch_except_p && ISEQ_BODY(iseq)->catch_table) {
1772 ruby_xfree_sized(ISEQ_BODY(iseq)->catch_table, iseq_catch_table_bytes(ISEQ_BODY(iseq)->catch_table->size));
1773 ISEQ_BODY(iseq)->catch_table = NULL;
1774 }
1775
1776 if (compile_debug > 1) {
1777 VALUE str = rb_iseq_disasm(iseq);
1778 printf("%s\n", StringValueCStr(str));
1779 }
1780 verify_call_cache(iseq);
1781 debugs("[compile step: finish]\n");
1782
1783 return COMPILE_OK;
1784}
1785
1786static int
1787iseq_set_exception_local_table(rb_iseq_t *iseq)
1788{
1789 ISEQ_BODY(iseq)->local_table_size = numberof(rb_iseq_shared_exc_local_tbl);
1790 ISEQ_BODY(iseq)->local_table = rb_iseq_shared_exc_local_tbl;
1791 ISEQ_BODY(iseq)->lvar_states.list = NULL; // $! is read-only, so don't need lvar_states
1792 return COMPILE_OK;
1793}
1794
1795static int
1796get_lvar_level(const rb_iseq_t *iseq)
1797{
1798 int lev = 0;
1799 while (iseq != ISEQ_BODY(iseq)->local_iseq) {
1800 lev++;
1801 iseq = ISEQ_BODY(iseq)->parent_iseq;
1802 }
1803 return lev;
1804}
1805
1806static int
1807get_dyna_var_idx_at_raw(const rb_iseq_t *iseq, ID id)
1808{
1809 unsigned int i;
1810
1811 for (i = 0; i < ISEQ_BODY(iseq)->local_table_size; i++) {
1812 if (ISEQ_BODY(iseq)->local_table[i] == id) {
1813 return (int)i;
1814 }
1815 }
1816 return -1;
1817}
1818
1819static int
1820get_local_var_idx(const rb_iseq_t *iseq, ID id)
1821{
1822 int idx = get_dyna_var_idx_at_raw(ISEQ_BODY(iseq)->local_iseq, id);
1823
1824 if (idx < 0) {
1825 COMPILE_ERROR(iseq, ISEQ_LAST_LINE(iseq),
1826 "get_local_var_idx: %d", idx);
1827 }
1828
1829 return idx;
1830}
1831
1832static int
1833get_dyna_var_idx(const rb_iseq_t *iseq, ID id, int *level, int *ls)
1834{
1835 int lv = 0, idx = -1;
1836 const rb_iseq_t *const topmost_iseq = iseq;
1837
1838 while (iseq) {
1839 idx = get_dyna_var_idx_at_raw(iseq, id);
1840 if (idx >= 0) {
1841 break;
1842 }
1843 iseq = ISEQ_BODY(iseq)->parent_iseq;
1844 lv++;
1845 }
1846
1847 if (idx < 0) {
1848 COMPILE_ERROR(topmost_iseq, ISEQ_LAST_LINE(topmost_iseq),
1849 "get_dyna_var_idx: -1");
1850 }
1851
1852 *level = lv;
1853 *ls = ISEQ_BODY(iseq)->local_table_size;
1854 return idx;
1855}
1856
1857static int
1858iseq_local_block_param_p(const rb_iseq_t *iseq, unsigned int idx, unsigned int level)
1859{
1860 const struct rb_iseq_constant_body *body;
1861 while (level > 0) {
1862 iseq = ISEQ_BODY(iseq)->parent_iseq;
1863 level--;
1864 }
1865 body = ISEQ_BODY(iseq);
1866 if (body->local_iseq == iseq && /* local variables */
1867 body->param.flags.has_block &&
1868 body->local_table_size - body->param.block_start == idx) {
1869 return TRUE;
1870 }
1871 else {
1872 return FALSE;
1873 }
1874}
1875
1876static int
1877iseq_block_param_id_p(const rb_iseq_t *iseq, ID id, int *pidx, int *plevel)
1878{
1879 int level, ls;
1880 int idx = get_dyna_var_idx(iseq, id, &level, &ls);
1881 if (iseq_local_block_param_p(iseq, ls - idx, level)) {
1882 *pidx = ls - idx;
1883 *plevel = level;
1884 return TRUE;
1885 }
1886 else {
1887 return FALSE;
1888 }
1889}
1890
1891static void
1892access_outer_variables(const rb_iseq_t *iseq, int level, ID id, bool write)
1893{
1894 int isolated_depth = ISEQ_COMPILE_DATA(iseq)->isolated_depth;
1895
1896 if (isolated_depth && level >= isolated_depth) {
1897 if (id == rb_intern("yield")) {
1898 COMPILE_ERROR(iseq, ISEQ_LAST_LINE(iseq), "can not yield from isolated Proc");
1899 }
1900 else {
1901 COMPILE_ERROR(iseq, ISEQ_LAST_LINE(iseq), "can not access variable '%s' from isolated Proc", rb_id2name(id));
1902 }
1903 }
1904
1905 for (int i=0; i<level; i++) {
1906 VALUE val;
1907 struct rb_id_table *ovs = ISEQ_BODY(iseq)->outer_variables;
1908
1909 if (!ovs) {
1910 ovs = ISEQ_BODY(iseq)->outer_variables = rb_id_table_create(0);
1911 }
1912
1913 if (rb_id_table_lookup(ISEQ_BODY(iseq)->outer_variables, id, &val)) {
1914 if (write && !val) {
1915 rb_id_table_insert(ISEQ_BODY(iseq)->outer_variables, id, Qtrue);
1916 }
1917 }
1918 else {
1919 rb_id_table_insert(ISEQ_BODY(iseq)->outer_variables, id, RBOOL(write));
1920 }
1921
1922 iseq = ISEQ_BODY(iseq)->parent_iseq;
1923 }
1924}
1925
1926static ID
1927iseq_lvar_id(const rb_iseq_t *iseq, int idx, int level)
1928{
1929 for (int i=0; i<level; i++) {
1930 iseq = ISEQ_BODY(iseq)->parent_iseq;
1931 }
1932
1933 ID id = ISEQ_BODY(iseq)->local_table[ISEQ_BODY(iseq)->local_table_size - idx];
1934 // fprintf(stderr, "idx:%d level:%d ID:%s\n", idx, level, rb_id2name(id));
1935 return id;
1936}
1937
1938static void
1939update_lvar_state(const rb_iseq_t *iseq, int level, int idx)
1940{
1941 for (int i=0; i<level; i++) {
1942 iseq = ISEQ_BODY(iseq)->parent_iseq;
1943 }
1944
1945 uint8_t *states = iseq_lvar_states(ISEQ_BODY(iseq));
1946 int table_idx = ISEQ_BODY(iseq)->local_table_size - idx;
1947 switch (iseq_lvar_state_get(states, table_idx)) {
1948 case lvar_uninitialized:
1949 iseq_lvar_state_set(states, table_idx, lvar_initialized);
1950 break;
1951 case lvar_initialized:
1952 iseq_lvar_state_set(states, table_idx, lvar_reassigned);
1953 break;
1954 case lvar_reassigned:
1955 /* nothing */
1956 break;
1957 default:
1958 rb_bug("unreachable");
1959 }
1960}
1961
1962static int
1963iseq_set_parameters_lvar_state(const rb_iseq_t *iseq)
1964{
1965 uint8_t *states = iseq_lvar_states(ISEQ_BODY(iseq));
1966
1967 for (unsigned int i=0; i<ISEQ_BODY(iseq)->param.size; i++) {
1968 iseq_lvar_state_set(states, i, lvar_initialized);
1969 }
1970
1971 int lead_num = ISEQ_BODY(iseq)->param.lead_num;
1972 int opt_num = ISEQ_BODY(iseq)->param.opt_num;
1973 for (int i=0; i<opt_num; i++) {
1974 iseq_lvar_state_set(states, lead_num + i, lvar_uninitialized);
1975 }
1976
1977 return COMPILE_OK;
1978}
1979
1980static void
1981iseq_add_getlocal(rb_iseq_t *iseq, LINK_ANCHOR *const seq, const NODE *const line_node, int idx, int level)
1982{
1983 if (iseq_local_block_param_p(iseq, idx, level)) {
1984 ADD_INSN2(seq, line_node, getblockparam, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level));
1985 }
1986 else {
1987 ADD_INSN2(seq, line_node, getlocal, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level));
1988 }
1989 if (level > 0) access_outer_variables(iseq, level, iseq_lvar_id(iseq, idx, level), Qfalse);
1990}
1991
1992static void
1993iseq_add_setlocal(rb_iseq_t *iseq, LINK_ANCHOR *const seq, const NODE *const line_node, int idx, int level)
1994{
1995 if (iseq_local_block_param_p(iseq, idx, level)) {
1996 ADD_INSN2(seq, line_node, setblockparam, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level));
1997 }
1998 else {
1999 ADD_INSN2(seq, line_node, setlocal, INT2FIX((idx) + VM_ENV_DATA_SIZE - 1), INT2FIX(level));
2000 }
2001 update_lvar_state(iseq, level, idx);
2002 if (level > 0) access_outer_variables(iseq, level, iseq_lvar_id(iseq, idx, level), Qtrue);
2003}
2004
2005
2006
2007static void
2008iseq_calc_param_size(rb_iseq_t *iseq)
2009{
2010 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
2011 if (body->param.flags.has_opt ||
2012 body->param.flags.has_post ||
2013 body->param.flags.has_rest ||
2014 body->param.flags.has_block ||
2015 body->param.flags.has_kw ||
2016 body->param.flags.has_kwrest) {
2017
2018 if (body->param.flags.has_block) {
2019 body->param.size = body->param.block_start + 1;
2020 }
2021 else if (body->param.flags.has_kwrest) {
2022 body->param.size = body->param.keyword->rest_start + 1;
2023 }
2024 else if (body->param.flags.has_kw) {
2025 body->param.size = body->param.keyword->bits_start + 1;
2026 }
2027 else if (body->param.flags.has_post) {
2028 body->param.size = rb_iseq_param_post_start(body) + body->param.post_num;
2029 }
2030 else if (body->param.flags.has_rest) {
2031 body->param.size = rb_iseq_param_rest_start(body) + 1;
2032 }
2033 else if (body->param.flags.has_opt) {
2034 body->param.size = body->param.lead_num + body->param.opt_num;
2035 }
2036 else {
2038 }
2039 }
2040 else {
2041 body->param.size = body->param.lead_num;
2042 }
2043}
2044
2045static int
2046iseq_set_arguments_keywords(rb_iseq_t *iseq, LINK_ANCHOR *const optargs,
2047 const struct rb_args_info *args, int arg_size)
2048{
2049 const rb_node_kw_arg_t *node = args->kw_args;
2050 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
2051 struct rb_iseq_param_keyword *keyword;
2052 const VALUE default_values = rb_ary_hidden_new(1);
2053 const VALUE complex_mark = rb_str_tmp_new(0);
2054 int kw = 0, rkw = 0, i;
2055
2056 body->param.flags.has_kw = TRUE;
2057 body->param.keyword = keyword = ZALLOC_N(struct rb_iseq_param_keyword, 1);
2058
2059 while (node) {
2060 kw++;
2061 if (get_nd_value(node->nd_body) == NODE_SPECIAL_REQUIRED_KEYWORD) {
2062 rkw++;
2063 }
2064 node = node->nd_next;
2065 }
2066 if (kw > VM_CALL_KW_LEN_MAX) {
2067 COMPILE_ERROR(ERROR_ARGS_AT(RNODE(args->kw_args)) "too many keyword parameters (%d, maximum is %d)",
2068 kw, (int)VM_CALL_KW_LEN_MAX);
2069 }
2070 arg_size += kw;
2071 keyword->bits_start = arg_size++;
2072 keyword->num = kw;
2073 keyword->required_num = rkw;
2074 keyword->table = &body->local_table[keyword->bits_start - keyword->num];
2075
2076 if (RNODE_DVAR(args->kw_rest_arg)->nd_vid != 0) {
2077 ID kw_id = ISEQ_BODY(iseq)->local_table[arg_size];
2078 keyword->rest_start = arg_size++;
2079 body->param.flags.has_kwrest = TRUE;
2080
2081 if (kw_id == idPow) body->param.flags.anon_kwrest = TRUE;
2082 }
2083
2084 node = args->kw_args;
2085 while (node) {
2086 const NODE *val_node = get_nd_value(node->nd_body);
2087 VALUE dv;
2088
2089 if (val_node != NODE_SPECIAL_REQUIRED_KEYWORD) {
2090 switch (nd_type(val_node)) {
2091 case NODE_SYM:
2092 dv = rb_node_sym_string_val(val_node);
2093 break;
2094 case NODE_REGX:
2095 dv = rb_node_regx_string_val(val_node);
2096 break;
2097 case NODE_LINE:
2098 dv = rb_node_line_lineno_val(val_node);
2099 break;
2100 case NODE_INTEGER:
2101 dv = rb_node_integer_literal_val(val_node);
2102 break;
2103 case NODE_FLOAT:
2104 dv = rb_node_float_literal_val(val_node);
2105 break;
2106 case NODE_RATIONAL:
2107 dv = rb_node_rational_literal_val(val_node);
2108 break;
2109 case NODE_IMAGINARY:
2110 dv = rb_node_imaginary_literal_val(val_node);
2111 break;
2112 case NODE_ENCODING:
2113 dv = rb_node_encoding_val(val_node);
2114 break;
2115 case NODE_NIL:
2116 dv = Qnil;
2117 break;
2118 case NODE_TRUE:
2119 dv = Qtrue;
2120 break;
2121 case NODE_FALSE:
2122 dv = Qfalse;
2123 break;
2124 default:
2125 NO_CHECK(COMPILE_POPPED(optargs, "kwarg", RNODE(node))); /* nd_type_p(node, NODE_KW_ARG) */
2126 dv = complex_mark;
2127 }
2128
2129 rb_ary_push(default_values, dv);
2130 }
2131
2132 node = node->nd_next;
2133 }
2134
2135 if (RARRAY_LEN(default_values)) {
2136 VALUE *dvs = ALLOC_N(VALUE, RARRAY_LEN(default_values));
2137
2138 for (i = 0; i < RARRAY_LEN(default_values); i++) {
2139 VALUE dv = RARRAY_AREF(default_values, i);
2140 if (dv == complex_mark) dv = Qundef;
2142 RB_OBJ_WRITE(iseq, &dvs[i], dv);
2143 }
2144
2145 keyword->default_values = dvs;
2146 }
2147 return arg_size;
2148}
2149
2150static void
2151iseq_set_use_block(rb_iseq_t *iseq)
2152{
2153 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
2154 if (!body->param.flags.use_block) {
2155 body->param.flags.use_block = 1;
2156
2157 rb_vm_t *vm = GET_VM();
2158
2159 if (!rb_warning_category_enabled_p(RB_WARN_CATEGORY_STRICT_UNUSED_BLOCK)) {
2160 st_data_t key = (st_data_t)rb_intern_str(body->location.label); // String -> ID
2161 set_insert(&vm->unused_block_warning_table, key);
2162 }
2163 }
2164}
2165
2166static int
2167iseq_set_arguments(rb_iseq_t *iseq, LINK_ANCHOR *const optargs, const NODE *const node_args)
2168{
2169 debugs("iseq_set_arguments: %s\n", node_args ? "" : "0");
2170
2171 if (node_args) {
2172 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
2173 const struct rb_args_info *const args = &RNODE_ARGS(node_args)->nd_ainfo;
2174 ID rest_id = 0;
2175 int last_comma = 0;
2176 ID block_id = 0;
2177 int arg_size;
2178
2179 EXPECT_NODE("iseq_set_arguments", node_args, NODE_ARGS, COMPILE_NG);
2180
2181 body->param.lead_num = arg_size = (int)args->pre_args_num;
2182 if (body->param.lead_num > 0) body->param.flags.has_lead = TRUE;
2183 debugs(" - argc: %d\n", body->param.lead_num);
2184
2185 rest_id = args->rest_arg;
2186 if (rest_id == NODE_SPECIAL_EXCESSIVE_COMMA) {
2187 last_comma = 1;
2188 rest_id = 0;
2189 }
2190 block_id = args->block_arg;
2191
2192 bool optimized_forward = (args->forwarding && args->pre_args_num == 0 && !args->opt_args);
2193
2194 if (optimized_forward) {
2195 rest_id = 0;
2196 block_id = 0;
2197 }
2198
2199 if (args->opt_args) {
2200 const rb_node_opt_arg_t *node = args->opt_args;
2201 LABEL *label;
2202 VALUE labels = rb_ary_hidden_new(1);
2203 VALUE *opt_table;
2204 int i = 0, j;
2205
2206 while (node) {
2207 label = NEW_LABEL(nd_line(RNODE(node)));
2208 rb_ary_push(labels, (VALUE)label | 1);
2209 ADD_LABEL(optargs, label);
2210 NO_CHECK(COMPILE_POPPED(optargs, "optarg", node->nd_body));
2211 node = node->nd_next;
2212 i += 1;
2213 }
2214
2215 /* last label */
2216 label = NEW_LABEL(nd_line(node_args));
2217 rb_ary_push(labels, (VALUE)label | 1);
2218 ADD_LABEL(optargs, label);
2219
2220 opt_table = ALLOC_N(VALUE, i+1);
2221
2222 MEMCPY(opt_table, RARRAY_CONST_PTR(labels), VALUE, i+1);
2223 for (j = 0; j < i+1; j++) {
2224 opt_table[j] &= ~1;
2225 }
2226 rb_ary_clear(labels);
2227
2228 body->param.flags.has_opt = TRUE;
2229 body->param.opt_num = i;
2230 body->param.opt_table = opt_table;
2231 arg_size += i;
2232 }
2233
2234 if (rest_id) {
2235 RUBY_ASSERT(rb_iseq_param_rest_start(body) == arg_size);
2236 arg_size++;
2237 body->param.flags.has_rest = TRUE;
2238 if (rest_id == '*') body->param.flags.anon_rest = TRUE;
2239 }
2240
2241 if (args->first_post_arg) {
2242 RUBY_ASSERT(rb_iseq_param_post_start(body) == arg_size);
2243 body->param.post_num = args->post_args_num;
2244 body->param.flags.has_post = TRUE;
2245 arg_size += args->post_args_num;
2246 }
2247
2248 if (args->kw_args) {
2249 arg_size = iseq_set_arguments_keywords(iseq, optargs, args, arg_size);
2250 }
2251 else if (args->kw_rest_arg && !optimized_forward) {
2252 ID kw_id = ISEQ_BODY(iseq)->local_table[arg_size];
2253 struct rb_iseq_param_keyword *keyword = ZALLOC_N(struct rb_iseq_param_keyword, 1);
2254 keyword->rest_start = arg_size++;
2255 body->param.keyword = keyword;
2256 body->param.flags.has_kwrest = TRUE;
2257
2258 static ID anon_kwrest = 0;
2259 if (!anon_kwrest) anon_kwrest = rb_intern("**");
2260 if (kw_id == anon_kwrest) body->param.flags.anon_kwrest = TRUE;
2261 }
2262 else if (args->no_kwarg) {
2263 body->param.flags.accepts_no_kwarg = TRUE;
2264 }
2265
2266 if (args->no_blockarg) {
2267 body->param.flags.accepts_no_block = TRUE;
2268 }
2269 else if (block_id) {
2270 body->param.block_start = arg_size++;
2271 body->param.flags.has_block = TRUE;
2272 iseq_set_use_block(iseq);
2273 }
2274
2275 // Only optimize specifically methods like this: `foo(...)`
2276 if (optimized_forward) {
2277 body->param.flags.use_block = 1;
2278 body->param.flags.forwardable = TRUE;
2279 arg_size = 1;
2280 }
2281
2282 iseq_calc_param_size(iseq);
2283 body->param.size = arg_size;
2284
2285 if (args->pre_init) { /* m_init */
2286 NO_CHECK(COMPILE_POPPED(optargs, "init arguments (m)", args->pre_init));
2287 }
2288 if (args->post_init) { /* p_init */
2289 NO_CHECK(COMPILE_POPPED(optargs, "init arguments (p)", args->post_init));
2290 }
2291
2292 if (body->type == ISEQ_TYPE_BLOCK) {
2293 if (body->param.flags.has_opt == FALSE &&
2294 body->param.flags.has_post == FALSE &&
2295 body->param.flags.has_rest == FALSE &&
2296 body->param.flags.has_kw == FALSE &&
2297 body->param.flags.has_kwrest == FALSE) {
2298
2299 if (body->param.lead_num == 1 && last_comma == 0) {
2300 /* {|a|} */
2301 body->param.flags.ambiguous_param0 = TRUE;
2302 }
2303 }
2304 }
2305 }
2306
2307 return COMPILE_OK;
2308}
2309
2310static int
2311iseq_set_local_table(rb_iseq_t *iseq, const rb_ast_id_table_t *tbl, const NODE *const node_args)
2312{
2313 unsigned int size = tbl ? tbl->size : 0;
2314 unsigned int offset = 0;
2315
2316 if (node_args) {
2317 struct rb_args_info *args = &RNODE_ARGS(node_args)->nd_ainfo;
2318
2319 // If we have a function that only has `...` as the parameter,
2320 // then its local table should only be `...`
2321 // FIXME: I think this should be fixed in the AST rather than special case here.
2322 if (args->forwarding && args->pre_args_num == 0 && !args->opt_args) {
2323 CHECK(size >= 3);
2324 size -= 3;
2325 offset += 3;
2326 }
2327 }
2328
2329 if (size > 0) {
2330 ID *ids = ALLOC_N(ID, size);
2331 MEMCPY(ids, tbl->ids + offset, ID, size);
2332 ISEQ_BODY(iseq)->local_table = ids;
2333
2334 if (ISEQ_LVAR_STATES_EMBED_P(size)) {
2335 /* states are embedded in the body; zero them out */
2336 memset(ISEQ_BODY(iseq)->lvar_states.single, 0, sizeof(ISEQ_BODY(iseq)->lvar_states.single));
2337 }
2338 else {
2339 ISEQ_BODY(iseq)->lvar_states.list = ZALLOC_N(uint8_t, ISEQ_LVAR_STATES_BUFLEN(size));
2340 }
2341 }
2342 ISEQ_BODY(iseq)->local_table_size = size;
2343
2344 debugs("iseq_set_local_table: %u\n", ISEQ_BODY(iseq)->local_table_size);
2345 return COMPILE_OK;
2346}
2347
2348int
2349rb_iseq_cdhash_cmp(VALUE val, VALUE lit)
2350{
2351 int tval, tlit;
2352
2353 if (val == lit) {
2354 return 0;
2355 }
2356 else if ((tlit = OBJ_BUILTIN_TYPE(lit)) == -1) {
2357 return val != lit;
2358 }
2359 else if ((tval = OBJ_BUILTIN_TYPE(val)) == -1) {
2360 return -1;
2361 }
2362 else if (tlit != tval) {
2363 return -1;
2364 }
2365 else if (tlit == T_SYMBOL) {
2366 return val != lit;
2367 }
2368 else if (tlit == T_STRING) {
2369 return rb_str_hash_cmp(lit, val);
2370 }
2371 else if (tlit == T_BIGNUM) {
2372 long x = FIX2LONG(rb_big_cmp(lit, val));
2373
2374 /* Given lit and val are both Bignum, x must be -1, 0, 1.
2375 * There is no need to call rb_fix2int here. */
2376 RUBY_ASSERT((x == 1) || (x == 0) || (x == -1));
2377 return (int)x;
2378 }
2379 else if (tlit == T_FLOAT) {
2380 return rb_float_cmp(lit, val);
2381 }
2382 else if (tlit == T_RATIONAL) {
2383 const struct RRational *rat1 = RRATIONAL(val);
2384 const struct RRational *rat2 = RRATIONAL(lit);
2385 return rb_iseq_cdhash_cmp(rat1->num, rat2->num) || rb_iseq_cdhash_cmp(rat1->den, rat2->den);
2386 }
2387 else if (tlit == T_COMPLEX) {
2388 const struct RComplex *comp1 = RCOMPLEX(val);
2389 const struct RComplex *comp2 = RCOMPLEX(lit);
2390 return rb_iseq_cdhash_cmp(comp1->real, comp2->real) || rb_iseq_cdhash_cmp(comp1->imag, comp2->imag);
2391 }
2392 else if (tlit == T_REGEXP) {
2393 return rb_reg_equal(val, lit) ? 0 : -1;
2394 }
2395 else {
2397 }
2398}
2399
2400st_index_t
2401rb_iseq_cdhash_hash(VALUE a)
2402{
2403 switch (OBJ_BUILTIN_TYPE(a)) {
2404 case -1:
2405 case T_SYMBOL:
2406 return (st_index_t)a;
2407 case T_STRING:
2408 return rb_str_hash(a);
2409 case T_BIGNUM:
2410 return FIX2LONG(rb_big_hash(a));
2411 case T_FLOAT:
2412 return rb_dbl_long_hash(RFLOAT_VALUE(a));
2413 case T_RATIONAL:
2414 return rb_rational_hash(a);
2415 case T_COMPLEX:
2416 return rb_complex_hash(a);
2417 case T_REGEXP:
2418 return NUM2LONG(rb_reg_hash(a));
2419 default:
2421 }
2422}
2423
2424static const struct st_hash_type cdhash_type = {
2425 rb_iseq_cdhash_cmp,
2426 rb_iseq_cdhash_hash,
2427};
2428
2429static VALUE
2430cdhash_new(size_t size)
2431{
2432 VALUE cdhash = rb_imemo_cdhash_new(size, &cdhash_type);
2433 RB_OBJ_SET_SHAREABLE(cdhash);
2434 return cdhash;
2435}
2436
2437static void
2438cdhash_aset(VALUE cdhash, VALUE key, VALUE val)
2439{
2440 st_table *tbl = rb_imemo_cdhash_tbl(cdhash);
2441 st_insert(tbl, key, val);
2442 RB_OBJ_WRITTEN(cdhash, Qundef, key);
2443}
2444
2445static void
2446cdhash_aset_if_missing(VALUE cdhash, VALUE key, VALUE val)
2447{
2448 st_table *tbl = rb_imemo_cdhash_tbl(cdhash);
2449 VALUE dontcare;
2450 if (!st_lookup(tbl, key, &dontcare)) {
2451 st_insert(tbl, key, val);
2452 RB_OBJ_WRITTEN(cdhash, Qundef, key);
2453 }
2454}
2455
2457 VALUE hash;
2458 int pos;
2459 int len;
2460};
2461
2462static int
2463cdhash_set_label_check_i(st_data_t key, st_data_t value, st_data_t argp, int error)
2464{
2465 return ST_REPLACE;
2466}
2467
2468static int
2469cdhash_set_label_replace_i(st_data_t *key, st_data_t *value, st_data_t ptr, int existing)
2470{
2471 struct cdhash_set_label_struct *data = (struct cdhash_set_label_struct *)ptr;
2472 LABEL *lobj = (LABEL *)(*value & ~1);
2473 *value = lobj->position - (data->pos+data->len);
2474 return ST_CONTINUE;
2475}
2476
2477static inline VALUE
2478get_ivar_ic_value(rb_iseq_t *iseq,ID id)
2479{
2480 return INT2FIX(ISEQ_BODY(iseq)->ivc_size++);
2481}
2482
2483static inline VALUE
2484get_cvar_ic_value(rb_iseq_t *iseq,ID id)
2485{
2486 VALUE val;
2487 struct rb_id_table *tbl = ISEQ_COMPILE_DATA(iseq)->ivar_cache_table;
2488 if (tbl) {
2489 if (rb_id_table_lookup(tbl,id,&val)) {
2490 return val;
2491 }
2492 }
2493 else {
2494 tbl = rb_id_table_create(1);
2495 ISEQ_COMPILE_DATA(iseq)->ivar_cache_table = tbl;
2496 }
2497 val = INT2FIX(ISEQ_BODY(iseq)->icvarc_size++);
2498 rb_id_table_insert(tbl,id,val);
2499 return val;
2500}
2501
2502#define BADINSN_DUMP(anchor, list, dest) \
2503 dump_disasm_list_with_cursor(FIRST_ELEMENT(anchor), list, dest)
2504
2505#define BADINSN_ERROR \
2506 (SIZED_FREE_N(generated_iseq, generated_iseq_size), \
2507 BADINSN_DUMP(anchor, list, NULL), \
2508 COMPILE_ERROR)
2509
2510static int
2511fix_sp_depth(rb_iseq_t *iseq, LINK_ANCHOR *const anchor)
2512{
2513 int stack_max = 0, sp = 0, line = 0;
2514 LINK_ELEMENT *list;
2515
2516 for (list = FIRST_ELEMENT(anchor); list; list = list->next) {
2517 if (IS_LABEL(list)) {
2518 LABEL *lobj = (LABEL *)list;
2519 lobj->set = TRUE;
2520 }
2521 }
2522
2523 for (list = FIRST_ELEMENT(anchor); list; list = list->next) {
2524 switch (list->type) {
2525 case ISEQ_ELEMENT_INSN:
2526 {
2527 int j, len, insn;
2528 const char *types;
2529 VALUE *operands;
2530 INSN *iobj = (INSN *)list;
2531
2532 /* update sp */
2533 sp = calc_sp_depth(sp, iobj);
2534 if (sp < 0) {
2535 BADINSN_DUMP(anchor, list, NULL);
2536 COMPILE_ERROR(iseq, iobj->insn_info.line_no,
2537 "argument stack underflow (%d)", sp);
2538 return -1;
2539 }
2540 if (sp > stack_max) {
2541 stack_max = sp;
2542 }
2543
2544 line = iobj->insn_info.line_no;
2545 /* fprintf(stderr, "insn: %-16s, sp: %d\n", insn_name(iobj->insn_id), sp); */
2546 operands = iobj->operands;
2547 insn = iobj->insn_id;
2548 types = insn_op_types(insn);
2549 len = insn_len(insn);
2550
2551 /* operand check */
2552 if (iobj->operand_size != len - 1) {
2553 /* printf("operand size miss! (%d, %d)\n", iobj->operand_size, len); */
2554 BADINSN_DUMP(anchor, list, NULL);
2555 COMPILE_ERROR(iseq, iobj->insn_info.line_no,
2556 "operand size miss! (%d for %d)",
2557 iobj->operand_size, len - 1);
2558 return -1;
2559 }
2560
2561 for (j = 0; types[j]; j++) {
2562 if (types[j] == TS_OFFSET) {
2563 /* label(destination position) */
2564 LABEL *lobj = (LABEL *)operands[j];
2565 if (!lobj->set) {
2566 BADINSN_DUMP(anchor, list, NULL);
2567 COMPILE_ERROR(iseq, iobj->insn_info.line_no,
2568 "unknown label: "LABEL_FORMAT, lobj->label_no);
2569 return -1;
2570 }
2571 if (lobj->sp == -1) {
2572 lobj->sp = sp;
2573 }
2574 else if (lobj->sp != sp) {
2575 VALUE path = rb_iseq_path(iseq);
2576 debugs("%.*s:%d: sp inconsistency found but ignored (" LABEL_FORMAT " sp: %d, calculated sp: %d)\n",
2577 RSTRING_LENINT(path), RSTRING_PTR(path), line,
2578 lobj->label_no, lobj->sp, sp);
2579 }
2580 }
2581 }
2582 break;
2583 }
2584 case ISEQ_ELEMENT_LABEL:
2585 {
2586 LABEL *lobj = (LABEL *)list;
2587 if (lobj->sp == -1) {
2588 lobj->sp = sp;
2589 }
2590 else {
2591 if (lobj->sp != sp) {
2592 VALUE path = rb_iseq_path(iseq);
2593 debugs("%.*s:%d: sp inconsistency found but ignored (" LABEL_FORMAT " sp: %d, calculated sp: %d)\n",
2594 RSTRING_LENINT(path), RSTRING_PTR(path), line,
2595 lobj->label_no, lobj->sp, sp);
2596 }
2597 sp = lobj->sp;
2598 }
2599 break;
2600 }
2601 case ISEQ_ELEMENT_TRACE:
2602 {
2603 /* ignore */
2604 break;
2605 }
2606 case ISEQ_ELEMENT_ADJUST:
2607 {
2608 ADJUST *adjust = (ADJUST *)list;
2609 int orig_sp = sp;
2610
2611 sp = adjust->label ? adjust->label->sp : 0;
2612 if (adjust->line_no != -1 && orig_sp - sp < 0) {
2613 BADINSN_DUMP(anchor, list, NULL);
2614 COMPILE_ERROR(iseq, adjust->line_no,
2615 "iseq_set_sequence: adjust bug %d < %d",
2616 orig_sp, sp);
2617 return -1;
2618 }
2619 break;
2620 }
2621 default:
2622 BADINSN_DUMP(anchor, list, NULL);
2623 COMPILE_ERROR(iseq, line, "unknown list type: %d", list->type);
2624 return -1;
2625 }
2626 }
2627 return stack_max;
2628}
2629
2630static void
2631add_node_id(uint8_t *node_ids, unsigned int *node_ids_size, int node_id, int *prev_node_id)
2632{
2633 int delta = node_id - *prev_node_id;
2634 uint32_t zz = ((uint32_t)delta << 1) ^ (uint32_t)(delta >> 31);
2635 *prev_node_id = node_id;
2636 do {
2637 uint8_t byte = zz & 0x7f;
2638 zz >>= 7;
2639 node_ids[(*node_ids_size)++] = zz ? (byte | 0x80) : byte;
2640 } while (zz);
2641}
2642
2643static int
2644add_insn_info(struct iseq_insn_info_entry *insns_info, unsigned int *positions,
2645 int insns_info_index, int code_index, const INSN *iobj)
2646{
2647 if (insns_info_index == 0 ||
2648 insns_info[insns_info_index-1].line_no != iobj->insn_info.line_no ||
2649 insns_info[insns_info_index-1].events != iobj->insn_info.events) {
2650 insns_info[insns_info_index].line_no = iobj->insn_info.line_no;
2651 insns_info[insns_info_index].events = iobj->insn_info.events;
2652 positions[insns_info_index] = code_index;
2653 return TRUE;
2654 }
2655 return FALSE;
2656}
2657
2658static int
2659add_adjust_info(struct iseq_insn_info_entry *insns_info, unsigned int *positions,
2660 int insns_info_index, int code_index, const ADJUST *adjust)
2661{
2662 insns_info[insns_info_index].line_no = adjust->line_no;
2663 insns_info[insns_info_index].events = 0;
2664 positions[insns_info_index] = code_index;
2665 return TRUE;
2666}
2667
2668struct ic_site {
2669 rb_const_path_t path;
2670 unsigned int index;
2671};
2672
2673static unsigned int
2674dedup_const_path_ics(struct ic_site *sites, unsigned int count)
2675{
2676 unsigned int distinct = 0;
2677
2678 if (count <= 32) {
2679 for (unsigned int i = 0; i < count; i++) {
2680 unsigned int j;
2681 for (j = 0; j < i; j++) {
2682 if (sites[i].path == sites[j].path) {
2683 break;
2684 }
2685 }
2686
2687 if (j == i) { // no match
2688 sites[i].index = distinct++;
2689 }
2690 else { // match
2691 sites[i].index = sites[j].index;
2692 }
2693 }
2694 }
2695 else {
2696 st_table table;
2697 st_init_existing_numtable_with_size(&table, count);
2698
2699 for (unsigned int i = 0; i < count; i++) {
2700 st_data_t index;
2701 if (!st_lookup(&table, (st_data_t)sites[i].path, &index)) {
2702 index = distinct++;
2703 st_insert(&table, (st_data_t)sites[i].path, index);
2704 }
2705 sites[i].index = (unsigned int)index;
2706 }
2707 st_free_embedded_table(&table);
2708 }
2709
2710 return distinct;
2711}
2712
2716static int
2717iseq_set_sequence(rb_iseq_t *iseq, LINK_ANCHOR *const anchor)
2718{
2719 struct iseq_insn_info_entry *insns_info;
2720 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
2721 LINK_ELEMENT *list;
2722 VALUE *generated_iseq;
2723 rb_iseq_events_t events = 0;
2724 long data = 0;
2725
2726 int insn_num, code_index, insns_info_index, sp = 0;
2727 VALUE ic_site_buf = 0;
2728 unsigned int ic_site_count = 0, ic_site_cursor = 0;
2729 struct ic_site *ic_sites = ALLOCV_N(struct ic_site, ic_site_buf, body->ic_size);
2730 int stack_max = fix_sp_depth(iseq, anchor);
2731
2732 if (stack_max < 0) return COMPILE_NG;
2733
2734 /* fix label position */
2735 insn_num = code_index = 0;
2736 for (list = FIRST_ELEMENT(anchor); list; list = list->next) {
2737 switch (list->type) {
2738 case ISEQ_ELEMENT_INSN:
2739 {
2740 INSN *iobj = (INSN *)list;
2741 /* update sp */
2742 sp = calc_sp_depth(sp, iobj);
2743 insn_num++;
2744 if (iobj->insn_id == BIN(opt_getconstant_path)) {
2745 if (UNLIKELY(ic_site_count >= body->ic_size)) {
2746 COMPILE_ERROR(iseq, iobj->insn_info.line_no,
2747 "iseq_set_sequence: ic_index overflow: size: %d", body->ic_size);
2748 return COMPILE_NG;
2749 }
2750 ic_sites[ic_site_count++].path = (rb_const_path_t)OPERAND_AT(iobj, 0);
2751 }
2752 events = iobj->insn_info.events |= events;
2753 if (ISEQ_COVERAGE(iseq)) {
2754 if (ISEQ_LINE_COVERAGE(iseq) && (events & RUBY_EVENT_COVERAGE_LINE) &&
2755 !(rb_get_coverage_mode() & COVERAGE_TARGET_ONESHOT_LINES)) {
2756 int line = iobj->insn_info.line_no - 1;
2757 if (line >= 0 && line < RARRAY_LEN(ISEQ_LINE_COVERAGE(iseq))) {
2758 RARRAY_ASET(ISEQ_LINE_COVERAGE(iseq), line, INT2FIX(0));
2759 }
2760 }
2761 if (ISEQ_BRANCH_COVERAGE(iseq) && (events & RUBY_EVENT_COVERAGE_BRANCH)) {
2762 while (RARRAY_LEN(ISEQ_PC2BRANCHINDEX(iseq)) <= code_index) {
2763 rb_ary_push(ISEQ_PC2BRANCHINDEX(iseq), Qnil);
2764 }
2765 RARRAY_ASET(ISEQ_PC2BRANCHINDEX(iseq), code_index, INT2FIX(data));
2766 }
2767 }
2768 code_index += insn_data_length(iobj);
2769 events = 0;
2770 data = 0;
2771 break;
2772 }
2773 case ISEQ_ELEMENT_LABEL:
2774 {
2775 LABEL *lobj = (LABEL *)list;
2776 lobj->position = code_index;
2777 if (lobj->sp != sp) {
2778 VALUE path = rb_iseq_path(iseq);
2779 debugs("%.*s: sp inconsistency found but ignored (" LABEL_FORMAT " sp: %d, calculated sp: %d)\n",
2780 RSTRING_LENINT(path), RSTRING_PTR(path),
2781 lobj->label_no, lobj->sp, sp);
2782 }
2783 sp = lobj->sp;
2784 break;
2785 }
2786 case ISEQ_ELEMENT_TRACE:
2787 {
2788 TRACE *trace = (TRACE *)list;
2789 events |= trace->event;
2790 if (trace->event & RUBY_EVENT_COVERAGE_BRANCH) data = trace->data;
2791 break;
2792 }
2793 case ISEQ_ELEMENT_ADJUST:
2794 {
2795 ADJUST *adjust = (ADJUST *)list;
2796 int orig_sp = sp;
2797 /* A restore changes the stack depth even though it emits no
2798 * instructions. */
2799 sp = adjust->label ? adjust->label->sp : 0;
2800 if (adjust->line_no != -1 && orig_sp > sp) {
2801 if (orig_sp - sp > 1) code_index++; /* 1 operand */
2802 code_index++; /* insn */
2803 insn_num++;
2804 }
2805 break;
2806 }
2807 default: break;
2808 }
2809 }
2810
2811 body->ic_size = dedup_const_path_ics(ic_sites, ic_site_count);
2812
2813 /* make instruction sequence */
2814 const int generated_iseq_size = code_index;
2815 generated_iseq = ALLOC_N(VALUE, code_index);
2816
2817 VALUE insns_info_buf;
2818 insns_info = ALLOCV_N(struct iseq_insn_info_entry, insns_info_buf, insn_num);
2819
2820 VALUE positions_buf;
2821 unsigned int *positions = ALLOCV_N(unsigned int, positions_buf, insn_num);
2822 VALUE node_ids_buf;
2823 uint8_t *node_ids = ALLOCV_N(uint8_t, node_ids_buf, (size_t)insn_num * 5);
2824 unsigned int node_ids_size = 0;
2825 int prev_node_id = 0;
2826 if (ISEQ_IS_SIZE(body)) {
2827 body->is_entries = ZALLOC_N(union iseq_inline_storage_entry, ISEQ_IS_SIZE(body));
2828 }
2829 else {
2830 body->is_entries = NULL;
2831 }
2832
2833 if (body->ci_size) {
2834 body->call_data = ZALLOC_N(struct rb_call_data, body->ci_size);
2835 }
2836 else {
2837 body->call_data = NULL;
2838 }
2839 ISEQ_COMPILE_DATA(iseq)->ci_index = 0;
2840
2841 // Calculate the bitmask buffer size.
2842 // Round the generated_iseq size up to the nearest multiple
2843 // of the number of bits in an unsigned long.
2844
2845 // Allocate enough room for the bitmask list
2846 iseq_bits_t * mark_offset_bits;
2847 int code_size = code_index;
2848
2849 bool needs_bitmap = false;
2850
2851 const size_t mark_offset_bits_size = ISEQ_MBITS_BUFLEN(code_index);
2852 if (mark_offset_bits_size == 1) {
2853 mark_offset_bits = &ISEQ_COMPILE_DATA(iseq)->mark_bits.single;
2854 ISEQ_COMPILE_DATA(iseq)->is_single_mark_bit = true;
2855 }
2856 else {
2857 mark_offset_bits = ZALLOC_N(iseq_bits_t, mark_offset_bits_size);
2858 ISEQ_COMPILE_DATA(iseq)->mark_bits.list = mark_offset_bits;
2859 ISEQ_COMPILE_DATA(iseq)->is_single_mark_bit = false;
2860 }
2861
2862 ISEQ_COMPILE_DATA(iseq)->iseq_encoded = (void *)generated_iseq;
2863 ISEQ_COMPILE_DATA(iseq)->iseq_size = code_index;
2864
2865 list = FIRST_ELEMENT(anchor);
2866 insns_info_index = code_index = sp = 0;
2867
2868 while (list) {
2869 switch (list->type) {
2870 case ISEQ_ELEMENT_INSN:
2871 {
2872 int j, len, insn;
2873 const char *types;
2874 VALUE *operands;
2875 INSN *iobj = (INSN *)list;
2876
2877 /* update sp */
2878 sp = calc_sp_depth(sp, iobj);
2879 /* fprintf(stderr, "insn: %-16s, sp: %d\n", insn_name(iobj->insn_id), sp); */
2880 operands = iobj->operands;
2881 insn = iobj->insn_id;
2882 generated_iseq[code_index] = insn;
2883 types = insn_op_types(insn);
2884 len = insn_len(insn);
2885
2886 for (j = 0; types[j]; j++) {
2887 char type = types[j];
2888
2889 /* printf("--> [%c - (%d-%d)]\n", type, k, j); */
2890 switch (type) {
2891 case TS_OFFSET:
2892 {
2893 /* label(destination position) */
2894 LABEL *lobj = (LABEL *)operands[j];
2895 generated_iseq[code_index + 1 + j] = lobj->position - (code_index + len);
2896 break;
2897 }
2898 case TS_CDHASH:
2899 {
2900 VALUE map = operands[j];
2901 struct cdhash_set_label_struct data;
2902 data.hash = map;
2903 data.pos = code_index;
2904 data.len = len;
2905 st_foreach_with_replace(rb_imemo_cdhash_tbl(map), cdhash_set_label_check_i, cdhash_set_label_replace_i, (VALUE)&data);
2906
2907 generated_iseq[code_index + 1 + j] = map;
2908 ISEQ_MBITS_SET(mark_offset_bits, code_index + 1 + j);
2909 RB_OBJ_WRITTEN(iseq, Qundef, map);
2910 needs_bitmap = true;
2911 break;
2912 }
2913 case TS_LINDEX:
2914 case TS_NUM: /* ulong */
2915 generated_iseq[code_index + 1 + j] = FIX2INT(operands[j]);
2916 break;
2917 case TS_ISEQ: /* iseq */
2918 case TS_VALUE: /* VALUE */
2919 {
2920 VALUE v = operands[j];
2921 generated_iseq[code_index + 1 + j] = v;
2922 /* to mark ruby object */
2923 if (!SPECIAL_CONST_P(v)) {
2924 RB_OBJ_WRITTEN(iseq, Qundef, v);
2925 ISEQ_MBITS_SET(mark_offset_bits, code_index + 1 + j);
2926 needs_bitmap = true;
2927 }
2928 break;
2929 }
2930 /* [ TS_IVC | TS_ICVARC | TS_IC ] */
2931 case TS_IC: /* inline cache: constants */
2932 {
2933 const struct ic_site *site = &ic_sites[ic_site_cursor++];
2934 IC ic = &ISEQ_IS_ENTRY_START(body, type)[site->index].ic_cache;
2935 ic->const_path = site->path;
2936
2937 generated_iseq[code_index + 1 + j] = (VALUE)ic;
2938 }
2939 break;
2940 case TS_IVC: /* inline ivar cache */
2941 {
2942 unsigned int ic_index = FIX2UINT(operands[j]);
2943
2944 IVC cache = ((IVC)&body->is_entries[ic_index]);
2945
2946 if (insn == BIN(setinstancevariable)) {
2947 cache->iv_set_name = SYM2ID(operands[j - 1]);
2948 cache->value = IVAR_CACHE_INIT;
2949 }
2950 else {
2951 cache->iv_set_name = 0;
2952 cache->value = rb_getivar_cache_pack(ROOT_SHAPE_ID, ATTR_INDEX_NOT_SET);
2953 }
2954 }
2955 case TS_ICVARC: /* inline cvar cache */
2956 {
2957 unsigned int ic_index = FIX2UINT(operands[j]);
2958 IC ic = &ISEQ_IS_ENTRY_START(body, type)[ic_index].ic_cache;
2959 if (UNLIKELY(ic_index >= ISEQ_IS_SIZE(body))) {
2960 BADINSN_DUMP(anchor, &iobj->link, 0);
2961 COMPILE_ERROR(iseq, iobj->insn_info.line_no,
2962 "iseq_set_sequence: ic_index overflow: index: %d, size: %d",
2963 ic_index, ISEQ_IS_SIZE(body));
2964 }
2965 generated_iseq[code_index + 1 + j] = (VALUE)ic;
2966
2967 break;
2968 }
2969 case TS_CALLDATA:
2970 {
2971 const struct rb_callinfo *source_ci = (const struct rb_callinfo *)operands[j];
2972 RUBY_ASSERT(ISEQ_COMPILE_DATA(iseq)->ci_index <= body->ci_size);
2973 struct rb_call_data *cd = &body->call_data[ISEQ_COMPILE_DATA(iseq)->ci_index++];
2974 cd->ci = source_ci;
2975 cd->cc = vm_cc_empty();
2976 generated_iseq[code_index + 1 + j] = (VALUE)cd;
2977 break;
2978 }
2979 case TS_ID: /* ID */
2980 generated_iseq[code_index + 1 + j] = SYM2ID(operands[j]);
2981 break;
2982 case TS_FUNCPTR:
2983 generated_iseq[code_index + 1 + j] = operands[j];
2984 break;
2985 case TS_BUILTIN:
2986 generated_iseq[code_index + 1 + j] = operands[j];
2987 break;
2988 default:
2989 BADINSN_ERROR(iseq, iobj->insn_info.line_no,
2990 "unknown operand type: %c", type);
2991 return COMPILE_NG;
2992 }
2993 }
2994 if (add_insn_info(insns_info, positions, insns_info_index, code_index, iobj)) insns_info_index++;
2995 add_node_id(node_ids, &node_ids_size, iobj->insn_info.node_id, &prev_node_id);
2996 code_index += len;
2997 break;
2998 }
2999 case ISEQ_ELEMENT_LABEL:
3000 {
3001 LABEL *lobj = (LABEL *)list;
3002 if (lobj->sp != sp) {
3003 VALUE path = rb_iseq_path(iseq);
3004 debugs("%.*s: sp inconsistency found but ignored (" LABEL_FORMAT " sp: %d, calculated sp: %d)\n",
3005 RSTRING_LENINT(path), RSTRING_PTR(path),
3006 lobj->label_no, lobj->sp, sp);
3007 }
3008 sp = lobj->sp;
3009 break;
3010 }
3011 case ISEQ_ELEMENT_ADJUST:
3012 {
3013 ADJUST *adjust = (ADJUST *)list;
3014 int orig_sp = sp;
3015
3016 if (adjust->label) {
3017 sp = adjust->label->sp;
3018 }
3019 else {
3020 sp = 0;
3021 }
3022
3023 if (adjust->line_no != -1) {
3024 const int diff = orig_sp - sp;
3025 if (diff > 0) {
3026 if (insns_info_index == 0) {
3027 COMPILE_ERROR(iseq, adjust->line_no,
3028 "iseq_set_sequence: adjust bug (ISEQ_ELEMENT_ADJUST must not be the first in iseq)");
3029 }
3030 if (add_adjust_info(insns_info, positions, insns_info_index, code_index, adjust)) insns_info_index++;
3031 add_node_id(node_ids, &node_ids_size, -1, &prev_node_id);
3032 }
3033 if (diff > 1) {
3034 generated_iseq[code_index++] = BIN(adjuststack);
3035 generated_iseq[code_index++] = orig_sp - sp;
3036 }
3037 else if (diff == 1) {
3038 generated_iseq[code_index++] = BIN(pop);
3039 }
3040 else if (diff < 0) {
3041 int label_no = adjust->label ? adjust->label->label_no : -1;
3042 SIZED_FREE_N(generated_iseq, generated_iseq_size);
3043 if (ISEQ_MBITS_BUFLEN(code_size) > 1) {
3044 SIZED_FREE_N(mark_offset_bits, ISEQ_MBITS_BUFLEN(code_index));
3045 }
3046 debug_list(anchor, list);
3047 COMPILE_ERROR(iseq, adjust->line_no,
3048 "iseq_set_sequence: adjust bug to %d %d < %d",
3049 label_no, orig_sp, sp);
3050 return COMPILE_NG;
3051 }
3052 }
3053 break;
3054 }
3055 default:
3056 /* ignore */
3057 break;
3058 }
3059 list = list->next;
3060 }
3061
3062 body->iseq_encoded = (void *)generated_iseq;
3063 body->iseq_size = code_index;
3064 body->stack_max = stack_max;
3065
3066 if (ISEQ_COMPILE_DATA(iseq)->is_single_mark_bit) {
3067 body->mark_bits.single = ISEQ_COMPILE_DATA(iseq)->mark_bits.single;
3068 }
3069 else {
3070 if (needs_bitmap) {
3071 body->mark_bits.list = mark_offset_bits;
3072 }
3073 else {
3074 body->mark_bits.list = NULL;
3075 ISEQ_COMPILE_DATA(iseq)->mark_bits.list = NULL;
3076 SIZED_FREE_N(mark_offset_bits, mark_offset_bits_size);
3077 }
3078 }
3079
3080 rb_iseq_insn_info_setup(body, insns_info, positions, insns_info_index, node_ids, node_ids_size);
3081 ALLOCV_END(node_ids_buf);
3082 ALLOCV_END(insns_info_buf);
3083 ALLOCV_END(positions_buf);
3084
3085 ALLOCV_END(ic_site_buf);
3086 return COMPILE_OK;
3087}
3088
3089static int
3090label_get_position(LABEL *lobj)
3091{
3092 return lobj->position;
3093}
3094
3095static int
3096label_get_sp(LABEL *lobj)
3097{
3098 return lobj->sp;
3099}
3100
3101static int
3102iseq_set_exception_table(rb_iseq_t *iseq)
3103{
3104 const VALUE *tptr, *ptr;
3105 unsigned int tlen, i, table_size = 0;
3106 struct iseq_catch_table_entry *entry;
3107
3108 ISEQ_BODY(iseq)->catch_table = NULL;
3109
3110 VALUE catch_table_ary = ISEQ_COMPILE_DATA(iseq)->catch_table_ary;
3111 if (NIL_P(catch_table_ary)) return COMPILE_OK;
3112 tlen = (int)RARRAY_LEN(catch_table_ary);
3113 tptr = RARRAY_CONST_PTR(catch_table_ary);
3114
3115 if (tlen > 0) {
3116 struct iseq_catch_table *table = xmalloc(iseq_catch_table_bytes(tlen));
3117 table->size = tlen;
3118
3119 for (i = 0; i < table->size; i++) {
3120 ptr = RARRAY_CONST_PTR(tptr[i]);
3121 int start = label_get_position((LABEL *)(ptr[1] & ~1));
3122 int end = label_get_position((LABEL *)(ptr[2] & ~1));
3123 int cont = 0;
3124 int sp = 0;
3125 if (start < 0 || end < 0) {
3126 if ((ptr[0] & 0xffff) != CATCH_TYPE_ENSURE) continue;
3127 if (start < 0) start = 0;
3128 if (end < 0) end = 0;
3129 }
3130 if (ptr[4]) {
3131 LABEL *lobj = (LABEL *)(ptr[4] & ~1);
3132 cont = label_get_position(lobj);
3133 if (cont < 0) continue;
3134 sp = label_get_sp(lobj);
3135 }
3136
3137 entry = UNALIGNED_MEMBER_PTR(table, entries[table_size++]);
3138 entry->type = (enum rb_catch_type)(ptr[0] & 0xffff);
3139 entry->start = (unsigned int)start;
3140 entry->end = (unsigned int)end;
3141 entry->iseq = (rb_iseq_t *)ptr[3];
3142 RB_OBJ_WRITTEN(iseq, Qundef, entry->iseq);
3143
3144 /* stack depth */
3145 if (ptr[4]) {
3146 entry->cont = (unsigned int)cont;
3147 entry->sp = sp;
3148
3149 /* TODO: Dirty Hack! Fix me */
3150 if (entry->type == CATCH_TYPE_RESCUE ||
3151 entry->type == CATCH_TYPE_BREAK ||
3152 entry->type == CATCH_TYPE_NEXT) {
3153 RUBY_ASSERT(entry->sp > 0);
3154 entry->sp--;
3155 }
3156 }
3157 else {
3158 entry->cont = 0;
3159 }
3160 }
3161 table->size = table_size;
3162 if (table_size == 0) {
3163 ruby_xfree_sized(table, iseq_catch_table_bytes(tlen));
3164 table = NULL;
3165 }
3166 else if (table_size < tlen) {
3167 table = ruby_xrealloc(table, iseq_catch_table_bytes(table_size));
3168 }
3169 ISEQ_BODY(iseq)->catch_table = table;
3170 RB_OBJ_WRITE(iseq, &ISEQ_COMPILE_DATA(iseq)->catch_table_ary, 0); /* free */
3171 }
3172
3173 RB_GC_GUARD(catch_table_ary);
3174
3175 return COMPILE_OK;
3176}
3177
3178/*
3179 * set optional argument table
3180 * def foo(a, b=expr1, c=expr2)
3181 * =>
3182 * b:
3183 * expr1
3184 * c:
3185 * expr2
3186 */
3187static int
3188iseq_set_optargs_table(rb_iseq_t *iseq)
3189{
3190 int i;
3191 VALUE *opt_table = (VALUE *)ISEQ_BODY(iseq)->param.opt_table;
3192
3193 if (ISEQ_BODY(iseq)->param.flags.has_opt) {
3194 for (i = 0; i < ISEQ_BODY(iseq)->param.opt_num + 1; i++) {
3195 opt_table[i] = label_get_position((LABEL *)opt_table[i]);
3196 }
3197 }
3198 return COMPILE_OK;
3199}
3200
3201static LINK_ELEMENT *
3202get_destination_insn(INSN *iobj)
3203{
3204 LABEL *lobj = (LABEL *)OPERAND_AT(iobj, 0);
3205 LINK_ELEMENT *list;
3206 rb_iseq_events_t events = 0;
3207
3208 list = lobj->link.next;
3209 while (list) {
3210 switch (list->type) {
3211 case ISEQ_ELEMENT_INSN:
3212 case ISEQ_ELEMENT_ADJUST:
3213 goto found;
3214 case ISEQ_ELEMENT_LABEL:
3215 /* ignore */
3216 break;
3217 case ISEQ_ELEMENT_TRACE:
3218 {
3219 TRACE *trace = (TRACE *)list;
3220 events |= trace->event;
3221 }
3222 break;
3223 default: break;
3224 }
3225 list = list->next;
3226 }
3227 found:
3228 if (list && IS_INSN(list)) {
3229 INSN *iobj = (INSN *)list;
3230 iobj->insn_info.events |= events;
3231 }
3232 return list;
3233}
3234
3235static LINK_ELEMENT *
3236get_next_insn(INSN *iobj)
3237{
3238 LINK_ELEMENT *list = iobj->link.next;
3239
3240 while (list) {
3241 if (IS_INSN(list) || IS_ADJUST(list)) {
3242 return list;
3243 }
3244 list = list->next;
3245 }
3246 return 0;
3247}
3248
3249static LINK_ELEMENT *
3250get_prev_insn(INSN *iobj)
3251{
3252 LINK_ELEMENT *list = iobj->link.prev;
3253
3254 while (list) {
3255 if (IS_INSN(list) || IS_ADJUST(list)) {
3256 return list;
3257 }
3258 list = list->prev;
3259 }
3260 return 0;
3261}
3262
3263static void
3264unref_destination(INSN *iobj, int pos)
3265{
3266 LABEL *lobj = (LABEL *)OPERAND_AT(iobj, pos);
3267 --lobj->refcnt;
3268 if (!lobj->refcnt) ELEM_REMOVE(&lobj->link);
3269}
3270
3271static bool
3272replace_destination(INSN *dobj, INSN *nobj)
3273{
3274 VALUE n = OPERAND_AT(nobj, 0);
3275 LABEL *dl = (LABEL *)OPERAND_AT(dobj, 0);
3276 LABEL *nl = (LABEL *)n;
3277 if (dl == nl) return false;
3278 --dl->refcnt;
3279 ++nl->refcnt;
3280 OPERAND_AT(dobj, 0) = n;
3281 if (!dl->refcnt) ELEM_REMOVE(&dl->link);
3282 return true;
3283}
3284
3285static LABEL*
3286find_destination(INSN *i)
3287{
3288 int pos, len = insn_len(i->insn_id);
3289 for (pos = 0; pos < len; ++pos) {
3290 if (insn_op_types(i->insn_id)[pos] == TS_OFFSET) {
3291 return (LABEL *)OPERAND_AT(i, pos);
3292 }
3293 }
3294 return 0;
3295}
3296
3298 const unsigned int capacity;
3299 unsigned int gen;
3300 int *counts;
3301 unsigned int *stamps;
3302};
3303
3304static int
3305unreachable_unref_count(const struct unreachable_unref *unref, const LABEL *lab)
3306{
3307 unsigned int no = (unsigned int)lab->label_no;
3308 return unref->stamps[no] == unref->gen ? unref->counts[no] : 0;
3309}
3310
3311static void
3312unreachable_unref_increment(const struct unreachable_unref *unref, const LABEL *lab)
3313{
3314 unsigned int no = (unsigned int)lab->label_no;
3315 if (unref->stamps[no] != unref->gen) {
3316 unref->stamps[no] = unref->gen;
3317 unref->counts[no] = 0;
3318 }
3319 unref->counts[no]++;
3320}
3321
3322static int
3323remove_unreachable_chunk(rb_iseq_t *iseq, struct unreachable_unref *unref, LINK_ELEMENT *i)
3324{
3325 LINK_ELEMENT *first = i, *end, *scan, *pending_end = 0;
3326 LABEL *pending = 0;
3327
3328 if (!i) return 0;
3329 if (++unref->gen == 0) {
3330 /* The stamp wrapped around, so every stale stamp became ambiguous. */
3331 MEMZERO(unref->stamps, unsigned int, unref->capacity);
3332 unref->gen = 1;
3333 }
3334
3335 end = i;
3336 scan = i;
3337 do {
3338 LABEL *lab;
3339 if (IS_INSN(scan)) {
3340 if (IS_INSN_ID(scan, leave)) {
3341 if (pending) break;
3342 end = scan;
3343 break;
3344 }
3345 else if ((lab = find_destination((INSN *)scan)) != 0) {
3346 unreachable_unref_increment(unref, lab);
3347 if (lab == pending && lab->refcnt <= unreachable_unref_count(unref, lab)) {
3348 pending = 0;
3349 }
3350 }
3351 }
3352 else if (IS_LABEL(scan)) {
3353 lab = (LABEL *)scan;
3354 if (lab->unremovable) {
3355 if (pending) break;
3356 return 0;
3357 }
3358 if (lab->refcnt > unreachable_unref_count(unref, lab)) {
3359 if (pending) break;
3360 pending = lab;
3361 pending_end = (scan == first) ? 0 : end;
3362 }
3363 continue;
3364 }
3365 else if (IS_ADJUST(scan)) {
3366 if (pending) break;
3367 return 0;
3368 }
3369 if (!pending) end = scan;
3370 } while ((scan = scan->next) != 0);
3371
3372 if (pending) {
3373 if (!pending_end) return 0;
3374 end = pending_end;
3375 }
3376 i = first;
3377 do {
3378 if (IS_INSN(i)) {
3379 struct rb_iseq_constant_body *body = ISEQ_BODY(iseq);
3380 VALUE insn = INSN_OF(i);
3381 int pos, len = insn_len(insn);
3382 for (pos = 0; pos < len; ++pos) {
3383 switch (insn_op_types(insn)[pos]) {
3384 case TS_OFFSET:
3385 unref_destination((INSN *)i, pos);
3386 break;
3387 case TS_CALLDATA:
3388 --(body->ci_size);
3389 break;
3390 }
3391 }
3392 }
3393 ELEM_REMOVE(i);
3394 } while ((i != end) && (i = i->next) != 0);
3395 return 1;
3396}
3397
3398static int
3399iseq_pop_newarray(rb_iseq_t *iseq, INSN *iobj)
3400{
3401 switch (OPERAND_AT(iobj, 0)) {
3402 case INT2FIX(0): /* empty array */
3403 ELEM_REMOVE(&iobj->link);
3404 return TRUE;
3405 case INT2FIX(1): /* single element array */
3406 ELEM_REMOVE(&iobj->link);
3407 return FALSE;
3408 default:
3409 iobj->insn_id = BIN(adjuststack);
3410 return TRUE;
3411 }
3412}
3413
3414static int
3415is_frozen_putstring(INSN *insn, VALUE *op)
3416{
3417 if (IS_INSN_ID(insn, dupstring) || IS_INSN_ID(insn, dupchilledstring)) {
3418 *op = OPERAND_AT(insn, 0);
3419 return 1;
3420 }
3421 else if (IS_INSN_ID(insn, putobject)) { /* frozen_string_literal */
3422 *op = OPERAND_AT(insn, 0);
3423 return RB_TYPE_P(*op, T_STRING);
3424 }
3425 return 0;
3426}
3427
3428static int
3429insn_has_label_before(LINK_ELEMENT *elem)
3430{
3431 LINK_ELEMENT *prev = elem->prev;
3432 while (prev) {
3433 if (prev->type == ISEQ_ELEMENT_LABEL) {
3434 LABEL *label = (LABEL *)prev;
3435 if (label->refcnt > 0) {
3436 return 1;
3437 }
3438 }
3439 else if (prev->type == ISEQ_ELEMENT_INSN) {
3440 break;
3441 }
3442 prev = prev->prev;
3443 }
3444 return 0;
3445}
3446
3447static int
3448optimize_checktype(rb_iseq_t *iseq, INSN *iobj)
3449{
3450 /*
3451 * putobject obj
3452 * dup
3453 * checktype T_XXX
3454 * branchif l1
3455 * l2:
3456 * ...
3457 * l1:
3458 *
3459 * => obj is a T_XXX
3460 *
3461 * putobject obj (T_XXX)
3462 * jump L1
3463 * L1:
3464 *
3465 * => obj is not a T_XXX
3466 *
3467 * putobject obj (T_XXX)
3468 * jump L2
3469 * L2:
3470 */
3471 int line, node_id;
3472 INSN *niobj, *ciobj, *dup = 0;
3473 LABEL *dest = 0;
3474 VALUE type;
3475
3476 switch (INSN_OF(iobj)) {
3477 case BIN(dupstring):
3478 case BIN(dupchilledstring):
3480 break;
3481 case BIN(putnil):
3482 type = INT2FIX(T_NIL);
3483 break;
3484 case BIN(putobject):
3485 type = INT2FIX(TYPE(OPERAND_AT(iobj, 0)));
3486 break;
3487 default: return FALSE;
3488 }
3489
3490 ciobj = (INSN *)get_next_insn(iobj);
3491 if (IS_INSN_ID(ciobj, jump)) {
3492 ciobj = (INSN *)get_next_insn((INSN*)OPERAND_AT(ciobj, 0));
3493 }
3494 if (IS_INSN_ID(ciobj, dup)) {
3495 ciobj = (INSN *)get_next_insn(dup = ciobj);
3496 }
3497 if (!ciobj || !IS_INSN_ID(ciobj, checktype)) return FALSE;
3498 niobj = (INSN *)get_next_insn(ciobj);
3499 if (!niobj) {
3500 /* TODO: putobject true/false */
3501 return FALSE;
3502 }
3503 switch (INSN_OF(niobj)) {
3504 case BIN(branchif):
3505 if (OPERAND_AT(ciobj, 0) == type) {
3506 dest = (LABEL *)OPERAND_AT(niobj, 0);
3507 }
3508 break;
3509 case BIN(branchunless):
3510 if (OPERAND_AT(ciobj, 0) != type) {
3511 dest = (LABEL *)OPERAND_AT(niobj, 0);
3512 }
3513 break;
3514 default:
3515 return FALSE;
3516 }
3517 line = ciobj->insn_info.line_no;
3518 node_id = ciobj->insn_info.node_id;
3519 if (!dest) {
3520 if (niobj->link.next && IS_LABEL(niobj->link.next)) {
3521 dest = (LABEL *)niobj->link.next; /* reuse label */
3522 }
3523 else {
3524 dest = NEW_LABEL(line);
3525 ELEM_INSERT_NEXT(&niobj->link, &dest->link);
3526 }
3527 }
3528 INSERT_AFTER_INSN1(iobj, line, node_id, jump, dest);
3529 LABEL_REF(dest);
3530 if (!dup) INSERT_AFTER_INSN(iobj, line, node_id, pop);
3531 return TRUE;
3532}
3533
3534static const struct rb_callinfo *
3535ci_flag_set(const rb_iseq_t *iseq, const struct rb_callinfo *ci, unsigned int add)
3536{
3537 const struct rb_callinfo *nci = vm_ci_new(vm_ci_mid(ci),
3538 vm_ci_flag(ci) | add,
3539 vm_ci_argc(ci),
3540 vm_ci_kwarg(ci));
3541 RB_OBJ_WRITTEN(iseq, ci, nci);
3542 return nci;
3543}
3544
3545static const struct rb_callinfo *
3546ci_argc_set(const rb_iseq_t *iseq, const struct rb_callinfo *ci, int argc)
3547{
3548 const struct rb_callinfo *nci = vm_ci_new(vm_ci_mid(ci),
3549 vm_ci_flag(ci),
3550 argc,
3551 vm_ci_kwarg(ci));
3552 RB_OBJ_WRITTEN(iseq, ci, nci);
3553 return nci;
3554}
3555
3556#define vm_ci_simple(ci) (vm_ci_flag(ci) & VM_CALL_ARGS_SIMPLE)
3557
3558static VALUE
3559iseq_reg_compile(rb_iseq_t *iseq, VALUE str, int options, const char *sourcefile, int sourceline)
3560{
3561 VALUE errinfo = rb_errinfo();
3562 VALUE re = rb_reg_compile(str, options, sourcefile, sourceline);
3563 if (NIL_P(re)) {
3564 VALUE message = rb_attr_get(rb_errinfo(), idMesg);
3565 rb_set_errinfo(errinfo);
3566 COMPILE_ERROR(iseq, sourceline, "%" PRIsVALUE, message);
3567 }
3568 else {
3570 }
3571 return re;
3572}
3573
3574static int
3575iseq_peephole_optimize(rb_iseq_t *iseq, struct unreachable_unref *unref, LINK_ELEMENT *list, const int do_tailcallopt)
3576{
3577 INSN *const iobj = (INSN *)list;
3578
3579 again:
3580 optimize_checktype(iseq, iobj);
3581
3582 if (IS_INSN_ID(iobj, jump)) {
3583 INSN *niobj, *diobj, *piobj;
3584 diobj = (INSN *)get_destination_insn(iobj);
3585 niobj = (INSN *)get_next_insn(iobj);
3586
3587 if (diobj == niobj) {
3588 /*
3589 * jump LABEL
3590 * LABEL:
3591 * =>
3592 * LABEL:
3593 */
3594 unref_destination(iobj, 0);
3595 ELEM_REMOVE(&iobj->link);
3596 return COMPILE_OK;
3597 }
3598 else if (iobj != diobj && IS_INSN(&diobj->link) &&
3599 IS_INSN_ID(diobj, jump) &&
3600 OPERAND_AT(iobj, 0) != OPERAND_AT(diobj, 0) &&
3601 diobj->insn_info.events == 0) {
3602 /*
3603 * useless jump elimination:
3604 * jump LABEL1
3605 * ...
3606 * LABEL1:
3607 * jump LABEL2
3608 *
3609 * => in this case, first jump instruction should jump to
3610 * LABEL2 directly
3611 */
3612 if (replace_destination(iobj, diobj)) {
3613 remove_unreachable_chunk(iseq, unref, iobj->link.next);
3614 goto again;
3615 }
3616 }
3617 else if (IS_INSN_ID(diobj, leave)) {
3618 /*
3619 * jump LABEL
3620 * ...
3621 * LABEL:
3622 * leave
3623 * =>
3624 * leave
3625 * ...
3626 * LABEL:
3627 * leave
3628 */
3629 /* replace */
3630 unref_destination(iobj, 0);
3631 iobj->insn_id = BIN(leave);
3632 iobj->operand_size = 0;
3633 iobj->insn_info = diobj->insn_info;
3634 goto again;
3635 }
3636 else if (IS_INSN(iobj->link.prev) &&
3637 (piobj = (INSN *)iobj->link.prev) &&
3638 (IS_INSN_ID(piobj, branchif) ||
3639 IS_INSN_ID(piobj, branchunless))) {
3640 INSN *pdiobj = (INSN *)get_destination_insn(piobj);
3641 if (niobj == pdiobj) {
3642 int refcnt = IS_LABEL(piobj->link.next) ?
3643 ((LABEL *)piobj->link.next)->refcnt : 0;
3644 /*
3645 * useless jump elimination (if/unless destination):
3646 * if L1
3647 * jump L2
3648 * L1:
3649 * ...
3650 * L2:
3651 *
3652 * ==>
3653 * unless L2
3654 * L1:
3655 * ...
3656 * L2:
3657 */
3658 piobj->insn_id = (IS_INSN_ID(piobj, branchif))
3659 ? BIN(branchunless) : BIN(branchif);
3660 if (replace_destination(piobj, iobj) && refcnt <= 1) {
3661 ELEM_REMOVE(&iobj->link);
3662 }
3663 else {
3664 /* TODO: replace other branch destinations too */
3665 }
3666 return COMPILE_OK;
3667 }
3668 else if (diobj == pdiobj) {
3669 /*
3670 * useless jump elimination (if/unless before jump):
3671 * L1:
3672 * ...
3673 * if L1
3674 * jump L1
3675 *
3676 * ==>
3677 * L1:
3678 * ...
3679 * pop
3680 * jump L1
3681 */
3682 INSN *popiobj = new_insn_core(iseq, iobj->insn_info.line_no, iobj->insn_info.node_id, BIN(pop), 0, 0);
3683 ELEM_REPLACE(&piobj->link, &popiobj->link);
3684 }
3685 }
3686 if (remove_unreachable_chunk(iseq, unref, iobj->link.next)) {
3687 goto again;
3688 }
3689 }
3690
3691 /*
3692 * dupstring "beg"
3693 * dupstring "end"
3694 * newrange excl
3695 *
3696 * ==>
3697 *
3698 * putobject "beg".."end"
3699 */
3700 if (IS_INSN_ID(iobj, newrange)) {
3701 INSN *const range = iobj;
3702 INSN *beg, *end;
3703 VALUE str_beg, str_end;
3704
3705 if ((end = (INSN *)get_prev_insn(range)) != 0 &&
3706 is_frozen_putstring(end, &str_end) &&
3707 (beg = (INSN *)get_prev_insn(end)) != 0 &&
3708 is_frozen_putstring(beg, &str_beg) &&
3709 !(insn_has_label_before(&beg->link) || insn_has_label_before(&end->link))) {
3710 int excl = FIX2INT(OPERAND_AT(range, 0));
3711 VALUE lit_range = RB_OBJ_SET_SHAREABLE(rb_range_new(str_beg, str_end, excl));
3712
3713 ELEM_REMOVE(&beg->link);
3714 ELEM_REMOVE(&end->link);
3715 range->insn_id = BIN(putobject);
3716 OPERAND_AT(range, 0) = lit_range;
3717 RB_OBJ_WRITTEN(iseq, Qundef, lit_range);
3718 }
3719 }
3720
3721 if (IS_INSN_ID(iobj, leave)) {
3722 remove_unreachable_chunk(iseq, unref, iobj->link.next);
3723 }
3724
3725 /*
3726 * ...
3727 * duparray [...]
3728 * concatarray | concattoarray
3729 * =>
3730 * ...
3731 * putobject [...]
3732 * concatarray | concattoarray
3733 */
3734 if (IS_INSN_ID(iobj, duparray)) {
3735 LINK_ELEMENT *next = iobj->link.next;
3736 if (IS_INSN(next) && (IS_INSN_ID(next, concatarray) || IS_INSN_ID(next, concattoarray))) {
3737 iobj->insn_id = BIN(putobject);
3738 }
3739 }
3740
3741 /*
3742 * duparray [...]
3743 * send <calldata!mid:freeze, argc:0, ARGS_SIMPLE>, nil
3744 * =>
3745 * opt_ary_freeze [...], <calldata!mid:freeze, argc:0, ARGS_SIMPLE>
3746 */
3747 if (IS_INSN_ID(iobj, duparray)) {
3748 LINK_ELEMENT *next = iobj->link.next;
3749 if (IS_INSN(next) && (IS_INSN_ID(next, send))) {
3750 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(next, 0);
3751 const rb_iseq_t *blockiseq = (rb_iseq_t *)OPERAND_AT(next, 1);
3752
3753 if (vm_ci_simple(ci) && vm_ci_argc(ci) == 0 && blockiseq == NULL && vm_ci_mid(ci) == idFreeze) {
3754 VALUE ary = iobj->operands[0];
3756
3757 insn_replace_with_operands(iseq, iobj, BIN(opt_ary_freeze), 2, ary, (VALUE)ci);
3758 ELEM_REMOVE(next);
3759 }
3760 }
3761 }
3762
3763 /*
3764 * duphash {...}
3765 * send <calldata!mid:freeze, argc:0, ARGS_SIMPLE>, nil
3766 * =>
3767 * opt_hash_freeze {...}, <calldata!mid:freeze, argc:0, ARGS_SIMPLE>
3768 */
3769 if (IS_INSN_ID(iobj, duphash)) {
3770 LINK_ELEMENT *next = iobj->link.next;
3771 if (IS_INSN(next) && (IS_INSN_ID(next, send))) {
3772 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(next, 0);
3773 const rb_iseq_t *blockiseq = (rb_iseq_t *)OPERAND_AT(next, 1);
3774
3775 if (vm_ci_simple(ci) && vm_ci_argc(ci) == 0 && blockiseq == NULL && vm_ci_mid(ci) == idFreeze) {
3776 VALUE hash = iobj->operands[0];
3777 rb_obj_reveal(hash, rb_cHash);
3779
3780 insn_replace_with_operands(iseq, iobj, BIN(opt_hash_freeze), 2, hash, (VALUE)ci);
3781 ELEM_REMOVE(next);
3782 }
3783 }
3784 }
3785
3786 /*
3787 * newarray 0
3788 * send <calldata!mid:freeze, argc:0, ARGS_SIMPLE>, nil
3789 * =>
3790 * opt_ary_freeze [], <calldata!mid:freeze, argc:0, ARGS_SIMPLE>
3791 */
3792 if (IS_INSN_ID(iobj, newarray) && iobj->operands[0] == INT2FIX(0)) {
3793 LINK_ELEMENT *next = iobj->link.next;
3794 if (IS_INSN(next) && (IS_INSN_ID(next, send))) {
3795 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(next, 0);
3796 const rb_iseq_t *blockiseq = (rb_iseq_t *)OPERAND_AT(next, 1);
3797
3798 if (vm_ci_simple(ci) && vm_ci_argc(ci) == 0 && blockiseq == NULL && vm_ci_mid(ci) == idFreeze) {
3799 insn_replace_with_operands(iseq, iobj, BIN(opt_ary_freeze), 2, rb_cArray_empty_frozen, (VALUE)ci);
3800 ELEM_REMOVE(next);
3801 }
3802 }
3803 }
3804
3805 /*
3806 * newhash 0
3807 * send <calldata!mid:freeze, argc:0, ARGS_SIMPLE>, nil
3808 * =>
3809 * opt_hash_freeze {}, <calldata!mid:freeze, argc:0, ARGS_SIMPLE>
3810 */
3811 if (IS_INSN_ID(iobj, newhash) && iobj->operands[0] == INT2FIX(0)) {
3812 LINK_ELEMENT *next = iobj->link.next;
3813 if (IS_INSN(next) && (IS_INSN_ID(next, send))) {
3814 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(next, 0);
3815 const rb_iseq_t *blockiseq = (rb_iseq_t *)OPERAND_AT(next, 1);
3816
3817 if (vm_ci_simple(ci) && vm_ci_argc(ci) == 0 && blockiseq == NULL && vm_ci_mid(ci) == idFreeze) {
3818 insn_replace_with_operands(iseq, iobj, BIN(opt_hash_freeze), 2, rb_cHash_empty_frozen, (VALUE)ci);
3819 ELEM_REMOVE(next);
3820 }
3821 }
3822 }
3823
3824 if (IS_INSN_ID(iobj, branchif) ||
3825 IS_INSN_ID(iobj, branchnil) ||
3826 IS_INSN_ID(iobj, branchunless)) {
3827 /*
3828 * if L1
3829 * ...
3830 * L1:
3831 * jump L2
3832 * =>
3833 * if L2
3834 */
3835 INSN *nobj = (INSN *)get_destination_insn(iobj);
3836
3837 /* This jump-jump optimization may ignore line events on the jump
3838 * instruction being skipped. For example, the Line 2 TracePoint
3839 * event would otherwise never fire in the following code:
3840 *
3841 * 1: raise if 1 == 2
3842 * 2: while true
3843 * 3: break
3844 * 4: end
3845 *
3846 * Do not skip a jump that carries a line event. This applies even
3847 * when coverage is disabled because TracePoint consumes the same
3848 * event. [Bug #15980]
3849 */
3850 int stop_optimization =
3851 nobj->link.type == ISEQ_ELEMENT_INSN &&
3852 (nobj->insn_info.events & (RUBY_EVENT_LINE | RUBY_EVENT_COVERAGE_LINE));
3853 if (!stop_optimization) {
3854 INSN *pobj = (INSN *)iobj->link.prev;
3855 int prev_dup = 0;
3856 if (pobj) {
3857 if (!IS_INSN(&pobj->link))
3858 pobj = 0;
3859 else if (IS_INSN_ID(pobj, dup))
3860 prev_dup = 1;
3861 }
3862
3863 for (;;) {
3864 if (IS_INSN(&nobj->link) && IS_INSN_ID(nobj, jump)) {
3865 if (!replace_destination(iobj, nobj)) break;
3866 }
3867 else if (prev_dup && IS_INSN(&nobj->link) && IS_INSN_ID(nobj, dup) &&
3868 !!(nobj = (INSN *)nobj->link.next) &&
3869 IS_INSN(&nobj->link) &&
3870 /* basic blocks, with no labels in the middle */
3871 nobj->insn_id == iobj->insn_id) {
3872 /*
3873 * dup
3874 * if L1
3875 * ...
3876 * L1:
3877 * dup
3878 * if L2
3879 * =>
3880 * dup
3881 * if L2
3882 * ...
3883 * L1:
3884 * dup
3885 * if L2
3886 */
3887 if (!replace_destination(iobj, nobj)) break;
3888 }
3889 else if (pobj) {
3890 /*
3891 * putnil
3892 * if L1
3893 * =>
3894 * # nothing
3895 *
3896 * putobject true
3897 * if L1
3898 * =>
3899 * jump L1
3900 *
3901 * dupstring ".."
3902 * if L1
3903 * =>
3904 * jump L1
3905 *
3906 * dupstring ".."
3907 * dup
3908 * if L1
3909 * =>
3910 * dupstring ".."
3911 * jump L1
3912 *
3913 */
3914 int cond;
3915 if (prev_dup && IS_INSN(pobj->link.prev)) {
3916 pobj = (INSN *)pobj->link.prev;
3917 }
3918 if (IS_INSN_ID(pobj, putobject)) {
3919 cond = (IS_INSN_ID(iobj, branchif) ?
3920 OPERAND_AT(pobj, 0) != Qfalse :
3921 IS_INSN_ID(iobj, branchunless) ?
3922 OPERAND_AT(pobj, 0) == Qfalse :
3923 FALSE);
3924 }
3925 else if (IS_INSN_ID(pobj, dupstring) ||
3926 IS_INSN_ID(pobj, duparray) ||
3927 IS_INSN_ID(pobj, newarray)) {
3928 cond = IS_INSN_ID(iobj, branchif);
3929 }
3930 else if (IS_INSN_ID(pobj, putnil)) {
3931 cond = !IS_INSN_ID(iobj, branchif);
3932 }
3933 else break;
3934 if (prev_dup || !IS_INSN_ID(pobj, newarray)) {
3935 ELEM_REMOVE(iobj->link.prev);
3936 }
3937 else if (!iseq_pop_newarray(iseq, pobj)) {
3938 pobj = new_insn_core(iseq, pobj->insn_info.line_no, pobj->insn_info.node_id, BIN(pop), 0, NULL);
3939 ELEM_INSERT_PREV(&iobj->link, &pobj->link);
3940 }
3941 if (cond) {
3942 if (prev_dup) {
3943 pobj = new_insn_core(iseq, pobj->insn_info.line_no, pobj->insn_info.node_id, BIN(putnil), 0, NULL);
3944 ELEM_INSERT_NEXT(&iobj->link, &pobj->link);
3945 }
3946 iobj->insn_id = BIN(jump);
3947 goto again;
3948 }
3949 else {
3950 unref_destination(iobj, 0);
3951 ELEM_REMOVE(&iobj->link);
3952 }
3953 break;
3954 }
3955 else break;
3956 {
3957 LINK_ELEMENT *dest = get_destination_insn(nobj);
3958 if (!dest || !IS_INSN(dest)) break;
3959 nobj = (INSN *)dest;
3960 }
3961 }
3962 }
3963 }
3964
3965 if (IS_INSN_ID(iobj, pop)) {
3966 /*
3967 * putself / putnil / putobject obj / dupstring "..."
3968 * pop
3969 * =>
3970 * # do nothing
3971 */
3972 LINK_ELEMENT *prev = iobj->link.prev;
3973 if (IS_INSN(prev)) {
3974 enum ruby_vminsn_type previ = ((INSN *)prev)->insn_id;
3975 if (previ == BIN(putobject) || previ == BIN(putnil) ||
3976 previ == BIN(putself) || previ == BIN(dupstring) ||
3977 previ == BIN(dupchilledstring) ||
3978 previ == BIN(dup) ||
3979 previ == BIN(getlocal) ||
3980 previ == BIN(getblockparam) ||
3981 previ == BIN(getblockparamproxy) ||
3982 previ == BIN(getinstancevariable) ||
3983 previ == BIN(duparray)) {
3984 /* just push operand or static value and pop soon, no
3985 * side effects */
3986 ELEM_REMOVE(prev);
3987 ELEM_REMOVE(&iobj->link);
3988 }
3989 else if (previ == BIN(newarray) && iseq_pop_newarray(iseq, (INSN*)prev)) {
3990 ELEM_REMOVE(&iobj->link);
3991 }
3992 else if (previ == BIN(concatarray)) {
3993 INSN *piobj = (INSN *)prev;
3994 INSERT_BEFORE_INSN1(piobj, piobj->insn_info.line_no, piobj->insn_info.node_id, splatarray, Qfalse);
3995 INSN_OF(piobj) = BIN(pop);
3996 }
3997 else if (previ == BIN(concatstrings)) {
3998 if (OPERAND_AT(prev, 0) == INT2FIX(1)) {
3999 ELEM_REMOVE(prev);
4000 }
4001 else {
4002 ELEM_REMOVE(&iobj->link);
4003 INSN_OF(prev) = BIN(adjuststack);
4004 }
4005 }
4006 }
4007 }
4008
4009 if (IS_INSN_ID(iobj, newarray) ||
4010 IS_INSN_ID(iobj, duparray) ||
4011 IS_INSN_ID(iobj, concatarray) ||
4012 IS_INSN_ID(iobj, splatarray) ||
4013 0) {
4014 /*
4015 * newarray N
4016 * splatarray
4017 * =>
4018 * newarray N
4019 * newarray always puts an array
4020 */
4021 LINK_ELEMENT *next = iobj->link.next;
4022 if (IS_INSN(next) && IS_INSN_ID(next, splatarray)) {
4023 /* remove splatarray following always-array insn */
4024 ELEM_REMOVE(next);
4025 }
4026 }
4027
4028 if (IS_INSN_ID(iobj, newarray)) {
4029 LINK_ELEMENT *next = iobj->link.next;
4030 if (IS_INSN(next) && IS_INSN_ID(next, expandarray) &&
4031 OPERAND_AT(next, 1) == INT2FIX(0)) {
4032 VALUE op1, op2;
4033 op1 = OPERAND_AT(iobj, 0);
4034 op2 = OPERAND_AT(next, 0);
4035 ELEM_REMOVE(next);
4036
4037 if (op1 == op2) {
4038 /*
4039 * newarray 2
4040 * expandarray 2, 0
4041 * =>
4042 * swap
4043 */
4044 if (op1 == INT2FIX(2)) {
4045 INSN_OF(iobj) = BIN(swap);
4046 iobj->operand_size = 0;
4047 }
4048 /*
4049 * newarray X
4050 * expandarray X, 0
4051 * =>
4052 * opt_reverse X
4053 */
4054 else {
4055 INSN_OF(iobj) = BIN(opt_reverse);
4056 }
4057 }
4058 else {
4059 long diff = FIX2LONG(op1) - FIX2LONG(op2);
4060 INSN_OF(iobj) = BIN(opt_reverse);
4061 OPERAND_AT(iobj, 0) = OPERAND_AT(next, 0);
4062
4063 if (op1 > op2) {
4064 /* X > Y
4065 * newarray X
4066 * expandarray Y, 0
4067 * =>
4068 * pop * (Y-X)
4069 * opt_reverse Y
4070 */
4071 for (; diff > 0; diff--) {
4072 INSERT_BEFORE_INSN(iobj, iobj->insn_info.line_no, iobj->insn_info.node_id, pop);
4073 }
4074 }
4075 else { /* (op1 < op2) */
4076 /* X < Y
4077 * newarray X
4078 * expandarray Y, 0
4079 * =>
4080 * putnil * (Y-X)
4081 * opt_reverse Y
4082 */
4083 for (; diff < 0; diff++) {
4084 INSERT_BEFORE_INSN(iobj, iobj->insn_info.line_no, iobj->insn_info.node_id, putnil);
4085 }
4086 }
4087 }
4088 }
4089 }
4090
4091 if (IS_INSN_ID(iobj, duparray)) {
4092 LINK_ELEMENT *next = iobj->link.next;
4093 /*
4094 * duparray obj
4095 * expandarray X, 0
4096 * =>
4097 * putobject obj
4098 * expandarray X, 0
4099 */
4100 if (IS_INSN(next) && IS_INSN_ID(next, expandarray)) {
4101 INSN_OF(iobj) = BIN(putobject);
4102 }
4103 }
4104
4105 if (IS_INSN_ID(iobj, anytostring)) {
4106 LINK_ELEMENT *next = iobj->link.next;
4107 /*
4108 * anytostring
4109 * concatstrings 1
4110 * =>
4111 * anytostring
4112 */
4113 if (IS_INSN(next) && IS_INSN_ID(next, concatstrings) &&
4114 OPERAND_AT(next, 0) == INT2FIX(1)) {
4115 ELEM_REMOVE(next);
4116 }
4117 }
4118
4119 if (IS_INSN_ID(iobj, dupstring) || IS_INSN_ID(iobj, dupchilledstring) ||
4120 (IS_INSN_ID(iobj, putobject) && RB_TYPE_P(OPERAND_AT(iobj, 0), T_STRING))) {
4121 /*
4122 * dupstring ""
4123 * concatstrings N
4124 * =>
4125 * concatstrings N-1
4126 */
4127 if (IS_NEXT_INSN_ID(&iobj->link, concatstrings) &&
4128 RSTRING_LEN(OPERAND_AT(iobj, 0)) == 0) {
4129 INSN *next = (INSN *)iobj->link.next;
4130 if ((OPERAND_AT(next, 0) = FIXNUM_INC(OPERAND_AT(next, 0), -1)) == INT2FIX(1)) {
4131 ELEM_REMOVE(&next->link);
4132 }
4133 ELEM_REMOVE(&iobj->link);
4134 }
4135 if (IS_NEXT_INSN_ID(&iobj->link, toregexp)) {
4136 INSN *next = (INSN *)iobj->link.next;
4137 if (OPERAND_AT(next, 1) == INT2FIX(1)) {
4138 VALUE src = OPERAND_AT(iobj, 0);
4139 int opt = (int)FIX2LONG(OPERAND_AT(next, 0));
4140 VALUE path = rb_iseq_path(iseq);
4141 int line = iobj->insn_info.line_no;
4142 VALUE re = iseq_reg_compile(iseq, src, opt, RSTRING_PTR(path), line);
4143 /* The folded operand is a Regexp, so the instruction must be
4144 * putobject: dupstring/dupchilledstring would resurrect the
4145 * Regexp as a String at run time (e.g. for a /o regexp whose
4146 * interpolation folds to a constant, such as /#{"a"}/o). */
4147 iobj->insn_id = BIN(putobject);
4148 RB_OBJ_WRITE(iseq, &OPERAND_AT(iobj, 0), re);
4149 ELEM_REMOVE(iobj->link.next);
4150 }
4151 }
4152 }
4153
4154 if (IS_INSN_ID(iobj, concatstrings)) {
4155 /*
4156 * concatstrings N
4157 * concatstrings M
4158 * =>
4159 * concatstrings N+M-1
4160 */
4161 LINK_ELEMENT *next = iobj->link.next;
4162 INSN *jump = 0;
4163 if (IS_INSN(next) && IS_INSN_ID(next, jump))
4164 next = get_destination_insn(jump = (INSN *)next);
4165 if (IS_INSN(next) && IS_INSN_ID(next, concatstrings)) {
4166 int n = FIX2INT(OPERAND_AT(iobj, 0)) + FIX2INT(OPERAND_AT(next, 0)) - 1;
4167 OPERAND_AT(iobj, 0) = INT2FIX(n);
4168 if (jump) {
4169 LABEL *label = ((LABEL *)OPERAND_AT(jump, 0));
4170 if (!--label->refcnt) {
4171 ELEM_REMOVE(&label->link);
4172 }
4173 else {
4174 label = NEW_LABEL(0);
4175 OPERAND_AT(jump, 0) = (VALUE)label;
4176 }
4177 label->refcnt++;
4178 ELEM_INSERT_NEXT(next, &label->link);
4179 CHECK(iseq_peephole_optimize(iseq, unref, get_next_insn(jump), do_tailcallopt));
4180 }
4181 else {
4182 ELEM_REMOVE(next);
4183 }
4184 }
4185 }
4186
4187 if (do_tailcallopt &&
4188 (IS_INSN_ID(iobj, send) ||
4189 IS_INSN_ID(iobj, invokesuper))) {
4190 /*
4191 * send ...
4192 * leave
4193 * =>
4194 * send ..., ... | VM_CALL_TAILCALL, ...
4195 * leave # unreachable
4196 */
4197 INSN *piobj = NULL;
4198 if (iobj->link.next) {
4199 LINK_ELEMENT *next = iobj->link.next;
4200 do {
4201 if (!IS_INSN(next)) {
4202 next = next->next;
4203 continue;
4204 }
4205 switch (INSN_OF(next)) {
4206 case BIN(nop):
4207 next = next->next;
4208 break;
4209 case BIN(jump):
4210 /* if cond
4211 * return tailcall
4212 * end
4213 */
4214 next = get_destination_insn((INSN *)next);
4215 break;
4216 case BIN(leave):
4217 piobj = iobj;
4218 /* fall through */
4219 default:
4220 next = NULL;
4221 break;
4222 }
4223 } while (next);
4224 }
4225
4226 if (piobj) {
4227 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(piobj, 0);
4228 if (IS_INSN_ID(piobj, send) ||
4229 IS_INSN_ID(piobj, invokesuper)) {
4230 if (OPERAND_AT(piobj, 1) == 0) { /* no blockiseq */
4231 ci = ci_flag_set(iseq, ci, VM_CALL_TAILCALL);
4232 OPERAND_AT(piobj, 0) = (VALUE)ci;
4233 RB_OBJ_WRITTEN(iseq, Qundef, ci);
4234 }
4235 }
4236 else {
4237 ci = ci_flag_set(iseq, ci, VM_CALL_TAILCALL);
4238 OPERAND_AT(piobj, 0) = (VALUE)ci;
4239 RB_OBJ_WRITTEN(iseq, Qundef, ci);
4240 }
4241 }
4242 }
4243
4244 if (IS_INSN_ID(iobj, dup)) {
4245 if (IS_NEXT_INSN_ID(&iobj->link, setlocal)) {
4246 LINK_ELEMENT *set1 = iobj->link.next, *set2 = NULL;
4247
4248 /*
4249 * dup
4250 * setlocal x, y
4251 * setlocal x, y
4252 * =>
4253 * dup
4254 * setlocal x, y
4255 */
4256 if (IS_NEXT_INSN_ID(set1, setlocal)) {
4257 set2 = set1->next;
4258 if (OPERAND_AT(set1, 0) == OPERAND_AT(set2, 0) &&
4259 OPERAND_AT(set1, 1) == OPERAND_AT(set2, 1)) {
4260 ELEM_REMOVE(set1);
4261 ELEM_REMOVE(&iobj->link);
4262 }
4263 }
4264
4265 /*
4266 * dup
4267 * setlocal x, y
4268 * dup
4269 * setlocal x, y
4270 * =>
4271 * dup
4272 * setlocal x, y
4273 */
4274 else if (IS_NEXT_INSN_ID(set1, dup) &&
4275 IS_NEXT_INSN_ID(set1->next, setlocal)) {
4276 set2 = set1->next->next;
4277 if (OPERAND_AT(set1, 0) == OPERAND_AT(set2, 0) &&
4278 OPERAND_AT(set1, 1) == OPERAND_AT(set2, 1)) {
4279 ELEM_REMOVE(set1->next);
4280 ELEM_REMOVE(set2);
4281 }
4282 }
4283 }
4284 }
4285
4286 /*
4287 * getlocal x, y
4288 * dup
4289 * setlocal x, y
4290 * =>
4291 * dup
4292 */
4293 if (IS_INSN_ID(iobj, getlocal)) {
4294 LINK_ELEMENT *niobj = &iobj->link;
4295 if (IS_NEXT_INSN_ID(niobj, dup)) {
4296 niobj = niobj->next;
4297 }
4298 if (IS_NEXT_INSN_ID(niobj, setlocal)) {
4299 LINK_ELEMENT *set1 = niobj->next;
4300 if (OPERAND_AT(iobj, 0) == OPERAND_AT(set1, 0) &&
4301 OPERAND_AT(iobj, 1) == OPERAND_AT(set1, 1)) {
4302 ELEM_REMOVE(set1);
4303 ELEM_REMOVE(niobj);
4304 }
4305 }
4306 }
4307
4308 /*
4309 * opt_invokebuiltin_delegate
4310 * trace
4311 * leave
4312 * =>
4313 * opt_invokebuiltin_delegate_leave
4314 * trace
4315 * leave
4316 */
4317 if (IS_INSN_ID(iobj, opt_invokebuiltin_delegate)) {
4318 if (IS_TRACE(iobj->link.next)) {
4319 if (IS_NEXT_INSN_ID(iobj->link.next, leave)) {
4320 iobj->insn_id = BIN(opt_invokebuiltin_delegate_leave);
4321 const struct rb_builtin_function *bf = (const struct rb_builtin_function *)iobj->operands[0];
4322 if (iobj == (INSN *)list && bf->argc == 0 && (ISEQ_BODY(iseq)->builtin_attrs & BUILTIN_ATTR_LEAF)) {
4323 ISEQ_BODY(iseq)->builtin_attrs |= BUILTIN_ATTR_SINGLE_NOARG_LEAF;
4324 }
4325 }
4326 }
4327 }
4328
4329 /*
4330 * getblockparam
4331 * branchif / branchunless
4332 * =>
4333 * getblockparamproxy
4334 * branchif / branchunless
4335 */
4336 if (IS_INSN_ID(iobj, getblockparam)) {
4337 if (IS_NEXT_INSN_ID(&iobj->link, branchif) || IS_NEXT_INSN_ID(&iobj->link, branchunless)) {
4338 iobj->insn_id = BIN(getblockparamproxy);
4339 }
4340 }
4341
4342 if (IS_INSN_ID(iobj, splatarray) && OPERAND_AT(iobj, 0) == false) {
4343 LINK_ELEMENT *niobj = &iobj->link;
4344 if (IS_NEXT_INSN_ID(niobj, duphash)) {
4345 niobj = niobj->next;
4346 LINK_ELEMENT *siobj;
4347 unsigned int set_flags = 0, unset_flags = 0;
4348
4349 /*
4350 * Eliminate hash allocation for f(*a, kw: 1)
4351 *
4352 * splatarray false
4353 * duphash
4354 * send ARGS_SPLAT|KW_SPLAT|KW_SPLAT_MUT and not ARGS_BLOCKARG
4355 * =>
4356 * splatarray false
4357 * putobject
4358 * send ARGS_SPLAT|KW_SPLAT
4359 */
4360 if (IS_NEXT_INSN_ID(niobj, send)) {
4361 siobj = niobj->next;
4362 set_flags = VM_CALL_ARGS_SPLAT|VM_CALL_KW_SPLAT|VM_CALL_KW_SPLAT_MUT;
4363 unset_flags = VM_CALL_ARGS_BLOCKARG;
4364 }
4365 /*
4366 * Eliminate hash allocation for f(*a, kw: 1, &{arg,lvar,@iv})
4367 *
4368 * splatarray false
4369 * duphash
4370 * getlocal / getinstancevariable / getblockparamproxy
4371 * send ARGS_SPLAT|KW_SPLAT|KW_SPLAT_MUT|ARGS_BLOCKARG
4372 * =>
4373 * splatarray false
4374 * putobject
4375 * getlocal / getinstancevariable / getblockparamproxy
4376 * send ARGS_SPLAT|KW_SPLAT|ARGS_BLOCKARG
4377 */
4378 else if ((IS_NEXT_INSN_ID(niobj, getlocal) || IS_NEXT_INSN_ID(niobj, getinstancevariable) ||
4379 IS_NEXT_INSN_ID(niobj, getblockparamproxy)) && (IS_NEXT_INSN_ID(niobj->next, send))) {
4380 siobj = niobj->next->next;
4381 set_flags = VM_CALL_ARGS_SPLAT|VM_CALL_KW_SPLAT|VM_CALL_KW_SPLAT_MUT|VM_CALL_ARGS_BLOCKARG;
4382 }
4383
4384 if (set_flags) {
4385 const struct rb_callinfo *ci = (const struct rb_callinfo *)OPERAND_AT(siobj, 0);
4386 unsigned int flags = vm_ci_flag(ci);
4387 if ((flags & set_flags) == set_flags && !(flags & unset_flags)) {
4388 ((INSN*)niobj)->insn_id = BIN(putobject);
4389 RB_OBJ_WRITE(iseq, &OPERAND_AT(niobj, 0), RB_OBJ_SET_SHAREABLE(rb_hash_freeze(rb_hash_resurrect(OPERAND_AT(niobj, 0)))));
4390
4391 const struct rb_callinfo *nci = vm_ci_new(vm_ci_mid(ci),
4392 flags & ~VM_CALL_KW_SPLAT_MUT, vm_ci_argc(ci), vm_ci_kwarg(ci));
4393 RB_OBJ_WRITTEN(iseq, ci, nci);
4394 OPERAND_AT(siobj, 0) = (VALUE)nci;
4395 }
4396 }
4397 }
4398 }
4399
4400 /*
4401 * putself / (or any other independent instruction)
4402 * putnil / (or any other independent instruction)
4403 * swap
4404 * =>
4405 * putnil / (or any other independent instruction)
4406 * putself / (or any other independent instruction)
4407 */
4408 if (IS_NEXT_INSN_ID(&iobj->link, swap)) {
4409 LINK_ELEMENT *second = &iobj->link;
4410 LINK_ELEMENT *first = second->prev;
4411 LINK_ELEMENT *swap = second->next;
4412
4413 if (IS_INDEPENDENT_INSN(first) && IS_INDEPENDENT_INSN(second)) {
4414 ELEM_REMOVE(swap);
4415 ELEM_SWAP(first, second);
4416 }
4417 }
4418
4419 return COMPILE_OK;
4420}
4421
4422static int
4423insn_set_specialized_instruction(rb_iseq_t *iseq, INSN *iobj, int insn_id)
4424{
4425 if (insn_id == BIN(opt_neq)) {
4426 VALUE original_ci = iobj->operands[0];
4427 VALUE new_ci = (VALUE)new_callinfo(iseq, idEq, 1, 0, NULL, FALSE);
4428 insn_replace_with_operands(iseq, iobj, insn_id, 2, new_ci, original_ci);
4429 }
4430 else {
4431 iobj->insn_id = insn_id;
4432 iobj->operand_size = insn_len(insn_id) - 1;
4433 }
4434 iobj->insn_info.events |= RUBY_EVENT_C_CALL | RUBY_EVENT_C_RETURN;
4435
4436 return COMPILE_OK;
4437}
4438
4439static int
4440iseq_specialized_instruction(rb_iseq_t *iseq, INSN *iobj)
4441{
4442 if (IS_INSN_ID(iobj, newarray) && iobj->link.next &&
4443 IS_INSN(iobj->link.next)) {
4444 /*
4445 * [a, b, ...].max/min -> a, b, c, opt_newarray_send max/min
4446 */
4447 INSN *niobj = (INSN *)iobj->link.next;
4448 if (IS_INSN_ID(niobj, send)) {
4449 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(niobj, 0);
4450 if (vm_ci_simple(ci) && vm_ci_argc(ci) == 0) {
4451 VALUE method = INT2FIX(0);
4452 switch (vm_ci_mid(ci)) {
4453 case idMax:
4454 method = INT2FIX(VM_OPT_NEWARRAY_SEND_MAX);
4455 break;
4456 case idMin:
4457 method = INT2FIX(VM_OPT_NEWARRAY_SEND_MIN);
4458 break;
4459 case idHash:
4460 method = INT2FIX(VM_OPT_NEWARRAY_SEND_HASH);
4461 break;
4462 }
4463
4464 if (method != INT2FIX(0)) {
4465 VALUE num = iobj->operands[0];
4466 insn_replace_with_operands(iseq, iobj, BIN(opt_newarray_send), 2, num, method);
4467 ELEM_REMOVE(&niobj->link);
4468 return COMPILE_OK;
4469 }
4470 }
4471 }
4472 else if ((IS_INSN_ID(niobj, dupstring) || IS_INSN_ID(niobj, dupchilledstring) ||
4473 (IS_INSN_ID(niobj, putobject) && RB_TYPE_P(OPERAND_AT(niobj, 0), T_STRING))) &&
4474 IS_NEXT_INSN_ID(&niobj->link, send)) {
4475 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT((INSN *)niobj->link.next, 0);
4476 if (vm_ci_simple(ci) && vm_ci_argc(ci) == 1 && vm_ci_mid(ci) == idPack) {
4477 VALUE num = iobj->operands[0];
4478 insn_replace_with_operands(iseq, iobj, BIN(opt_newarray_send), 2, FIXNUM_INC(num, 1), INT2FIX(VM_OPT_NEWARRAY_SEND_PACK));
4479 ELEM_REMOVE(&iobj->link);
4480 ELEM_REMOVE(niobj->link.next);
4481 ELEM_INSERT_NEXT(&niobj->link, &iobj->link);
4482 return COMPILE_OK;
4483 }
4484 }
4485 // newarray n, dupchilledstring "E", getlocal b, send :pack with {buffer: b}
4486 // -> dupchilledstring "E", getlocal b, opt_newarray_send n+2, :pack, :buffer
4487 else if ((IS_INSN_ID(niobj, dupstring) || IS_INSN_ID(niobj, dupchilledstring) ||
4488 (IS_INSN_ID(niobj, putobject) && RB_TYPE_P(OPERAND_AT(niobj, 0), T_STRING))) &&
4489 IS_NEXT_INSN_ID(&niobj->link, getlocal) &&
4490 (niobj->link.next && IS_NEXT_INSN_ID(niobj->link.next, send))) {
4491 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT((INSN *)(niobj->link.next)->next, 0);
4492 const struct rb_callinfo_kwarg *kwarg = vm_ci_kwarg(ci);
4493 if (vm_ci_mid(ci) == idPack && vm_ci_argc(ci) == 2 &&
4494 (kwarg && kwarg->keyword_len == 1 && kwarg->keywords[0] == rb_id2sym(idBuffer))) {
4495 VALUE num = iobj->operands[0];
4496 insn_replace_with_operands(iseq, iobj, BIN(opt_newarray_send), 2, FIXNUM_INC(num, 2), INT2FIX(VM_OPT_NEWARRAY_SEND_PACK_BUFFER));
4497 // Remove the "send" insn.
4498 ELEM_REMOVE((niobj->link.next)->next);
4499 // Remove the modified insn from its original "newarray" position...
4500 ELEM_REMOVE(&iobj->link);
4501 // and insert it after the buffer insn.
4502 ELEM_INSERT_NEXT(niobj->link.next, &iobj->link);
4503 return COMPILE_OK;
4504 }
4505 }
4506
4507 // Break the "else if" chain since some prior checks abort after sub-ifs.
4508 // We already found "newarray". To match `[...].include?(arg)` we look for
4509 // the instruction(s) representing the argument followed by a "send".
4510 if ((IS_INSN_ID(niobj, dupstring) || IS_INSN_ID(niobj, dupchilledstring) ||
4511 IS_INSN_ID(niobj, putobject) ||
4512 IS_INSN_ID(niobj, putself) ||
4513 IS_INSN_ID(niobj, getlocal) ||
4514 IS_INSN_ID(niobj, getinstancevariable)) &&
4515 IS_NEXT_INSN_ID(&niobj->link, send)) {
4516
4517 LINK_ELEMENT *sendobj = &(niobj->link); // Below we call ->next;
4518 const struct rb_callinfo *ci;
4519 // Allow any number (0 or more) of simple method calls on the argument
4520 // (as in `[...].include?(arg.method1.method2)`.
4521 do {
4522 sendobj = sendobj->next;
4523 ci = (struct rb_callinfo *)OPERAND_AT(sendobj, 0);
4524 } while (vm_ci_simple(ci) && vm_ci_argc(ci) == 0 && IS_NEXT_INSN_ID(sendobj, send));
4525
4526 // If this send is for .include? with one arg we can do our opt.
4527 if (vm_ci_simple(ci) && vm_ci_argc(ci) == 1 && vm_ci_mid(ci) == idIncludeP) {
4528 VALUE num = iobj->operands[0];
4529 INSN *sendins = (INSN *)sendobj;
4530 insn_replace_with_operands(iseq, sendins, BIN(opt_newarray_send), 2, FIXNUM_INC(num, 1), INT2FIX(VM_OPT_NEWARRAY_SEND_INCLUDE_P));
4531 // Remove the original "newarray" insn.
4532 ELEM_REMOVE(&iobj->link);
4533 return COMPILE_OK;
4534 }
4535 }
4536 }
4537
4538 /*
4539 * duparray [...]
4540 * some insn for the arg...
4541 * send <calldata!mid:include?, argc:1, ARGS_SIMPLE>, nil
4542 * =>
4543 * arg insn...
4544 * opt_duparray_send [...], :include?, 1
4545 */
4546 if (IS_INSN_ID(iobj, duparray) && iobj->link.next && IS_INSN(iobj->link.next)) {
4547 INSN *niobj = (INSN *)iobj->link.next;
4548 if ((IS_INSN_ID(niobj, getlocal) ||
4549 IS_INSN_ID(niobj, getinstancevariable) ||
4550 IS_INSN_ID(niobj, putself) ||
4551 IS_INSN_ID(niobj, putobject) ||
4552 IS_INSN_ID(niobj, putnil)) &&
4553 IS_NEXT_INSN_ID(&niobj->link, send)) {
4554
4555 LINK_ELEMENT *sendobj = &(niobj->link); // Below we call ->next;
4556 const struct rb_callinfo *ci;
4557 // Allow any number (0 or more) of simple method calls on the argument
4558 // (as in `[...].include?(arg.method1.method2)`.
4559 do {
4560 sendobj = sendobj->next;
4561 ci = (struct rb_callinfo *)OPERAND_AT(sendobj, 0);
4562 } while (vm_ci_simple(ci) && vm_ci_argc(ci) == 0 && IS_NEXT_INSN_ID(sendobj, send));
4563
4564 if (vm_ci_simple(ci) && vm_ci_argc(ci) == 1 && vm_ci_mid(ci) == idIncludeP) {
4565 // Move the array arg from duparray to opt_duparray_send.
4566 VALUE ary = iobj->operands[0];
4568
4569 INSN *sendins = (INSN *)sendobj;
4570 insn_replace_with_operands(iseq, sendins, BIN(opt_duparray_send), 3, ary, rb_id2sym(idIncludeP), INT2FIX(1));
4571
4572 // Remove the duparray insn.
4573 ELEM_REMOVE(&iobj->link);
4574 return COMPILE_OK;
4575 }
4576 }
4577 }
4578
4579
4580 if (IS_INSN_ID(iobj, send)) {
4581 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(iobj, 0);
4582 const rb_iseq_t *blockiseq = (rb_iseq_t *)OPERAND_AT(iobj, 1);
4583
4584#define SP_INSN(opt) insn_set_specialized_instruction(iseq, iobj, BIN(opt_##opt))
4585 if (vm_ci_simple(ci)) {
4586 switch (vm_ci_argc(ci)) {
4587 case 0:
4588 switch (vm_ci_mid(ci)) {
4589 case idLength: SP_INSN(length); return COMPILE_OK;
4590 case idSize: SP_INSN(size); return COMPILE_OK;
4591 case idEmptyP: SP_INSN(empty_p);return COMPILE_OK;
4592 case idNilP: SP_INSN(nil_p); return COMPILE_OK;
4593 case idSucc: SP_INSN(succ); return COMPILE_OK;
4594 case idNot: SP_INSN(not); return COMPILE_OK;
4595 }
4596 break;
4597 case 1:
4598 switch (vm_ci_mid(ci)) {
4599 case idPLUS: SP_INSN(plus); return COMPILE_OK;
4600 case idMINUS: SP_INSN(minus); return COMPILE_OK;
4601 case idMULT: SP_INSN(mult); return COMPILE_OK;
4602 case idDIV: SP_INSN(div); return COMPILE_OK;
4603 case idMOD: SP_INSN(mod); return COMPILE_OK;
4604 case idEq: SP_INSN(eq); return COMPILE_OK;
4605 case idNeq: SP_INSN(neq); return COMPILE_OK;
4606 case idEqTilde:SP_INSN(regexpmatch2);return COMPILE_OK;
4607 case idLT: SP_INSN(lt); return COMPILE_OK;
4608 case idLE: SP_INSN(le); return COMPILE_OK;
4609 case idGT: SP_INSN(gt); return COMPILE_OK;
4610 case idGE: SP_INSN(ge); return COMPILE_OK;
4611 case idLTLT: SP_INSN(ltlt); return COMPILE_OK;
4612 case idAREF: SP_INSN(aref); return COMPILE_OK;
4613 case idAnd: SP_INSN(and); return COMPILE_OK;
4614 case idOr: SP_INSN(or); return COMPILE_OK;
4615 }
4616 break;
4617 case 2:
4618 switch (vm_ci_mid(ci)) {
4619 case idASET: SP_INSN(aset); return COMPILE_OK;
4620 }
4621 break;
4622 }
4623 }
4624
4625 if ((vm_ci_flag(ci) & (VM_CALL_ARGS_BLOCKARG | VM_CALL_FORWARDING)) == 0 && blockiseq == NULL) {
4626 iobj->insn_id = BIN(opt_send_without_block);
4627 iobj->operand_size = insn_len(iobj->insn_id) - 1;
4628 }
4629 }
4630#undef SP_INSN
4631
4632 return COMPILE_OK;
4633}
4634
4635static inline int
4636tailcallable_p(rb_iseq_t *iseq)
4637{
4638 switch (ISEQ_BODY(iseq)->type) {
4639 case ISEQ_TYPE_TOP:
4640 case ISEQ_TYPE_EVAL:
4641 case ISEQ_TYPE_MAIN:
4642 /* not tail callable because cfp will be over popped */
4643 case ISEQ_TYPE_RESCUE:
4644 case ISEQ_TYPE_ENSURE:
4645 /* rescue block can't tail call because of errinfo */
4646 return FALSE;
4647 default:
4648 return TRUE;
4649 }
4650}
4651
4652static int
4653iseq_optimize(rb_iseq_t *iseq, LINK_ANCHOR *const anchor)
4654{
4655 LINK_ELEMENT *list;
4656 const int do_peepholeopt = ISEQ_COMPILE_DATA(iseq)->option->peephole_optimization;
4657 const int do_tailcallopt = tailcallable_p(iseq) &&
4658 ISEQ_COMPILE_DATA(iseq)->option->tailcall_optimization;
4659 const int do_si = ISEQ_COMPILE_DATA(iseq)->option->specialized_instruction;
4660 const int do_ou = ISEQ_COMPILE_DATA(iseq)->option->operands_unification;
4661 const int do_without_ints = ISEQ_BODY(iseq)->builtin_attrs & BUILTIN_ATTR_WITHOUT_INTERRUPTS;
4662 int rescue_level = 0;
4663 int tailcallopt = do_tailcallopt;
4664
4665 list = FIRST_ELEMENT(anchor);
4666
4667 int do_block_optimization = 0;
4668 LABEL * block_loop_label = NULL;
4669
4670 int nlabels = ISEQ_COMPILE_DATA(iseq)->label_no;
4671 VALUE unref_counts_buf = 0, unref_stamps_buf = 0;
4673 .capacity = nlabels,
4674 .gen = 0,
4675 .counts = ALLOCV_N(int, unref_counts_buf, nlabels),
4676 .stamps = ALLOCV_N(unsigned int, unref_stamps_buf, nlabels),
4677 };
4678 MEMZERO(unreachable_unref.counts, int, nlabels);
4679 MEMZERO(unreachable_unref.stamps, unsigned int, nlabels);
4680
4681 // If we're optimizing a block
4682 if (ISEQ_BODY(iseq)->type == ISEQ_TYPE_BLOCK) {
4683 do_block_optimization = 1;
4684
4685 // If the block starts with a nop and a label,
4686 // record the label so we can detect if it's a jump target
4687 LINK_ELEMENT * le = FIRST_ELEMENT(anchor)->next;
4688 if (IS_INSN(le) && IS_INSN_ID((INSN *)le, nop) && IS_LABEL(le->next)) {
4689 block_loop_label = (LABEL *)le->next;
4690 }
4691 }
4692
4693 while (list) {
4694 if (IS_INSN(list)) {
4695 if (do_peepholeopt) {
4696 iseq_peephole_optimize(iseq, &unreachable_unref, list, tailcallopt);
4697 }
4698 if (do_si) {
4699 iseq_specialized_instruction(iseq, (INSN *)list);
4700 }
4701 if (do_ou) {
4702 insn_operands_unification((INSN *)list);
4703 }
4704
4705 if (do_without_ints) {
4706 INSN *item = (INSN *)list;
4707 if (IS_INSN_ID(item, jump)) {
4708 item->insn_id = BIN(jump_without_ints);
4709 }
4710 else if (IS_INSN_ID(item, branchif)) {
4711 item->insn_id = BIN(branchif_without_ints);
4712 }
4713 else if (IS_INSN_ID(item, branchunless)) {
4714 item->insn_id = BIN(branchunless_without_ints);
4715 }
4716 else if (IS_INSN_ID(item, branchnil)) {
4717 item->insn_id = BIN(branchnil_without_ints);
4718 }
4719 }
4720
4721 if (do_block_optimization) {
4722 INSN * item = (INSN *)list;
4723 // Give up if there is a throw
4724 if (IS_INSN_ID(item, throw)) {
4725 do_block_optimization = 0;
4726 }
4727 else {
4728 // If the instruction has a jump target, check if the
4729 // jump target is the block loop label
4730 const char *types = insn_op_types(item->insn_id);
4731 for (int j = 0; types[j]; j++) {
4732 if (types[j] == TS_OFFSET) {
4733 // If the jump target is equal to the block loop
4734 // label, then we can't do the optimization because
4735 // the leading `nop` instruction fires the block
4736 // entry tracepoint
4737 LABEL * target = (LABEL *)OPERAND_AT(item, j);
4738 if (target == block_loop_label) {
4739 do_block_optimization = 0;
4740 }
4741 }
4742 }
4743 }
4744 }
4745 }
4746 if (IS_LABEL(list)) {
4747 switch (((LABEL *)list)->rescued) {
4748 case LABEL_RESCUE_BEG:
4749 rescue_level++;
4750 tailcallopt = FALSE;
4751 break;
4752 case LABEL_RESCUE_END:
4753 if (!--rescue_level) tailcallopt = do_tailcallopt;
4754 break;
4755 }
4756 }
4757 list = list->next;
4758 }
4759
4760 if (do_block_optimization) {
4761 LINK_ELEMENT * le = FIRST_ELEMENT(anchor)->next;
4762 if (IS_INSN(le) && IS_INSN_ID((INSN *)le, nop)) {
4763 ELEM_REMOVE(le);
4764 }
4765 }
4766
4767 ALLOCV_END(unref_counts_buf);
4768 ALLOCV_END(unref_stamps_buf);
4769 return COMPILE_OK;
4770}
4771
4772#if OPT_INSTRUCTIONS_UNIFICATION
4773static INSN *
4774new_unified_insn(rb_iseq_t *iseq,
4775 int insn_id, int size, LINK_ELEMENT *seq_list)
4776{
4777 INSN *iobj = 0;
4778 LINK_ELEMENT *list = seq_list;
4779 int i, argc = 0;
4780 VALUE *operands = 0, *ptr = 0;
4781
4782
4783 /* count argc */
4784 for (i = 0; i < size; i++) {
4785 iobj = (INSN *)list;
4786 argc += iobj->operand_size;
4787 list = list->next;
4788 }
4789
4790 if (argc > 0) {
4791 ptr = operands = compile_data_alloc2_type(iseq, VALUE, argc);
4792 }
4793
4794 /* copy operands */
4795 list = seq_list;
4796 for (i = 0; i < size; i++) {
4797 iobj = (INSN *)list;
4798 MEMCPY(ptr, iobj->operands, VALUE, iobj->operand_size);
4799 ptr += iobj->operand_size;
4800 list = list->next;
4801 }
4802
4803 return new_insn_core(iseq, iobj->insn_info.line_no, iobj->insn_info.node_id, insn_id, argc, operands);
4804}
4805#endif
4806
4807/*
4808 * This scheme can get more performance if do this optimize with
4809 * label address resolving.
4810 * It's future work (if compile time was bottle neck).
4811 */
4812static int
4813iseq_insns_unification(rb_iseq_t *iseq, LINK_ANCHOR *const anchor)
4814{
4815#if OPT_INSTRUCTIONS_UNIFICATION
4816 LINK_ELEMENT *list;
4817 INSN *iobj, *niobj;
4818 int id, k;
4819 intptr_t j;
4820
4821 list = FIRST_ELEMENT(anchor);
4822 while (list) {
4823 if (IS_INSN(list)) {
4824 iobj = (INSN *)list;
4825 id = iobj->insn_id;
4826 if (unified_insns_data[id] != 0) {
4827 const int *const *entry = unified_insns_data[id];
4828 for (j = 1; j < (intptr_t)entry[0]; j++) {
4829 const int *unified = entry[j];
4830 LINK_ELEMENT *li = list->next;
4831 for (k = 2; k < unified[1]; k++) {
4832 if (!IS_INSN(li) ||
4833 ((INSN *)li)->insn_id != unified[k]) {
4834 goto miss;
4835 }
4836 li = li->next;
4837 }
4838 /* matched */
4839 niobj =
4840 new_unified_insn(iseq, unified[0], unified[1] - 1,
4841 list);
4842
4843 /* insert to list */
4844 niobj->link.prev = (LINK_ELEMENT *)iobj->link.prev;
4845 niobj->link.next = li;
4846 if (li) {
4847 li->prev = (LINK_ELEMENT *)niobj;
4848 }
4849
4850 list->prev->next = (LINK_ELEMENT *)niobj;
4851 list = (LINK_ELEMENT *)niobj;
4852 break;
4853 miss:;
4854 }
4855 }
4856 }
4857 list = list->next;
4858 }
4859#endif
4860 return COMPILE_OK;
4861}
4862
4863static int
4864all_string_result_p(const NODE *node)
4865{
4866 if (!node) return FALSE;
4867 switch (nd_type(node)) {
4868 case NODE_STR: case NODE_DSTR: case NODE_FILE:
4869 return TRUE;
4870 case NODE_IF: case NODE_UNLESS:
4871 if (!RNODE_IF(node)->nd_body || !RNODE_IF(node)->nd_else) return FALSE;
4872 if (all_string_result_p(RNODE_IF(node)->nd_body))
4873 return all_string_result_p(RNODE_IF(node)->nd_else);
4874 return FALSE;
4875 case NODE_AND: case NODE_OR:
4876 if (!RNODE_AND(node)->nd_2nd)
4877 return all_string_result_p(RNODE_AND(node)->nd_1st);
4878 if (!all_string_result_p(RNODE_AND(node)->nd_1st))
4879 return FALSE;
4880 return all_string_result_p(RNODE_AND(node)->nd_2nd);
4881 default:
4882 return FALSE;
4883 }
4884}
4885
4887 rb_iseq_t *const iseq;
4888 LINK_ANCHOR *const ret;
4889 VALUE lit;
4890 const NODE *lit_node;
4891 int cnt;
4892 int dregx;
4893};
4894
4895static int
4896append_dstr_fragment(struct dstr_ctxt *args, const NODE *const node, rb_parser_string_t *str)
4897{
4898 VALUE s = rb_str_new_mutable_parser_string(str);
4899 if (args->dregx) {
4900 VALUE error = rb_reg_check_preprocess(s);
4901 if (!NIL_P(error)) {
4902 COMPILE_ERROR(args->iseq, nd_line(node), "%" PRIsVALUE, error);
4903 return COMPILE_NG;
4904 }
4905 }
4906 if (NIL_P(args->lit)) {
4907 args->lit = s;
4908 args->lit_node = node;
4909 }
4910 else {
4911 rb_str_buf_append(args->lit, s);
4912 }
4913 return COMPILE_OK;
4914}
4915
4916static void
4917flush_dstr_fragment(struct dstr_ctxt *args)
4918{
4919 if (!NIL_P(args->lit)) {
4920 rb_iseq_t *iseq = args->iseq;
4921 VALUE lit = args->lit;
4922 args->lit = Qnil;
4923 lit = rb_fstring(lit);
4924 ADD_INSN1(args->ret, args->lit_node, putobject, lit);
4925 RB_OBJ_WRITTEN(args->iseq, Qundef, lit);
4926 args->cnt++;
4927 }
4928}
4929
4930static int
4931compile_dstr_fragments_0(struct dstr_ctxt *args, const NODE *const node)
4932{
4933 const struct RNode_LIST *list = RNODE_DSTR(node)->nd_next;
4934 rb_parser_string_t *str = RNODE_DSTR(node)->string;
4935
4936 if (str) {
4937 CHECK(append_dstr_fragment(args, node, str));
4938 }
4939
4940 while (list) {
4941 const NODE *const head = list->nd_head;
4942 if (nd_type_p(head, NODE_STR)) {
4943 CHECK(append_dstr_fragment(args, node, RNODE_STR(head)->string));
4944 }
4945 else if (nd_type_p(head, NODE_DSTR)) {
4946 CHECK(compile_dstr_fragments_0(args, head));
4947 }
4948 else {
4949 flush_dstr_fragment(args);
4950 rb_iseq_t *iseq = args->iseq;
4951 CHECK(COMPILE(args->ret, "each string", head));
4952 args->cnt++;
4953 }
4954 list = (struct RNode_LIST *)list->nd_next;
4955 }
4956 return COMPILE_OK;
4957}
4958
4959static int
4960compile_dstr_fragments(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int *cntp, int dregx)
4961{
4962 struct dstr_ctxt args = {
4963 .iseq = iseq, .ret = ret,
4964 .lit = Qnil, .lit_node = NULL,
4965 .cnt = 0, .dregx = dregx,
4966 };
4967 CHECK(compile_dstr_fragments_0(&args, node));
4968 flush_dstr_fragment(&args);
4969
4970 *cntp = args.cnt;
4971
4972 return COMPILE_OK;
4973}
4974
4975static int
4976compile_block(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *node, int popped)
4977{
4978 while (node && nd_type_p(node, NODE_BLOCK)) {
4979 CHECK(COMPILE_(ret, "BLOCK body", RNODE_BLOCK(node)->nd_head,
4980 (RNODE_BLOCK(node)->nd_next ? 1 : popped)));
4981 node = RNODE_BLOCK(node)->nd_next;
4982 }
4983 if (node) {
4984 CHECK(COMPILE_(ret, "BLOCK next", RNODE_BLOCK(node)->nd_next, popped));
4985 }
4986 return COMPILE_OK;
4987}
4988
4989static void
4990compile_file_path(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int frozen_string_literal)
4991{
4992 ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
4993 ADD_INSN1(ret, node, putobject, INT2FIX(frozen_string_literal));
4994 ADD_SEND(ret, node, id_core_iseq_path, INT2FIX(1));
4995}
4996
4997static int
4998compile_dstr(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node)
4999{
5000 int cnt;
5001 if (!RNODE_DSTR(node)->nd_next) {
5002 VALUE lit = rb_node_dstr_string_val(node);
5003 ADD_INSN1(ret, node, dupstring, lit);
5005 RB_OBJ_WRITTEN(iseq, Qundef, lit);
5006 }
5007 else {
5008 CHECK(compile_dstr_fragments(iseq, ret, node, &cnt, FALSE));
5009 ADD_INSN1(ret, node, concatstrings, INT2FIX(cnt));
5010 }
5011 return COMPILE_OK;
5012}
5013
5014static int
5015compile_dregx(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
5016{
5017 int cnt;
5018 int cflag = (int)RNODE_DREGX(node)->as.nd_cflag;
5019
5020 if (!RNODE_DREGX(node)->nd_next) {
5021 if (!popped) {
5022 VALUE src = rb_node_dregx_string_val(node);
5023 VALUE match = iseq_reg_compile(iseq, src, cflag, NULL, 0);
5024 ADD_INSN1(ret, node, putobject, match);
5025 RB_OBJ_WRITTEN(iseq, Qundef, match);
5026 }
5027 return COMPILE_OK;
5028 }
5029
5030 CHECK(compile_dstr_fragments(iseq, ret, node, &cnt, TRUE));
5031 ADD_INSN2(ret, node, toregexp, INT2FIX(cflag), INT2FIX(cnt));
5032
5033 if (popped) {
5034 ADD_INSN(ret, node, pop);
5035 }
5036
5037 return COMPILE_OK;
5038}
5039
5040static int
5041compile_flip_flop(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int again,
5042 LABEL *then_label, LABEL *else_label)
5043{
5044 const int line = nd_line(node);
5045 LABEL *lend = NEW_LABEL(line);
5046 rb_num_t cnt = ISEQ_FLIP_CNT_INCREMENT(ISEQ_BODY(iseq)->local_iseq)
5047 + VM_SVAR_FLIPFLOP_START;
5048 VALUE key = INT2FIX(cnt);
5049
5050 ADD_INSN2(ret, node, getspecial, key, INT2FIX(0));
5051 ADD_INSNL(ret, node, branchif, lend);
5052
5053 /* *flip == 0 */
5054 CHECK(COMPILE(ret, "flip2 beg", RNODE_FLIP2(node)->nd_beg));
5055 ADD_INSNL(ret, node, branchunless, else_label);
5056 ADD_INSN1(ret, node, putobject, Qtrue);
5057 ADD_INSN1(ret, node, setspecial, key);
5058 if (!again) {
5059 ADD_INSNL(ret, node, jump, then_label);
5060 }
5061
5062 /* *flip == 1 */
5063 ADD_LABEL(ret, lend);
5064 CHECK(COMPILE(ret, "flip2 end", RNODE_FLIP2(node)->nd_end));
5065 ADD_INSNL(ret, node, branchunless, then_label);
5066 ADD_INSN1(ret, node, putobject, Qfalse);
5067 ADD_INSN1(ret, node, setspecial, key);
5068 ADD_INSNL(ret, node, jump, then_label);
5069
5070 return COMPILE_OK;
5071}
5072
5073static int
5074compile_branch_condition(rb_iseq_t *iseq, LINK_ANCHOR *ret, const NODE *cond,
5075 LABEL *then_label, LABEL *else_label);
5076
5077#define COMPILE_SINGLE 2
5078static int
5079compile_logical(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *cond,
5080 LABEL *then_label, LABEL *else_label)
5081{
5082 DECL_ANCHOR(seq);
5083 INIT_ANCHOR(seq);
5084 LABEL *label = NEW_LABEL(nd_line(cond));
5085 if (!then_label) then_label = label;
5086 else if (!else_label) else_label = label;
5087
5088 CHECK(compile_branch_condition(iseq, seq, cond, then_label, else_label));
5089
5090 if (LIST_INSN_SIZE_ONE(seq)) {
5091 INSN *insn = (INSN *)ELEM_FIRST_INSN(FIRST_ELEMENT(seq));
5092 if (insn->insn_id == BIN(jump) && (LABEL *)(insn->operands[0]) == label)
5093 return COMPILE_OK;
5094 }
5095 if (!label->refcnt) {
5096 return COMPILE_SINGLE;
5097 }
5098 ADD_LABEL(seq, label);
5099 ADD_SEQ(ret, seq);
5100 return COMPILE_OK;
5101}
5102
5103static int
5104compile_branch_condition(rb_iseq_t *iseq, LINK_ANCHOR *ret, const NODE *cond,
5105 LABEL *then_label, LABEL *else_label)
5106{
5107 int ok;
5108 DECL_ANCHOR(ignore);
5109
5110 again:
5111 switch (nd_type(cond)) {
5112 case NODE_AND:
5113 CHECK(ok = compile_logical(iseq, ret, RNODE_AND(cond)->nd_1st, NULL, else_label));
5114 cond = RNODE_AND(cond)->nd_2nd;
5115 if (ok == COMPILE_SINGLE) {
5116 ADD_INSNL(ret, cond, jump, else_label);
5117 INIT_ANCHOR(ignore);
5118 ret = ignore;
5119 then_label = NEW_LABEL(nd_line(cond));
5120 }
5121 goto again;
5122 case NODE_OR:
5123 CHECK(ok = compile_logical(iseq, ret, RNODE_OR(cond)->nd_1st, then_label, NULL));
5124 cond = RNODE_OR(cond)->nd_2nd;
5125 if (ok == COMPILE_SINGLE) {
5126 ADD_INSNL(ret, cond, jump, then_label);
5127 INIT_ANCHOR(ignore);
5128 ret = ignore;
5129 else_label = NEW_LABEL(nd_line(cond));
5130 }
5131 goto again;
5132 case NODE_SYM:
5133 case NODE_LINE:
5134 case NODE_FILE:
5135 case NODE_ENCODING:
5136 case NODE_INTEGER: /* NODE_INTEGER is always true */
5137 case NODE_FLOAT: /* NODE_FLOAT is always true */
5138 case NODE_RATIONAL: /* NODE_RATIONAL is always true */
5139 case NODE_IMAGINARY: /* NODE_IMAGINARY is always true */
5140 case NODE_TRUE:
5141 case NODE_STR:
5142 case NODE_REGX:
5143 case NODE_ZLIST:
5144 case NODE_LAMBDA:
5145 /* printf("useless condition eliminate (%s)\n", ruby_node_name(nd_type(cond))); */
5146 ADD_INSNL(ret, cond, jump, then_label);
5147 return COMPILE_OK;
5148 case NODE_FALSE:
5149 case NODE_NIL:
5150 /* printf("useless condition eliminate (%s)\n", ruby_node_name(nd_type(cond))); */
5151 ADD_INSNL(ret, cond, jump, else_label);
5152 return COMPILE_OK;
5153 case NODE_LIST:
5154 case NODE_ARGSCAT:
5155 case NODE_DREGX:
5156 case NODE_DSTR:
5157 CHECK(COMPILE_POPPED(ret, "branch condition", cond));
5158 ADD_INSNL(ret, cond, jump, then_label);
5159 return COMPILE_OK;
5160 case NODE_FLIP2:
5161 CHECK(compile_flip_flop(iseq, ret, cond, TRUE, then_label, else_label));
5162 return COMPILE_OK;
5163 case NODE_FLIP3:
5164 CHECK(compile_flip_flop(iseq, ret, cond, FALSE, then_label, else_label));
5165 return COMPILE_OK;
5166 case NODE_DEFINED:
5167 CHECK(compile_defined_expr(iseq, ret, cond, Qfalse, ret == ignore));
5168 break;
5169 default:
5170 {
5171 DECL_ANCHOR(cond_seq);
5172 INIT_ANCHOR(cond_seq);
5173
5174 CHECK(COMPILE(cond_seq, "branch condition", cond));
5175
5176 if (LIST_INSN_SIZE_ONE(cond_seq)) {
5177 INSN *insn = (INSN *)ELEM_FIRST_INSN(FIRST_ELEMENT(cond_seq));
5178 if (insn->insn_id == BIN(putobject)) {
5179 if (RTEST(insn->operands[0])) {
5180 ADD_INSNL(ret, cond, jump, then_label);
5181 // maybe unreachable
5182 return COMPILE_OK;
5183 }
5184 else {
5185 ADD_INSNL(ret, cond, jump, else_label);
5186 return COMPILE_OK;
5187 }
5188 }
5189 }
5190 ADD_SEQ(ret, cond_seq);
5191 }
5192 break;
5193 }
5194
5195 ADD_INSNL(ret, cond, branchunless, else_label);
5196 ADD_INSNL(ret, cond, jump, then_label);
5197 return COMPILE_OK;
5198}
5199
5200#define HASH_BRACE 1
5201
5202static int
5203keyword_node_p(const NODE *const node)
5204{
5205 return nd_type_p(node, NODE_HASH) && (RNODE_HASH(node)->nd_brace & HASH_BRACE) != HASH_BRACE;
5206}
5207
5208static VALUE
5209get_symbol_value(rb_iseq_t *iseq, const NODE *node)
5210{
5211 switch (nd_type(node)) {
5212 case NODE_SYM:
5213 return rb_node_sym_string_val(node);
5214 default:
5215 UNKNOWN_NODE("get_symbol_value", node, Qnil);
5216 }
5217}
5218
5219static VALUE
5220node_hash_unique_key_index(rb_iseq_t *iseq, rb_node_hash_t *node_hash, int *count_ptr)
5221{
5222 NODE *node = node_hash->nd_head;
5223 VALUE hash = rb_hash_new();
5224 VALUE ary = rb_ary_new();
5225
5226 for (int i = 0; node != NULL; i++, node = RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_next) {
5227 VALUE key = get_symbol_value(iseq, RNODE_LIST(node)->nd_head);
5228 VALUE idx = rb_hash_aref(hash, key);
5229 if (!NIL_P(idx)) {
5230 rb_ary_store(ary, FIX2INT(idx), Qfalse);
5231 (*count_ptr)--;
5232 }
5233 rb_hash_aset(hash, key, INT2FIX(i));
5234 rb_ary_store(ary, i, Qtrue);
5235 (*count_ptr)++;
5236 }
5237
5238 return ary;
5239}
5240
5241static int
5242compile_keyword_arg(rb_iseq_t *iseq, LINK_ANCHOR *const ret,
5243 const NODE *const root_node,
5244 struct rb_callinfo_kwarg **const kw_arg_ptr,
5245 unsigned int *flag)
5246{
5247 RUBY_ASSERT(nd_type_p(root_node, NODE_HASH));
5248 RUBY_ASSERT(kw_arg_ptr != NULL);
5249
5250 if (RNODE_HASH(root_node)->nd_head && nd_type_p(RNODE_HASH(root_node)->nd_head, NODE_LIST)) {
5251 const NODE *node = RNODE_HASH(root_node)->nd_head;
5252 int seen_nodes = 0;
5253
5254 while (node) {
5255 const NODE *key_node = RNODE_LIST(node)->nd_head;
5256 seen_nodes++;
5257
5258 RUBY_ASSERT(nd_type_p(node, NODE_LIST));
5259 if (key_node && nd_type_p(key_node, NODE_SYM)) {
5260 /* can be keywords */
5261 }
5262 else {
5263 if (flag) {
5264 *flag |= VM_CALL_KW_SPLAT;
5265 if (seen_nodes > 1 || RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_next) {
5266 /* A new hash will be created for the keyword arguments
5267 * in this case, so mark the method as passing mutable
5268 * keyword splat.
5269 */
5270 *flag |= VM_CALL_KW_SPLAT_MUT;
5271 }
5272 }
5273 return FALSE;
5274 }
5275 node = RNODE_LIST(node)->nd_next; /* skip value node */
5276 node = RNODE_LIST(node)->nd_next;
5277 }
5278
5279 /* may be keywords */
5280 node = RNODE_HASH(root_node)->nd_head;
5281 {
5282 int len = 0;
5283 VALUE key_index = node_hash_unique_key_index(iseq, RNODE_HASH(root_node), &len);
5284
5285 if (len > VM_CALL_KW_LEN_MAX) {
5286 COMPILE_ERROR(ERROR_ARGS_AT(root_node) "too many keyword arguments (%d, maximum is %d)",
5287 len, (int)VM_CALL_KW_LEN_MAX);
5288 }
5289
5290 struct rb_callinfo_kwarg *kw_arg =
5291 rb_xmalloc_mul_add(len, sizeof(VALUE), sizeof(struct rb_callinfo_kwarg));
5292 VALUE *keywords = kw_arg->keywords;
5293 int i = 0;
5294 int j = 0;
5295 kw_arg->references = 0;
5296 kw_arg->keyword_len = len;
5297
5298 *kw_arg_ptr = kw_arg;
5299
5300 for (i=0; node != NULL; i++, node = RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_next) {
5301 const NODE *key_node = RNODE_LIST(node)->nd_head;
5302 const NODE *val_node = RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_head;
5303 int popped = TRUE;
5304 if (rb_ary_entry(key_index, i)) {
5305 keywords[j] = get_symbol_value(iseq, key_node);
5306 j++;
5307 popped = FALSE;
5308 }
5309 NO_CHECK(COMPILE_(ret, "keyword values", val_node, popped));
5310 }
5311 RUBY_ASSERT(j == len);
5312 return TRUE;
5313 }
5314 }
5315 return FALSE;
5316}
5317
5318static int
5319compile_args(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *node, NODE **kwnode_ptr)
5320{
5321 int len = 0;
5322
5323 for (; node; len++, node = RNODE_LIST(node)->nd_next) {
5324 if (CPDEBUG > 0) {
5325 EXPECT_NODE("compile_args", node, NODE_LIST, -1);
5326 }
5327
5328 if (RNODE_LIST(node)->nd_next == NULL && keyword_node_p(RNODE_LIST(node)->nd_head)) { /* last node is kwnode */
5329 *kwnode_ptr = RNODE_LIST(node)->nd_head;
5330 }
5331 else {
5332 // A keyword hash in a non-final position is a positional value.
5333 NO_CHECK(COMPILE_(ret, "array element", RNODE_LIST(node)->nd_head, FALSE));
5334 }
5335 }
5336
5337 return len;
5338}
5339
5340static inline bool
5341frozen_string_literal_p(const rb_iseq_t *iseq)
5342{
5343 return ISEQ_COMPILE_DATA(iseq)->option->frozen_string_literal > 0;
5344}
5345
5346static inline bool
5347static_literal_node_p(const NODE *node, const rb_iseq_t *iseq, bool hash_key)
5348{
5349 switch (nd_type(node)) {
5350 case NODE_SYM:
5351 case NODE_REGX:
5352 case NODE_LINE:
5353 case NODE_ENCODING:
5354 case NODE_INTEGER:
5355 case NODE_FLOAT:
5356 case NODE_RATIONAL:
5357 case NODE_IMAGINARY:
5358 case NODE_NIL:
5359 case NODE_TRUE:
5360 case NODE_FALSE:
5361 return TRUE;
5362 case NODE_STR:
5363 return hash_key || frozen_string_literal_p(iseq);
5364 default:
5365 return FALSE;
5366 }
5367}
5368
5369static inline VALUE
5370static_literal_value(const NODE *node, rb_iseq_t *iseq)
5371{
5372 switch (nd_type(node)) {
5373 case NODE_INTEGER:
5374 {
5375 VALUE lit = rb_node_integer_literal_val(node);
5376 if (!SPECIAL_CONST_P(lit)) RB_OBJ_SET_SHAREABLE(lit);
5377 return lit;
5378 }
5379 case NODE_FLOAT:
5380 {
5381 VALUE lit = rb_node_float_literal_val(node);
5382 if (!SPECIAL_CONST_P(lit)) RB_OBJ_SET_SHAREABLE(lit);
5383 return lit;
5384 }
5385 case NODE_RATIONAL:
5386 return rb_ractor_make_shareable(rb_node_rational_literal_val(node));
5387 case NODE_IMAGINARY:
5388 return rb_ractor_make_shareable(rb_node_imaginary_literal_val(node));
5389 case NODE_NIL:
5390 return Qnil;
5391 case NODE_TRUE:
5392 return Qtrue;
5393 case NODE_FALSE:
5394 return Qfalse;
5395 case NODE_SYM:
5396 return rb_node_sym_string_val(node);
5397 case NODE_REGX:
5398 return RB_OBJ_SET_SHAREABLE(rb_node_regx_string_val(node));
5399 case NODE_LINE:
5400 return rb_node_line_lineno_val(node);
5401 case NODE_ENCODING:
5402 return rb_node_encoding_val(node);
5403 case NODE_FILE:
5404 case NODE_STR:
5405 if (ISEQ_COMPILE_DATA(iseq)->option->debug_frozen_string_literal || RTEST(ruby_debug)) {
5406 VALUE lit = get_string_value(node);
5407 VALUE str = rb_str_with_debug_created_info(lit, rb_iseq_path(iseq), (int)nd_line(node));
5409 return str;
5410 }
5411 else {
5412 return get_string_value(node);
5413 }
5414 default:
5415 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
5416 }
5417}
5418
5419static int
5420compile_array(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *node, int popped, bool first_chunk)
5421{
5422 const NODE *line_node = node;
5423
5424 if (nd_type_p(node, NODE_ZLIST)) {
5425 if (!popped) {
5426 ADD_INSN1(ret, line_node, newarray, INT2FIX(0));
5427 }
5428 return 0;
5429 }
5430
5431 EXPECT_NODE("compile_array", node, NODE_LIST, -1);
5432
5433 if (popped) {
5434 for (; node; node = RNODE_LIST(node)->nd_next) {
5435 NO_CHECK(COMPILE_(ret, "array element", RNODE_LIST(node)->nd_head, popped));
5436 }
5437 return 1;
5438 }
5439
5440 /* Compilation of an array literal.
5441 * The following code is essentially the same as:
5442 *
5443 * for (int count = 0; node; count++; node->nd_next) {
5444 * compile(node->nd_head);
5445 * }
5446 * ADD_INSN(newarray, count);
5447 *
5448 * However, there are three points.
5449 *
5450 * - The code above causes stack overflow for a big string literal.
5451 * The following limits the stack length up to max_stack_len.
5452 *
5453 * [x1,x2,...,x10000] =>
5454 * push x1 ; push x2 ; ...; push x256; newarray 256;
5455 * push x257; push x258; ...; push x512; pushtoarray 256;
5456 * push x513; push x514; ...; push x768; pushtoarray 256;
5457 * ...
5458 *
5459 * - Long subarray can be optimized by pre-allocating a hidden array.
5460 *
5461 * [1,2,3,...,100] =>
5462 * duparray [1,2,3,...,100]
5463 *
5464 * [x, 1,2,3,...,100, z] =>
5465 * push x; newarray 1;
5466 * putobject [1,2,3,...,100] (<- hidden array); concattoarray;
5467 * push z; pushtoarray 1;
5468 *
5469 * - If the last element is a keyword, pushtoarraykwsplat should be emitted
5470 * to only push it onto the array if it is not empty
5471 * (Note: a keyword is NODE_HASH which is not static_literal_node_p.)
5472 *
5473 * [1,2,3,**kw] =>
5474 * putobject 1; putobject 2; putobject 3; newarray 3; ...; pushtoarraykwsplat kw
5475 */
5476
5477 const int max_stack_len = 0x100;
5478 const int min_tmp_ary_len = 0x40;
5479 int stack_len = 0;
5480
5481 /* Either create a new array, or push to the existing array */
5482#define FLUSH_CHUNK \
5483 if (stack_len) { \
5484 if (first_chunk) ADD_INSN1(ret, line_node, newarray, INT2FIX(stack_len)); \
5485 else ADD_INSN1(ret, line_node, pushtoarray, INT2FIX(stack_len)); \
5486 first_chunk = FALSE; \
5487 stack_len = 0; \
5488 }
5489
5490 while (node) {
5491 int count = 1;
5492
5493 /* pre-allocation check (this branch can be omittable) */
5494 if (static_literal_node_p(RNODE_LIST(node)->nd_head, iseq, false)) {
5495 /* count the elements that are optimizable */
5496 const NODE *node_tmp = RNODE_LIST(node)->nd_next;
5497 for (; node_tmp && static_literal_node_p(RNODE_LIST(node_tmp)->nd_head, iseq, false); node_tmp = RNODE_LIST(node_tmp)->nd_next)
5498 count++;
5499
5500 if ((first_chunk && stack_len == 0 && !node_tmp) || count >= min_tmp_ary_len) {
5501 /* The literal contains only optimizable elements, or the subarray is long enough */
5502 VALUE ary = rb_ary_hidden_new(count);
5503
5504 /* Create a hidden array */
5505 for (; count; count--, node = RNODE_LIST(node)->nd_next)
5506 rb_ary_push(ary, static_literal_value(RNODE_LIST(node)->nd_head, iseq));
5508
5509 /* Emit optimized code */
5510 FLUSH_CHUNK;
5511 if (first_chunk) {
5512 ADD_INSN1(ret, line_node, duparray, ary);
5513 first_chunk = FALSE;
5514 }
5515 else {
5516 ADD_INSN1(ret, line_node, putobject, ary);
5517 ADD_INSN(ret, line_node, concattoarray);
5518 }
5520 RB_OBJ_WRITTEN(iseq, Qundef, ary);
5521 }
5522 }
5523
5524 /* Base case: Compile "count" elements */
5525 for (; count; count--, node = RNODE_LIST(node)->nd_next) {
5526 if (CPDEBUG > 0) {
5527 EXPECT_NODE("compile_array", node, NODE_LIST, -1);
5528 }
5529
5530 if (!RNODE_LIST(node)->nd_next && keyword_node_p(RNODE_LIST(node)->nd_head)) {
5531 /* Create array or push existing non-keyword elements onto array */
5532 if (stack_len == 0 && first_chunk) {
5533 ADD_INSN1(ret, line_node, newarray, INT2FIX(0));
5534 }
5535 else {
5536 FLUSH_CHUNK;
5537 }
5538 NO_CHECK(COMPILE_(ret, "array element", RNODE_LIST(node)->nd_head, 0));
5539 ADD_INSN(ret, line_node, pushtoarraykwsplat);
5540 return 1;
5541 }
5542 else {
5543 NO_CHECK(COMPILE_(ret, "array element", RNODE_LIST(node)->nd_head, 0));
5544 stack_len++;
5545 }
5546
5547 /* If there are many pushed elements, flush them to avoid stack overflow */
5548 if (stack_len >= max_stack_len) FLUSH_CHUNK;
5549 }
5550 }
5551
5552 FLUSH_CHUNK;
5553#undef FLUSH_CHUNK
5554 return 1;
5555}
5556
5557static inline int
5558static_literal_node_pair_p(const NODE *node, const rb_iseq_t *iseq)
5559{
5560 return RNODE_LIST(node)->nd_head && static_literal_node_p(RNODE_LIST(node)->nd_head, iseq, true) && static_literal_node_p(RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_head, iseq, false);
5561}
5562
5563static int
5564compile_hash(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *node, int method_call_keywords, int popped)
5565{
5566 const NODE *line_node = node;
5567
5568 node = RNODE_HASH(node)->nd_head;
5569
5570 if (!node || nd_type_p(node, NODE_ZLIST)) {
5571 if (!popped) {
5572 ADD_INSN1(ret, line_node, newhash, INT2FIX(0));
5573 }
5574 return 0;
5575 }
5576
5577 EXPECT_NODE("compile_hash", node, NODE_LIST, -1);
5578
5579 if (popped) {
5580 for (; node; node = RNODE_LIST(node)->nd_next) {
5581 NO_CHECK(COMPILE_(ret, "hash element", RNODE_LIST(node)->nd_head, popped));
5582 }
5583 return 1;
5584 }
5585
5586 /* Compilation of a hash literal (or keyword arguments).
5587 * This is very similar to compile_array, but there are some differences:
5588 *
5589 * - It contains key-value pairs. So we need to take every two elements.
5590 * We can assume that the length is always even.
5591 *
5592 * - Merging is done by a method call (id_core_hash_merge_bang_ptr).
5593 * Sometimes we need to insert the receiver, so "anchor" is needed.
5594 * In addition, a method call is much slower than concatarray.
5595 * So it pays only when the subsequence is really long.
5596 * (min_tmp_hash_len must be much larger than min_tmp_ary_len.)
5597 *
5598 * - We need to handle keyword splat: **kw.
5599 * For **kw, the key part (node->nd_head) is NULL, and the value part
5600 * (node->nd_next->nd_head) is "kw".
5601 * The code is a bit difficult to avoid hash allocation for **{}.
5602 */
5603
5604 const int max_stack_len = 0x100;
5605 const int min_tmp_hash_len = 0x800;
5606 int stack_len = 0;
5607 int first_chunk = 1;
5608 DECL_ANCHOR(anchor);
5609 INIT_ANCHOR(anchor);
5610
5611 /* Convert pushed elements to a hash, and merge if needed */
5612#define FLUSH_CHUNK() \
5613 if (stack_len) { \
5614 if (first_chunk) { \
5615 APPEND_LIST(ret, anchor); \
5616 ADD_INSN1(ret, line_node, newhash, INT2FIX(stack_len)); \
5617 } \
5618 else { \
5619 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE)); \
5620 ADD_INSN(ret, line_node, swap); \
5621 APPEND_LIST(ret, anchor); \
5622 ADD_SEND(ret, line_node, id_core_hash_merge_bang_ptr, INT2FIX(stack_len + 1)); \
5623 } \
5624 INIT_ANCHOR(anchor); \
5625 first_chunk = stack_len = 0; \
5626 }
5627
5628 while (node) {
5629 int count = 1;
5630
5631 /* pre-allocation check (this branch can be omittable) */
5632 if (static_literal_node_pair_p(node, iseq)) {
5633 /* count the elements that are optimizable */
5634 const NODE *node_tmp = RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_next;
5635 for (; node_tmp && static_literal_node_pair_p(node_tmp, iseq); node_tmp = RNODE_LIST(RNODE_LIST(node_tmp)->nd_next)->nd_next)
5636 count++;
5637
5638 if ((first_chunk && stack_len == 0 && !node_tmp) || count >= min_tmp_hash_len) {
5639 /* The literal contains only optimizable elements, or the subsequence is long enough */
5640 VALUE ary = rb_ary_hidden_new(count);
5641
5642 /* Create a hidden hash */
5643 for (; count; count--, node = RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_next) {
5644 VALUE elem[2];
5645 elem[0] = static_literal_value(RNODE_LIST(node)->nd_head, iseq);
5646 if (!RB_SPECIAL_CONST_P(elem[0])) RB_OBJ_SET_FROZEN_SHAREABLE(elem[0]);
5647 elem[1] = static_literal_value(RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_head, iseq);
5648 if (!RB_SPECIAL_CONST_P(elem[1])) RB_OBJ_SET_FROZEN_SHAREABLE(elem[1]);
5649 rb_ary_cat(ary, elem, 2);
5650 }
5651 VALUE hash = rb_hash_alloc_fixed_size(Qfalse, RARRAY_LEN(ary) / 2);
5652 rb_hash_bulk_insert(RARRAY_LEN(ary), RARRAY_CONST_PTR(ary), hash);
5653 RB_GC_GUARD(ary);
5654 hash = RB_OBJ_SET_FROZEN_SHAREABLE(hash);
5655
5656 /* Emit optimized code */
5657 FLUSH_CHUNK();
5658 if (first_chunk) {
5659 ADD_INSN1(ret, line_node, duphash, hash);
5660 first_chunk = 0;
5661 }
5662 else {
5663 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
5664 ADD_INSN(ret, line_node, swap);
5665
5666 ADD_INSN1(ret, line_node, putobject, hash);
5667
5668 ADD_SEND(ret, line_node, id_core_hash_merge_bang_kwd, INT2FIX(2));
5669 }
5670 RB_OBJ_WRITTEN(iseq, Qundef, hash);
5671 }
5672 }
5673
5674 /* Base case: Compile "count" elements */
5675 for (; count; count--, node = RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_next) {
5676
5677 if (CPDEBUG > 0) {
5678 EXPECT_NODE("compile_hash", node, NODE_LIST, -1);
5679 }
5680
5681 if (RNODE_LIST(node)->nd_head) {
5682 /* Normal key-value pair */
5683 NO_CHECK(COMPILE_(anchor, "hash key element", RNODE_LIST(node)->nd_head, 0));
5684 NO_CHECK(COMPILE_(anchor, "hash value element", RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_head, 0));
5685 stack_len += 2;
5686
5687 /* If there are many pushed elements, flush them to avoid stack overflow */
5688 if (stack_len >= max_stack_len) FLUSH_CHUNK();
5689 }
5690 else {
5691 /* kwsplat case: foo(..., **kw, ...) */
5692 FLUSH_CHUNK();
5693
5694 const NODE *kw = RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_head;
5695 int empty_kw = nd_type_p(kw, NODE_HASH) && (!RNODE_HASH(kw)->nd_head); /* foo( ..., **{}, ...) */
5696 int first_kw = first_chunk && stack_len == 0; /* foo(1,2,3, **kw, ...) */
5697 int last_kw = !RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_next; /* foo( ..., **kw) */
5698 int only_kw = last_kw && first_kw; /* foo(1,2,3, **kw) */
5699
5700 empty_kw = empty_kw || nd_type_p(kw, NODE_NIL); /* foo( ..., **nil, ...) */
5701 if (empty_kw) {
5702 if (only_kw && method_call_keywords) {
5703 /* **{} appears at the only keyword argument in method call,
5704 * so it won't be modified.
5705 * kw is a special NODE_LIT that contains a special empty hash,
5706 * so this emits: putobject {}.
5707 * This is only done for method calls and not for literal hashes,
5708 * because literal hashes should always result in a new hash.
5709 */
5710 NO_CHECK(COMPILE(ret, "keyword splat", kw));
5711 }
5712 else if (first_kw) {
5713 /* **{} appears as the first keyword argument, so it may be modified.
5714 * We need to create a fresh hash object.
5715 */
5716 ADD_INSN1(ret, line_node, newhash, INT2FIX(0));
5717 }
5718 /* Any empty keyword splats that are not the first can be ignored.
5719 * since merging an empty hash into the existing hash is the same
5720 * as not merging it. */
5721 }
5722 else {
5723 if (only_kw && method_call_keywords) {
5724 /* **kw is only keyword argument in method call.
5725 * Use directly. This will be not be flagged as mutable.
5726 * This is only done for method calls and not for literal hashes,
5727 * because literal hashes should always result in a new hash.
5728 */
5729 NO_CHECK(COMPILE(ret, "keyword splat", kw));
5730 }
5731 else {
5732 /* There is more than one keyword argument, or this is not a method
5733 * call. In that case, we need to add an empty hash (if first keyword),
5734 * or merge the hash to the accumulated hash (if not the first keyword).
5735 */
5736 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
5737 if (first_kw) ADD_INSN1(ret, line_node, newhash, INT2FIX(0));
5738 else ADD_INSN(ret, line_node, swap);
5739
5740 NO_CHECK(COMPILE(ret, "keyword splat", kw));
5741
5742 ADD_SEND(ret, line_node, id_core_hash_merge_bang_kwd, INT2FIX(2));
5743 }
5744 }
5745
5746 first_chunk = 0;
5747 }
5748 }
5749 }
5750
5751 FLUSH_CHUNK();
5752#undef FLUSH_CHUNK
5753 return 1;
5754}
5755
5756static VALUE
5757rb_node_case_when_optimizable_literal(const NODE *const node)
5758{
5759 switch (nd_type(node)) {
5760 case NODE_INTEGER:
5761 return rb_node_integer_literal_val(node);
5762 case NODE_FLOAT: {
5763 VALUE v = rb_node_float_literal_val(node);
5764 double ival;
5765
5766 if (modf(RFLOAT_VALUE(v), &ival) == 0.0) {
5767 return FIXABLE(ival) ? LONG2FIX((long)ival) : rb_dbl2big(ival);
5768 }
5769 return v;
5770 }
5771 case NODE_RATIONAL:
5772 case NODE_IMAGINARY:
5773 return Qundef;
5774 case NODE_NIL:
5775 return Qnil;
5776 case NODE_TRUE:
5777 return Qtrue;
5778 case NODE_FALSE:
5779 return Qfalse;
5780 case NODE_SYM:
5781 return rb_node_sym_string_val(node);
5782 case NODE_LINE:
5783 return rb_node_line_lineno_val(node);
5784 case NODE_STR:
5785 return rb_node_str_string_val(node);
5786 }
5787 return Qundef;
5788}
5789
5790static int
5791when_vals(rb_iseq_t *iseq, LINK_ANCHOR *const cond_seq, const NODE *vals,
5792 LABEL *l1, int only_special_literals, VALUE literals)
5793{
5794 while (vals) {
5795 const NODE *val = RNODE_LIST(vals)->nd_head;
5796 VALUE lit = rb_node_case_when_optimizable_literal(val);
5797
5798 if (UNDEF_P(lit)) {
5799 only_special_literals = 0;
5800 }
5801 else {
5802 cdhash_aset_if_missing(literals, lit, (VALUE)(l1));
5803 }
5804
5805 if (nd_type_p(val, NODE_STR)) {
5806 debugp_param("nd_lit", get_string_value(val));
5807 lit = get_string_value(val);
5808 ADD_INSN1(cond_seq, val, putobject, lit);
5809 RB_OBJ_WRITTEN(iseq, Qundef, lit);
5810 }
5811 else {
5812 if (!COMPILE(cond_seq, "when cond", val)) return -1;
5813 }
5814
5815 // Emit pattern === target
5816 ADD_INSN1(cond_seq, vals, topn, INT2FIX(1));
5817 ADD_CALL(cond_seq, vals, idEqq, INT2FIX(1));
5818 ADD_INSNL(cond_seq, val, branchif, l1);
5819 vals = RNODE_LIST(vals)->nd_next;
5820 }
5821 return only_special_literals;
5822}
5823
5824static int
5825when_splat_vals(rb_iseq_t *iseq, LINK_ANCHOR *const cond_seq, const NODE *vals,
5826 LABEL *l1, int only_special_literals, VALUE literals)
5827{
5828 const NODE *line_node = vals;
5829
5830 switch (nd_type(vals)) {
5831 case NODE_LIST:
5832 if (when_vals(iseq, cond_seq, vals, l1, only_special_literals, literals) < 0)
5833 return COMPILE_NG;
5834 break;
5835 case NODE_SPLAT:
5836 ADD_INSN (cond_seq, line_node, dup);
5837 CHECK(COMPILE(cond_seq, "when splat", RNODE_SPLAT(vals)->nd_head));
5838 ADD_INSN1(cond_seq, line_node, splatarray, Qfalse);
5839 ADD_INSN1(cond_seq, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_CASE | VM_CHECKMATCH_ARRAY));
5840 ADD_INSNL(cond_seq, line_node, branchif, l1);
5841 break;
5842 case NODE_ARGSCAT:
5843 CHECK(when_splat_vals(iseq, cond_seq, RNODE_ARGSCAT(vals)->nd_head, l1, only_special_literals, literals));
5844 CHECK(when_splat_vals(iseq, cond_seq, RNODE_ARGSCAT(vals)->nd_body, l1, only_special_literals, literals));
5845 break;
5846 case NODE_ARGSPUSH:
5847 CHECK(when_splat_vals(iseq, cond_seq, RNODE_ARGSPUSH(vals)->nd_head, l1, only_special_literals, literals));
5848 ADD_INSN (cond_seq, line_node, dup);
5849 CHECK(COMPILE(cond_seq, "when argspush body", RNODE_ARGSPUSH(vals)->nd_body));
5850 ADD_INSN1(cond_seq, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_CASE));
5851 ADD_INSNL(cond_seq, line_node, branchif, l1);
5852 break;
5853 default:
5854 ADD_INSN (cond_seq, line_node, dup);
5855 CHECK(COMPILE(cond_seq, "when val", vals));
5856 ADD_INSN1(cond_seq, line_node, splatarray, Qfalse);
5857 ADD_INSN1(cond_seq, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_CASE | VM_CHECKMATCH_ARRAY));
5858 ADD_INSNL(cond_seq, line_node, branchif, l1);
5859 break;
5860 }
5861 return COMPILE_OK;
5862}
5863
5864/* Multiple Assignment Handling
5865 *
5866 * In order to handle evaluation of multiple assignment such that the left hand side
5867 * is evaluated before the right hand side, we need to process the left hand side
5868 * and see if there are any attributes that need to be assigned, or constants set
5869 * on explicit objects. If so, we add instructions to evaluate the receiver of
5870 * any assigned attributes or constants before we process the right hand side.
5871 *
5872 * For a multiple assignment such as:
5873 *
5874 * l1.m1, l2[0] = r3, r4
5875 *
5876 * We start off evaluating l1 and l2, then we evaluate r3 and r4, then we
5877 * assign the result of r3 to l1.m1, and then the result of r4 to l2.m2.
5878 * On the VM stack, this looks like:
5879 *
5880 * self # putself
5881 * l1 # send
5882 * l1, self # putself
5883 * l1, l2 # send
5884 * l1, l2, 0 # putobject 0
5885 * l1, l2, 0, [r3, r4] # after evaluation of RHS
5886 * l1, l2, 0, [r3, r4], r4, r3 # expandarray
5887 * l1, l2, 0, [r3, r4], r4, r3, l1 # topn 5
5888 * l1, l2, 0, [r3, r4], r4, l1, r3 # swap
5889 * l1, l2, 0, [r3, r4], r4, m1= # send
5890 * l1, l2, 0, [r3, r4], r4 # pop
5891 * l1, l2, 0, [r3, r4], r4, l2 # topn 3
5892 * l1, l2, 0, [r3, r4], r4, l2, 0 # topn 3
5893 * l1, l2, 0, [r3, r4], r4, l2, 0, r4 # topn 2
5894 * l1, l2, 0, [r3, r4], r4, []= # send
5895 * l1, l2, 0, [r3, r4], r4 # pop
5896 * l1, l2, 0, [r3, r4] # pop
5897 * [r3, r4], l2, 0, [r3, r4] # setn 3
5898 * [r3, r4], l2, 0 # pop
5899 * [r3, r4], l2 # pop
5900 * [r3, r4] # pop
5901 *
5902 * This is made more complex when you have to handle splats, post args,
5903 * and arbitrary levels of nesting. You need to keep track of the total
5904 * number of attributes to set, and for each attribute, how many entries
5905 * are on the stack before the final attribute, in order to correctly
5906 * calculate the topn value to use to get the receiver of the attribute
5907 * setter method.
5908 *
5909 * A brief description of the VM stack for simple multiple assignment
5910 * with no splat (rhs_array will not be present if the return value of
5911 * the multiple assignment is not needed):
5912 *
5913 * lhs_attr1, lhs_attr2, ..., rhs_array, ..., rhs_arg2, rhs_arg1
5914 *
5915 * For multiple assignment with splats, while processing the part before
5916 * the splat (splat+post here is an array of the splat and the post arguments):
5917 *
5918 * lhs_attr1, lhs_attr2, ..., rhs_array, splat+post, ..., rhs_arg2, rhs_arg1
5919 *
5920 * When processing the splat and post arguments:
5921 *
5922 * lhs_attr1, lhs_attr2, ..., rhs_array, ..., post_arg2, post_arg1, splat
5923 *
5924 * When processing nested multiple assignment, existing values on the stack
5925 * are kept. So for:
5926 *
5927 * (l1.m1, l2.m2), l3.m3, l4* = [r1, r2], r3, r4
5928 *
5929 * The stack layout would be the following before processing the nested
5930 * multiple assignment:
5931 *
5932 * l1, l2, [[r1, r2], r3, r4], [r4], r3, [r1, r2]
5933 *
5934 * In order to handle this correctly, we need to keep track of the nesting
5935 * level for each attribute assignment, as well as the attribute number
5936 * (left hand side attributes are processed left to right) and number of
5937 * arguments to pass to the setter method. struct masgn_lhs_node tracks
5938 * this information.
5939 *
5940 * We also need to track information for the entire multiple assignment, such
5941 * as the total number of arguments, and the current nesting level, to
5942 * handle both nested multiple assignment as well as cases where the
5943 * rhs is not needed. We also need to keep track of all attribute
5944 * assignments in this, which we do using a linked listed. struct masgn_state
5945 * tracks this information.
5946 */
5947
5949 INSN *before_insn;
5950 struct masgn_lhs_node *next;
5951 const NODE *line_node;
5952 int argn;
5953 int num_args;
5954 int lhs_pos;
5955};
5956
5958 struct masgn_lhs_node *first_memo;
5959 struct masgn_lhs_node *last_memo;
5960 int lhs_level;
5961 int num_args;
5962 bool nested;
5963};
5964
5965static int
5966add_masgn_lhs_node(struct masgn_state *state, int lhs_pos, const NODE *line_node, int argc, INSN *before_insn)
5967{
5968 if (!state) {
5969 rb_bug("no masgn_state");
5970 }
5971
5972 struct masgn_lhs_node *memo;
5973 memo = malloc(sizeof(struct masgn_lhs_node));
5974 if (!memo) {
5975 return COMPILE_NG;
5976 }
5977
5978 memo->before_insn = before_insn;
5979 memo->line_node = line_node;
5980 memo->argn = state->num_args + 1;
5981 memo->num_args = argc;
5982 state->num_args += argc;
5983 memo->lhs_pos = lhs_pos;
5984 memo->next = NULL;
5985 if (!state->first_memo) {
5986 state->first_memo = memo;
5987 }
5988 else {
5989 state->last_memo->next = memo;
5990 }
5991 state->last_memo = memo;
5992
5993 return COMPILE_OK;
5994}
5995
5996static int compile_massign0(rb_iseq_t *iseq, LINK_ANCHOR *const pre, LINK_ANCHOR *const rhs, LINK_ANCHOR *const lhs, LINK_ANCHOR *const post, const NODE *const node, struct masgn_state *state, int popped);
5997
5998static int
5999compile_massign_lhs(rb_iseq_t *iseq, LINK_ANCHOR *const pre, LINK_ANCHOR *const rhs, LINK_ANCHOR *const lhs, LINK_ANCHOR *const post, const NODE *const node, struct masgn_state *state, int lhs_pos)
6000{
6001 switch (nd_type(node)) {
6002 case NODE_ATTRASGN: {
6003 INSN *iobj;
6004 const NODE *line_node = node;
6005
6006 CHECK(COMPILE_POPPED(pre, "masgn lhs (NODE_ATTRASGN)", node));
6007
6008 bool safenav_call = false;
6009 LINK_ELEMENT *insn_element = LAST_ELEMENT(pre);
6010 iobj = (INSN *)get_prev_insn((INSN *)insn_element); /* send insn */
6011 ASSUME(iobj);
6012 ELEM_REMOVE(insn_element);
6013 if (!IS_INSN_ID(iobj, send)) {
6014 safenav_call = true;
6015 iobj = (INSN *)get_prev_insn(iobj);
6016 ELEM_INSERT_NEXT(&iobj->link, insn_element);
6017 }
6018 (pre->last = iobj->link.prev)->next = 0;
6019
6020 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(iobj, 0);
6021 int argc = vm_ci_argc(ci) + 1;
6022 ci = ci_argc_set(iseq, ci, argc);
6023 OPERAND_AT(iobj, 0) = (VALUE)ci;
6024 RB_OBJ_WRITTEN(iseq, Qundef, ci);
6025
6026 if (argc == 1) {
6027 ADD_INSN(lhs, line_node, swap);
6028 }
6029 else {
6030 ADD_INSN1(lhs, line_node, topn, INT2FIX(argc));
6031 }
6032
6033 if (!add_masgn_lhs_node(state, lhs_pos, line_node, argc, (INSN *)LAST_ELEMENT(lhs))) {
6034 return COMPILE_NG;
6035 }
6036
6037 iobj->link.prev = lhs->last;
6038 lhs->last->next = &iobj->link;
6039 for (lhs->last = &iobj->link; lhs->last->next; lhs->last = lhs->last->next);
6040 if (vm_ci_flag(ci) & VM_CALL_ARGS_SPLAT) {
6041 int argc = vm_ci_argc(ci);
6042 bool dupsplat = false;
6043 ci = ci_argc_set(iseq, ci, argc - 1);
6044 if (!(vm_ci_flag(ci) & VM_CALL_ARGS_SPLAT_MUT)) {
6045 /* Given h[*a], _ = ary
6046 * setup_args sets VM_CALL_ARGS_SPLAT and not VM_CALL_ARGS_SPLAT_MUT
6047 * `a` must be dupped, because it will be appended with ary[0]
6048 * Since you are dupping `a`, you can set VM_CALL_ARGS_SPLAT_MUT
6049 */
6050 dupsplat = true;
6051 ci = ci_flag_set(iseq, ci, VM_CALL_ARGS_SPLAT_MUT);
6052 }
6053 OPERAND_AT(iobj, 0) = (VALUE)ci;
6054 RB_OBJ_WRITTEN(iseq, Qundef, ci);
6055
6056 /* Given: h[*a], h[*b, 1] = ary
6057 * h[*a] uses splatarray false and does not set VM_CALL_ARGS_SPLAT_MUT,
6058 * so this uses splatarray true on a to dup it before using pushtoarray
6059 * h[*b, 1] uses splatarray true and sets VM_CALL_ARGS_SPLAT_MUT,
6060 * so you can use pushtoarray directly
6061 */
6062 int line_no = nd_line(line_node);
6063 int node_id = nd_node_id(line_node);
6064
6065 if (dupsplat) {
6066 INSERT_BEFORE_INSN(iobj, line_no, node_id, swap);
6067 INSERT_BEFORE_INSN1(iobj, line_no, node_id, splatarray, Qtrue);
6068 INSERT_BEFORE_INSN(iobj, line_no, node_id, swap);
6069 }
6070 INSERT_BEFORE_INSN1(iobj, line_no, node_id, pushtoarray, INT2FIX(1));
6071 }
6072 if (!safenav_call) {
6073 ADD_INSN(lhs, line_node, pop);
6074 if (argc != 1) {
6075 ADD_INSN(lhs, line_node, pop);
6076 }
6077 }
6078 for (int i=0; i < argc; i++) {
6079 ADD_INSN(post, line_node, pop);
6080 }
6081 break;
6082 }
6083 case NODE_MASGN: {
6084 DECL_ANCHOR(nest_rhs);
6085 INIT_ANCHOR(nest_rhs);
6086 DECL_ANCHOR(nest_lhs);
6087 INIT_ANCHOR(nest_lhs);
6088
6089 int prev_level = state->lhs_level;
6090 bool prev_nested = state->nested;
6091 state->nested = 1;
6092 state->lhs_level = lhs_pos - 1;
6093 CHECK(compile_massign0(iseq, pre, nest_rhs, nest_lhs, post, node, state, 1));
6094 state->lhs_level = prev_level;
6095 state->nested = prev_nested;
6096
6097 ADD_SEQ(lhs, nest_rhs);
6098 ADD_SEQ(lhs, nest_lhs);
6099 break;
6100 }
6101 case NODE_CDECL:
6102 if (!RNODE_CDECL(node)->nd_vid) {
6103 /* Special handling only needed for expr::C, not for C */
6104 INSN *iobj;
6105
6106 CHECK(COMPILE_POPPED(pre, "masgn lhs (NODE_CDECL)", node));
6107
6108 LINK_ELEMENT *insn_element = LAST_ELEMENT(pre);
6109 iobj = (INSN *)insn_element; /* setconstant insn */
6110 ELEM_REMOVE((LINK_ELEMENT *)get_prev_insn((INSN *)get_prev_insn(iobj)));
6111 ELEM_REMOVE((LINK_ELEMENT *)get_prev_insn(iobj));
6112 ELEM_REMOVE(insn_element);
6113 pre->last = iobj->link.prev;
6114 ADD_ELEM(lhs, (LINK_ELEMENT *)iobj);
6115
6116 if (!add_masgn_lhs_node(state, lhs_pos, node, 1, (INSN *)LAST_ELEMENT(lhs))) {
6117 return COMPILE_NG;
6118 }
6119
6120 ADD_INSN(post, node, pop);
6121 break;
6122 }
6123 /* Fallthrough */
6124 default: {
6125 DECL_ANCHOR(anchor);
6126 INIT_ANCHOR(anchor);
6127 CHECK(COMPILE_POPPED(anchor, "masgn lhs", node));
6128 ELEM_REMOVE(FIRST_ELEMENT(anchor));
6129 ADD_SEQ(lhs, anchor);
6130 }
6131 }
6132
6133 return COMPILE_OK;
6134}
6135
6136static int
6137compile_massign_opt_lhs(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *lhsn)
6138{
6139 if (lhsn) {
6140 CHECK(compile_massign_opt_lhs(iseq, ret, RNODE_LIST(lhsn)->nd_next));
6141 CHECK(compile_massign_lhs(iseq, ret, ret, ret, ret, RNODE_LIST(lhsn)->nd_head, NULL, 0));
6142 }
6143 return COMPILE_OK;
6144}
6145
6146static int
6147compile_massign_opt(rb_iseq_t *iseq, LINK_ANCHOR *const ret,
6148 const NODE *rhsn, const NODE *orig_lhsn)
6149{
6150 VALUE mem[64];
6151 const int memsize = numberof(mem);
6152 int memindex = 0;
6153 int llen = 0, rlen = 0;
6154 int i;
6155 const NODE *lhsn = orig_lhsn;
6156
6157#define MEMORY(v) { \
6158 int i; \
6159 if (memindex == memsize) return 0; \
6160 for (i=0; i<memindex; i++) { \
6161 if (mem[i] == (v)) return 0; \
6162 } \
6163 mem[memindex++] = (v); \
6164}
6165
6166 if (rhsn == 0 || !nd_type_p(rhsn, NODE_LIST)) {
6167 return 0;
6168 }
6169
6170 while (lhsn) {
6171 const NODE *ln = RNODE_LIST(lhsn)->nd_head;
6172 switch (nd_type(ln)) {
6173 case NODE_LASGN:
6174 case NODE_DASGN:
6175 case NODE_IASGN:
6176 case NODE_CVASGN:
6177 MEMORY(get_nd_vid(ln));
6178 break;
6179 default:
6180 return 0;
6181 }
6182 lhsn = RNODE_LIST(lhsn)->nd_next;
6183 llen++;
6184 }
6185
6186 while (rhsn) {
6187 if (llen <= rlen) {
6188 NO_CHECK(COMPILE_POPPED(ret, "masgn val (popped)", RNODE_LIST(rhsn)->nd_head));
6189 }
6190 else {
6191 NO_CHECK(COMPILE(ret, "masgn val", RNODE_LIST(rhsn)->nd_head));
6192 }
6193 rhsn = RNODE_LIST(rhsn)->nd_next;
6194 rlen++;
6195 }
6196
6197 if (llen > rlen) {
6198 for (i=0; i<llen-rlen; i++) {
6199 ADD_INSN(ret, orig_lhsn, putnil);
6200 }
6201 }
6202
6203 compile_massign_opt_lhs(iseq, ret, orig_lhsn);
6204 return 1;
6205}
6206
6207static int
6208compile_massign0(rb_iseq_t *iseq, LINK_ANCHOR *const pre, LINK_ANCHOR *const rhs, LINK_ANCHOR *const lhs, LINK_ANCHOR *const post, const NODE *const node, struct masgn_state *state, int popped)
6209{
6210 const NODE *rhsn = RNODE_MASGN(node)->nd_value;
6211 const NODE *splatn = RNODE_MASGN(node)->nd_args;
6212 const NODE *lhsn = RNODE_MASGN(node)->nd_head;
6213 const NODE *lhsn_count = lhsn;
6214 int lhs_splat = (splatn && NODE_NAMED_REST_P(splatn)) ? 1 : 0;
6215
6216 int llen = 0;
6217 int lpos = 0;
6218
6219 while (lhsn_count) {
6220 llen++;
6221 lhsn_count = RNODE_LIST(lhsn_count)->nd_next;
6222 }
6223 while (lhsn) {
6224 CHECK(compile_massign_lhs(iseq, pre, rhs, lhs, post, RNODE_LIST(lhsn)->nd_head, state, (llen - lpos) + lhs_splat + state->lhs_level));
6225 lpos++;
6226 lhsn = RNODE_LIST(lhsn)->nd_next;
6227 }
6228
6229 if (lhs_splat) {
6230 if (nd_type_p(splatn, NODE_POSTARG)) {
6231 /*a, b, *r, p1, p2 */
6232 const NODE *postn = RNODE_POSTARG(splatn)->nd_2nd;
6233 const NODE *restn = RNODE_POSTARG(splatn)->nd_1st;
6234 int plen = (int)RNODE_LIST(postn)->as.nd_alen;
6235 int ppos = 0;
6236 int flag = 0x02 | (NODE_NAMED_REST_P(restn) ? 0x01 : 0x00);
6237
6238 ADD_INSN2(lhs, splatn, expandarray, INT2FIX(plen), INT2FIX(flag));
6239
6240 if (NODE_NAMED_REST_P(restn)) {
6241 CHECK(compile_massign_lhs(iseq, pre, rhs, lhs, post, restn, state, 1 + plen + state->lhs_level));
6242 }
6243 while (postn) {
6244 CHECK(compile_massign_lhs(iseq, pre, rhs, lhs, post, RNODE_LIST(postn)->nd_head, state, (plen - ppos) + state->lhs_level));
6245 ppos++;
6246 postn = RNODE_LIST(postn)->nd_next;
6247 }
6248 }
6249 else {
6250 /* a, b, *r */
6251 CHECK(compile_massign_lhs(iseq, pre, rhs, lhs, post, splatn, state, 1 + state->lhs_level));
6252 }
6253 }
6254
6255 if (!state->nested) {
6256 NO_CHECK(COMPILE(rhs, "normal masgn rhs", rhsn));
6257 }
6258
6259 if (!popped) {
6260 ADD_INSN(rhs, node, dup);
6261 }
6262 ADD_INSN2(rhs, node, expandarray, INT2FIX(llen), INT2FIX(lhs_splat));
6263 return COMPILE_OK;
6264}
6265
6266static int
6267compile_massign(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
6268{
6269 if (!popped || RNODE_MASGN(node)->nd_args || !compile_massign_opt(iseq, ret, RNODE_MASGN(node)->nd_value, RNODE_MASGN(node)->nd_head)) {
6270 struct masgn_state state;
6271 state.lhs_level = popped ? 0 : 1;
6272 state.nested = 0;
6273 state.num_args = 0;
6274 state.first_memo = NULL;
6275 state.last_memo = NULL;
6276
6277 DECL_ANCHOR(pre);
6278 INIT_ANCHOR(pre);
6279 DECL_ANCHOR(rhs);
6280 INIT_ANCHOR(rhs);
6281 DECL_ANCHOR(lhs);
6282 INIT_ANCHOR(lhs);
6283 DECL_ANCHOR(post);
6284 INIT_ANCHOR(post);
6285 int ok = compile_massign0(iseq, pre, rhs, lhs, post, node, &state, popped);
6286
6287 struct masgn_lhs_node *memo = state.first_memo, *tmp_memo;
6288 while (memo) {
6289 VALUE topn_arg = INT2FIX((state.num_args - memo->argn) + memo->lhs_pos);
6290 for (int i = 0; i < memo->num_args; i++) {
6291 INSERT_BEFORE_INSN1(memo->before_insn, nd_line(memo->line_node), nd_node_id(memo->line_node), topn, topn_arg);
6292 }
6293 tmp_memo = memo->next;
6294 free(memo);
6295 memo = tmp_memo;
6296 }
6297 CHECK(ok);
6298
6299 ADD_SEQ(ret, pre);
6300 ADD_SEQ(ret, rhs);
6301 ADD_SEQ(ret, lhs);
6302 if (!popped && state.num_args >= 1) {
6303 /* make sure rhs array is returned before popping */
6304 ADD_INSN1(ret, node, setn, INT2FIX(state.num_args));
6305 }
6306 ADD_SEQ(ret, post);
6307 }
6308 return COMPILE_OK;
6309}
6310
6311static size_t
6312constant_path_size(const NODE *node, bool *absolute)
6313{
6314 size_t size = 1;
6315 while (true) {
6316 switch (nd_type(node)) {
6317 case NODE_CONST:
6318 return size;
6319 case NODE_COLON3:
6320 *absolute = true;
6321 return size;
6322 case NODE_COLON2:
6323 node = RNODE_COLON2(node)->nd_head;
6324 size++;
6325 break;
6326 default:
6327 return 0;
6328 }
6329 }
6330}
6331
6332static rb_const_path_t
6333compile_const_path(rb_iseq_t *iseq, const NODE *node)
6334{
6335 bool absolute = false;
6336 size_t size = constant_path_size(node, &absolute);
6337 if (size == 0) {
6338 return 0;
6339 }
6340
6341 VALUE buf_v;
6342 ID *ids = ALLOCV_N(ID, buf_v, size);
6343
6344 for (size_t i = size; i > 0; i--) {
6345 switch (nd_type(node)) {
6346 case NODE_CONST:
6347 ids[i - 1] = RNODE_CONST(node)->nd_vid;
6348 break;
6349 case NODE_COLON3:
6350 ids[i - 1] = RNODE_COLON3(node)->nd_mid;
6351 break;
6352 default:
6353 ids[i - 1] = RNODE_COLON2(node)->nd_mid;
6354 node = RNODE_COLON2(node)->nd_head;
6355 break;
6356 }
6357 }
6358 rb_const_path_t const_path = rb_const_path_from_ids(absolute, ids, size);
6359 ALLOCV_END(buf_v);
6360 return const_path;
6361}
6362
6363static int
6364compile_const_prefix(rb_iseq_t *iseq, const NODE *const node,
6365 LINK_ANCHOR *const pref, LINK_ANCHOR *const body)
6366{
6367 switch (nd_type(node)) {
6368 case NODE_CONST:
6369 debugi("compile_const_prefix - colon", RNODE_CONST(node)->nd_vid);
6370 ADD_INSN1(body, node, putobject, Qtrue);
6371 ADD_INSN1(body, node, getconstant, ID2SYM(RNODE_CONST(node)->nd_vid));
6372 break;
6373 case NODE_COLON3:
6374 debugi("compile_const_prefix - colon3", RNODE_COLON3(node)->nd_mid);
6375 ADD_INSN(body, node, pop);
6376 ADD_INSN1(body, node, putobject, rb_cObject);
6377 ADD_INSN1(body, node, putobject, Qtrue);
6378 ADD_INSN1(body, node, getconstant, ID2SYM(RNODE_COLON3(node)->nd_mid));
6379 break;
6380 case NODE_COLON2:
6381 CHECK(compile_const_prefix(iseq, RNODE_COLON2(node)->nd_head, pref, body));
6382 debugi("compile_const_prefix - colon2", RNODE_COLON2(node)->nd_mid);
6383 ADD_INSN1(body, node, putobject, Qfalse);
6384 ADD_INSN1(body, node, getconstant, ID2SYM(RNODE_COLON2(node)->nd_mid));
6385 break;
6386 default:
6387 CHECK(COMPILE(pref, "const colon2 prefix", node));
6388 break;
6389 }
6390 return COMPILE_OK;
6391}
6392
6393static int
6394cpath_const_p(const NODE *node)
6395{
6396 switch (nd_type(node)) {
6397 case NODE_CONST:
6398 case NODE_COLON3:
6399 return TRUE;
6400 case NODE_COLON2:
6401 if (RNODE_COLON2(node)->nd_head) {
6402 return cpath_const_p(RNODE_COLON2(node)->nd_head);
6403 }
6404 return TRUE;
6405 default:
6406 return FALSE;
6407 }
6408}
6409
6410static int
6411compile_cpath(LINK_ANCHOR *const ret, rb_iseq_t *iseq, const NODE *cpath)
6412{
6413 if (nd_type_p(cpath, NODE_COLON3)) {
6414 /* toplevel class ::Foo */
6415 ADD_INSN1(ret, cpath, putobject, rb_cObject);
6416 return VM_DEFINECLASS_FLAG_SCOPED;
6417 }
6418 else if (nd_type_p(cpath, NODE_COLON2) && RNODE_COLON2(cpath)->nd_head) {
6419 /* Bar::Foo or expr::Foo */
6420 NO_CHECK(COMPILE(ret, "nd_else->nd_head", RNODE_COLON2(cpath)->nd_head));
6421 int flags = VM_DEFINECLASS_FLAG_SCOPED;
6422 if (!cpath_const_p(RNODE_COLON2(cpath)->nd_head)) {
6423 flags |= VM_DEFINECLASS_FLAG_DYNAMIC_CREF;
6424 }
6425 return flags;
6426 }
6427 else {
6428 /* class at cbase Foo */
6429 ADD_INSN1(ret, cpath, putspecialobject,
6430 INT2FIX(VM_SPECIAL_OBJECT_CONST_BASE));
6431 return 0;
6432 }
6433}
6434
6435static inline int
6436private_recv_p(const NODE *node)
6437{
6438 NODE *recv = get_nd_recv(node);
6439 if (recv && nd_type_p(recv, NODE_SELF)) {
6440 return RNODE_SELF(recv)->nd_state != 0;
6441 }
6442 return 0;
6443}
6444
6445static void
6446defined_expr(rb_iseq_t *iseq, LINK_ANCHOR *const ret,
6447 const NODE *const node, LABEL **lfinish, VALUE needstr, bool ignore);
6448
6449static int
6450compile_call(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, const enum node_type type, const NODE *const line_node, int popped, bool assume_receiver);
6451
6452static void
6453defined_expr0(rb_iseq_t *iseq, LINK_ANCHOR *const ret,
6454 const NODE *const node, LABEL **lfinish, VALUE needstr,
6455 bool keep_result)
6456{
6457 enum defined_type expr_type = DEFINED_NOT_DEFINED;
6458 enum node_type type;
6459 const int line = nd_line(node);
6460 const NODE *line_node = node;
6461
6462 switch (type = nd_type(node)) {
6463
6464 /* easy literals */
6465 case NODE_NIL:
6466 expr_type = DEFINED_NIL;
6467 break;
6468 case NODE_SELF:
6469 expr_type = DEFINED_SELF;
6470 break;
6471 case NODE_TRUE:
6472 expr_type = DEFINED_TRUE;
6473 break;
6474 case NODE_FALSE:
6475 expr_type = DEFINED_FALSE;
6476 break;
6477
6478 case NODE_HASH:
6479 case NODE_LIST:{
6480 const NODE *vals = (nd_type(node) == NODE_HASH) ? RNODE_HASH(node)->nd_head : node;
6481
6482 if (vals) {
6483 do {
6484 if (RNODE_LIST(vals)->nd_head) {
6485 defined_expr0(iseq, ret, RNODE_LIST(vals)->nd_head, lfinish, Qfalse, false);
6486
6487 if (!lfinish[1]) {
6488 lfinish[1] = NEW_LABEL(line);
6489 }
6490 ADD_INSNL(ret, line_node, branchunless, lfinish[1]);
6491 }
6492 } while ((vals = RNODE_LIST(vals)->nd_next) != NULL);
6493 }
6494 }
6495 /* fall through */
6496 case NODE_STR:
6497 case NODE_SYM:
6498 case NODE_REGX:
6499 case NODE_LINE:
6500 case NODE_FILE:
6501 case NODE_ENCODING:
6502 case NODE_INTEGER:
6503 case NODE_FLOAT:
6504 case NODE_RATIONAL:
6505 case NODE_IMAGINARY:
6506 case NODE_ZLIST:
6507 case NODE_AND:
6508 case NODE_OR:
6509 default:
6510 expr_type = DEFINED_EXPR;
6511 break;
6512
6513 case NODE_SPLAT:
6514 defined_expr0(iseq, ret, RNODE_LIST(node)->nd_head, lfinish, Qfalse, false);
6515 if (!lfinish[1]) {
6516 lfinish[1] = NEW_LABEL(line);
6517 }
6518 ADD_INSNL(ret, line_node, branchunless, lfinish[1]);
6519 expr_type = DEFINED_EXPR;
6520 break;
6521
6522 /* variables */
6523 case NODE_LVAR:
6524 case NODE_DVAR:
6525 expr_type = DEFINED_LVAR;
6526 break;
6527
6528#define PUSH_VAL(type) (needstr == Qfalse ? Qtrue : rb_iseq_defined_string(type))
6529 case NODE_IVAR:
6530 ADD_INSN3(ret, line_node, definedivar,
6531 ID2SYM(RNODE_IVAR(node)->nd_vid), get_ivar_ic_value(iseq,RNODE_IVAR(node)->nd_vid), PUSH_VAL(DEFINED_IVAR));
6532 return;
6533
6534 case NODE_GVAR:
6535 ADD_INSN(ret, line_node, putnil);
6536 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_GVAR),
6537 ID2SYM(RNODE_GVAR(node)->nd_vid), PUSH_VAL(DEFINED_GVAR));
6538 return;
6539
6540 case NODE_CVAR:
6541 ADD_INSN(ret, line_node, putnil);
6542 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_CVAR),
6543 ID2SYM(RNODE_CVAR(node)->nd_vid), PUSH_VAL(DEFINED_CVAR));
6544 return;
6545
6546 case NODE_CONST:
6547 ADD_INSN(ret, line_node, putnil);
6548 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_CONST),
6549 ID2SYM(RNODE_CONST(node)->nd_vid), PUSH_VAL(DEFINED_CONST));
6550 return;
6551 case NODE_COLON2:
6552 if (!lfinish[1]) {
6553 lfinish[1] = NEW_LABEL(line);
6554 }
6555 defined_expr0(iseq, ret, RNODE_COLON2(node)->nd_head, lfinish, Qfalse, false);
6556 ADD_INSNL(ret, line_node, branchunless, lfinish[1]);
6557 NO_CHECK(COMPILE(ret, "defined/colon2#nd_head", RNODE_COLON2(node)->nd_head));
6558
6559 if (rb_is_const_id(RNODE_COLON2(node)->nd_mid)) {
6560 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_CONST_FROM),
6561 ID2SYM(RNODE_COLON2(node)->nd_mid), PUSH_VAL(DEFINED_CONST));
6562 }
6563 else {
6564 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_METHOD),
6565 ID2SYM(RNODE_COLON2(node)->nd_mid), PUSH_VAL(DEFINED_METHOD));
6566 }
6567 return;
6568 case NODE_COLON3:
6569 ADD_INSN1(ret, line_node, putobject, rb_cObject);
6570 ADD_INSN3(ret, line_node, defined,
6571 INT2FIX(DEFINED_CONST_FROM), ID2SYM(RNODE_COLON3(node)->nd_mid), PUSH_VAL(DEFINED_CONST));
6572 return;
6573
6574 /* method dispatch */
6575 case NODE_CALL:
6576 case NODE_OPCALL:
6577 case NODE_VCALL:
6578 case NODE_FCALL:
6579 case NODE_ATTRASGN:{
6580 const int explicit_receiver =
6581 (type == NODE_CALL || type == NODE_OPCALL ||
6582 (type == NODE_ATTRASGN && !private_recv_p(node)));
6583
6584 if (get_nd_args(node) || explicit_receiver) {
6585 if (!lfinish[1]) {
6586 lfinish[1] = NEW_LABEL(line);
6587 }
6588 if (!lfinish[2]) {
6589 lfinish[2] = NEW_LABEL(line);
6590 }
6591 }
6592 if (get_nd_args(node)) {
6593 defined_expr0(iseq, ret, get_nd_args(node), lfinish, Qfalse, false);
6594 ADD_INSNL(ret, line_node, branchunless, lfinish[1]);
6595 }
6596 if (explicit_receiver) {
6597 defined_expr0(iseq, ret, get_nd_recv(node), lfinish, Qfalse, true);
6598 switch (nd_type(get_nd_recv(node))) {
6599 case NODE_CALL:
6600 case NODE_OPCALL:
6601 case NODE_VCALL:
6602 case NODE_FCALL:
6603 case NODE_ATTRASGN:
6604 ADD_INSNL(ret, line_node, branchunless, lfinish[2]);
6605 compile_call(iseq, ret, get_nd_recv(node), nd_type(get_nd_recv(node)), line_node, 0, true);
6606 break;
6607 default:
6608 ADD_INSNL(ret, line_node, branchunless, lfinish[1]);
6609 NO_CHECK(COMPILE(ret, "defined/recv", get_nd_recv(node)));
6610 break;
6611 }
6612 if (keep_result) {
6613 ADD_INSN(ret, line_node, dup);
6614 }
6615 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_METHOD),
6616 ID2SYM(get_node_call_nd_mid(node)), PUSH_VAL(DEFINED_METHOD));
6617 }
6618 else {
6619 ADD_INSN(ret, line_node, putself);
6620 if (keep_result) {
6621 ADD_INSN(ret, line_node, dup);
6622 }
6623 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_FUNC),
6624 ID2SYM(get_node_call_nd_mid(node)), PUSH_VAL(DEFINED_METHOD));
6625 }
6626 return;
6627 }
6628
6629 case NODE_YIELD:
6630 ADD_INSN(ret, line_node, putnil);
6631 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_YIELD), 0,
6632 PUSH_VAL(DEFINED_YIELD));
6633 iseq_set_use_block(ISEQ_BODY(iseq)->local_iseq);
6634 return;
6635
6636 case NODE_BACK_REF:
6637 case NODE_NTH_REF:
6638 ADD_INSN(ret, line_node, putnil);
6639 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_REF),
6640 INT2FIX((RNODE_BACK_REF(node)->nd_nth << 1) | (type == NODE_BACK_REF)),
6641 PUSH_VAL(DEFINED_GVAR));
6642 return;
6643
6644 case NODE_SUPER:
6645 case NODE_ZSUPER:
6646 ADD_INSN(ret, line_node, putnil);
6647 ADD_INSN3(ret, line_node, defined, INT2FIX(DEFINED_ZSUPER), 0,
6648 PUSH_VAL(DEFINED_ZSUPER));
6649 return;
6650
6651#undef PUSH_VAL
6652 case NODE_OP_ASGN1:
6653 case NODE_OP_ASGN2:
6654 case NODE_OP_ASGN_OR:
6655 case NODE_OP_ASGN_AND:
6656 case NODE_MASGN:
6657 case NODE_LASGN:
6658 case NODE_DASGN:
6659 case NODE_GASGN:
6660 case NODE_IASGN:
6661 case NODE_CDECL:
6662 case NODE_CVASGN:
6663 case NODE_OP_CDECL:
6664 expr_type = DEFINED_ASGN;
6665 break;
6666 }
6667
6668 RUBY_ASSERT(expr_type != DEFINED_NOT_DEFINED);
6669
6670 if (needstr != Qfalse) {
6671 VALUE str = rb_iseq_defined_string(expr_type);
6672 ADD_INSN1(ret, line_node, putobject, str);
6673 }
6674 else {
6675 ADD_INSN1(ret, line_node, putobject, Qtrue);
6676 }
6677}
6678
6679static void
6680build_defined_rescue_iseq(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const void *unused)
6681{
6682 ADD_SYNTHETIC_INSN(ret, 0, -1, putnil);
6683 iseq_set_exception_local_table(iseq);
6684}
6685
6686static void
6687defined_expr(rb_iseq_t *iseq, LINK_ANCHOR *const ret,
6688 const NODE *const node, LABEL **lfinish, VALUE needstr, bool ignore)
6689{
6690 LINK_ELEMENT *lcur = ret->last;
6691 defined_expr0(iseq, ret, node, lfinish, needstr, false);
6692 if (lfinish[1]) {
6693 int line = nd_line(node);
6694 LABEL *lstart = NEW_LABEL(line);
6695 LABEL *lend = NEW_LABEL(line);
6696 const rb_iseq_t *rescue;
6698 rb_iseq_new_with_callback_new_callback(build_defined_rescue_iseq, NULL);
6699 rescue = NEW_CHILD_ISEQ_WITH_CALLBACK(ifunc,
6700 rb_str_concat(rb_str_new2("defined guard in "),
6701 ISEQ_BODY(iseq)->location.label),
6702 ISEQ_TYPE_RESCUE, 0);
6703 lstart->rescued = LABEL_RESCUE_BEG;
6704 lend->rescued = LABEL_RESCUE_END;
6705 APPEND_LABEL(ret, lcur, lstart);
6706 ADD_LABEL(ret, lend);
6707 if (!ignore) {
6708 ADD_CATCH_ENTRY(CATCH_TYPE_RESCUE, lstart, lend, rescue, lfinish[1]);
6709 }
6710 }
6711}
6712
6713static int
6714compile_defined_expr(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, VALUE needstr, bool ignore)
6715{
6716 const int line = nd_line(node);
6717 const NODE *line_node = node;
6718 if (!RNODE_DEFINED(node)->nd_head) {
6719 VALUE str = rb_iseq_defined_string(DEFINED_NIL);
6720 ADD_INSN1(ret, line_node, putobject, str);
6721 }
6722 else {
6723 LABEL *lfinish[3];
6724 LINK_ELEMENT *last = ret->last;
6725 lfinish[0] = NEW_LABEL(line);
6726 lfinish[1] = 0;
6727 lfinish[2] = 0;
6728 defined_expr(iseq, ret, RNODE_DEFINED(node)->nd_head, lfinish, needstr, ignore);
6729 if (lfinish[1]) {
6730 ELEM_INSERT_NEXT(last, &new_insn_body(iseq, nd_line(line_node), nd_node_id(line_node), BIN(putnil), 0)->link);
6731 ADD_INSN(ret, line_node, swap);
6732 if (lfinish[2]) {
6733 ADD_LABEL(ret, lfinish[2]);
6734 }
6735 ADD_INSN(ret, line_node, pop);
6736 ADD_LABEL(ret, lfinish[1]);
6737 }
6738 ADD_LABEL(ret, lfinish[0]);
6739 }
6740 return COMPILE_OK;
6741}
6742
6743static VALUE
6744make_name_for_block(const rb_iseq_t *orig_iseq)
6745{
6746 int level = 1;
6747 const rb_iseq_t *iseq = orig_iseq;
6748
6749 if (ISEQ_BODY(orig_iseq)->parent_iseq != 0) {
6750 while (ISEQ_BODY(orig_iseq)->local_iseq != iseq) {
6751 if (ISEQ_BODY(iseq)->type == ISEQ_TYPE_BLOCK) {
6752 level++;
6753 }
6754 iseq = ISEQ_BODY(iseq)->parent_iseq;
6755 }
6756 }
6757
6758 if (level == 1) {
6759 return rb_sprintf("block in %"PRIsVALUE, ISEQ_BODY(iseq)->location.label);
6760 }
6761 else {
6762 return rb_sprintf("block (%d levels) in %"PRIsVALUE, level, ISEQ_BODY(iseq)->location.label);
6763 }
6764}
6765
6766static void
6767push_ensure_entry(rb_iseq_t *iseq,
6769 struct ensure_range *er, const void *const node)
6770{
6771 enl->ensure_node = node;
6772 enl->prev = ISEQ_COMPILE_DATA(iseq)->ensure_node_stack; /* prev */
6773 enl->erange = er;
6774 ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = enl;
6775}
6776
6777static void
6778add_ensure_range(rb_iseq_t *iseq, struct ensure_range *erange,
6779 LABEL *lstart, LABEL *lend)
6780{
6781 struct ensure_range *ne =
6782 compile_data_alloc_type(iseq, struct ensure_range);
6783
6784 while (erange->next != 0) {
6785 erange = erange->next;
6786 }
6787 ne->next = 0;
6788 ne->begin = lend;
6789 ne->end = erange->end;
6790 erange->end = lstart;
6791
6792 erange->next = ne;
6793}
6794
6795static bool
6796has_ensure_iseq(const rb_iseq_t *iseq)
6797{
6799 for (e = ISEQ_COMPILE_DATA(iseq)->ensure_node_stack; e; e = e->prev) {
6800 if (e->ensure_node) return true;
6801 }
6802 return false;
6803}
6804
6805static bool
6806can_add_ensure_iseq(const rb_iseq_t *iseq)
6807{
6808 return !ISEQ_COMPILE_DATA(iseq)->in_rescue || !has_ensure_iseq(iseq);
6809}
6810
6811static bool
6812can_inline_return(const rb_iseq_t *iseq, enum rb_iseq_type type)
6813{
6814 return type == ISEQ_TYPE_METHOD &&
6815 ((!ISEQ_COMPILE_DATA(iseq)->in_rescue && !ISEQ_COMPILE_DATA(iseq)->redo_label) || !has_ensure_iseq(iseq));
6816}
6817
6818static void
6819add_ensure_iseq(LINK_ANCHOR *const ret, rb_iseq_t *iseq, int is_return)
6820{
6821 RUBY_ASSERT(can_add_ensure_iseq(iseq));
6822
6824 ISEQ_COMPILE_DATA(iseq)->ensure_node_stack;
6825 struct iseq_compile_data_ensure_node_stack *prev_enlp = enlp;
6826 DECL_ANCHOR(ensure);
6827
6828 INIT_ANCHOR(ensure);
6829 while (enlp) {
6830 if (enlp->erange != NULL) {
6831 DECL_ANCHOR(ensure_part);
6832 LABEL *lstart = NEW_LABEL(0);
6833 LABEL *lend = NEW_LABEL(0);
6834 INIT_ANCHOR(ensure_part);
6835
6836 add_ensure_range(iseq, enlp->erange, lstart, lend);
6837
6838 ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = enlp->prev;
6839 ADD_LABEL(ensure_part, lstart);
6840 NO_CHECK(COMPILE_POPPED(ensure_part, "ensure part", enlp->ensure_node));
6841 ADD_LABEL(ensure_part, lend);
6842 ADD_SEQ(ensure, ensure_part);
6843 }
6844 else {
6845 if (!is_return) {
6846 break;
6847 }
6848 }
6849 enlp = enlp->prev;
6850 }
6851 ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = prev_enlp;
6852 ADD_SEQ(ret, ensure);
6853}
6854
6855#if RUBY_DEBUG
6856static int
6857check_keyword(const NODE *node)
6858{
6859 /* This check is essentially a code clone of compile_keyword_arg. */
6860
6861 if (nd_type_p(node, NODE_LIST)) {
6862 while (RNODE_LIST(node)->nd_next) {
6863 node = RNODE_LIST(node)->nd_next;
6864 }
6865 node = RNODE_LIST(node)->nd_head;
6866 }
6867
6868 return keyword_node_p(node);
6869}
6870#endif
6871
6872static bool
6873keyword_node_single_splat_p(NODE *kwnode)
6874{
6875 RUBY_ASSERT(keyword_node_p(kwnode));
6876
6877 NODE *node = RNODE_HASH(kwnode)->nd_head;
6878 return RNODE_LIST(node)->nd_head == NULL &&
6879 RNODE_LIST(RNODE_LIST(node)->nd_next)->nd_next == NULL;
6880}
6881
6882static void
6883compile_single_keyword_splat_mutable(rb_iseq_t *iseq, LINK_ANCHOR *const args, const NODE *argn,
6884 NODE *kwnode, unsigned int *flag_ptr)
6885{
6886 if (flag_ptr) *flag_ptr |= VM_CALL_KW_SPLAT_MUT;
6887 ADD_INSN1(args, argn, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
6888 ADD_INSN1(args, argn, newhash, INT2FIX(0));
6889 compile_hash(iseq, args, kwnode, TRUE, FALSE);
6890 ADD_SEND(args, argn, id_core_hash_merge_kwd, INT2FIX(2));
6891}
6892
6893#define SPLATARRAY_FALSE 0
6894#define SPLATARRAY_TRUE 1
6895#define DUP_SINGLE_KW_SPLAT 2
6896
6897static int
6898setup_args_core(rb_iseq_t *iseq, LINK_ANCHOR *const args, const NODE *argn,
6899 unsigned int *dup_rest, unsigned int *flag_ptr, struct rb_callinfo_kwarg **kwarg_ptr)
6900{
6901 if (!argn) return 0;
6902
6903 NODE *kwnode = NULL;
6904
6905 switch (nd_type(argn)) {
6906 case NODE_LIST: {
6907 // f(x, y, z)
6908 int len = compile_args(iseq, args, argn, &kwnode);
6909 RUBY_ASSERT(flag_ptr == NULL || (*flag_ptr & VM_CALL_ARGS_SPLAT) == 0);
6910
6911 if (kwnode) {
6912 if (kwarg_ptr && compile_keyword_arg(iseq, args, kwnode, kwarg_ptr, flag_ptr)) {
6913 len -= 1;
6914 }
6915 else {
6916 if (keyword_node_single_splat_p(kwnode) && (*dup_rest & DUP_SINGLE_KW_SPLAT)) {
6917 compile_single_keyword_splat_mutable(iseq, args, argn, kwnode, flag_ptr);
6918 }
6919 else {
6920 compile_hash(iseq, args, kwnode, kwarg_ptr != NULL, FALSE);
6921 }
6922 }
6923 }
6924
6925 return len;
6926 }
6927 case NODE_SPLAT: {
6928 // f(*a)
6929 NO_CHECK(COMPILE(args, "args (splat)", RNODE_SPLAT(argn)->nd_head));
6930 ADD_INSN1(args, argn, splatarray, RBOOL(*dup_rest & SPLATARRAY_TRUE));
6931 if (*dup_rest & SPLATARRAY_TRUE) *dup_rest &= ~SPLATARRAY_TRUE;
6932 if (flag_ptr) *flag_ptr |= VM_CALL_ARGS_SPLAT;
6933 RUBY_ASSERT(flag_ptr == NULL || (*flag_ptr & VM_CALL_KW_SPLAT) == 0);
6934 return 1;
6935 }
6936 case NODE_ARGSCAT: {
6937 if (flag_ptr) *flag_ptr |= VM_CALL_ARGS_SPLAT;
6938 int argc = setup_args_core(iseq, args, RNODE_ARGSCAT(argn)->nd_head, dup_rest, NULL, NULL);
6939 bool args_pushed = false;
6940
6941 if (nd_type_p(RNODE_ARGSCAT(argn)->nd_body, NODE_LIST)) {
6942 int rest_len = compile_args(iseq, args, RNODE_ARGSCAT(argn)->nd_body, &kwnode);
6943 if (kwnode) rest_len--;
6944 ADD_INSN1(args, argn, pushtoarray, INT2FIX(rest_len));
6945 args_pushed = true;
6946 }
6947 else {
6948 RUBY_ASSERT(!check_keyword(RNODE_ARGSCAT(argn)->nd_body));
6949 NO_CHECK(COMPILE(args, "args (cat: splat)", RNODE_ARGSCAT(argn)->nd_body));
6950 }
6951
6952 if (nd_type_p(RNODE_ARGSCAT(argn)->nd_head, NODE_LIST)) {
6953 ADD_INSN1(args, argn, splatarray, RBOOL(*dup_rest & SPLATARRAY_TRUE));
6954 if (*dup_rest & SPLATARRAY_TRUE) *dup_rest &= ~SPLATARRAY_TRUE;
6955 argc += 1;
6956 }
6957 else if (!args_pushed) {
6958 ADD_INSN(args, argn, concattoarray);
6959 }
6960
6961 // f(..., *a, ..., k1:1, ...) #=> f(..., *[*a, ...], **{k1:1, ...})
6962 if (kwnode) {
6963 compile_hash(iseq, args, kwnode, flag_ptr != NULL, FALSE);
6964 if (flag_ptr) {
6965 // Pass keyword arguments to the method call.
6966 *flag_ptr |= VM_CALL_KW_SPLAT;
6967 argc += 1;
6968 }
6969 else {
6970 // Inside a splat array, this hash is a positional element.
6971 ADD_INSN1(args, argn, pushtoarray, INT2FIX(1));
6972 }
6973 }
6974
6975 return argc;
6976 }
6977 case NODE_ARGSPUSH: {
6978 if (flag_ptr) *flag_ptr |= VM_CALL_ARGS_SPLAT;
6979 int argc = setup_args_core(iseq, args, RNODE_ARGSPUSH(argn)->nd_head, dup_rest, NULL, NULL);
6980
6981 if (nd_type_p(RNODE_ARGSPUSH(argn)->nd_body, NODE_LIST)) {
6982 int rest_len = compile_args(iseq, args, RNODE_ARGSPUSH(argn)->nd_body, &kwnode);
6983 if (kwnode) rest_len--;
6984 ADD_INSN1(args, argn, newarray, INT2FIX(rest_len));
6985 ADD_INSN1(args, argn, pushtoarray, INT2FIX(1));
6986 }
6987 else {
6988 if (keyword_node_p(RNODE_ARGSPUSH(argn)->nd_body)) {
6989 kwnode = RNODE_ARGSPUSH(argn)->nd_body;
6990 }
6991 else {
6992 NO_CHECK(COMPILE(args, "args (cat: splat)", RNODE_ARGSPUSH(argn)->nd_body));
6993 ADD_INSN1(args, argn, pushtoarray, INT2FIX(1));
6994 }
6995 }
6996
6997 if (kwnode) {
6998 // At the call site this is f(*a, k:1). While building a splat
6999 // array, append the hash as a positional element instead.
7000 if (flag_ptr) *flag_ptr |= VM_CALL_KW_SPLAT;
7001 if (!keyword_node_single_splat_p(kwnode)) {
7002 if (flag_ptr) *flag_ptr |= VM_CALL_KW_SPLAT_MUT;
7003 compile_hash(iseq, args, kwnode, flag_ptr != NULL, FALSE);
7004 }
7005 else if (*dup_rest & DUP_SINGLE_KW_SPLAT) {
7006 compile_single_keyword_splat_mutable(iseq, args, argn, kwnode, flag_ptr);
7007 }
7008 else {
7009 compile_hash(iseq, args, kwnode, flag_ptr != NULL, FALSE);
7010 }
7011 if (flag_ptr) {
7012 argc += 1;
7013 }
7014 else {
7015 ADD_INSN1(args, argn, pushtoarray, INT2FIX(1));
7016 }
7017 }
7018
7019 return argc;
7020 }
7021 default: {
7022 UNKNOWN_NODE("setup_arg", argn, Qnil);
7023 }
7024 }
7025}
7026
7027static void
7028setup_args_splat_mut(unsigned int *flag, int dup_rest, int initial_dup_rest)
7029{
7030 if ((*flag & VM_CALL_ARGS_SPLAT) && dup_rest != initial_dup_rest) {
7031 *flag |= VM_CALL_ARGS_SPLAT_MUT;
7032 }
7033}
7034
7035static bool
7036setup_args_dup_rest_p(const NODE *argn)
7037{
7038 switch(nd_type(argn)) {
7039 case NODE_LVAR:
7040 case NODE_DVAR:
7041 case NODE_GVAR:
7042 case NODE_IVAR:
7043 case NODE_CVAR:
7044 case NODE_CONST:
7045 case NODE_COLON3:
7046 case NODE_INTEGER:
7047 case NODE_FLOAT:
7048 case NODE_RATIONAL:
7049 case NODE_IMAGINARY:
7050 case NODE_STR:
7051 case NODE_SYM:
7052 case NODE_REGX:
7053 case NODE_SELF:
7054 case NODE_NIL:
7055 case NODE_TRUE:
7056 case NODE_FALSE:
7057 case NODE_LAMBDA:
7058 case NODE_NTH_REF:
7059 case NODE_BACK_REF:
7060 return false;
7061 case NODE_COLON2:
7062 return setup_args_dup_rest_p(RNODE_COLON2(argn)->nd_head);
7063 case NODE_LIST:
7064 while (argn) {
7065 if (setup_args_dup_rest_p(RNODE_LIST(argn)->nd_head)) {
7066 return true;
7067 }
7068 argn = RNODE_LIST(argn)->nd_next;
7069 }
7070 return false;
7071 default:
7072 return true;
7073 }
7074}
7075
7076static VALUE
7077setup_args(rb_iseq_t *iseq, LINK_ANCHOR *const args, const NODE *argn,
7078 unsigned int *flag, struct rb_callinfo_kwarg **keywords)
7079{
7080 VALUE ret;
7081 unsigned int dup_rest = SPLATARRAY_TRUE, initial_dup_rest;
7082 RUBY_ASSERT(flag);
7083
7084 if (argn) {
7085 const NODE *check_arg = nd_type_p(argn, NODE_BLOCK_PASS) ?
7086 RNODE_BLOCK_PASS(argn)->nd_head : argn;
7087
7088 if (check_arg) {
7089 switch(nd_type(check_arg)) {
7090 case(NODE_SPLAT):
7091 // avoid caller side array allocation for f(*arg)
7092 dup_rest = SPLATARRAY_FALSE;
7093 break;
7094 case(NODE_ARGSCAT):
7095 // avoid caller side array allocation for f(1, *arg)
7096 dup_rest = !nd_type_p(RNODE_ARGSCAT(check_arg)->nd_head, NODE_LIST);
7097 break;
7098 case(NODE_ARGSPUSH):
7099 // avoid caller side array allocation for f(*arg, **hash) and f(1, *arg, **hash)
7100 dup_rest = !((nd_type_p(RNODE_ARGSPUSH(check_arg)->nd_head, NODE_SPLAT) ||
7101 (nd_type_p(RNODE_ARGSPUSH(check_arg)->nd_head, NODE_ARGSCAT) &&
7102 nd_type_p(RNODE_ARGSCAT(RNODE_ARGSPUSH(check_arg)->nd_head)->nd_head, NODE_LIST))) &&
7103 nd_type_p(RNODE_ARGSPUSH(check_arg)->nd_body, NODE_HASH) &&
7104 !RNODE_HASH(RNODE_ARGSPUSH(check_arg)->nd_body)->nd_brace);
7105
7106 if (dup_rest == SPLATARRAY_FALSE) {
7107 // require allocation for keyword key/value/splat that may modify splatted argument
7108 NODE *node = RNODE_HASH(RNODE_ARGSPUSH(check_arg)->nd_body)->nd_head;
7109 while (node) {
7110 NODE *key_node = RNODE_LIST(node)->nd_head;
7111 if (key_node && setup_args_dup_rest_p(key_node)) {
7112 dup_rest = SPLATARRAY_TRUE;
7113 break;
7114 }
7115
7116 node = RNODE_LIST(node)->nd_next;
7117 NODE *value_node = RNODE_LIST(node)->nd_head;
7118 if (setup_args_dup_rest_p(value_node)) {
7119 dup_rest = SPLATARRAY_TRUE;
7120 break;
7121 }
7122
7123 node = RNODE_LIST(node)->nd_next;
7124 }
7125 }
7126 break;
7127 default:
7128 break;
7129 }
7130 }
7131
7132 if (check_arg != argn && setup_args_dup_rest_p(RNODE_BLOCK_PASS(argn)->nd_body)) {
7133 // for block pass that may modify splatted argument, dup rest and kwrest if given
7134 dup_rest = SPLATARRAY_TRUE | DUP_SINGLE_KW_SPLAT;
7135 }
7136 }
7137 initial_dup_rest = dup_rest;
7138
7139 if (argn && nd_type_p(argn, NODE_BLOCK_PASS)) {
7140 DECL_ANCHOR(arg_block);
7141 INIT_ANCHOR(arg_block);
7142
7143 if (RNODE_BLOCK_PASS(argn)->forwarding && ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq)->param.flags.forwardable) {
7144 int idx = ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq)->local_table_size;// - get_local_var_idx(iseq, idDot3);
7145
7146 RUBY_ASSERT(nd_type_p(RNODE_BLOCK_PASS(argn)->nd_head, NODE_ARGSPUSH));
7147 const NODE * arg_node =
7148 RNODE_ARGSPUSH(RNODE_BLOCK_PASS(argn)->nd_head)->nd_head;
7149
7150 int argc = 0;
7151
7152 // Only compile leading args:
7153 // foo(x, y, ...)
7154 // ^^^^
7155 if (nd_type_p(arg_node, NODE_ARGSCAT)) {
7156 argc += setup_args_core(iseq, args, RNODE_ARGSCAT(arg_node)->nd_head, &dup_rest, flag, keywords);
7157 }
7158
7159 *flag |= VM_CALL_FORWARDING;
7160
7161 ADD_GETLOCAL(args, argn, idx, get_lvar_level(iseq));
7162 setup_args_splat_mut(flag, dup_rest, initial_dup_rest);
7163 return INT2FIX(argc);
7164 }
7165 else {
7166 *flag |= VM_CALL_ARGS_BLOCKARG;
7167
7168 NO_CHECK(COMPILE(arg_block, "block", RNODE_BLOCK_PASS(argn)->nd_body));
7169 }
7170
7171 if (LIST_INSN_SIZE_ONE(arg_block)) {
7172 LINK_ELEMENT *elem = FIRST_ELEMENT(arg_block);
7173 if (IS_INSN(elem)) {
7174 INSN *iobj = (INSN *)elem;
7175 if (iobj->insn_id == BIN(getblockparam)) {
7176 iobj->insn_id = BIN(getblockparamproxy);
7177 }
7178 }
7179 }
7180 ret = INT2FIX(setup_args_core(iseq, args, RNODE_BLOCK_PASS(argn)->nd_head, &dup_rest, flag, keywords));
7181 ADD_SEQ(args, arg_block);
7182 }
7183 else {
7184 ret = INT2FIX(setup_args_core(iseq, args, argn, &dup_rest, flag, keywords));
7185 }
7186 setup_args_splat_mut(flag, dup_rest, initial_dup_rest);
7187 return ret;
7188}
7189
7190static void
7191build_postexe_iseq(rb_iseq_t *iseq, LINK_ANCHOR *ret, const void *ptr)
7192{
7193 const NODE *body = ptr;
7194 int line = nd_line(body);
7195 VALUE argc = INT2FIX(0);
7196 const rb_iseq_t *block = NEW_CHILD_ISEQ(body, make_name_for_block(ISEQ_BODY(iseq)->parent_iseq), ISEQ_TYPE_BLOCK, line);
7197
7198 ADD_INSN1(ret, body, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
7199 ADD_CALL_WITH_BLOCK(ret, body, id_core_set_postexe, argc, block);
7200 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)block);
7201 iseq_set_local_table(iseq, 0, 0);
7202}
7203
7204static void
7205compile_named_capture_assign(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node)
7206{
7207 const NODE *vars;
7208 LINK_ELEMENT *last;
7209 int line = nd_line(node);
7210 const NODE *line_node = node;
7211 LABEL *fail_label = NEW_LABEL(line), *end_label = NEW_LABEL(line);
7212
7213#if !(defined(NAMED_CAPTURE_BY_SVAR) && NAMED_CAPTURE_BY_SVAR-0)
7214 ADD_INSN1(ret, line_node, getglobal, ID2SYM(idBACKREF));
7215#else
7216 ADD_INSN2(ret, line_node, getspecial, INT2FIX(1) /* '~' */, INT2FIX(0));
7217#endif
7218 ADD_INSN(ret, line_node, dup);
7219 ADD_INSNL(ret, line_node, branchunless, fail_label);
7220
7221 for (vars = node; vars; vars = RNODE_BLOCK(vars)->nd_next) {
7222 INSN *cap;
7223 if (RNODE_BLOCK(vars)->nd_next) {
7224 ADD_INSN(ret, line_node, dup);
7225 }
7226 last = ret->last;
7227 NO_CHECK(COMPILE_POPPED(ret, "capture", RNODE_BLOCK(vars)->nd_head));
7228 last = last->next; /* putobject :var */
7229 cap = new_insn_send(iseq, nd_line(line_node), nd_node_id(line_node), idAREF, INT2FIX(1),
7230 NULL, INT2FIX(0), NULL);
7231 ELEM_INSERT_PREV(last->next, (LINK_ELEMENT *)cap);
7232#if !defined(NAMED_CAPTURE_SINGLE_OPT) || NAMED_CAPTURE_SINGLE_OPT-0
7233 if (!RNODE_BLOCK(vars)->nd_next && vars == node) {
7234 /* only one name */
7235 DECL_ANCHOR(nom);
7236
7237 INIT_ANCHOR(nom);
7238 ADD_INSNL(nom, line_node, jump, end_label);
7239 ADD_LABEL(nom, fail_label);
7240# if 0 /* $~ must be MatchData or nil */
7241 ADD_INSN(nom, line_node, pop);
7242 ADD_INSN(nom, line_node, putnil);
7243# endif
7244 ADD_LABEL(nom, end_label);
7245 (nom->last->next = cap->link.next)->prev = nom->last;
7246 (cap->link.next = nom->anchor.next)->prev = &cap->link;
7247 return;
7248 }
7249#endif
7250 }
7251 ADD_INSNL(ret, line_node, jump, end_label);
7252 ADD_LABEL(ret, fail_label);
7253 ADD_INSN(ret, line_node, pop);
7254 for (vars = node; vars; vars = RNODE_BLOCK(vars)->nd_next) {
7255 last = ret->last;
7256 NO_CHECK(COMPILE_POPPED(ret, "capture", RNODE_BLOCK(vars)->nd_head));
7257 last = last->next; /* putobject :var */
7258 ((INSN*)last)->insn_id = BIN(putnil);
7259 ((INSN*)last)->operand_size = 0;
7260 }
7261 ADD_LABEL(ret, end_label);
7262}
7263
7264static int
7265optimizable_range_item_p(const NODE *n)
7266{
7267 if (!n) return FALSE;
7268 switch (nd_type(n)) {
7269 case NODE_LINE:
7270 return TRUE;
7271 case NODE_INTEGER:
7272 return TRUE;
7273 case NODE_NIL:
7274 return TRUE;
7275 default:
7276 return FALSE;
7277 }
7278}
7279
7280static VALUE
7281optimized_range_item(const NODE *n)
7282{
7283 switch (nd_type(n)) {
7284 case NODE_LINE:
7285 return rb_node_line_lineno_val(n);
7286 case NODE_INTEGER:
7287 return rb_node_integer_literal_val(n);
7288 case NODE_FLOAT:
7289 return rb_node_float_literal_val(n);
7290 case NODE_RATIONAL:
7291 return rb_node_rational_literal_val(n);
7292 case NODE_IMAGINARY:
7293 return rb_node_imaginary_literal_val(n);
7294 case NODE_NIL:
7295 return Qnil;
7296 default:
7297 rb_bug("unexpected node: %s", ruby_node_name(nd_type(n)));
7298 }
7299}
7300
7301static int
7302compile_if(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped, const enum node_type type)
7303{
7304 const NODE *const node_body = type == NODE_IF ? RNODE_IF(node)->nd_body : RNODE_UNLESS(node)->nd_else;
7305 const NODE *const node_else = type == NODE_IF ? RNODE_IF(node)->nd_else : RNODE_UNLESS(node)->nd_body;
7306
7307 const int line = nd_line(node);
7308 const NODE *line_node = node;
7309 DECL_ANCHOR(cond_seq);
7310 LABEL *then_label, *else_label, *end_label;
7311 VALUE branches = Qfalse;
7312
7313 INIT_ANCHOR(cond_seq);
7314 then_label = NEW_LABEL(line);
7315 else_label = NEW_LABEL(line);
7316 end_label = 0;
7317
7318 NODE *cond = RNODE_IF(node)->nd_cond;
7319 if (nd_type(cond) == NODE_BLOCK) {
7320 cond = RNODE_BLOCK(cond)->nd_head;
7321 }
7322
7323 CHECK(compile_branch_condition(iseq, cond_seq, cond, then_label, else_label));
7324 ADD_SEQ(ret, cond_seq);
7325
7326 if (then_label->refcnt && else_label->refcnt) {
7327 branches = decl_branch_base(iseq, nd_node_id(node), nd_code_loc(node), type == NODE_IF ? "if" : "unless");
7328 }
7329
7330 if (then_label->refcnt) {
7331 ADD_LABEL(ret, then_label);
7332
7333 DECL_ANCHOR(then_seq);
7334 INIT_ANCHOR(then_seq);
7335 CHECK(COMPILE_(then_seq, "then", node_body, popped));
7336
7337 if (else_label->refcnt) {
7338 const NODE *const coverage_node = node_body ? node_body : node;
7339 add_trace_branch_coverage(
7340 iseq,
7341 ret,
7342 nd_code_loc(coverage_node),
7343 nd_node_id(coverage_node),
7344 0,
7345 type == NODE_IF ? "then" : "else",
7346 branches);
7347 end_label = NEW_LABEL(line);
7348 ADD_INSNL(then_seq, line_node, jump, end_label);
7349 if (!popped) {
7350 ADD_INSN(then_seq, line_node, pop);
7351 }
7352 }
7353 ADD_SEQ(ret, then_seq);
7354 }
7355
7356 if (else_label->refcnt) {
7357 ADD_LABEL(ret, else_label);
7358
7359 DECL_ANCHOR(else_seq);
7360 INIT_ANCHOR(else_seq);
7361 CHECK(COMPILE_(else_seq, "else", node_else, popped));
7362
7363 if (then_label->refcnt) {
7364 const NODE *const coverage_node = node_else ? node_else : node;
7365 add_trace_branch_coverage(
7366 iseq,
7367 ret,
7368 nd_code_loc(coverage_node),
7369 nd_node_id(coverage_node),
7370 1,
7371 type == NODE_IF ? "else" : "then",
7372 branches);
7373 }
7374 ADD_SEQ(ret, else_seq);
7375 }
7376
7377 if (end_label) {
7378 ADD_LABEL(ret, end_label);
7379 }
7380
7381 return COMPILE_OK;
7382}
7383
7384static int
7385compile_case(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const orig_node, int popped)
7386{
7387 const NODE *vals;
7388 const NODE *node = orig_node;
7389 LABEL *endlabel, *elselabel;
7390 DECL_ANCHOR(head);
7391 DECL_ANCHOR(body_seq);
7392 DECL_ANCHOR(cond_seq);
7393 int only_special_literals = 1;
7394 VALUE literals = cdhash_new(0);
7395 int line;
7396 enum node_type type;
7397 const NODE *line_node;
7398 VALUE branches = Qfalse;
7399 int branch_id = 0;
7400
7401 INIT_ANCHOR(head);
7402 INIT_ANCHOR(body_seq);
7403 INIT_ANCHOR(cond_seq);
7404
7405 CHECK(COMPILE(head, "case base", RNODE_CASE(node)->nd_head));
7406
7407 branches = decl_branch_base(iseq, nd_node_id(node), nd_code_loc(node), "case");
7408
7409 node = RNODE_CASE(node)->nd_body;
7410 EXPECT_NODE("NODE_CASE", node, NODE_WHEN, COMPILE_NG);
7411 type = nd_type(node);
7412 line = nd_line(node);
7413 line_node = node;
7414
7415 endlabel = NEW_LABEL(line);
7416 elselabel = NEW_LABEL(line);
7417
7418 ADD_SEQ(ret, head); /* case VAL */
7419
7420 while (type == NODE_WHEN) {
7421 LABEL *l1;
7422
7423 l1 = NEW_LABEL(line);
7424 ADD_LABEL(body_seq, l1);
7425 ADD_INSN(body_seq, line_node, pop);
7426
7427 const NODE *const coverage_node = RNODE_WHEN(node)->nd_body ? RNODE_WHEN(node)->nd_body : node;
7428 add_trace_branch_coverage(
7429 iseq,
7430 body_seq,
7431 nd_code_loc(coverage_node),
7432 nd_node_id(coverage_node),
7433 branch_id++,
7434 "when",
7435 branches);
7436
7437 CHECK(COMPILE_(body_seq, "when body", RNODE_WHEN(node)->nd_body, popped));
7438 ADD_INSNL(body_seq, line_node, jump, endlabel);
7439
7440 vals = RNODE_WHEN(node)->nd_head;
7441 if (vals) {
7442 switch (nd_type(vals)) {
7443 case NODE_LIST:
7444 only_special_literals = when_vals(iseq, cond_seq, vals, l1, only_special_literals, literals);
7445 if (only_special_literals < 0) return COMPILE_NG;
7446 break;
7447 case NODE_SPLAT:
7448 case NODE_ARGSCAT:
7449 case NODE_ARGSPUSH:
7450 only_special_literals = 0;
7451 CHECK(when_splat_vals(iseq, cond_seq, vals, l1, only_special_literals, literals));
7452 break;
7453 default:
7454 UNKNOWN_NODE("NODE_CASE", vals, COMPILE_NG);
7455 }
7456 }
7457 else {
7458 EXPECT_NODE_NONULL("NODE_CASE", node, NODE_LIST, COMPILE_NG);
7459 }
7460
7461 node = RNODE_WHEN(node)->nd_next;
7462 if (!node) {
7463 break;
7464 }
7465 type = nd_type(node);
7466 line = nd_line(node);
7467 line_node = node;
7468 }
7469 /* else */
7470 if (node) {
7471 ADD_LABEL(cond_seq, elselabel);
7472 ADD_INSN(cond_seq, line_node, pop);
7473 add_trace_branch_coverage(iseq, cond_seq, nd_code_loc(node), nd_node_id(node), branch_id, "else", branches);
7474 CHECK(COMPILE_(cond_seq, "else", node, popped));
7475 ADD_INSNL(cond_seq, line_node, jump, endlabel);
7476 }
7477 else {
7478 debugs("== else (implicit)\n");
7479 ADD_LABEL(cond_seq, elselabel);
7480 ADD_INSN(cond_seq, orig_node, pop);
7481 add_trace_branch_coverage(iseq, cond_seq, nd_code_loc(orig_node), nd_node_id(orig_node), branch_id, "else", branches);
7482 if (!popped) {
7483 ADD_INSN(cond_seq, orig_node, putnil);
7484 }
7485 ADD_INSNL(cond_seq, orig_node, jump, endlabel);
7486 }
7487
7488 if (only_special_literals && ISEQ_COMPILE_DATA(iseq)->option->specialized_instruction) {
7489 ADD_INSN(ret, orig_node, dup);
7490 ADD_INSN2(ret, orig_node, opt_case_dispatch, literals, elselabel);
7491 RB_OBJ_WRITTEN(iseq, Qundef, literals);
7492 LABEL_REF(elselabel);
7493 }
7494
7495 ADD_SEQ(ret, cond_seq);
7496 ADD_SEQ(ret, body_seq);
7497 ADD_LABEL(ret, endlabel);
7498 return COMPILE_OK;
7499}
7500
7501static int
7502compile_case2(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const orig_node, int popped)
7503{
7504 const NODE *vals;
7505 const NODE *val;
7506 const NODE *node = RNODE_CASE2(orig_node)->nd_body;
7507 LABEL *endlabel;
7508 DECL_ANCHOR(body_seq);
7509 VALUE branches = Qfalse;
7510 int branch_id = 0;
7511
7512 branches = decl_branch_base(iseq, nd_node_id(orig_node), nd_code_loc(orig_node), "case");
7513
7514 INIT_ANCHOR(body_seq);
7515 endlabel = NEW_LABEL(nd_line(node));
7516
7517 while (node && nd_type_p(node, NODE_WHEN)) {
7518 const int line = nd_line(node);
7519 LABEL *l1 = NEW_LABEL(line);
7520 ADD_LABEL(body_seq, l1);
7521
7522 const NODE *const coverage_node = RNODE_WHEN(node)->nd_body ? RNODE_WHEN(node)->nd_body : node;
7523 add_trace_branch_coverage(
7524 iseq,
7525 body_seq,
7526 nd_code_loc(coverage_node),
7527 nd_node_id(coverage_node),
7528 branch_id++,
7529 "when",
7530 branches);
7531
7532 CHECK(COMPILE_(body_seq, "when", RNODE_WHEN(node)->nd_body, popped));
7533 ADD_INSNL(body_seq, node, jump, endlabel);
7534
7535 vals = RNODE_WHEN(node)->nd_head;
7536 if (!vals) {
7537 EXPECT_NODE_NONULL("NODE_WHEN", node, NODE_LIST, COMPILE_NG);
7538 }
7539 switch (nd_type(vals)) {
7540 case NODE_LIST:
7541 while (vals) {
7542 LABEL *lnext;
7543 val = RNODE_LIST(vals)->nd_head;
7544 lnext = NEW_LABEL(nd_line(val));
7545 debug_compile("== when2\n", (void)0);
7546 CHECK(compile_branch_condition(iseq, ret, val, l1, lnext));
7547 ADD_LABEL(ret, lnext);
7548 vals = RNODE_LIST(vals)->nd_next;
7549 }
7550 break;
7551 case NODE_SPLAT:
7552 case NODE_ARGSCAT:
7553 case NODE_ARGSPUSH:
7554 ADD_INSN(ret, vals, putnil);
7555 CHECK(COMPILE(ret, "when2/cond splat", vals));
7556 ADD_INSN1(ret, vals, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_WHEN | VM_CHECKMATCH_ARRAY));
7557 ADD_INSNL(ret, vals, branchif, l1);
7558 break;
7559 default:
7560 UNKNOWN_NODE("NODE_WHEN", vals, COMPILE_NG);
7561 }
7562 node = RNODE_WHEN(node)->nd_next;
7563 }
7564 /* else */
7565 const NODE *const coverage_node = node ? node : orig_node;
7566 add_trace_branch_coverage(
7567 iseq,
7568 ret,
7569 nd_code_loc(coverage_node),
7570 nd_node_id(coverage_node),
7571 branch_id,
7572 "else",
7573 branches);
7574 CHECK(COMPILE_(ret, "else", node, popped));
7575 ADD_INSNL(ret, orig_node, jump, endlabel);
7576
7577 ADD_SEQ(ret, body_seq);
7578 ADD_LABEL(ret, endlabel);
7579 return COMPILE_OK;
7580}
7581
7582static int iseq_compile_pattern_match(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, LABEL *unmatched, bool in_single_pattern, bool in_alt_pattern, int base_index, bool use_deconstructed_cache);
7583
7584static int iseq_compile_pattern_constant(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, LABEL *match_failed, bool in_single_pattern, int base_index);
7585static int iseq_compile_array_deconstruct(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, LABEL *deconstruct, LABEL *deconstructed, LABEL *match_failed, LABEL *type_error, bool in_single_pattern, int base_index, bool use_deconstructed_cache);
7586static int iseq_compile_pattern_set_general_errmsg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, VALUE errmsg, int base_index);
7587static int iseq_compile_pattern_set_length_errmsg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, VALUE errmsg, VALUE pattern_length, int base_index);
7588static int iseq_compile_pattern_set_eqq_errmsg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int base_index);
7589
7590#define CASE3_BI_OFFSET_DECONSTRUCTED_CACHE 0
7591#define CASE3_BI_OFFSET_ERROR_STRING 1
7592#define CASE3_BI_OFFSET_KEY_ERROR_P 2
7593#define CASE3_BI_OFFSET_KEY_ERROR_MATCHEE 3
7594#define CASE3_BI_OFFSET_KEY_ERROR_KEY 4
7595
7596static int
7597iseq_compile_pattern_each(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, LABEL *matched, LABEL *unmatched, bool in_single_pattern, bool in_alt_pattern, int base_index, bool use_deconstructed_cache)
7598{
7599 const int line = nd_line(node);
7600 const NODE *line_node = node;
7601
7602 switch (nd_type(node)) {
7603 case NODE_ARYPTN: {
7604 /*
7605 * if pattern.use_rest_num?
7606 * rest_num = 0
7607 * end
7608 * if pattern.has_constant_node?
7609 * unless pattern.constant === obj
7610 * goto match_failed
7611 * end
7612 * end
7613 * unless obj.respond_to?(:deconstruct)
7614 * goto match_failed
7615 * end
7616 * d = obj.deconstruct
7617 * unless Array === d
7618 * goto type_error
7619 * end
7620 * min_argc = pattern.pre_args_num + pattern.post_args_num
7621 * if pattern.has_rest_arg?
7622 * unless d.length >= min_argc
7623 * goto match_failed
7624 * end
7625 * else
7626 * unless d.length == min_argc
7627 * goto match_failed
7628 * end
7629 * end
7630 * pattern.pre_args_num.each do |i|
7631 * unless pattern.pre_args[i].match?(d[i])
7632 * goto match_failed
7633 * end
7634 * end
7635 * if pattern.use_rest_num?
7636 * rest_num = d.length - min_argc
7637 * if pattern.has_rest_arg? && pattern.has_rest_arg_id # not `*`, but `*rest`
7638 * unless pattern.rest_arg.match?(d[pattern.pre_args_num, rest_num])
7639 * goto match_failed
7640 * end
7641 * end
7642 * end
7643 * pattern.post_args_num.each do |i|
7644 * j = pattern.pre_args_num + i
7645 * j += rest_num
7646 * unless pattern.post_args[i].match?(d[j])
7647 * goto match_failed
7648 * end
7649 * end
7650 * goto matched
7651 * type_error:
7652 * FrozenCore.raise TypeError
7653 * match_failed:
7654 * goto unmatched
7655 */
7656 const NODE *args = RNODE_ARYPTN(node)->pre_args;
7657 const int pre_args_num = RNODE_ARYPTN(node)->pre_args ? rb_long2int(RNODE_LIST(RNODE_ARYPTN(node)->pre_args)->as.nd_alen) : 0;
7658 const int post_args_num = RNODE_ARYPTN(node)->post_args ? rb_long2int(RNODE_LIST(RNODE_ARYPTN(node)->post_args)->as.nd_alen) : 0;
7659
7660 const int min_argc = pre_args_num + post_args_num;
7661 const int use_rest_num = RNODE_ARYPTN(node)->rest_arg && (NODE_NAMED_REST_P(RNODE_ARYPTN(node)->rest_arg) ||
7662 (!NODE_NAMED_REST_P(RNODE_ARYPTN(node)->rest_arg) && post_args_num > 0));
7663
7664 LABEL *match_failed, *type_error, *deconstruct, *deconstructed;
7665 int i;
7666 match_failed = NEW_LABEL(line);
7667 type_error = NEW_LABEL(line);
7668 deconstruct = NEW_LABEL(line);
7669 deconstructed = NEW_LABEL(line);
7670
7671 if (use_rest_num) {
7672 ADD_INSN1(ret, line_node, putobject, INT2FIX(0)); /* allocate stack for rest_num */
7673 ADD_INSN(ret, line_node, swap);
7674 if (base_index) {
7675 base_index++;
7676 }
7677 }
7678
7679 CHECK(iseq_compile_pattern_constant(iseq, ret, node, match_failed, in_single_pattern, base_index));
7680
7681 CHECK(iseq_compile_array_deconstruct(iseq, ret, node, deconstruct, deconstructed, match_failed, type_error, in_single_pattern, base_index, use_deconstructed_cache));
7682
7683 ADD_INSN(ret, line_node, dup);
7684 ADD_SEND(ret, line_node, idLength, INT2FIX(0));
7685 ADD_INSN1(ret, line_node, putobject, INT2FIX(min_argc));
7686 ADD_SEND(ret, line_node, RNODE_ARYPTN(node)->rest_arg ? idGE : idEq, INT2FIX(1)); // (1)
7687 if (in_single_pattern) {
7688 CHECK(iseq_compile_pattern_set_length_errmsg(iseq, ret, node,
7689 RNODE_ARYPTN(node)->rest_arg ? rb_fstring_lit("%p length mismatch (given %p, expected %p+)") :
7690 rb_fstring_lit("%p length mismatch (given %p, expected %p)"),
7691 INT2FIX(min_argc), base_index + 1 /* (1) */));
7692 }
7693 ADD_INSNL(ret, line_node, branchunless, match_failed);
7694
7695 for (i = 0; i < pre_args_num; i++) {
7696 ADD_INSN(ret, line_node, dup);
7697 ADD_INSN1(ret, line_node, putobject, INT2FIX(i));
7698 ADD_SEND(ret, line_node, idAREF, INT2FIX(1)); // (2)
7699 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_LIST(args)->nd_head, match_failed, in_single_pattern, in_alt_pattern, base_index + 1 /* (2) */, false));
7700 args = RNODE_LIST(args)->nd_next;
7701 }
7702
7703 if (RNODE_ARYPTN(node)->rest_arg) {
7704 if (NODE_NAMED_REST_P(RNODE_ARYPTN(node)->rest_arg)) {
7705 ADD_INSN(ret, line_node, dup);
7706 ADD_INSN1(ret, line_node, putobject, INT2FIX(pre_args_num));
7707 ADD_INSN1(ret, line_node, topn, INT2FIX(1));
7708 ADD_SEND(ret, line_node, idLength, INT2FIX(0));
7709 ADD_INSN1(ret, line_node, putobject, INT2FIX(min_argc));
7710 ADD_SEND(ret, line_node, idMINUS, INT2FIX(1));
7711 ADD_INSN1(ret, line_node, setn, INT2FIX(4));
7712 ADD_SEND(ret, line_node, idAREF, INT2FIX(2)); // (3)
7713
7714 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_ARYPTN(node)->rest_arg, match_failed, in_single_pattern, in_alt_pattern, base_index + 1 /* (3) */, false));
7715 }
7716 else {
7717 if (post_args_num > 0) {
7718 ADD_INSN(ret, line_node, dup);
7719 ADD_SEND(ret, line_node, idLength, INT2FIX(0));
7720 ADD_INSN1(ret, line_node, putobject, INT2FIX(min_argc));
7721 ADD_SEND(ret, line_node, idMINUS, INT2FIX(1));
7722 ADD_INSN1(ret, line_node, setn, INT2FIX(2));
7723 ADD_INSN(ret, line_node, pop);
7724 }
7725 }
7726 }
7727
7728 args = RNODE_ARYPTN(node)->post_args;
7729 for (i = 0; i < post_args_num; i++) {
7730 ADD_INSN(ret, line_node, dup);
7731
7732 ADD_INSN1(ret, line_node, putobject, INT2FIX(pre_args_num + i));
7733 ADD_INSN1(ret, line_node, topn, INT2FIX(3));
7734 ADD_SEND(ret, line_node, idPLUS, INT2FIX(1));
7735
7736 ADD_SEND(ret, line_node, idAREF, INT2FIX(1)); // (4)
7737 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_LIST(args)->nd_head, match_failed, in_single_pattern, in_alt_pattern, base_index + 1 /* (4) */, false));
7738 args = RNODE_LIST(args)->nd_next;
7739 }
7740
7741 ADD_INSN(ret, line_node, pop);
7742 if (use_rest_num) {
7743 ADD_INSN(ret, line_node, pop);
7744 }
7745 ADD_INSNL(ret, line_node, jump, matched);
7746 ADD_INSN(ret, line_node, putnil);
7747 if (use_rest_num) {
7748 ADD_INSN(ret, line_node, putnil);
7749 }
7750
7751 ADD_LABEL(ret, type_error);
7752 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
7753 ADD_INSN1(ret, line_node, putobject, rb_eTypeError);
7754 ADD_INSN1(ret, line_node, putobject, rb_fstring_lit("deconstruct must return Array"));
7755 ADD_SEND(ret, line_node, id_core_raise, INT2FIX(2));
7756 ADD_INSN(ret, line_node, pop);
7757
7758 ADD_LABEL(ret, match_failed);
7759 ADD_INSN(ret, line_node, pop);
7760 if (use_rest_num) {
7761 ADD_INSN(ret, line_node, pop);
7762 }
7763 ADD_INSNL(ret, line_node, jump, unmatched);
7764
7765 break;
7766 }
7767 case NODE_FNDPTN: {
7768 /*
7769 * if pattern.has_constant_node?
7770 * unless pattern.constant === obj
7771 * goto match_failed
7772 * end
7773 * end
7774 * unless obj.respond_to?(:deconstruct)
7775 * goto match_failed
7776 * end
7777 * d = obj.deconstruct
7778 * unless Array === d
7779 * goto type_error
7780 * end
7781 * unless d.length >= pattern.args_num
7782 * goto match_failed
7783 * end
7784 *
7785 * begin
7786 * len = d.length
7787 * limit = d.length - pattern.args_num
7788 * i = 0
7789 * while i <= limit
7790 * if pattern.args_num.times.all? {|j| pattern.args[j].match?(d[i+j]) }
7791 * if pattern.has_pre_rest_arg_id
7792 * unless pattern.pre_rest_arg.match?(d[0, i])
7793 * goto find_failed
7794 * end
7795 * end
7796 * if pattern.has_post_rest_arg_id
7797 * unless pattern.post_rest_arg.match?(d[i+pattern.args_num, len])
7798 * goto find_failed
7799 * end
7800 * end
7801 * goto find_succeeded
7802 * end
7803 * i+=1
7804 * end
7805 * find_failed:
7806 * goto match_failed
7807 * find_succeeded:
7808 * end
7809 *
7810 * goto matched
7811 * type_error:
7812 * FrozenCore.raise TypeError
7813 * match_failed:
7814 * goto unmatched
7815 */
7816 const NODE *args = RNODE_FNDPTN(node)->args;
7817 const int args_num = RNODE_FNDPTN(node)->args ? rb_long2int(RNODE_LIST(RNODE_FNDPTN(node)->args)->as.nd_alen) : 0;
7818
7819 LABEL *match_failed, *type_error, *deconstruct, *deconstructed;
7820 match_failed = NEW_LABEL(line);
7821 type_error = NEW_LABEL(line);
7822 deconstruct = NEW_LABEL(line);
7823 deconstructed = NEW_LABEL(line);
7824
7825 CHECK(iseq_compile_pattern_constant(iseq, ret, node, match_failed, in_single_pattern, base_index));
7826
7827 CHECK(iseq_compile_array_deconstruct(iseq, ret, node, deconstruct, deconstructed, match_failed, type_error, in_single_pattern, base_index, use_deconstructed_cache));
7828
7829 ADD_INSN(ret, line_node, dup);
7830 ADD_SEND(ret, line_node, idLength, INT2FIX(0));
7831 ADD_INSN1(ret, line_node, putobject, INT2FIX(args_num));
7832 ADD_SEND(ret, line_node, idGE, INT2FIX(1)); // (1)
7833 if (in_single_pattern) {
7834 CHECK(iseq_compile_pattern_set_length_errmsg(iseq, ret, node, rb_fstring_lit("%p length mismatch (given %p, expected %p+)"), INT2FIX(args_num), base_index + 1 /* (1) */));
7835 }
7836 ADD_INSNL(ret, line_node, branchunless, match_failed);
7837
7838 {
7839 LABEL *while_begin = NEW_LABEL(nd_line(node));
7840 LABEL *next_loop = NEW_LABEL(nd_line(node));
7841 LABEL *find_succeeded = NEW_LABEL(line);
7842 LABEL *find_failed = NEW_LABEL(nd_line(node));
7843 int j;
7844
7845 ADD_INSN(ret, line_node, dup); /* allocate stack for len */
7846 ADD_SEND(ret, line_node, idLength, INT2FIX(0)); // (2)
7847
7848 ADD_INSN(ret, line_node, dup); /* allocate stack for limit */
7849 ADD_INSN1(ret, line_node, putobject, INT2FIX(args_num));
7850 ADD_SEND(ret, line_node, idMINUS, INT2FIX(1)); // (3)
7851
7852 ADD_INSN1(ret, line_node, putobject, INT2FIX(0)); /* allocate stack for i */ // (4)
7853
7854 ADD_LABEL(ret, while_begin);
7855
7856 ADD_INSN(ret, line_node, dup);
7857 ADD_INSN1(ret, line_node, topn, INT2FIX(2));
7858 ADD_SEND(ret, line_node, idLE, INT2FIX(1));
7859 ADD_INSNL(ret, line_node, branchunless, find_failed);
7860
7861 for (j = 0; j < args_num; j++) {
7862 ADD_INSN1(ret, line_node, topn, INT2FIX(3));
7863 ADD_INSN1(ret, line_node, topn, INT2FIX(1));
7864 if (j != 0) {
7865 ADD_INSN1(ret, line_node, putobject, INT2FIX(j));
7866 ADD_SEND(ret, line_node, idPLUS, INT2FIX(1));
7867 }
7868 ADD_SEND(ret, line_node, idAREF, INT2FIX(1)); // (5)
7869
7870 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_LIST(args)->nd_head, next_loop, in_single_pattern, in_alt_pattern, base_index + 4 /* (2), (3), (4), (5) */, false));
7871 args = RNODE_LIST(args)->nd_next;
7872 }
7873
7874 if (NODE_NAMED_REST_P(RNODE_FNDPTN(node)->pre_rest_arg)) {
7875 ADD_INSN1(ret, line_node, topn, INT2FIX(3));
7876 ADD_INSN1(ret, line_node, putobject, INT2FIX(0));
7877 ADD_INSN1(ret, line_node, topn, INT2FIX(2));
7878 ADD_SEND(ret, line_node, idAREF, INT2FIX(2)); // (6)
7879 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_FNDPTN(node)->pre_rest_arg, find_failed, in_single_pattern, in_alt_pattern, base_index + 4 /* (2), (3), (4), (6) */, false));
7880 }
7881 if (NODE_NAMED_REST_P(RNODE_FNDPTN(node)->post_rest_arg)) {
7882 ADD_INSN1(ret, line_node, topn, INT2FIX(3));
7883 ADD_INSN1(ret, line_node, topn, INT2FIX(1));
7884 ADD_INSN1(ret, line_node, putobject, INT2FIX(args_num));
7885 ADD_SEND(ret, line_node, idPLUS, INT2FIX(1));
7886 ADD_INSN1(ret, line_node, topn, INT2FIX(3));
7887 ADD_SEND(ret, line_node, idAREF, INT2FIX(2)); // (7)
7888 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_FNDPTN(node)->post_rest_arg, find_failed, in_single_pattern, in_alt_pattern, base_index + 4 /* (2), (3),(4), (7) */, false));
7889 }
7890 ADD_INSNL(ret, line_node, jump, find_succeeded);
7891
7892 ADD_LABEL(ret, next_loop);
7893 ADD_INSN1(ret, line_node, putobject, INT2FIX(1));
7894 ADD_SEND(ret, line_node, idPLUS, INT2FIX(1));
7895 ADD_INSNL(ret, line_node, jump, while_begin);
7896
7897 ADD_LABEL(ret, find_failed);
7898 ADD_INSN1(ret, line_node, adjuststack, INT2FIX(3));
7899 if (in_single_pattern) {
7900 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
7901 ADD_INSN1(ret, line_node, putobject, rb_fstring_lit("%p does not match to find pattern"));
7902 ADD_INSN1(ret, line_node, topn, INT2FIX(2));
7903 ADD_SEND(ret, line_node, id_core_sprintf, INT2FIX(2)); // (8)
7904 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_ERROR_STRING + 1 /* (8) */)); // (9)
7905
7906 ADD_INSN1(ret, line_node, putobject, Qfalse);
7907 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_KEY_ERROR_P + 2 /* (8), (9) */));
7908
7909 ADD_INSN(ret, line_node, pop);
7910 ADD_INSN(ret, line_node, pop);
7911 }
7912 ADD_INSNL(ret, line_node, jump, match_failed);
7913 ADD_INSN1(ret, line_node, dupn, INT2FIX(3));
7914
7915 ADD_LABEL(ret, find_succeeded);
7916 ADD_INSN1(ret, line_node, adjuststack, INT2FIX(3));
7917 }
7918
7919 ADD_INSN(ret, line_node, pop);
7920 ADD_INSNL(ret, line_node, jump, matched);
7921 ADD_INSN(ret, line_node, putnil);
7922
7923 ADD_LABEL(ret, type_error);
7924 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
7925 ADD_INSN1(ret, line_node, putobject, rb_eTypeError);
7926 ADD_INSN1(ret, line_node, putobject, rb_fstring_lit("deconstruct must return Array"));
7927 ADD_SEND(ret, line_node, id_core_raise, INT2FIX(2));
7928 ADD_INSN(ret, line_node, pop);
7929
7930 ADD_LABEL(ret, match_failed);
7931 ADD_INSN(ret, line_node, pop);
7932 ADD_INSNL(ret, line_node, jump, unmatched);
7933
7934 break;
7935 }
7936 case NODE_HSHPTN: {
7937 /*
7938 * keys = nil
7939 * if pattern.has_kw_args_node? && !pattern.has_kw_rest_arg_node?
7940 * keys = pattern.kw_args_node.keys
7941 * end
7942 * if pattern.has_constant_node?
7943 * unless pattern.constant === obj
7944 * goto match_failed
7945 * end
7946 * end
7947 * unless obj.respond_to?(:deconstruct_keys)
7948 * goto match_failed
7949 * end
7950 * d = obj.deconstruct_keys(keys)
7951 * unless Hash === d
7952 * goto type_error
7953 * end
7954 * if pattern.has_kw_rest_arg_node?
7955 * d = d.dup
7956 * end
7957 * if pattern.has_kw_args_node?
7958 * pattern.kw_args_node.each |k,|
7959 * unless d.key?(k)
7960 * goto match_failed
7961 * end
7962 * end
7963 * pattern.kw_args_node.each |k, pat|
7964 * if pattern.has_kw_rest_arg_node?
7965 * unless pat.match?(d.delete(k))
7966 * goto match_failed
7967 * end
7968 * else
7969 * unless pat.match?(d[k])
7970 * goto match_failed
7971 * end
7972 * end
7973 * end
7974 * else
7975 * unless d.empty?
7976 * goto match_failed
7977 * end
7978 * end
7979 * if pattern.has_kw_rest_arg_node?
7980 * if pattern.no_rest_keyword?
7981 * unless d.empty?
7982 * goto match_failed
7983 * end
7984 * else
7985 * unless pattern.kw_rest_arg_node.match?(d)
7986 * goto match_failed
7987 * end
7988 * end
7989 * end
7990 * goto matched
7991 * type_error:
7992 * FrozenCore.raise TypeError
7993 * match_failed:
7994 * goto unmatched
7995 */
7996 LABEL *match_failed, *type_error;
7997 VALUE keys = Qnil;
7998
7999 match_failed = NEW_LABEL(line);
8000 type_error = NEW_LABEL(line);
8001
8002 if (RNODE_HSHPTN(node)->nd_pkwargs && !RNODE_HSHPTN(node)->nd_pkwrestarg) {
8003 const NODE *kw_args = RNODE_HASH(RNODE_HSHPTN(node)->nd_pkwargs)->nd_head;
8004 keys = rb_ary_new_capa(kw_args ? RNODE_LIST(kw_args)->as.nd_alen/2 : 0);
8005 while (kw_args) {
8006 rb_ary_push(keys, get_symbol_value(iseq, RNODE_LIST(kw_args)->nd_head));
8007 kw_args = RNODE_LIST(RNODE_LIST(kw_args)->nd_next)->nd_next;
8008 }
8009 }
8010
8011 CHECK(iseq_compile_pattern_constant(iseq, ret, node, match_failed, in_single_pattern, base_index));
8012
8013 ADD_INSN(ret, line_node, dup);
8014 ADD_INSN1(ret, line_node, putobject, ID2SYM(rb_intern("deconstruct_keys")));
8015 ADD_SEND(ret, line_node, idRespond_to, INT2FIX(1)); // (1)
8016 if (in_single_pattern) {
8017 CHECK(iseq_compile_pattern_set_general_errmsg(iseq, ret, node, rb_fstring_lit("%p does not respond to #deconstruct_keys"), base_index + 1 /* (1) */));
8018 }
8019 ADD_INSNL(ret, line_node, branchunless, match_failed);
8020
8021 if (NIL_P(keys)) {
8022 ADD_INSN(ret, line_node, putnil);
8023 }
8024 else {
8026 ADD_INSN1(ret, line_node, duparray, keys);
8027 RB_OBJ_WRITTEN(iseq, Qundef, rb_obj_hide(keys));
8028 }
8029 ADD_SEND(ret, line_node, rb_intern("deconstruct_keys"), INT2FIX(1)); // (2)
8030
8031 ADD_INSN(ret, line_node, dup);
8032 ADD_INSN1(ret, line_node, checktype, INT2FIX(T_HASH));
8033 ADD_INSNL(ret, line_node, branchunless, type_error);
8034
8035 if (RNODE_HSHPTN(node)->nd_pkwrestarg) {
8036 ADD_SEND(ret, line_node, rb_intern("dup"), INT2FIX(0));
8037 }
8038
8039 if (RNODE_HSHPTN(node)->nd_pkwargs) {
8040 int i;
8041 int keys_num;
8042 const NODE *args;
8043 args = RNODE_HASH(RNODE_HSHPTN(node)->nd_pkwargs)->nd_head;
8044 if (args) {
8045 DECL_ANCHOR(match_values);
8046 INIT_ANCHOR(match_values);
8047 keys_num = rb_long2int(RNODE_LIST(args)->as.nd_alen) / 2;
8048 for (i = 0; i < keys_num; i++) {
8049 NODE *key_node = RNODE_LIST(args)->nd_head;
8050 NODE *value_node = RNODE_LIST(RNODE_LIST(args)->nd_next)->nd_head;
8051 VALUE key = get_symbol_value(iseq, key_node);
8052
8053 ADD_INSN(ret, line_node, dup);
8054 ADD_INSN1(ret, line_node, putobject, key);
8055 ADD_SEND(ret, line_node, rb_intern("key?"), INT2FIX(1)); // (3)
8056 if (in_single_pattern) {
8057 LABEL *match_succeeded;
8058 match_succeeded = NEW_LABEL(line);
8059
8060 ADD_INSN(ret, line_node, dup);
8061 ADD_INSNL(ret, line_node, branchif, match_succeeded);
8062
8063 VALUE str = rb_str_freeze(rb_sprintf("key not found: %+"PRIsVALUE, key));
8064 ADD_INSN1(ret, line_node, putobject, RB_OBJ_SET_SHAREABLE(str)); // (4)
8065 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_ERROR_STRING + 2 /* (3), (4) */));
8066 ADD_INSN1(ret, line_node, putobject, Qtrue); // (5)
8067 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_KEY_ERROR_P + 3 /* (3), (4), (5) */));
8068 ADD_INSN1(ret, line_node, topn, INT2FIX(3)); // (6)
8069 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_KEY_ERROR_MATCHEE + 4 /* (3), (4), (5), (6) */));
8070 ADD_INSN1(ret, line_node, putobject, key); // (7)
8071 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_KEY_ERROR_KEY + 5 /* (3), (4), (5), (6), (7) */));
8072
8073 ADD_INSN1(ret, line_node, adjuststack, INT2FIX(4));
8074
8075 ADD_LABEL(ret, match_succeeded);
8076 }
8077 ADD_INSNL(ret, line_node, branchunless, match_failed);
8078
8079 ADD_INSN(match_values, line_node, dup);
8080 ADD_INSN1(match_values, line_node, putobject, key);
8081 ADD_SEND(match_values, line_node, RNODE_HSHPTN(node)->nd_pkwrestarg ? rb_intern("delete") : idAREF, INT2FIX(1)); // (8)
8082 CHECK(iseq_compile_pattern_match(iseq, match_values, value_node, match_failed, in_single_pattern, in_alt_pattern, base_index + 1 /* (8) */, false));
8083 args = RNODE_LIST(RNODE_LIST(args)->nd_next)->nd_next;
8084 }
8085 ADD_SEQ(ret, match_values);
8086 }
8087 }
8088 else {
8089 ADD_INSN(ret, line_node, dup);
8090 ADD_SEND(ret, line_node, idEmptyP, INT2FIX(0)); // (9)
8091 if (in_single_pattern) {
8092 CHECK(iseq_compile_pattern_set_general_errmsg(iseq, ret, node, rb_fstring_lit("%p is not empty"), base_index + 1 /* (9) */));
8093 }
8094 ADD_INSNL(ret, line_node, branchunless, match_failed);
8095 }
8096
8097 if (RNODE_HSHPTN(node)->nd_pkwrestarg) {
8098 if (RNODE_HSHPTN(node)->nd_pkwrestarg == NODE_SPECIAL_NO_REST_KEYWORD) {
8099 ADD_INSN(ret, line_node, dup);
8100 ADD_SEND(ret, line_node, idEmptyP, INT2FIX(0)); // (10)
8101 if (in_single_pattern) {
8102 CHECK(iseq_compile_pattern_set_general_errmsg(iseq, ret, node, rb_fstring_lit("rest of %p is not empty"), base_index + 1 /* (10) */));
8103 }
8104 ADD_INSNL(ret, line_node, branchunless, match_failed);
8105 }
8106 else {
8107 ADD_INSN(ret, line_node, dup); // (11)
8108 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_HSHPTN(node)->nd_pkwrestarg, match_failed, in_single_pattern, in_alt_pattern, base_index + 1 /* (11) */, false));
8109 }
8110 }
8111
8112 ADD_INSN(ret, line_node, pop);
8113 ADD_INSNL(ret, line_node, jump, matched);
8114 ADD_INSN(ret, line_node, putnil);
8115
8116 ADD_LABEL(ret, type_error);
8117 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
8118 ADD_INSN1(ret, line_node, putobject, rb_eTypeError);
8119 ADD_INSN1(ret, line_node, putobject, rb_fstring_lit("deconstruct_keys must return Hash"));
8120 ADD_SEND(ret, line_node, id_core_raise, INT2FIX(2));
8121 ADD_INSN(ret, line_node, pop);
8122
8123 ADD_LABEL(ret, match_failed);
8124 ADD_INSN(ret, line_node, pop);
8125 ADD_INSNL(ret, line_node, jump, unmatched);
8126 break;
8127 }
8128 case NODE_SYM:
8129 case NODE_REGX:
8130 case NODE_LINE:
8131 case NODE_INTEGER:
8132 case NODE_FLOAT:
8133 case NODE_RATIONAL:
8134 case NODE_IMAGINARY:
8135 case NODE_FILE:
8136 case NODE_ENCODING:
8137 case NODE_STR:
8138 case NODE_XSTR:
8139 case NODE_DSTR:
8140 case NODE_DSYM:
8141 case NODE_DREGX:
8142 case NODE_LIST:
8143 case NODE_ZLIST:
8144 case NODE_LAMBDA:
8145 case NODE_DOT2:
8146 case NODE_DOT3:
8147 case NODE_CONST:
8148 case NODE_LVAR:
8149 case NODE_DVAR:
8150 case NODE_IVAR:
8151 case NODE_CVAR:
8152 case NODE_GVAR:
8153 case NODE_TRUE:
8154 case NODE_FALSE:
8155 case NODE_SELF:
8156 case NODE_NIL:
8157 case NODE_COLON2:
8158 case NODE_COLON3:
8159 case NODE_BEGIN:
8160 case NODE_BLOCK:
8161 case NODE_ONCE:
8162 CHECK(COMPILE(ret, "case in literal", node)); // (1)
8163 if (in_single_pattern) {
8164 ADD_INSN1(ret, line_node, dupn, INT2FIX(2));
8165 }
8166 ADD_INSN1(ret, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_CASE)); // (2)
8167 if (in_single_pattern) {
8168 CHECK(iseq_compile_pattern_set_eqq_errmsg(iseq, ret, node, base_index + 2 /* (1), (2) */));
8169 }
8170 ADD_INSNL(ret, line_node, branchif, matched);
8171 ADD_INSNL(ret, line_node, jump, unmatched);
8172 break;
8173 case NODE_LASGN: {
8174 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
8175 ID id = RNODE_LASGN(node)->nd_vid;
8176 int idx = ISEQ_BODY(body->local_iseq)->local_table_size - get_local_var_idx(iseq, id);
8177
8178 if (in_alt_pattern) {
8179 const char *name = rb_id2name(id);
8180 if (name && strlen(name) > 0 && name[0] != '_') {
8181 COMPILE_ERROR(ERROR_ARGS "illegal variable in alternative pattern (%"PRIsVALUE")",
8182 rb_id2str(id));
8183 return COMPILE_NG;
8184 }
8185 }
8186
8187 ADD_SETLOCAL(ret, line_node, idx, get_lvar_level(iseq));
8188 ADD_INSNL(ret, line_node, jump, matched);
8189 break;
8190 }
8191 case NODE_DASGN: {
8192 int idx, lv, ls;
8193 ID id = RNODE_DASGN(node)->nd_vid;
8194
8195 idx = get_dyna_var_idx(iseq, id, &lv, &ls);
8196
8197 if (in_alt_pattern) {
8198 const char *name = rb_id2name(id);
8199 if (name && strlen(name) > 0 && name[0] != '_') {
8200 COMPILE_ERROR(ERROR_ARGS "illegal variable in alternative pattern (%"PRIsVALUE")",
8201 rb_id2str(id));
8202 return COMPILE_NG;
8203 }
8204 }
8205
8206 if (idx < 0) {
8207 COMPILE_ERROR(ERROR_ARGS "NODE_DASGN: unknown id (%"PRIsVALUE")",
8208 rb_id2str(id));
8209 return COMPILE_NG;
8210 }
8211 ADD_SETLOCAL(ret, line_node, ls - idx, lv);
8212 ADD_INSNL(ret, line_node, jump, matched);
8213 break;
8214 }
8215 case NODE_IF:
8216 case NODE_UNLESS: {
8217 LABEL *match_failed;
8218 match_failed = unmatched;
8219 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_IF(node)->nd_body, unmatched, in_single_pattern, in_alt_pattern, base_index, use_deconstructed_cache));
8220 CHECK(COMPILE(ret, "case in if", RNODE_IF(node)->nd_cond));
8221 if (in_single_pattern) {
8222 LABEL *match_succeeded;
8223 match_succeeded = NEW_LABEL(line);
8224
8225 ADD_INSN(ret, line_node, dup);
8226 if (nd_type_p(node, NODE_IF)) {
8227 ADD_INSNL(ret, line_node, branchif, match_succeeded);
8228 }
8229 else {
8230 ADD_INSNL(ret, line_node, branchunless, match_succeeded);
8231 }
8232
8233 ADD_INSN1(ret, line_node, putobject, rb_fstring_lit("guard clause does not return true")); // (1)
8234 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_ERROR_STRING + 1 /* (1) */)); // (2)
8235 ADD_INSN1(ret, line_node, putobject, Qfalse);
8236 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_KEY_ERROR_P + 2 /* (1), (2) */));
8237
8238 ADD_INSN(ret, line_node, pop);
8239 ADD_INSN(ret, line_node, pop);
8240
8241 ADD_LABEL(ret, match_succeeded);
8242 }
8243 if (nd_type_p(node, NODE_IF)) {
8244 ADD_INSNL(ret, line_node, branchunless, match_failed);
8245 }
8246 else {
8247 ADD_INSNL(ret, line_node, branchif, match_failed);
8248 }
8249 ADD_INSNL(ret, line_node, jump, matched);
8250 break;
8251 }
8252 case NODE_HASH: {
8253 NODE *n;
8254 LABEL *match_failed;
8255 match_failed = NEW_LABEL(line);
8256
8257 n = RNODE_HASH(node)->nd_head;
8258 if (! (nd_type_p(n, NODE_LIST) && RNODE_LIST(n)->as.nd_alen == 2)) {
8259 COMPILE_ERROR(ERROR_ARGS "unexpected node");
8260 return COMPILE_NG;
8261 }
8262
8263 ADD_INSN(ret, line_node, dup); // (1)
8264 CHECK(iseq_compile_pattern_match(iseq, ret, RNODE_LIST(n)->nd_head, match_failed, in_single_pattern, in_alt_pattern, base_index + 1 /* (1) */, use_deconstructed_cache));
8265 CHECK(iseq_compile_pattern_each(iseq, ret, RNODE_LIST(RNODE_LIST(n)->nd_next)->nd_head, matched, match_failed, in_single_pattern, in_alt_pattern, base_index, false));
8266 ADD_INSN(ret, line_node, putnil);
8267
8268 ADD_LABEL(ret, match_failed);
8269 ADD_INSN(ret, line_node, pop);
8270 ADD_INSNL(ret, line_node, jump, unmatched);
8271 break;
8272 }
8273 case NODE_OR: {
8274 LABEL *match_succeeded, *fin;
8275 match_succeeded = NEW_LABEL(line);
8276 fin = NEW_LABEL(line);
8277
8278 ADD_INSN(ret, line_node, dup); // (1)
8279 CHECK(iseq_compile_pattern_each(iseq, ret, RNODE_OR(node)->nd_1st, match_succeeded, fin, in_single_pattern, true, base_index + 1 /* (1) */, use_deconstructed_cache));
8280 ADD_LABEL(ret, match_succeeded);
8281 ADD_INSN(ret, line_node, pop);
8282 ADD_INSNL(ret, line_node, jump, matched);
8283 ADD_INSN(ret, line_node, putnil);
8284 ADD_LABEL(ret, fin);
8285 CHECK(iseq_compile_pattern_each(iseq, ret, RNODE_OR(node)->nd_2nd, matched, unmatched, in_single_pattern, true, base_index, use_deconstructed_cache));
8286 break;
8287 }
8288 default:
8289 UNKNOWN_NODE("NODE_IN", node, COMPILE_NG);
8290 }
8291 return COMPILE_OK;
8292}
8293
8294static int
8295iseq_compile_pattern_match(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, LABEL *unmatched, bool in_single_pattern, bool in_alt_pattern, int base_index, bool use_deconstructed_cache)
8296{
8297 LABEL *fin = NEW_LABEL(nd_line(node));
8298 CHECK(iseq_compile_pattern_each(iseq, ret, node, fin, unmatched, in_single_pattern, in_alt_pattern, base_index, use_deconstructed_cache));
8299 ADD_LABEL(ret, fin);
8300 return COMPILE_OK;
8301}
8302
8303static int
8304iseq_compile_pattern_constant(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, LABEL *match_failed, bool in_single_pattern, int base_index)
8305{
8306 const NODE *line_node = node;
8307
8308 if (RNODE_ARYPTN(node)->nd_pconst) {
8309 ADD_INSN(ret, line_node, dup); // (1)
8310 CHECK(COMPILE(ret, "constant", RNODE_ARYPTN(node)->nd_pconst)); // (2)
8311 if (in_single_pattern) {
8312 ADD_INSN1(ret, line_node, dupn, INT2FIX(2));
8313 }
8314 ADD_INSN1(ret, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_CASE)); // (3)
8315 if (in_single_pattern) {
8316 CHECK(iseq_compile_pattern_set_eqq_errmsg(iseq, ret, node, base_index + 3 /* (1), (2), (3) */));
8317 }
8318 ADD_INSNL(ret, line_node, branchunless, match_failed);
8319 }
8320 return COMPILE_OK;
8321}
8322
8323
8324static int
8325iseq_compile_array_deconstruct(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, LABEL *deconstruct, LABEL *deconstructed, LABEL *match_failed, LABEL *type_error, bool in_single_pattern, int base_index, bool use_deconstructed_cache)
8326{
8327 const NODE *line_node = node;
8328
8329 // NOTE: this optimization allows us to re-use the #deconstruct value
8330 // (or its absence).
8331 if (use_deconstructed_cache) {
8332 // If value is nil then we haven't tried to deconstruct
8333 ADD_INSN1(ret, line_node, topn, INT2FIX(base_index + CASE3_BI_OFFSET_DECONSTRUCTED_CACHE));
8334 ADD_INSNL(ret, line_node, branchnil, deconstruct);
8335
8336 // If false then the value is not deconstructable
8337 ADD_INSN1(ret, line_node, topn, INT2FIX(base_index + CASE3_BI_OFFSET_DECONSTRUCTED_CACHE));
8338 ADD_INSNL(ret, line_node, branchunless, match_failed);
8339
8340 // Drop value, add deconstructed to the stack and jump
8341 ADD_INSN(ret, line_node, pop); // (1)
8342 ADD_INSN1(ret, line_node, topn, INT2FIX(base_index + CASE3_BI_OFFSET_DECONSTRUCTED_CACHE - 1 /* (1) */));
8343 ADD_INSNL(ret, line_node, jump, deconstructed);
8344 }
8345 else {
8346 ADD_INSNL(ret, line_node, jump, deconstruct);
8347 }
8348
8349 ADD_LABEL(ret, deconstruct);
8350 ADD_INSN(ret, line_node, dup);
8351 ADD_INSN1(ret, line_node, putobject, ID2SYM(rb_intern("deconstruct")));
8352 ADD_SEND(ret, line_node, idRespond_to, INT2FIX(1)); // (2)
8353
8354 // Cache the result of respond_to? (in case it's false is stays there, if true - it's overwritten after #deconstruct)
8355 if (use_deconstructed_cache) {
8356 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_DECONSTRUCTED_CACHE + 1 /* (2) */));
8357 }
8358
8359 if (in_single_pattern) {
8360 CHECK(iseq_compile_pattern_set_general_errmsg(iseq, ret, node, rb_fstring_lit("%p does not respond to #deconstruct"), base_index + 1 /* (2) */));
8361 }
8362
8363 ADD_INSNL(ret, line_node, branchunless, match_failed);
8364
8365 ADD_SEND(ret, line_node, rb_intern("deconstruct"), INT2FIX(0));
8366
8367 // Cache the result (if it's cacheable - currently, only top-level array patterns)
8368 if (use_deconstructed_cache) {
8369 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_DECONSTRUCTED_CACHE));
8370 }
8371
8372 ADD_INSN(ret, line_node, dup);
8373 ADD_INSN1(ret, line_node, checktype, INT2FIX(T_ARRAY));
8374 ADD_INSNL(ret, line_node, branchunless, type_error);
8375
8376 ADD_LABEL(ret, deconstructed);
8377
8378 return COMPILE_OK;
8379}
8380
8381static int
8382iseq_compile_pattern_set_general_errmsg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, VALUE errmsg, int base_index)
8383{
8384 /*
8385 * if match_succeeded?
8386 * goto match_succeeded
8387 * end
8388 * error_string = FrozenCore.sprintf(errmsg, matchee)
8389 * key_error_p = false
8390 * match_succeeded:
8391 */
8392 const int line = nd_line(node);
8393 const NODE *line_node = node;
8394 LABEL *match_succeeded = NEW_LABEL(line);
8395
8396 ADD_INSN(ret, line_node, dup);
8397 ADD_INSNL(ret, line_node, branchif, match_succeeded);
8398
8399 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
8400 ADD_INSN1(ret, line_node, putobject, errmsg);
8401 ADD_INSN1(ret, line_node, topn, INT2FIX(3));
8402 ADD_SEND(ret, line_node, id_core_sprintf, INT2FIX(2)); // (1)
8403 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_ERROR_STRING + 1 /* (1) */)); // (2)
8404
8405 ADD_INSN1(ret, line_node, putobject, Qfalse);
8406 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_KEY_ERROR_P + 2 /* (1), (2) */));
8407
8408 ADD_INSN(ret, line_node, pop);
8409 ADD_INSN(ret, line_node, pop);
8410 ADD_LABEL(ret, match_succeeded);
8411
8412 return COMPILE_OK;
8413}
8414
8415static int
8416iseq_compile_pattern_set_length_errmsg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, VALUE errmsg, VALUE pattern_length, int base_index)
8417{
8418 /*
8419 * if match_succeeded?
8420 * goto match_succeeded
8421 * end
8422 * error_string = FrozenCore.sprintf(errmsg, matchee, matchee.length, pat.length)
8423 * key_error_p = false
8424 * match_succeeded:
8425 */
8426 const int line = nd_line(node);
8427 const NODE *line_node = node;
8428 LABEL *match_succeeded = NEW_LABEL(line);
8429
8430 ADD_INSN(ret, line_node, dup);
8431 ADD_INSNL(ret, line_node, branchif, match_succeeded);
8432
8433 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
8434 ADD_INSN1(ret, line_node, putobject, errmsg);
8435 ADD_INSN1(ret, line_node, topn, INT2FIX(3));
8436 ADD_INSN(ret, line_node, dup);
8437 ADD_SEND(ret, line_node, idLength, INT2FIX(0));
8438 ADD_INSN1(ret, line_node, putobject, pattern_length);
8439 ADD_SEND(ret, line_node, id_core_sprintf, INT2FIX(4)); // (1)
8440 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_ERROR_STRING + 1 /* (1) */)); // (2)
8441
8442 ADD_INSN1(ret, line_node, putobject, Qfalse);
8443 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_KEY_ERROR_P + 2/* (1), (2) */));
8444
8445 ADD_INSN(ret, line_node, pop);
8446 ADD_INSN(ret, line_node, pop);
8447 ADD_LABEL(ret, match_succeeded);
8448
8449 return COMPILE_OK;
8450}
8451
8452static int
8453iseq_compile_pattern_set_eqq_errmsg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int base_index)
8454{
8455 /*
8456 * if match_succeeded?
8457 * goto match_succeeded
8458 * end
8459 * error_string = FrozenCore.sprintf("%p === %p does not return true", pat, matchee)
8460 * key_error_p = false
8461 * match_succeeded:
8462 */
8463 const int line = nd_line(node);
8464 const NODE *line_node = node;
8465 LABEL *match_succeeded = NEW_LABEL(line);
8466
8467 ADD_INSN(ret, line_node, dup);
8468 ADD_INSNL(ret, line_node, branchif, match_succeeded);
8469
8470 ADD_INSN1(ret, line_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
8471 ADD_INSN1(ret, line_node, putobject, rb_fstring_lit("%p === %p does not return true"));
8472 ADD_INSN1(ret, line_node, topn, INT2FIX(3));
8473 ADD_INSN1(ret, line_node, topn, INT2FIX(5));
8474 ADD_SEND(ret, line_node, id_core_sprintf, INT2FIX(3)); // (1)
8475 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_ERROR_STRING + 1 /* (1) */)); // (2)
8476
8477 ADD_INSN1(ret, line_node, putobject, Qfalse);
8478 ADD_INSN1(ret, line_node, setn, INT2FIX(base_index + CASE3_BI_OFFSET_KEY_ERROR_P + 2 /* (1), (2) */));
8479
8480 ADD_INSN(ret, line_node, pop);
8481 ADD_INSN(ret, line_node, pop);
8482
8483 ADD_LABEL(ret, match_succeeded);
8484 ADD_INSN1(ret, line_node, setn, INT2FIX(2));
8485 ADD_INSN(ret, line_node, pop);
8486 ADD_INSN(ret, line_node, pop);
8487
8488 return COMPILE_OK;
8489}
8490
8491static int
8492compile_case3(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const orig_node, int popped)
8493{
8494 const NODE *pattern;
8495 const NODE *node = orig_node;
8496 LABEL *endlabel, *elselabel;
8497 DECL_ANCHOR(head);
8498 DECL_ANCHOR(body_seq);
8499 DECL_ANCHOR(cond_seq);
8500 int line;
8501 enum node_type type;
8502 const NODE *line_node;
8503 VALUE branches = 0;
8504 int branch_id = 0;
8505 bool single_pattern;
8506
8507 INIT_ANCHOR(head);
8508 INIT_ANCHOR(body_seq);
8509 INIT_ANCHOR(cond_seq);
8510
8511 branches = decl_branch_base(iseq, nd_node_id(node), nd_code_loc(node), "case");
8512
8513 node = RNODE_CASE3(node)->nd_body;
8514 EXPECT_NODE("NODE_CASE3", node, NODE_IN, COMPILE_NG);
8515 type = nd_type(node);
8516 line = nd_line(node);
8517 line_node = node;
8518 single_pattern = !RNODE_IN(node)->nd_next;
8519
8520 endlabel = NEW_LABEL(line);
8521 elselabel = NEW_LABEL(line);
8522
8523 if (single_pattern) {
8524 /* allocate stack for ... */
8525 ADD_INSN(head, line_node, putnil); /* key_error_key */
8526 ADD_INSN(head, line_node, putnil); /* key_error_matchee */
8527 ADD_INSN1(head, line_node, putobject, Qfalse); /* key_error_p */
8528 ADD_INSN(head, line_node, putnil); /* error_string */
8529 }
8530 ADD_INSN(head, line_node, putnil); /* allocate stack for cached #deconstruct value */
8531
8532 CHECK(COMPILE(head, "case base", RNODE_CASE3(orig_node)->nd_head));
8533
8534 ADD_SEQ(ret, head); /* case VAL */
8535
8536 while (type == NODE_IN) {
8537 LABEL *l1;
8538
8539 if (branch_id) {
8540 ADD_INSN(body_seq, line_node, putnil);
8541 }
8542 l1 = NEW_LABEL(line);
8543 ADD_LABEL(body_seq, l1);
8544 ADD_INSN1(body_seq, line_node, adjuststack, INT2FIX(single_pattern ? 6 : 2));
8545
8546 const NODE *const coverage_node = RNODE_IN(node)->nd_body ? RNODE_IN(node)->nd_body : node;
8547 add_trace_branch_coverage(
8548 iseq,
8549 body_seq,
8550 nd_code_loc(coverage_node),
8551 nd_node_id(coverage_node),
8552 branch_id++,
8553 "in",
8554 branches);
8555
8556 CHECK(COMPILE_(body_seq, "in body", RNODE_IN(node)->nd_body, popped));
8557 ADD_INSNL(body_seq, line_node, jump, endlabel);
8558
8559 pattern = RNODE_IN(node)->nd_head;
8560 if (pattern) {
8561 int pat_line = nd_line(pattern);
8562 LABEL *next_pat = NEW_LABEL(pat_line);
8563 ADD_INSN (cond_seq, pattern, dup); /* dup case VAL */
8564 // NOTE: set base_index (it's "under" the matchee value, so it's position is 2)
8565 CHECK(iseq_compile_pattern_each(iseq, cond_seq, pattern, l1, next_pat, single_pattern, false, 2, true));
8566 ADD_LABEL(cond_seq, next_pat);
8567 LABEL_UNREMOVABLE(next_pat);
8568 }
8569 else {
8570 COMPILE_ERROR(ERROR_ARGS "unexpected node");
8571 return COMPILE_NG;
8572 }
8573
8574 node = RNODE_IN(node)->nd_next;
8575 if (!node) {
8576 break;
8577 }
8578 type = nd_type(node);
8579 line = nd_line(node);
8580 line_node = node;
8581 }
8582 /* else */
8583 if (node) {
8584 ADD_LABEL(cond_seq, elselabel);
8585 ADD_INSN(cond_seq, line_node, pop);
8586 ADD_INSN(cond_seq, line_node, pop); /* discard cached #deconstruct value */
8587 add_trace_branch_coverage(iseq, cond_seq, nd_code_loc(node), nd_node_id(node), branch_id, "else", branches);
8588 CHECK(COMPILE_(cond_seq, "else", node, popped));
8589 ADD_INSNL(cond_seq, line_node, jump, endlabel);
8590 ADD_INSN(cond_seq, line_node, putnil);
8591 if (popped) {
8592 ADD_INSN(cond_seq, line_node, putnil);
8593 }
8594 }
8595 else {
8596 debugs("== else (implicit)\n");
8597 ADD_LABEL(cond_seq, elselabel);
8598 add_trace_branch_coverage(iseq, cond_seq, nd_code_loc(orig_node), nd_node_id(orig_node), branch_id, "else", branches);
8599 ADD_INSN1(cond_seq, orig_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
8600
8601 if (single_pattern) {
8602 /*
8603 * if key_error_p
8604 * FrozenCore.raise NoMatchingPatternKeyError.new(FrozenCore.sprintf("%p: %s", case_val, error_string), matchee: key_error_matchee, key: key_error_key)
8605 * else
8606 * FrozenCore.raise NoMatchingPatternError, FrozenCore.sprintf("%p: %s", case_val, error_string)
8607 * end
8608 */
8609 LABEL *key_error, *fin;
8610 struct rb_callinfo_kwarg *kw_arg;
8611
8612 key_error = NEW_LABEL(line);
8613 fin = NEW_LABEL(line);
8614
8615 kw_arg = rb_xmalloc_mul_add(2, sizeof(VALUE), sizeof(struct rb_callinfo_kwarg));
8616 kw_arg->references = 0;
8617 kw_arg->keyword_len = 2;
8618 kw_arg->keywords[0] = ID2SYM(rb_intern("matchee"));
8619 kw_arg->keywords[1] = ID2SYM(rb_intern("key"));
8620
8621 ADD_INSN1(cond_seq, orig_node, topn, INT2FIX(CASE3_BI_OFFSET_KEY_ERROR_P + 2));
8622 ADD_INSNL(cond_seq, orig_node, branchif, key_error);
8623 ADD_INSN1(cond_seq, orig_node, putobject, rb_eNoMatchingPatternError);
8624 ADD_INSN1(cond_seq, orig_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
8625 ADD_INSN1(cond_seq, orig_node, putobject, rb_fstring_lit("%p: %s"));
8626 ADD_INSN1(cond_seq, orig_node, topn, INT2FIX(4)); /* case VAL */
8627 ADD_INSN1(cond_seq, orig_node, topn, INT2FIX(CASE3_BI_OFFSET_ERROR_STRING + 6));
8628 ADD_SEND(cond_seq, orig_node, id_core_sprintf, INT2FIX(3));
8629 ADD_SEND(cond_seq, orig_node, id_core_raise, INT2FIX(2));
8630 ADD_INSNL(cond_seq, orig_node, jump, fin);
8631
8632 ADD_LABEL(cond_seq, key_error);
8633 ADD_INSN1(cond_seq, orig_node, putobject, rb_eNoMatchingPatternKeyError);
8634 ADD_INSN1(cond_seq, orig_node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
8635 ADD_INSN1(cond_seq, orig_node, putobject, rb_fstring_lit("%p: %s"));
8636 ADD_INSN1(cond_seq, orig_node, topn, INT2FIX(4)); /* case VAL */
8637 ADD_INSN1(cond_seq, orig_node, topn, INT2FIX(CASE3_BI_OFFSET_ERROR_STRING + 6));
8638 ADD_SEND(cond_seq, orig_node, id_core_sprintf, INT2FIX(3));
8639 ADD_INSN1(cond_seq, orig_node, topn, INT2FIX(CASE3_BI_OFFSET_KEY_ERROR_MATCHEE + 4));
8640 ADD_INSN1(cond_seq, orig_node, topn, INT2FIX(CASE3_BI_OFFSET_KEY_ERROR_KEY + 5));
8641 ADD_SEND_R(cond_seq, orig_node, rb_intern("new"), INT2FIX(1), NULL, INT2FIX(VM_CALL_KWARG), kw_arg);
8642 ADD_SEND(cond_seq, orig_node, id_core_raise, INT2FIX(1));
8643
8644 ADD_LABEL(cond_seq, fin);
8645 }
8646 else {
8647 ADD_INSN1(cond_seq, orig_node, putobject, rb_eNoMatchingPatternError);
8648 ADD_INSN1(cond_seq, orig_node, topn, INT2FIX(2));
8649 ADD_SEND(cond_seq, orig_node, id_core_raise, INT2FIX(2));
8650 }
8651 ADD_INSN1(cond_seq, orig_node, adjuststack, INT2FIX(single_pattern ? 7 : 3));
8652 if (!popped) {
8653 ADD_INSN(cond_seq, orig_node, putnil);
8654 }
8655 ADD_INSNL(cond_seq, orig_node, jump, endlabel);
8656 ADD_INSN1(cond_seq, orig_node, dupn, INT2FIX(single_pattern ? 5 : 1));
8657 if (popped) {
8658 ADD_INSN(cond_seq, line_node, putnil);
8659 }
8660 }
8661
8662 ADD_SEQ(ret, cond_seq);
8663 ADD_SEQ(ret, body_seq);
8664 ADD_LABEL(ret, endlabel);
8665 return COMPILE_OK;
8666}
8667
8668#undef CASE3_BI_OFFSET_DECONSTRUCTED_CACHE
8669#undef CASE3_BI_OFFSET_ERROR_STRING
8670#undef CASE3_BI_OFFSET_KEY_ERROR_P
8671#undef CASE3_BI_OFFSET_KEY_ERROR_MATCHEE
8672#undef CASE3_BI_OFFSET_KEY_ERROR_KEY
8673
8674static int
8675compile_loop(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped, const enum node_type type)
8676{
8677 const int line = (int)nd_line(node);
8678 const NODE *line_node = node;
8679 int result = COMPILE_OK;
8680
8681 LABEL *prev_start_label = ISEQ_COMPILE_DATA(iseq)->start_label;
8682 LABEL *prev_end_label = ISEQ_COMPILE_DATA(iseq)->end_label;
8683 LABEL *prev_redo_label = ISEQ_COMPILE_DATA(iseq)->redo_label;
8684 int prev_loopval_popped = ISEQ_COMPILE_DATA(iseq)->loopval_popped;
8685 VALUE branches = Qfalse;
8686
8688
8689 LABEL *next_label = ISEQ_COMPILE_DATA(iseq)->start_label = NEW_LABEL(line); /* next */
8690 LABEL *redo_label = ISEQ_COMPILE_DATA(iseq)->redo_label = NEW_LABEL(line); /* redo */
8691 LABEL *break_label = ISEQ_COMPILE_DATA(iseq)->end_label = NEW_LABEL(line); /* break */
8692 LABEL *end_label = NEW_LABEL(line);
8693 LABEL *adjust_label = NEW_LABEL(line);
8694
8695 LABEL *next_catch_label = NEW_LABEL(line);
8696 LABEL *tmp_label = NULL;
8697
8698 ISEQ_COMPILE_DATA(iseq)->loopval_popped = 0;
8699 push_ensure_entry(iseq, &enl, NULL, NULL);
8700
8701 if (RNODE_WHILE(node)->nd_state == 1) {
8702 ADD_INSNL(ret, line_node, jump, next_label);
8703 }
8704 else {
8705 tmp_label = NEW_LABEL(line);
8706 ADD_INSNL(ret, line_node, jump, tmp_label);
8707 }
8708 ADD_LABEL(ret, adjust_label);
8709 ADD_INSN(ret, line_node, putnil);
8710 ADD_LABEL(ret, next_catch_label);
8711 ADD_INSN(ret, line_node, pop);
8712 ADD_INSNL(ret, line_node, jump, next_label);
8713 if (tmp_label) ADD_LABEL(ret, tmp_label);
8714
8715 ADD_LABEL(ret, redo_label);
8716 branches = decl_branch_base(iseq, nd_node_id(node), nd_code_loc(node), type == NODE_WHILE ? "while" : "until");
8717
8718 const NODE *const coverage_node = RNODE_WHILE(node)->nd_body ? RNODE_WHILE(node)->nd_body : node;
8719 add_trace_branch_coverage(
8720 iseq,
8721 ret,
8722 nd_code_loc(coverage_node),
8723 nd_node_id(coverage_node),
8724 0,
8725 "body",
8726 branches);
8727
8728 if (!COMPILE_POPPED(ret, "while body", RNODE_WHILE(node)->nd_body)) {
8729 result = COMPILE_NG;
8730 goto cleanup;
8731 }
8732 ADD_LABEL(ret, next_label); /* next */
8733
8734 if (type == NODE_WHILE) {
8735 if (!compile_branch_condition(iseq, ret, RNODE_WHILE(node)->nd_cond,
8736 redo_label, end_label)) {
8737 result = COMPILE_NG;
8738 goto cleanup;
8739 }
8740 }
8741 else {
8742 /* until */
8743 if (!compile_branch_condition(iseq, ret, RNODE_WHILE(node)->nd_cond,
8744 end_label, redo_label)) {
8745 result = COMPILE_NG;
8746 goto cleanup;
8747 }
8748 }
8749
8750 ADD_LABEL(ret, end_label);
8751 ADD_ADJUST_RESTORE(ret, adjust_label);
8752
8753 if (UNDEF_P(RNODE_WHILE(node)->nd_state)) {
8754 /* ADD_INSN(ret, line_node, putundef); */
8755 COMPILE_ERROR(ERROR_ARGS "unsupported: putundef");
8756 result = COMPILE_NG;
8757 goto cleanup;
8758 }
8759 else {
8760 ADD_INSN(ret, line_node, putnil);
8761 }
8762
8763 ADD_LABEL(ret, break_label); /* break */
8764
8765 if (popped) {
8766 ADD_INSN(ret, line_node, pop);
8767 }
8768
8769 ADD_CATCH_ENTRY(CATCH_TYPE_BREAK, redo_label, break_label, NULL,
8770 break_label);
8771 ADD_CATCH_ENTRY(CATCH_TYPE_NEXT, redo_label, break_label, NULL,
8772 next_catch_label);
8773 ADD_CATCH_ENTRY(CATCH_TYPE_REDO, redo_label, break_label, NULL,
8774 ISEQ_COMPILE_DATA(iseq)->redo_label);
8775
8776 cleanup:
8777 ISEQ_COMPILE_DATA(iseq)->start_label = prev_start_label;
8778 ISEQ_COMPILE_DATA(iseq)->end_label = prev_end_label;
8779 ISEQ_COMPILE_DATA(iseq)->redo_label = prev_redo_label;
8780 ISEQ_COMPILE_DATA(iseq)->loopval_popped = prev_loopval_popped;
8781 ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = enl.prev;
8782 return result;
8783}
8784
8785static int
8786compile_iter(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
8787{
8788 const int line = nd_line(node);
8789 const NODE *line_node = node;
8790 const rb_iseq_t *prevblock = ISEQ_COMPILE_DATA(iseq)->current_block;
8791 LABEL *retry_label = NEW_LABEL(line);
8792 LABEL *retry_end_l = NEW_LABEL(line);
8793 const rb_iseq_t *child_iseq;
8794
8795 ADD_LABEL(ret, retry_label);
8796 if (nd_type_p(node, NODE_FOR)) {
8797 CHECK(COMPILE(ret, "iter caller (for)", RNODE_FOR(node)->nd_iter));
8798
8799 ISEQ_COMPILE_DATA(iseq)->current_block = child_iseq =
8800 NEW_CHILD_ISEQ(RNODE_FOR(node)->nd_body, make_name_for_block(iseq),
8801 ISEQ_TYPE_BLOCK, line);
8802 ADD_SEND_WITH_BLOCK(ret, line_node, idEach, INT2FIX(0), child_iseq);
8803 }
8804 else {
8805 ISEQ_COMPILE_DATA(iseq)->current_block = child_iseq =
8806 NEW_CHILD_ISEQ(RNODE_ITER(node)->nd_body, make_name_for_block(iseq),
8807 ISEQ_TYPE_BLOCK, line);
8808 CHECK(COMPILE(ret, "iter caller", RNODE_ITER(node)->nd_iter));
8809 }
8810
8811 {
8812 // We need to put the label "retry_end_l" immediately after the last "send" instruction.
8813 // This because vm_throw checks if the break cont is equal to the index of next insn of the "send".
8814 // (Otherwise, it is considered "break from proc-closure". See "TAG_BREAK" handling in "vm_throw_start".)
8815 //
8816 // Normally, "send" instruction is at the last.
8817 // However, qcall under branch coverage measurement adds some instructions after the "send".
8818 //
8819 // Note that "invokesuper", "invokesuperforward" appears instead of "send".
8820 INSN *iobj;
8821 LINK_ELEMENT *last_elem = LAST_ELEMENT(ret);
8822 iobj = IS_INSN(last_elem) ? (INSN*) last_elem : (INSN*) get_prev_insn((INSN*) last_elem);
8823 while (!IS_INSN_ID(iobj, send) && !IS_INSN_ID(iobj, invokesuper) && !IS_INSN_ID(iobj, sendforward) && !IS_INSN_ID(iobj, invokesuperforward)) {
8824 iobj = (INSN*) get_prev_insn(iobj);
8825 }
8826 ELEM_INSERT_NEXT(&iobj->link, (LINK_ELEMENT*) retry_end_l);
8827
8828 // LINK_ANCHOR has a pointer to the last element, but ELEM_INSERT_NEXT does not update it
8829 // even if we add an insn to the last of LINK_ANCHOR. So this updates it manually.
8830 if (&iobj->link == LAST_ELEMENT(ret)) {
8831 ret->last = (LINK_ELEMENT*) retry_end_l;
8832 }
8833 }
8834
8835 if (popped) {
8836 ADD_INSN(ret, line_node, pop);
8837 }
8838
8839 ISEQ_COMPILE_DATA(iseq)->current_block = prevblock;
8840
8841 ADD_CATCH_ENTRY(CATCH_TYPE_BREAK, retry_label, retry_end_l, child_iseq, retry_end_l);
8842 return COMPILE_OK;
8843}
8844
8845static int
8846compile_for_masgn(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
8847{
8848 /* massign to var in "for"
8849 * (args.length == 1 && Array.try_convert(args[0])) || args
8850 */
8851 const NODE *line_node = node;
8852 const NODE *var = RNODE_FOR_MASGN(node)->nd_var;
8853 LABEL *not_single = NEW_LABEL(nd_line(var));
8854 LABEL *not_ary = NEW_LABEL(nd_line(var));
8855 CHECK(COMPILE(ret, "for var", var));
8856 ADD_INSN(ret, line_node, dup);
8857 ADD_CALL(ret, line_node, idLength, INT2FIX(0));
8858 ADD_INSN1(ret, line_node, putobject, INT2FIX(1));
8859 ADD_CALL(ret, line_node, idEq, INT2FIX(1));
8860 ADD_INSNL(ret, line_node, branchunless, not_single);
8861 ADD_INSN(ret, line_node, dup);
8862 ADD_INSN1(ret, line_node, putobject, INT2FIX(0));
8863 ADD_CALL(ret, line_node, idAREF, INT2FIX(1));
8864 ADD_INSN1(ret, line_node, putobject, rb_cArray);
8865 ADD_INSN(ret, line_node, swap);
8866 ADD_CALL(ret, line_node, rb_intern("try_convert"), INT2FIX(1));
8867 ADD_INSN(ret, line_node, dup);
8868 ADD_INSNL(ret, line_node, branchunless, not_ary);
8869 ADD_INSN(ret, line_node, swap);
8870 ADD_LABEL(ret, not_ary);
8871 ADD_INSN(ret, line_node, pop);
8872 ADD_LABEL(ret, not_single);
8873 return COMPILE_OK;
8874}
8875
8876static int
8877compile_break(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
8878{
8879 const NODE *line_node = node;
8880 unsigned long throw_flag = 0;
8881
8882 if (ISEQ_COMPILE_DATA(iseq)->redo_label != 0 && can_add_ensure_iseq(iseq)) {
8883 /* while/until */
8884 LABEL *splabel = NEW_LABEL(0);
8885 ADD_LABEL(ret, splabel);
8886 ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->redo_label);
8887 CHECK(COMPILE_(ret, "break val (while/until)", RNODE_BREAK(node)->nd_stts,
8888 ISEQ_COMPILE_DATA(iseq)->loopval_popped));
8889 add_ensure_iseq(ret, iseq, 0);
8890 ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->end_label);
8891 ADD_ADJUST_RESTORE(ret, splabel);
8892
8893 if (!popped) {
8894 ADD_INSN(ret, line_node, putnil);
8895 }
8896 }
8897 else {
8898 const rb_iseq_t *ip = iseq;
8899
8900 while (ip) {
8901 if (!ISEQ_COMPILE_DATA(ip)) {
8902 ip = 0;
8903 break;
8904 }
8905
8906 if (ISEQ_COMPILE_DATA(ip)->redo_label != 0) {
8907 throw_flag = VM_THROW_NO_ESCAPE_FLAG;
8908 }
8909 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_BLOCK) {
8910 throw_flag = 0;
8911 }
8912 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_EVAL) {
8913 COMPILE_ERROR(ERROR_ARGS "Can't escape from eval with break");
8914 return COMPILE_NG;
8915 }
8916 else {
8917 ip = ISEQ_BODY(ip)->parent_iseq;
8918 continue;
8919 }
8920
8921 /* escape from block */
8922 CHECK(COMPILE(ret, "break val (block)", RNODE_BREAK(node)->nd_stts));
8923 ADD_INSN1(ret, line_node, throw, INT2FIX(throw_flag | TAG_BREAK));
8924 if (popped) {
8925 ADD_INSN(ret, line_node, pop);
8926 }
8927 return COMPILE_OK;
8928 }
8929 COMPILE_ERROR(ERROR_ARGS "Invalid break");
8930 return COMPILE_NG;
8931 }
8932 return COMPILE_OK;
8933}
8934
8935static int
8936compile_next(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
8937{
8938 const NODE *line_node = node;
8939 unsigned long throw_flag = 0;
8940
8941 if (ISEQ_COMPILE_DATA(iseq)->redo_label != 0 && can_add_ensure_iseq(iseq)) {
8942 LABEL *splabel = NEW_LABEL(0);
8943 debugs("next in while loop\n");
8944 ADD_LABEL(ret, splabel);
8945 CHECK(COMPILE(ret, "next val/valid syntax?", RNODE_NEXT(node)->nd_stts));
8946 add_ensure_iseq(ret, iseq, 0);
8947 ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->redo_label);
8948 ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->start_label);
8949 ADD_ADJUST_RESTORE(ret, splabel);
8950 if (!popped) {
8951 ADD_INSN(ret, line_node, putnil);
8952 }
8953 }
8954 else if (ISEQ_COMPILE_DATA(iseq)->end_label && can_add_ensure_iseq(iseq)) {
8955 LABEL *splabel = NEW_LABEL(0);
8956 debugs("next in block\n");
8957 ADD_LABEL(ret, splabel);
8958 ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->start_label);
8959 CHECK(COMPILE(ret, "next val", RNODE_NEXT(node)->nd_stts));
8960 add_ensure_iseq(ret, iseq, 0);
8961 ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->end_label);
8962 ADD_ADJUST_RESTORE(ret, splabel);
8963
8964 if (!popped) {
8965 ADD_INSN(ret, line_node, putnil);
8966 }
8967 }
8968 else {
8969 const rb_iseq_t *ip = iseq;
8970
8971 while (ip) {
8972 if (!ISEQ_COMPILE_DATA(ip)) {
8973 ip = 0;
8974 break;
8975 }
8976
8977 throw_flag = VM_THROW_NO_ESCAPE_FLAG;
8978 if (ISEQ_COMPILE_DATA(ip)->redo_label != 0) {
8979 /* while loop */
8980 break;
8981 }
8982 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_BLOCK) {
8983 break;
8984 }
8985 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_EVAL) {
8986 COMPILE_ERROR(ERROR_ARGS "Can't escape from eval with next");
8987 return COMPILE_NG;
8988 }
8989
8990 ip = ISEQ_BODY(ip)->parent_iseq;
8991 }
8992 if (ip != 0) {
8993 CHECK(COMPILE(ret, "next val", RNODE_NEXT(node)->nd_stts));
8994 ADD_INSN1(ret, line_node, throw, INT2FIX(throw_flag | TAG_NEXT));
8995
8996 if (popped) {
8997 ADD_INSN(ret, line_node, pop);
8998 }
8999 }
9000 else {
9001 COMPILE_ERROR(ERROR_ARGS "Invalid next");
9002 return COMPILE_NG;
9003 }
9004 }
9005 return COMPILE_OK;
9006}
9007
9008static int
9009compile_redo(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
9010{
9011 const NODE *line_node = node;
9012
9013 if (ISEQ_COMPILE_DATA(iseq)->redo_label && can_add_ensure_iseq(iseq)) {
9014 LABEL *splabel = NEW_LABEL(0);
9015 debugs("redo in while");
9016 ADD_LABEL(ret, splabel);
9017 ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->redo_label);
9018 add_ensure_iseq(ret, iseq, 0);
9019 ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->redo_label);
9020 ADD_ADJUST_RESTORE(ret, splabel);
9021 if (!popped) {
9022 ADD_INSN(ret, line_node, putnil);
9023 }
9024 }
9025 else if (ISEQ_BODY(iseq)->type != ISEQ_TYPE_EVAL && ISEQ_COMPILE_DATA(iseq)->start_label && can_add_ensure_iseq(iseq)) {
9026 LABEL *splabel = NEW_LABEL(0);
9027
9028 debugs("redo in block");
9029 ADD_LABEL(ret, splabel);
9030 add_ensure_iseq(ret, iseq, 0);
9031 ADD_ADJUST(ret, line_node, ISEQ_COMPILE_DATA(iseq)->start_label);
9032 ADD_INSNL(ret, line_node, jump, ISEQ_COMPILE_DATA(iseq)->start_label);
9033 ADD_ADJUST_RESTORE(ret, splabel);
9034
9035 if (!popped) {
9036 ADD_INSN(ret, line_node, putnil);
9037 }
9038 }
9039 else {
9040 const rb_iseq_t *ip = iseq;
9041
9042 while (ip) {
9043 if (!ISEQ_COMPILE_DATA(ip)) {
9044 ip = 0;
9045 break;
9046 }
9047
9048 if (ISEQ_COMPILE_DATA(ip)->redo_label != 0) {
9049 break;
9050 }
9051 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_BLOCK) {
9052 break;
9053 }
9054 else if (ISEQ_BODY(ip)->type == ISEQ_TYPE_EVAL) {
9055 COMPILE_ERROR(ERROR_ARGS "Can't escape from eval with redo");
9056 return COMPILE_NG;
9057 }
9058
9059 ip = ISEQ_BODY(ip)->parent_iseq;
9060 }
9061 if (ip != 0) {
9062 ADD_INSN(ret, line_node, putnil);
9063 ADD_INSN1(ret, line_node, throw, INT2FIX(VM_THROW_NO_ESCAPE_FLAG | TAG_REDO));
9064
9065 if (popped) {
9066 ADD_INSN(ret, line_node, pop);
9067 }
9068 }
9069 else {
9070 COMPILE_ERROR(ERROR_ARGS "Invalid redo");
9071 return COMPILE_NG;
9072 }
9073 }
9074 return COMPILE_OK;
9075}
9076
9077static int
9078compile_retry(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
9079{
9080 const NODE *line_node = node;
9081
9082 if (ISEQ_BODY(iseq)->type == ISEQ_TYPE_RESCUE) {
9083 ADD_INSN(ret, line_node, putnil);
9084 ADD_INSN1(ret, line_node, throw, INT2FIX(TAG_RETRY));
9085
9086 if (popped) {
9087 ADD_INSN(ret, line_node, pop);
9088 }
9089 }
9090 else {
9091 COMPILE_ERROR(ERROR_ARGS "Invalid retry");
9092 return COMPILE_NG;
9093 }
9094 return COMPILE_OK;
9095}
9096
9097static int
9098compile_rescue(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
9099{
9100 const int line = nd_line(node);
9101 const NODE *line_node = node;
9102 LABEL *lstart = NEW_LABEL(line);
9103 LABEL *lend = NEW_LABEL(line);
9104 LABEL *lcont = NEW_LABEL(line);
9105 const rb_iseq_t *rescue = NEW_CHILD_ISEQ(RNODE_RESCUE(node)->nd_resq,
9106 rb_str_concat(rb_str_new2("rescue in "),
9107 ISEQ_BODY(iseq)->location.label),
9108 ISEQ_TYPE_RESCUE, line);
9109
9110 lstart->rescued = LABEL_RESCUE_BEG;
9111 lend->rescued = LABEL_RESCUE_END;
9112 ADD_LABEL(ret, lstart);
9113
9114 bool prev_in_rescue = ISEQ_COMPILE_DATA(iseq)->in_rescue;
9115 ISEQ_COMPILE_DATA(iseq)->in_rescue = true;
9116 {
9117 CHECK(COMPILE(ret, "rescue head", RNODE_RESCUE(node)->nd_head));
9118 }
9119 ISEQ_COMPILE_DATA(iseq)->in_rescue = prev_in_rescue;
9120
9121 ADD_LABEL(ret, lend);
9122 if (RNODE_RESCUE(node)->nd_else) {
9123 ADD_INSN(ret, line_node, pop);
9124 CHECK(COMPILE(ret, "rescue else", RNODE_RESCUE(node)->nd_else));
9125 }
9126 ADD_INSN(ret, line_node, nop);
9127 ADD_LABEL(ret, lcont);
9128
9129 if (popped) {
9130 ADD_INSN(ret, line_node, pop);
9131 }
9132
9133 /* register catch entry */
9134 ADD_CATCH_ENTRY(CATCH_TYPE_RESCUE, lstart, lend, rescue, lcont);
9135 ADD_CATCH_ENTRY(CATCH_TYPE_RETRY, lend, lcont, NULL, lstart);
9136 return COMPILE_OK;
9137}
9138
9139static int
9140compile_resbody(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
9141{
9142 const int line = nd_line(node);
9143 const NODE *line_node = node;
9144 const NODE *resq = node;
9145 const NODE *narg;
9146 LABEL *label_miss, *label_hit;
9147
9148 while (resq) {
9149 label_miss = NEW_LABEL(line);
9150 label_hit = NEW_LABEL(line);
9151
9152 narg = RNODE_RESBODY(resq)->nd_args;
9153 if (narg) {
9154 switch (nd_type(narg)) {
9155 case NODE_LIST:
9156 while (narg) {
9157 ADD_GETLOCAL(ret, line_node, LVAR_ERRINFO, 0);
9158 CHECK(COMPILE(ret, "rescue arg", RNODE_LIST(narg)->nd_head));
9159 ADD_INSN1(ret, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_RESCUE));
9160 ADD_INSNL(ret, line_node, branchif, label_hit);
9161 narg = RNODE_LIST(narg)->nd_next;
9162 }
9163 break;
9164 case NODE_SPLAT:
9165 case NODE_ARGSCAT:
9166 case NODE_ARGSPUSH:
9167 ADD_GETLOCAL(ret, line_node, LVAR_ERRINFO, 0);
9168 CHECK(COMPILE(ret, "rescue/cond splat", narg));
9169 ADD_INSN1(ret, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_RESCUE | VM_CHECKMATCH_ARRAY));
9170 ADD_INSNL(ret, line_node, branchif, label_hit);
9171 break;
9172 default:
9173 UNKNOWN_NODE("NODE_RESBODY", narg, COMPILE_NG);
9174 }
9175 }
9176 else {
9177 ADD_GETLOCAL(ret, line_node, LVAR_ERRINFO, 0);
9178 ADD_INSN1(ret, line_node, putobject, rb_eStandardError);
9179 ADD_INSN1(ret, line_node, checkmatch, INT2FIX(VM_CHECKMATCH_TYPE_RESCUE));
9180 ADD_INSNL(ret, line_node, branchif, label_hit);
9181 }
9182 ADD_INSNL(ret, line_node, jump, label_miss);
9183 ADD_LABEL(ret, label_hit);
9184 ADD_TRACE(ret, RUBY_EVENT_RESCUE);
9185
9186 if (RNODE_RESBODY(resq)->nd_exc_var) {
9187 CHECK(COMPILE_POPPED(ret, "resbody exc_var", RNODE_RESBODY(resq)->nd_exc_var));
9188 }
9189
9190 if (nd_type(RNODE_RESBODY(resq)->nd_body) == NODE_BEGIN && RNODE_BEGIN(RNODE_RESBODY(resq)->nd_body)->nd_body == NULL && !RNODE_RESBODY(resq)->nd_exc_var) {
9191 // empty body
9192 ADD_SYNTHETIC_INSN(ret, nd_line(RNODE_RESBODY(resq)->nd_body), -1, putnil);
9193 }
9194 else {
9195 CHECK(COMPILE(ret, "resbody body", RNODE_RESBODY(resq)->nd_body));
9196 }
9197
9198 if (ISEQ_COMPILE_DATA(iseq)->option->tailcall_optimization) {
9199 ADD_INSN(ret, line_node, nop);
9200 }
9201 ADD_INSN(ret, line_node, leave);
9202 ADD_LABEL(ret, label_miss);
9203 resq = RNODE_RESBODY(resq)->nd_next;
9204 }
9205 return COMPILE_OK;
9206}
9207
9208static int
9209stmts_first_lineno(const NODE *stmts)
9210{
9211 // nd_line is the condition's line in a multi-line `stmt if cond`, while a
9212 // `begin; rescue; end` statement has the `begin` line but nd_loc after it.
9213 const NODE *first = nd_type_p(stmts, NODE_BLOCK) ? RNODE_BLOCK(stmts)->nd_head : stmts;
9214 const int line = nd_first_lineno(stmts);
9215 return nd_line(first) < line ? nd_line(first) : line;
9216}
9217
9218static int
9219compile_ensure(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
9220{
9221 const int line = stmts_first_lineno(RNODE_ENSURE(node)->nd_ensr);
9222 const NODE *line_node = node;
9223 DECL_ANCHOR(ensr);
9224 const rb_iseq_t *ensure = NEW_CHILD_ISEQ(RNODE_ENSURE(node)->nd_ensr,
9225 rb_str_concat(rb_str_new2 ("ensure in "), ISEQ_BODY(iseq)->location.label),
9226 ISEQ_TYPE_ENSURE, line);
9227 LABEL *lstart = NEW_LABEL(line);
9228 LABEL *lend = NEW_LABEL(line);
9229 LABEL *lcont = NEW_LABEL(line);
9230 LINK_ELEMENT *last;
9231 int last_leave = 0;
9232 struct ensure_range er;
9234 struct ensure_range *erange;
9235 int result = COMPILE_OK;
9236
9237 INIT_ANCHOR(ensr);
9238 CHECK(COMPILE_POPPED(ensr, "ensure ensr", RNODE_ENSURE(node)->nd_ensr));
9239 last = ensr->last;
9240 last_leave = last && IS_INSN(last) && IS_INSN_ID(last, leave);
9241
9242 er.begin = lstart;
9243 er.end = lend;
9244 er.next = 0;
9245 push_ensure_entry(iseq, &enl, &er, RNODE_ENSURE(node)->nd_ensr);
9246
9247 ADD_LABEL(ret, lstart);
9248 if (!COMPILE_(ret, "ensure head", RNODE_ENSURE(node)->nd_head, (popped | last_leave))) {
9249 result = COMPILE_NG;
9250 goto cleanup;
9251 }
9252 ADD_LABEL(ret, lend);
9253 ADD_SEQ(ret, ensr);
9254 if (!popped && last_leave) ADD_INSN(ret, line_node, putnil);
9255 ADD_LABEL(ret, lcont);
9256 if (last_leave) ADD_INSN(ret, line_node, pop);
9257
9258 erange = ISEQ_COMPILE_DATA(iseq)->ensure_node_stack->erange;
9259 if (lstart->link.next != &lend->link) {
9260 while (erange) {
9261 ADD_CATCH_ENTRY(CATCH_TYPE_ENSURE, erange->begin, erange->end,
9262 ensure, lcont);
9263 erange = erange->next;
9264 }
9265 }
9266
9267 cleanup:
9268 ISEQ_COMPILE_DATA(iseq)->ensure_node_stack = enl.prev;
9269 return result;
9270}
9271
9272static int
9273compile_return(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
9274{
9275 const NODE *line_node = node;
9276
9277 if (iseq) {
9278 enum rb_iseq_type type = ISEQ_BODY(iseq)->type;
9279 const rb_iseq_t *is = iseq;
9280 enum rb_iseq_type t = type;
9281 const NODE *retval = RNODE_RETURN(node)->nd_stts;
9282 LABEL *splabel = 0;
9283
9284 while (t == ISEQ_TYPE_RESCUE || t == ISEQ_TYPE_ENSURE) {
9285 if (!(is = ISEQ_BODY(is)->parent_iseq)) break;
9286 t = ISEQ_BODY(is)->type;
9287 }
9288 switch (t) {
9289 case ISEQ_TYPE_TOP:
9290 case ISEQ_TYPE_MAIN:
9291 if (retval) {
9292 rb_warn("argument of top-level return is ignored");
9293 }
9294 if (is == iseq) {
9295 /* plain top-level, leave directly */
9296 type = ISEQ_TYPE_METHOD;
9297 }
9298 break;
9299 default:
9300 break;
9301 }
9302
9303 bool direct_return = can_inline_return(iseq, type);
9304 if (direct_return) {
9305 splabel = NEW_LABEL(0);
9306 ADD_LABEL(ret, splabel);
9307 ADD_ADJUST(ret, line_node, 0);
9308 }
9309
9310 CHECK(COMPILE(ret, "return nd_stts (return val)", retval));
9311
9312 if (direct_return) {
9313 add_ensure_iseq(ret, iseq, 1);
9314 ADD_TRACE(ret, RUBY_EVENT_RETURN);
9315 ADD_INSN(ret, line_node, leave);
9316 ADD_ADJUST_RESTORE(ret, splabel);
9317
9318 if (!popped) {
9319 ADD_INSN(ret, line_node, putnil);
9320 }
9321 }
9322 else {
9323 ADD_INSN1(ret, line_node, throw, INT2FIX(TAG_RETURN));
9324 if (popped) {
9325 ADD_INSN(ret, line_node, pop);
9326 }
9327 }
9328 }
9329 return COMPILE_OK;
9330}
9331
9332static bool
9333drop_unreachable_return(LINK_ANCHOR *ret)
9334{
9335 LINK_ELEMENT *i = ret->last, *last;
9336 if (!i) return false;
9337 if (IS_TRACE(i)) i = i->prev;
9338 if (!IS_INSN(i) || !IS_INSN_ID(i, putnil)) return false;
9339 last = i = i->prev;
9340 if (IS_ADJUST(i)) i = i->prev;
9341 if (!IS_INSN(i)) return false;
9342 switch (INSN_OF(i)) {
9343 case BIN(leave):
9344 case BIN(jump):
9345 break;
9346 default:
9347 return false;
9348 }
9349 (ret->last = last->prev)->next = NULL;
9350 return true;
9351}
9352
9353static int
9354compile_evstr(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
9355{
9356 CHECK(COMPILE_(ret, "nd_body", node, popped));
9357
9358 if (!popped && !all_string_result_p(node)) {
9359 const NODE *line_node = node;
9360 const unsigned int flag = VM_CALL_FCALL;
9361
9362 // Note, this dup could be removed if we are willing to change anytostring. It pops
9363 // two VALUEs off the stack when it could work by replacing the top most VALUE.
9364 ADD_INSN(ret, line_node, dup);
9365 ADD_INSN1(ret, line_node, objtostring, new_callinfo(iseq, idTo_s, 0, flag, NULL, FALSE));
9366 ADD_INSN(ret, line_node, anytostring);
9367 }
9368 return COMPILE_OK;
9369}
9370
9371static void
9372compile_lvar(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *line_node, ID id)
9373{
9374 int idx = ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq)->local_table_size - get_local_var_idx(iseq, id);
9375
9376 debugs("id: %s idx: %d\n", rb_id2name(id), idx);
9377 ADD_GETLOCAL(ret, line_node, idx, get_lvar_level(iseq));
9378}
9379
9380static LABEL *
9381qcall_branch_start(rb_iseq_t *iseq, LINK_ANCHOR *const recv, VALUE *branches, const NODE *node, const NODE *line_node)
9382{
9383 LABEL *else_label = NEW_LABEL(nd_line(line_node));
9384 VALUE br = 0;
9385
9386 br = decl_branch_base(iseq, nd_node_id(node), nd_code_loc(node), "&.");
9387 *branches = br;
9388 ADD_INSN(recv, line_node, dup);
9389 ADD_INSNL(recv, line_node, branchnil, else_label);
9390 add_trace_branch_coverage(iseq, recv, nd_code_loc(node), nd_node_id(node), 0, "then", br);
9391 return else_label;
9392}
9393
9394static void
9395qcall_branch_end(rb_iseq_t *iseq, LINK_ANCHOR *const ret, LABEL *else_label, VALUE branches, const NODE *node, const NODE *line_node)
9396{
9397 LABEL *end_label;
9398 if (!else_label) return;
9399 end_label = NEW_LABEL(nd_line(line_node));
9400 ADD_INSNL(ret, line_node, jump, end_label);
9401 ADD_LABEL(ret, else_label);
9402 add_trace_branch_coverage(iseq, ret, nd_code_loc(node), nd_node_id(node), 1, "else", branches);
9403 ADD_LABEL(ret, end_label);
9404}
9405
9406static int
9407compile_call_precheck_freeze(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, const NODE *line_node, int popped)
9408{
9409 /* optimization shortcut
9410 * "literal".freeze -> opt_str_freeze("literal")
9411 */
9412 if (get_nd_recv(node) &&
9413 nd_type_p(get_nd_recv(node), NODE_STR) &&
9414 (get_node_call_nd_mid(node) == idFreeze || get_node_call_nd_mid(node) == idUMinus) &&
9415 get_nd_args(node) == NULL &&
9416 ISEQ_COMPILE_DATA(iseq)->current_block == NULL &&
9417 ISEQ_COMPILE_DATA(iseq)->option->specialized_instruction) {
9418 VALUE str = get_string_value(get_nd_recv(node));
9419 if (get_node_call_nd_mid(node) == idUMinus) {
9420 ADD_INSN2(ret, line_node, opt_str_uminus, str,
9421 new_callinfo(iseq, idUMinus, 0, 0, NULL, FALSE));
9422 }
9423 else {
9424 ADD_INSN2(ret, line_node, opt_str_freeze, str,
9425 new_callinfo(iseq, idFreeze, 0, 0, NULL, FALSE));
9426 }
9427 RB_OBJ_WRITTEN(iseq, Qundef, str);
9428 if (popped) {
9429 ADD_INSN(ret, line_node, pop);
9430 }
9431 return TRUE;
9432 }
9433 return FALSE;
9434}
9435
9436static int
9437iseq_has_builtin_function_table(const rb_iseq_t *iseq)
9438{
9439 return ISEQ_COMPILE_DATA(iseq)->builtin_function_table != NULL;
9440}
9441
9442static const struct rb_builtin_function *
9443iseq_builtin_function_lookup(const rb_iseq_t *iseq, const char *name)
9444{
9445 int i;
9446 const struct rb_builtin_function *table = ISEQ_COMPILE_DATA(iseq)->builtin_function_table;
9447 for (i=0; table[i].index != -1; i++) {
9448 if (strcmp(table[i].name, name) == 0) {
9449 return &table[i];
9450 }
9451 }
9452 return NULL;
9453}
9454
9455static const char *
9456iseq_builtin_function_name(const enum node_type type, const NODE *recv, ID mid)
9457{
9458 const char *name = rb_id2name(mid);
9459 static const char prefix[] = "__builtin_";
9460 const size_t prefix_len = sizeof(prefix) - 1;
9461
9462 switch (type) {
9463 case NODE_CALL:
9464 if (recv) {
9465 switch (nd_type(recv)) {
9466 case NODE_VCALL:
9467 if (RNODE_VCALL(recv)->nd_mid == rb_intern("__builtin")) {
9468 return name;
9469 }
9470 break;
9471 case NODE_CONST:
9472 if (RNODE_CONST(recv)->nd_vid == rb_intern("Primitive")) {
9473 return name;
9474 }
9475 break;
9476 default: break;
9477 }
9478 }
9479 break;
9480 case NODE_VCALL:
9481 case NODE_FCALL:
9482 if (UNLIKELY(strncmp(prefix, name, prefix_len) == 0)) {
9483 return &name[prefix_len];
9484 }
9485 break;
9486 default: break;
9487 }
9488 return NULL;
9489}
9490
9491static int
9492delegate_call_p(const rb_iseq_t *iseq, unsigned int argc, const LINK_ANCHOR *args, unsigned int *pstart_index)
9493{
9494
9495 if (argc == 0) {
9496 *pstart_index = 0;
9497 return TRUE;
9498 }
9499 else if (argc <= ISEQ_BODY(iseq)->local_table_size) {
9500 unsigned int start=0;
9501
9502 // local_table: [p1, p2, p3, l1, l2, l3]
9503 // arguments: [p3, l1, l2] -> 2
9504 for (start = 0;
9505 argc + start <= ISEQ_BODY(iseq)->local_table_size;
9506 start++) {
9507 const LINK_ELEMENT *elem = FIRST_ELEMENT(args);
9508
9509 for (unsigned int i=start; i-start<argc; i++) {
9510 if (IS_INSN(elem) &&
9511 INSN_OF(elem) == BIN(getlocal)) {
9512 int local_index = FIX2INT(OPERAND_AT(elem, 0));
9513 int local_level = FIX2INT(OPERAND_AT(elem, 1));
9514
9515 if (local_level == 0) {
9516 unsigned int index = ISEQ_BODY(iseq)->local_table_size - (local_index - VM_ENV_DATA_SIZE + 1);
9517 if (0) { // for debug
9518 fprintf(stderr, "lvar:%s (%d), id:%s (%d) local_index:%d, local_size:%d\n",
9519 rb_id2name(ISEQ_BODY(iseq)->local_table[i]), i,
9520 rb_id2name(ISEQ_BODY(iseq)->local_table[index]), index,
9521 local_index, (int)ISEQ_BODY(iseq)->local_table_size);
9522 }
9523 if (i == index) {
9524 elem = elem->next;
9525 continue; /* for */
9526 }
9527 else {
9528 goto next;
9529 }
9530 }
9531 else {
9532 goto fail; // level != 0 is unsupported
9533 }
9534 }
9535 else {
9536 goto fail; // insn is not a getlocal
9537 }
9538 }
9539 goto success;
9540 next:;
9541 }
9542 fail:
9543 return FALSE;
9544 success:
9545 *pstart_index = start;
9546 return TRUE;
9547 }
9548 else {
9549 return FALSE;
9550 }
9551}
9552
9553static int
9554compile_builtin_attr_symbol(rb_iseq_t *iseq, VALUE symbol)
9555{
9556 VALUE string = rb_sym2str(symbol);
9557 if (rb_streql_lit(string, "leaf")) {
9558 ISEQ_BODY(iseq)->builtin_attrs |= BUILTIN_ATTR_LEAF;
9559 }
9560 else if (rb_streql_lit(string, "inline_block")) {
9561 ISEQ_BODY(iseq)->builtin_attrs |= BUILTIN_ATTR_INLINE_BLOCK;
9562 }
9563 else if (rb_streql_lit(string, "use_block")) {
9564 iseq_set_use_block(iseq);
9565 }
9566 else if (rb_streql_lit(string, "c_trace")) {
9567 // Let the iseq act like a C method in backtraces
9568 ISEQ_BODY(iseq)->builtin_attrs |= BUILTIN_ATTR_C_TRACE;
9569 }
9570 else if (rb_streql_lit(string, "without_interrupts")) {
9571 ISEQ_BODY(iseq)->builtin_attrs |= BUILTIN_ATTR_WITHOUT_INTERRUPTS;
9572 }
9573 else if (rb_streql_lit(string, "caller_user_box")) {
9574 ISEQ_BODY(iseq)->builtin_attrs |= BUILTIN_ATTR_CALLER_USER_BOX;
9575 }
9576 else if (rb_streql_lit(string, "always_inline")) {
9577 ISEQ_BODY(iseq)->builtin_attrs |= BUILTIN_ATTR_ALWAYS_INLINE;
9578 }
9579 else {
9580 return COMPILE_NG;
9581 }
9582 return COMPILE_OK;
9583}
9584
9585// Compile Primitive.attr! :leaf, ...
9586static int
9587compile_builtin_attr(rb_iseq_t *iseq, const NODE *node)
9588{
9589 VALUE symbol;
9590 if (!node) goto no_arg;
9591 while (node) {
9592 if (!nd_type_p(node, NODE_LIST)) goto bad_arg;
9593 const NODE *next = RNODE_LIST(node)->nd_next;
9594
9595 node = RNODE_LIST(node)->nd_head;
9596 if (!node) goto no_arg;
9597 switch (nd_type(node)) {
9598 case NODE_SYM:
9599 symbol = rb_node_sym_string_val(node);
9600 break;
9601 default:
9602 goto bad_arg;
9603 }
9604
9605 if (!SYMBOL_P(symbol)) goto non_symbol_arg;
9606 if (compile_builtin_attr_symbol(iseq, symbol) != COMPILE_OK) goto unknown_arg;
9607 node = next;
9608 }
9609 return COMPILE_OK;
9610 no_arg:
9611 COMPILE_ERROR(ERROR_ARGS "attr!: no argument");
9612 return COMPILE_NG;
9613 non_symbol_arg:
9614 COMPILE_ERROR(ERROR_ARGS "non symbol argument to attr!: %s", rb_builtin_class_name(symbol));
9615 return COMPILE_NG;
9616 unknown_arg:
9617 COMPILE_ERROR(ERROR_ARGS "unknown argument to attr!: %" PRIsVALUE, symbol);
9618 return COMPILE_NG;
9619 bad_arg:
9620 UNKNOWN_NODE("attr!", node, COMPILE_NG);
9621}
9622
9623static int
9624compile_builtin_arg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *node, const NODE *line_node, int popped)
9625{
9626 VALUE name;
9627
9628 if (!node) goto no_arg;
9629 if (!nd_type_p(node, NODE_LIST)) goto bad_arg;
9630 if (RNODE_LIST(node)->nd_next) goto too_many_arg;
9631 node = RNODE_LIST(node)->nd_head;
9632 if (!node) goto no_arg;
9633 switch (nd_type(node)) {
9634 case NODE_SYM:
9635 name = rb_node_sym_string_val(node);
9636 break;
9637 default:
9638 goto bad_arg;
9639 }
9640 if (!SYMBOL_P(name)) goto non_symbol_arg;
9641 if (!popped) {
9642 compile_lvar(iseq, ret, line_node, SYM2ID(name));
9643 }
9644 return COMPILE_OK;
9645 no_arg:
9646 COMPILE_ERROR(ERROR_ARGS "arg!: no argument");
9647 return COMPILE_NG;
9648 too_many_arg:
9649 COMPILE_ERROR(ERROR_ARGS "arg!: too many argument");
9650 return COMPILE_NG;
9651 non_symbol_arg:
9652 COMPILE_ERROR(ERROR_ARGS "non symbol argument to arg!: %s",
9653 rb_builtin_class_name(name));
9654 return COMPILE_NG;
9655 bad_arg:
9656 UNKNOWN_NODE("arg!", node, COMPILE_NG);
9657}
9658
9659static NODE *
9660mandatory_node(const rb_iseq_t *iseq, const NODE *cond_node)
9661{
9662 const NODE *node = ISEQ_COMPILE_DATA(iseq)->root_node;
9663 if (nd_type(node) == NODE_IF && RNODE_IF(node)->nd_cond == cond_node) {
9664 return RNODE_IF(node)->nd_body;
9665 }
9666 else {
9667 rb_bug("mandatory_node: can't find mandatory node");
9668 }
9669}
9670
9671static int
9672compile_builtin_mandatory_only_method(rb_iseq_t *iseq, const NODE *node, const NODE *line_node)
9673{
9674 // arguments
9675 struct rb_args_info args = {
9676 .pre_args_num = ISEQ_BODY(iseq)->param.lead_num,
9677 };
9678 rb_node_args_t args_node;
9679 rb_node_init(RNODE(&args_node), NODE_ARGS);
9680 args_node.nd_ainfo = args;
9681
9682 // local table without non-mandatory parameters
9683 const int skip_local_size = ISEQ_BODY(iseq)->param.size - ISEQ_BODY(iseq)->param.lead_num;
9684 const int table_size = ISEQ_BODY(iseq)->local_table_size - skip_local_size;
9685
9686 VALUE idtmp = 0;
9687 rb_ast_id_table_t *tbl = ALLOCV(idtmp, sizeof(rb_ast_id_table_t) + table_size * sizeof(ID));
9688 tbl->size = table_size;
9689
9690 int i;
9691
9692 // lead parameters
9693 for (i=0; i<ISEQ_BODY(iseq)->param.lead_num; i++) {
9694 tbl->ids[i] = ISEQ_BODY(iseq)->local_table[i];
9695 }
9696 // local variables
9697 for (; i<table_size; i++) {
9698 tbl->ids[i] = ISEQ_BODY(iseq)->local_table[i + skip_local_size];
9699 }
9700
9701 rb_node_scope_t scope_node;
9702 rb_node_init(RNODE(&scope_node), NODE_SCOPE);
9703 scope_node.nd_tbl = tbl;
9704 scope_node.nd_body = mandatory_node(iseq, node);
9705 scope_node.nd_parent = NULL;
9706 scope_node.nd_args = &args_node;
9707
9708 VALUE ast_value = rb_ruby_ast_new(RNODE(&scope_node));
9709
9710 const rb_iseq_t *mandatory_only_iseq =
9711 rb_iseq_new_with_opt(ast_value, rb_iseq_base_label(iseq),
9712 rb_iseq_path(iseq), rb_iseq_realpath(iseq),
9713 nd_line(line_node), NULL, 0,
9714 ISEQ_TYPE_METHOD, ISEQ_COMPILE_DATA(iseq)->option,
9715 ISEQ_SCRIPT_LINES(iseq));
9716 rb_iseq_mandatory_only_iseq_set(iseq, mandatory_only_iseq);
9717
9718 ALLOCV_END(idtmp);
9719 return COMPILE_OK;
9720}
9721
9722static int
9723compile_builtin_function_call(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, const NODE *line_node, int popped,
9724 const rb_iseq_t *parent_block, LINK_ANCHOR *args, const char *builtin_func)
9725{
9726 NODE *args_node = get_nd_args(node);
9727
9728 if (parent_block != NULL) {
9729 COMPILE_ERROR(ERROR_ARGS_AT(line_node) "should not call builtins here.");
9730 return COMPILE_NG;
9731 }
9732 else {
9733# define BUILTIN_INLINE_PREFIX "_bi"
9734 char inline_func[sizeof(BUILTIN_INLINE_PREFIX) + DECIMAL_SIZE_OF(int)];
9735 bool cconst = false;
9736 retry:;
9737 const struct rb_builtin_function *bf = iseq_builtin_function_lookup(iseq, builtin_func);
9738
9739 if (bf == NULL) {
9740 if (strcmp("cstmt!", builtin_func) == 0 ||
9741 strcmp("cexpr!", builtin_func) == 0) {
9742 // ok
9743 }
9744 else if (strcmp("cconst!", builtin_func) == 0) {
9745 cconst = true;
9746 }
9747 else if (strcmp("cinit!", builtin_func) == 0) {
9748 // ignore
9749 return COMPILE_OK;
9750 }
9751 else if (strcmp("attr!", builtin_func) == 0) {
9752 return compile_builtin_attr(iseq, args_node);
9753 }
9754 else if (strcmp("arg!", builtin_func) == 0) {
9755 return compile_builtin_arg(iseq, ret, args_node, line_node, popped);
9756 }
9757 else if (strcmp("mandatory_only?", builtin_func) == 0) {
9758 if (popped) {
9759 rb_bug("mandatory_only? should be in if condition");
9760 }
9761 else if (!LIST_INSN_SIZE_ZERO(ret)) {
9762 rb_bug("mandatory_only? should be put on top");
9763 }
9764
9765 ADD_INSN1(ret, line_node, putobject, Qfalse);
9766 return compile_builtin_mandatory_only_method(iseq, node, line_node);
9767 }
9768 else if (1) {
9769 rb_bug("can't find builtin function:%s", builtin_func);
9770 }
9771 else {
9772 COMPILE_ERROR(ERROR_ARGS "can't find builtin function:%s", builtin_func);
9773 return COMPILE_NG;
9774 }
9775
9776 int inline_index = nd_line(node);
9777 snprintf(inline_func, sizeof(inline_func), BUILTIN_INLINE_PREFIX "%d", inline_index);
9778 builtin_func = inline_func;
9779 args_node = NULL;
9780 goto retry;
9781 }
9782
9783 if (cconst) {
9784 typedef VALUE(*builtin_func0)(void *, VALUE);
9785 VALUE const_val = (*(builtin_func0)(uintptr_t)bf->func_ptr)(NULL, Qnil);
9786 ADD_INSN1(ret, line_node, putobject, const_val);
9787 return COMPILE_OK;
9788 }
9789
9790 // fprintf(stderr, "func_name:%s -> %p\n", builtin_func, bf->func_ptr);
9791
9792 unsigned int flag = 0;
9793 struct rb_callinfo_kwarg *keywords = NULL;
9794 VALUE argc = setup_args(iseq, args, args_node, &flag, &keywords);
9795
9796 if (FIX2INT(argc) != bf->argc) {
9797 COMPILE_ERROR(ERROR_ARGS "argc is not match for builtin function:%s (expect %d but %d)",
9798 builtin_func, bf->argc, FIX2INT(argc));
9799 return COMPILE_NG;
9800 }
9801
9802 unsigned int start_index;
9803 if (delegate_call_p(iseq, FIX2INT(argc), args, &start_index)) {
9804 ADD_INSN2(ret, line_node, opt_invokebuiltin_delegate, bf, INT2FIX(start_index));
9805 }
9806 else {
9807 ADD_SEQ(ret, args);
9808 ADD_INSN1(ret, line_node, invokebuiltin, bf);
9809 }
9810
9811 if (popped) ADD_INSN(ret, line_node, pop);
9812 return COMPILE_OK;
9813 }
9814}
9815
9816static int
9817compile_call(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, const enum node_type type, const NODE *const line_node, int popped, bool assume_receiver)
9818{
9819 /* call: obj.method(...)
9820 * fcall: func(...)
9821 * vcall: func
9822 */
9823 DECL_ANCHOR(recv);
9824 DECL_ANCHOR(args);
9825 ID mid = get_node_call_nd_mid(node);
9826 VALUE argc;
9827 unsigned int flag = 0;
9828 struct rb_callinfo_kwarg *keywords = NULL;
9829 const rb_iseq_t *parent_block = ISEQ_COMPILE_DATA(iseq)->current_block;
9830 LABEL *else_label = NULL;
9831 VALUE branches = Qfalse;
9832
9833 ISEQ_COMPILE_DATA(iseq)->current_block = NULL;
9834
9835 INIT_ANCHOR(recv);
9836 INIT_ANCHOR(args);
9837
9838#if OPT_SUPPORT_JOKE
9839 if (nd_type_p(node, NODE_VCALL)) {
9840 ID id_bitblt;
9841 ID id_answer;
9842
9843 CONST_ID(id_bitblt, "bitblt");
9844 CONST_ID(id_answer, "the_answer_to_life_the_universe_and_everything");
9845
9846 if (mid == id_bitblt) {
9847 ADD_INSN(ret, line_node, bitblt);
9848 return COMPILE_OK;
9849 }
9850 else if (mid == id_answer) {
9851 ADD_INSN(ret, line_node, answer);
9852 return COMPILE_OK;
9853 }
9854 }
9855 /* only joke */
9856 {
9857 ID goto_id;
9858 ID label_id;
9859
9860 CONST_ID(goto_id, "__goto__");
9861 CONST_ID(label_id, "__label__");
9862
9863 if (nd_type_p(node, NODE_FCALL) &&
9864 (mid == goto_id || mid == label_id)) {
9865 LABEL *label;
9866 st_data_t data;
9867 st_table *labels_table = ISEQ_COMPILE_DATA(iseq)->labels_table;
9868 VALUE label_name;
9869
9870 if (!labels_table) {
9871 labels_table = st_init_numtable();
9872 ISEQ_COMPILE_DATA(iseq)->labels_table = labels_table;
9873 }
9874 {
9875 COMPILE_ERROR(ERROR_ARGS "invalid goto/label format");
9876 return COMPILE_NG;
9877 }
9878
9879 if (mid == goto_id) {
9880 ADD_INSNL(ret, line_node, jump, label);
9881 }
9882 else {
9883 ADD_LABEL(ret, label);
9884 }
9885 return COMPILE_OK;
9886 }
9887 }
9888#endif
9889
9890 const char *builtin_func;
9891 if (UNLIKELY(iseq_has_builtin_function_table(iseq)) &&
9892 (builtin_func = iseq_builtin_function_name(type, get_nd_recv(node), mid)) != NULL) {
9893 return compile_builtin_function_call(iseq, ret, node, line_node, popped, parent_block, args, builtin_func);
9894 }
9895
9896 /* receiver */
9897 if (!assume_receiver) {
9898 if (type == NODE_CALL || type == NODE_OPCALL || type == NODE_QCALL) {
9899 int idx, level;
9900
9901 if ((mid == idCall || mid == idAREF || mid == idYield || mid == idEqq) &&
9902 nd_type_p(get_nd_recv(node), NODE_LVAR) &&
9903 iseq_block_param_id_p(iseq, RNODE_LVAR(get_nd_recv(node))->nd_vid, &idx, &level)) {
9904 ADD_INSN2(recv, get_nd_recv(node), getblockparamproxy, INT2FIX(idx + VM_ENV_DATA_SIZE - 1), INT2FIX(level));
9905 }
9906 else if (private_recv_p(node)) {
9907 ADD_INSN(recv, node, putself);
9908 flag |= VM_CALL_FCALL;
9909 }
9910 else {
9911 CHECK(COMPILE(recv, "recv", get_nd_recv(node)));
9912 }
9913
9914 if (type == NODE_QCALL) {
9915 else_label = qcall_branch_start(iseq, recv, &branches, node, line_node);
9916 }
9917 }
9918 else if (type == NODE_FCALL || type == NODE_VCALL) {
9919 ADD_CALL_RECEIVER(recv, line_node);
9920 }
9921 }
9922
9923 /* args */
9924 if (type != NODE_VCALL) {
9925 argc = setup_args(iseq, args, get_nd_args(node), &flag, &keywords);
9926 CHECK(!NIL_P(argc));
9927 }
9928 else {
9929 argc = INT2FIX(0);
9930 }
9931
9932 ADD_SEQ(ret, recv);
9933
9934 bool inline_new = ISEQ_COMPILE_DATA(iseq)->option->specialized_instruction &&
9935 mid == rb_intern("new") &&
9936 parent_block == NULL &&
9937 !(flag & VM_CALL_ARGS_BLOCKARG);
9938
9939 if (inline_new) {
9940 ADD_INSN(ret, node, putnil);
9941 ADD_INSN(ret, node, swap);
9942 }
9943
9944 ADD_SEQ(ret, args);
9945
9946 debugp_param("call args argc", argc);
9947 debugp_param("call method", ID2SYM(mid));
9948
9949 switch ((int)type) {
9950 case NODE_VCALL:
9951 flag |= VM_CALL_VCALL;
9952 /* VCALL is funcall, so fall through */
9953 case NODE_FCALL:
9954 flag |= VM_CALL_FCALL;
9955 }
9956
9957 if ((flag & VM_CALL_ARGS_BLOCKARG) && (flag & VM_CALL_KW_SPLAT) && !(flag & VM_CALL_KW_SPLAT_MUT)) {
9958 ADD_INSN(ret, line_node, splatkw);
9959 }
9960
9961 LABEL *not_basic_new = NEW_LABEL(nd_line(node));
9962 LABEL *not_basic_new_finish = NEW_LABEL(nd_line(node));
9963
9964 if (inline_new) {
9965 // Jump unless the receiver uses the "basic" implementation of "new"
9966 VALUE ci;
9967 if (flag & VM_CALL_FORWARDING) {
9968 ci = (VALUE)new_callinfo(iseq, mid, NUM2INT(argc) + 1, flag, keywords, 0);
9969 }
9970 else {
9971 ci = (VALUE)new_callinfo(iseq, mid, NUM2INT(argc), flag, keywords, 0);
9972 }
9973 ADD_INSN2(ret, node, opt_new, ci, not_basic_new);
9974 LABEL_REF(not_basic_new);
9975
9976 // optimized path
9977 ADD_SEND_R(ret, line_node, rb_intern("initialize"), argc, parent_block, INT2FIX(flag | VM_CALL_FCALL | VM_CALL_IGNORE_REFINEMENTS), keywords);
9978 ADD_INSNL(ret, line_node, jump, not_basic_new_finish);
9979
9980 ADD_LABEL(ret, not_basic_new);
9981 // Fall back to normal send
9982 ADD_SEND_R(ret, line_node, mid, argc, parent_block, INT2FIX(flag), keywords);
9983 ADD_INSN(ret, line_node, swap);
9984
9985 ADD_LABEL(ret, not_basic_new_finish);
9986 ADD_INSN(ret, line_node, pop);
9987 }
9988 else {
9989 ADD_SEND_R(ret, line_node, mid, argc, parent_block, INT2FIX(flag), keywords);
9990 }
9991
9992 qcall_branch_end(iseq, ret, else_label, branches, node, line_node);
9993 if (popped) {
9994 ADD_INSN(ret, line_node, pop);
9995 }
9996 return COMPILE_OK;
9997}
9998
9999static int
10000compile_op_asgn1(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
10001{
10002 const int line = nd_line(node);
10003 VALUE argc;
10004 unsigned int flag = 0;
10005 int asgnflag = 0;
10006 ID id = RNODE_OP_ASGN1(node)->nd_mid;
10007
10008 /*
10009 * a[x] (op)= y
10010 *
10011 * nil # nil
10012 * eval a # nil a
10013 * eval x # nil a x
10014 * dupn 2 # nil a x a x
10015 * send :[] # nil a x a[x]
10016 * eval y # nil a x a[x] y
10017 * send op # nil a x ret
10018 * setn 3 # ret a x ret
10019 * send []= # ret ?
10020 * pop # ret
10021 */
10022
10023 /*
10024 * nd_recv[nd_args->nd_body] (nd_mid)= nd_args->nd_head;
10025 * NODE_OP_ASGN nd_recv
10026 * nd_args->nd_head
10027 * nd_args->nd_body
10028 * nd_mid
10029 */
10030
10031 if (!popped) {
10032 ADD_INSN(ret, node, putnil);
10033 }
10034 asgnflag = COMPILE_RECV(ret, "NODE_OP_ASGN1 recv", node, RNODE_OP_ASGN1(node)->nd_recv);
10035 CHECK(asgnflag != -1);
10036 switch (nd_type(RNODE_OP_ASGN1(node)->nd_index)) {
10037 case NODE_ZLIST:
10038 argc = INT2FIX(0);
10039 break;
10040 default:
10041 argc = setup_args(iseq, ret, RNODE_OP_ASGN1(node)->nd_index, &flag, NULL);
10042 CHECK(!NIL_P(argc));
10043 }
10044 int dup_argn = FIX2INT(argc) + 1;
10045 ADD_INSN1(ret, node, dupn, INT2FIX(dup_argn));
10046 flag |= asgnflag;
10047 ADD_SEND_R(ret, node, idAREF, argc, NULL, INT2FIX(flag & ~VM_CALL_ARGS_SPLAT_MUT), NULL);
10048
10049 if (id == idOROP || id == idANDOP) {
10050 /* a[x] ||= y or a[x] &&= y
10051
10052 unless/if a[x]
10053 a[x]= y
10054 else
10055 nil
10056 end
10057 */
10058 LABEL *label = NEW_LABEL(line);
10059 LABEL *lfin = NEW_LABEL(line);
10060
10061 ADD_INSN(ret, node, dup);
10062 if (id == idOROP) {
10063 ADD_INSNL(ret, node, branchif, label);
10064 }
10065 else { /* idANDOP */
10066 ADD_INSNL(ret, node, branchunless, label);
10067 }
10068 ADD_INSN(ret, node, pop);
10069
10070 CHECK(COMPILE(ret, "NODE_OP_ASGN1 nd_rvalue: ", RNODE_OP_ASGN1(node)->nd_rvalue));
10071 if (!popped) {
10072 ADD_INSN1(ret, node, setn, INT2FIX(dup_argn+1));
10073 }
10074 if (flag & VM_CALL_ARGS_SPLAT) {
10075 if (!(flag & VM_CALL_ARGS_SPLAT_MUT)) {
10076 ADD_INSN(ret, node, swap);
10077 ADD_INSN1(ret, node, splatarray, Qtrue);
10078 ADD_INSN(ret, node, swap);
10079 flag |= VM_CALL_ARGS_SPLAT_MUT;
10080 }
10081 ADD_INSN1(ret, node, pushtoarray, INT2FIX(1));
10082 ADD_SEND_R(ret, node, idASET, argc, NULL, INT2FIX(flag), NULL);
10083 }
10084 else {
10085 ADD_SEND_R(ret, node, idASET, FIXNUM_INC(argc, 1), NULL, INT2FIX(flag), NULL);
10086 }
10087 ADD_INSN(ret, node, pop);
10088 ADD_INSNL(ret, node, jump, lfin);
10089 ADD_LABEL(ret, label);
10090 if (!popped) {
10091 ADD_INSN1(ret, node, setn, INT2FIX(dup_argn+1));
10092 }
10093 ADD_INSN1(ret, node, adjuststack, INT2FIX(dup_argn+1));
10094 ADD_LABEL(ret, lfin);
10095 }
10096 else {
10097 CHECK(COMPILE(ret, "NODE_OP_ASGN1 nd_rvalue: ", RNODE_OP_ASGN1(node)->nd_rvalue));
10098 ADD_SEND(ret, node, id, INT2FIX(1));
10099 if (!popped) {
10100 ADD_INSN1(ret, node, setn, INT2FIX(dup_argn+1));
10101 }
10102 if (flag & VM_CALL_ARGS_SPLAT) {
10103 if (flag & VM_CALL_KW_SPLAT) {
10104 ADD_INSN1(ret, node, topn, INT2FIX(2));
10105 if (!(flag & VM_CALL_ARGS_SPLAT_MUT)) {
10106 ADD_INSN1(ret, node, splatarray, Qtrue);
10107 flag |= VM_CALL_ARGS_SPLAT_MUT;
10108 }
10109 ADD_INSN(ret, node, swap);
10110 ADD_INSN1(ret, node, pushtoarray, INT2FIX(1));
10111 ADD_INSN1(ret, node, setn, INT2FIX(2));
10112 ADD_INSN(ret, node, pop);
10113 }
10114 else {
10115 if (!(flag & VM_CALL_ARGS_SPLAT_MUT)) {
10116 ADD_INSN(ret, node, swap);
10117 ADD_INSN1(ret, node, splatarray, Qtrue);
10118 ADD_INSN(ret, node, swap);
10119 flag |= VM_CALL_ARGS_SPLAT_MUT;
10120 }
10121 ADD_INSN1(ret, node, pushtoarray, INT2FIX(1));
10122 }
10123 ADD_SEND_R(ret, node, idASET, argc, NULL, INT2FIX(flag), NULL);
10124 }
10125 else {
10126 ADD_SEND_R(ret, node, idASET, FIXNUM_INC(argc, 1), NULL, INT2FIX(flag), NULL);
10127 }
10128 ADD_INSN(ret, node, pop);
10129 }
10130 return COMPILE_OK;
10131}
10132
10133static int
10134compile_op_asgn2(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
10135{
10136 const int line = nd_line(node);
10137 ID atype = RNODE_OP_ASGN2(node)->nd_mid;
10138 ID vid = RNODE_OP_ASGN2(node)->nd_vid, aid = rb_id_attrset(vid);
10139 int asgnflag;
10140 LABEL *lfin = NEW_LABEL(line);
10141 LABEL *lcfin = NEW_LABEL(line);
10142 LABEL *lskip = 0;
10143 /*
10144 class C; attr_accessor :c; end
10145 r = C.new
10146 r.a &&= v # asgn2
10147
10148 eval r # r
10149 dup # r r
10150 eval r.a # r o
10151
10152 # or
10153 dup # r o o
10154 if lcfin # r o
10155 pop # r
10156 eval v # r v
10157 swap # v r
10158 topn 1 # v r v
10159 send a= # v ?
10160 jump lfin # v ?
10161
10162 lcfin: # r o
10163 swap # o r
10164
10165 lfin: # o ?
10166 pop # o
10167
10168 # or (popped)
10169 if lcfin # r
10170 eval v # r v
10171 send a= # ?
10172 jump lfin # ?
10173
10174 lcfin: # r
10175
10176 lfin: # ?
10177 pop #
10178
10179 # and
10180 dup # r o o
10181 unless lcfin
10182 pop # r
10183 eval v # r v
10184 swap # v r
10185 topn 1 # v r v
10186 send a= # v ?
10187 jump lfin # v ?
10188
10189 # others
10190 eval v # r o v
10191 send ?? # r w
10192 send a= # w
10193
10194 */
10195
10196 asgnflag = COMPILE_RECV(ret, "NODE_OP_ASGN2#recv", node, RNODE_OP_ASGN2(node)->nd_recv);
10197 CHECK(asgnflag != -1);
10198 if (RNODE_OP_ASGN2(node)->nd_aid) {
10199 lskip = NEW_LABEL(line);
10200 ADD_INSN(ret, node, dup);
10201 ADD_INSNL(ret, node, branchnil, lskip);
10202 }
10203 ADD_INSN(ret, node, dup);
10204 ADD_SEND_WITH_FLAG(ret, node, vid, INT2FIX(0), INT2FIX(asgnflag));
10205
10206 if (atype == idOROP || atype == idANDOP) {
10207 if (!popped) {
10208 ADD_INSN(ret, node, dup);
10209 }
10210 if (atype == idOROP) {
10211 ADD_INSNL(ret, node, branchif, lcfin);
10212 }
10213 else { /* idANDOP */
10214 ADD_INSNL(ret, node, branchunless, lcfin);
10215 }
10216 if (!popped) {
10217 ADD_INSN(ret, node, pop);
10218 }
10219 CHECK(COMPILE(ret, "NODE_OP_ASGN2 val", RNODE_OP_ASGN2(node)->nd_value));
10220 if (!popped) {
10221 ADD_INSN(ret, node, swap);
10222 ADD_INSN1(ret, node, topn, INT2FIX(1));
10223 }
10224 ADD_SEND_WITH_FLAG(ret, node, aid, INT2FIX(1), INT2FIX(asgnflag));
10225 ADD_INSNL(ret, node, jump, lfin);
10226
10227 ADD_LABEL(ret, lcfin);
10228 if (!popped) {
10229 ADD_INSN(ret, node, swap);
10230 }
10231
10232 ADD_LABEL(ret, lfin);
10233 }
10234 else {
10235 CHECK(COMPILE(ret, "NODE_OP_ASGN2 val", RNODE_OP_ASGN2(node)->nd_value));
10236 ADD_SEND(ret, node, atype, INT2FIX(1));
10237 if (!popped) {
10238 ADD_INSN(ret, node, swap);
10239 ADD_INSN1(ret, node, topn, INT2FIX(1));
10240 }
10241 ADD_SEND_WITH_FLAG(ret, node, aid, INT2FIX(1), INT2FIX(asgnflag));
10242 }
10243 if (lskip && popped) {
10244 ADD_LABEL(ret, lskip);
10245 }
10246 ADD_INSN(ret, node, pop);
10247 if (lskip && !popped) {
10248 ADD_LABEL(ret, lskip);
10249 }
10250 return COMPILE_OK;
10251}
10252
10253static int compile_shareable_constant_value(rb_iseq_t *iseq, LINK_ANCHOR *ret, enum rb_parser_shareability shareable, const NODE *lhs, const NODE *value);
10254
10255static int
10256compile_op_cdecl(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
10257{
10258 const int line = nd_line(node);
10259 LABEL *lfin = 0;
10260 LABEL *lassign = 0;
10261 ID mid;
10262
10263 switch (nd_type(RNODE_OP_CDECL(node)->nd_head)) {
10264 case NODE_COLON3:
10265 ADD_INSN1(ret, node, putobject, rb_cObject);
10266 break;
10267 case NODE_COLON2:
10268 CHECK(COMPILE(ret, "NODE_OP_CDECL/colon2#nd_head", RNODE_COLON2(RNODE_OP_CDECL(node)->nd_head)->nd_head));
10269 break;
10270 default:
10271 COMPILE_ERROR(ERROR_ARGS "%s: invalid node in NODE_OP_CDECL",
10272 ruby_node_name(nd_type(RNODE_OP_CDECL(node)->nd_head)));
10273 return COMPILE_NG;
10274 }
10275 mid = get_node_colon_nd_mid(RNODE_OP_CDECL(node)->nd_head);
10276 /* cref */
10277 if (RNODE_OP_CDECL(node)->nd_aid == idOROP) {
10278 lassign = NEW_LABEL(line);
10279 ADD_INSN(ret, node, dup); /* cref cref */
10280 ADD_INSN3(ret, node, defined, INT2FIX(DEFINED_CONST_FROM),
10281 ID2SYM(mid), Qtrue); /* cref bool */
10282 ADD_INSNL(ret, node, branchunless, lassign); /* cref */
10283 }
10284 ADD_INSN(ret, node, dup); /* cref cref */
10285 ADD_INSN1(ret, node, putobject, Qtrue);
10286 ADD_INSN1(ret, node, getconstant, ID2SYM(mid)); /* cref obj */
10287
10288 if (RNODE_OP_CDECL(node)->nd_aid == idOROP || RNODE_OP_CDECL(node)->nd_aid == idANDOP) {
10289 lfin = NEW_LABEL(line);
10290 if (!popped) ADD_INSN(ret, node, dup); /* cref [obj] obj */
10291 if (RNODE_OP_CDECL(node)->nd_aid == idOROP)
10292 ADD_INSNL(ret, node, branchif, lfin);
10293 else /* idANDOP */
10294 ADD_INSNL(ret, node, branchunless, lfin);
10295 /* cref [obj] */
10296 if (!popped) ADD_INSN(ret, node, pop); /* cref */
10297 if (lassign) ADD_LABEL(ret, lassign);
10298 CHECK(compile_shareable_constant_value(iseq, ret, RNODE_OP_CDECL(node)->shareability, RNODE_OP_CDECL(node)->nd_head, RNODE_OP_CDECL(node)->nd_value));
10299 /* cref value */
10300 if (popped)
10301 ADD_INSN1(ret, node, topn, INT2FIX(1)); /* cref value cref */
10302 else {
10303 ADD_INSN1(ret, node, dupn, INT2FIX(2)); /* cref value cref value */
10304 ADD_INSN(ret, node, swap); /* cref value value cref */
10305 }
10306 ADD_INSN1(ret, node, setconstant, ID2SYM(mid)); /* cref [value] */
10307 ADD_LABEL(ret, lfin); /* cref [value] */
10308 if (!popped) ADD_INSN(ret, node, swap); /* [value] cref */
10309 ADD_INSN(ret, node, pop); /* [value] */
10310 }
10311 else {
10312 CHECK(compile_shareable_constant_value(iseq, ret, RNODE_OP_CDECL(node)->shareability, RNODE_OP_CDECL(node)->nd_head, RNODE_OP_CDECL(node)->nd_value));
10313 /* cref obj value */
10314 ADD_CALL(ret, node, RNODE_OP_CDECL(node)->nd_aid, INT2FIX(1));
10315 /* cref value */
10316 ADD_INSN(ret, node, swap); /* value cref */
10317 if (!popped) {
10318 ADD_INSN1(ret, node, topn, INT2FIX(1)); /* value cref value */
10319 ADD_INSN(ret, node, swap); /* value value cref */
10320 }
10321 ADD_INSN1(ret, node, setconstant, ID2SYM(mid));
10322 }
10323 return COMPILE_OK;
10324}
10325
10326static int
10327compile_op_log(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped, const enum node_type type)
10328{
10329 const int line = nd_line(node);
10330 LABEL *lfin = NEW_LABEL(line);
10331 LABEL *lassign;
10332
10333 if (type == NODE_OP_ASGN_OR && !nd_type_p(RNODE_OP_ASGN_OR(node)->nd_head, NODE_IVAR)) {
10334 LABEL *lfinish[2];
10335 lfinish[0] = lfin;
10336 lfinish[1] = 0;
10337 defined_expr(iseq, ret, RNODE_OP_ASGN_OR(node)->nd_head, lfinish, Qfalse, false);
10338 lassign = lfinish[1];
10339 if (!lassign) {
10340 lassign = NEW_LABEL(line);
10341 }
10342 ADD_INSNL(ret, node, branchunless, lassign);
10343 }
10344 else {
10345 lassign = NEW_LABEL(line);
10346 }
10347
10348 CHECK(COMPILE(ret, "NODE_OP_ASGN_AND/OR#nd_head", RNODE_OP_ASGN_OR(node)->nd_head));
10349
10350 if (!popped) {
10351 ADD_INSN(ret, node, dup);
10352 }
10353
10354 if (type == NODE_OP_ASGN_AND) {
10355 ADD_INSNL(ret, node, branchunless, lfin);
10356 }
10357 else {
10358 ADD_INSNL(ret, node, branchif, lfin);
10359 }
10360
10361 if (!popped) {
10362 ADD_INSN(ret, node, pop);
10363 }
10364
10365 ADD_LABEL(ret, lassign);
10366 CHECK(COMPILE_(ret, "NODE_OP_ASGN_AND/OR#nd_value", RNODE_OP_ASGN_OR(node)->nd_value, popped));
10367 ADD_LABEL(ret, lfin);
10368 return COMPILE_OK;
10369}
10370
10371static int
10372compile_super(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped, const enum node_type type)
10373{
10374 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
10375 DECL_ANCHOR(args);
10376 int argc;
10377 unsigned int flag = 0;
10378 struct rb_callinfo_kwarg *keywords = NULL;
10379 const rb_iseq_t *parent_block = ISEQ_COMPILE_DATA(iseq)->current_block;
10380 int use_block = 1;
10381
10382 INIT_ANCHOR(args);
10383 ISEQ_COMPILE_DATA(iseq)->current_block = NULL;
10384
10385 if (type == NODE_SUPER) {
10386 VALUE vargc = setup_args(iseq, args, RNODE_SUPER(node)->nd_args, &flag, &keywords);
10387 CHECK(!NIL_P(vargc));
10388 argc = FIX2INT(vargc);
10389 if ((flag & VM_CALL_ARGS_BLOCKARG) && (flag & VM_CALL_KW_SPLAT) && !(flag & VM_CALL_KW_SPLAT_MUT)) {
10390 ADD_INSN(args, node, splatkw);
10391 }
10392
10393 if (flag & VM_CALL_ARGS_BLOCKARG) {
10394 use_block = 0;
10395 }
10396 }
10397 else {
10398 /* NODE_ZSUPER */
10399 int i;
10400 const rb_iseq_t *liseq = body->local_iseq;
10401 const struct rb_iseq_constant_body *const local_body = ISEQ_BODY(liseq);
10402 const struct rb_iseq_param_keyword *const local_kwd = local_body->param.keyword;
10403 int lvar_level = get_lvar_level(iseq);
10404
10405 argc = local_body->param.lead_num;
10406
10407 /* normal arguments */
10408 for (i = 0; i < local_body->param.lead_num; i++) {
10409 int idx = local_body->local_table_size - i;
10410 ADD_GETLOCAL(args, node, idx, lvar_level);
10411 }
10412
10413 /* forward ... */
10414 if (local_body->param.flags.forwardable) {
10415 flag |= VM_CALL_FORWARDING;
10416 int idx = local_body->local_table_size - get_local_var_idx(liseq, idDot3);
10417 ADD_GETLOCAL(args, node, idx, lvar_level);
10418 }
10419
10420 if (local_body->param.flags.has_opt) {
10421 /* optional arguments */
10422 int j;
10423 for (j = 0; j < local_body->param.opt_num; j++) {
10424 int idx = local_body->local_table_size - (i + j);
10425 ADD_GETLOCAL(args, node, idx, lvar_level);
10426 }
10427 i += j;
10428 argc = i;
10429 }
10430 if (local_body->param.flags.has_rest) {
10431 /* rest argument */
10432 int idx = local_body->local_table_size - rb_iseq_param_rest_start(local_body);
10433 ADD_GETLOCAL(args, node, idx, lvar_level);
10434 ADD_INSN1(args, node, splatarray, RBOOL(local_body->param.flags.has_post));
10435
10436 argc = rb_iseq_param_rest_start(local_body) + 1;
10437 flag |= VM_CALL_ARGS_SPLAT;
10438 }
10439 if (local_body->param.flags.has_post) {
10440 /* post arguments */
10441 int post_len = local_body->param.post_num;
10442 int post_start = rb_iseq_param_post_start(local_body);
10443
10444 if (local_body->param.flags.has_rest) {
10445 int j;
10446 for (j=0; j<post_len; j++) {
10447 int idx = local_body->local_table_size - (post_start + j);
10448 ADD_GETLOCAL(args, node, idx, lvar_level);
10449 }
10450 ADD_INSN1(args, node, pushtoarray, INT2FIX(j));
10451 flag |= VM_CALL_ARGS_SPLAT_MUT;
10452 /* argc is settled at above */
10453 }
10454 else {
10455 int j;
10456 for (j=0; j<post_len; j++) {
10457 int idx = local_body->local_table_size - (post_start + j);
10458 ADD_GETLOCAL(args, node, idx, lvar_level);
10459 }
10460 argc = post_len + post_start;
10461 }
10462 }
10463
10464 if (local_body->param.flags.has_kw) { /* TODO: support keywords */
10465 int local_size = local_body->local_table_size;
10466 argc++;
10467
10468 /* The keyword rest local may have been reassigned to any
10469 * object, so it is never merged into in place. hash_merge_ptr
10470 * converts it with to_hash (nil being empty) and copies it into
10471 * a hash allocated at its final size. */
10472 if (local_body->param.flags.has_kwrest) {
10473 int idx = local_body->local_table_size - local_kwd->rest_start;
10474 RUBY_ASSERT(local_kwd->num > 0);
10475 ADD_INSN1(args, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
10476 ADD_GETLOCAL(args, node, idx, lvar_level);
10477 }
10478 for (i = 0; i < local_kwd->num; ++i) {
10479 ID id = local_kwd->table[i];
10480 int idx = local_size - get_local_var_idx(liseq, id);
10481 ADD_INSN1(args, node, putobject, ID2SYM(id));
10482 ADD_GETLOCAL(args, node, idx, lvar_level);
10483 }
10484 if (local_body->param.flags.has_kwrest) {
10485 ADD_SEND(args, node, id_core_hash_merge_ptr, INT2FIX(i * 2 + 1));
10486 }
10487 else {
10488 ADD_INSN1(args, node, newhash, INT2FIX(i * 2));
10489 }
10490 flag |= VM_CALL_KW_SPLAT| VM_CALL_KW_SPLAT_MUT;
10491 }
10492 else if (local_body->param.flags.has_kwrest) {
10493 int idx = local_body->local_table_size - local_kwd->rest_start;
10494 ADD_GETLOCAL(args, node, idx, lvar_level);
10495 argc++;
10496 flag |= VM_CALL_KW_SPLAT;
10497 }
10498 }
10499
10500 if (use_block && parent_block == NULL) {
10501 iseq_set_use_block(ISEQ_BODY(iseq)->local_iseq);
10502 }
10503
10504 flag |= VM_CALL_SUPER | VM_CALL_FCALL;
10505 if (type == NODE_ZSUPER) flag |= VM_CALL_ZSUPER;
10506 ADD_INSN(ret, node, putself);
10507 ADD_SEQ(ret, args);
10508
10509 const struct rb_callinfo * ci = new_callinfo(iseq, 0, argc, flag, keywords, parent_block != NULL);
10510
10511 if (vm_ci_flag(ci) & VM_CALL_FORWARDING) {
10512 ADD_INSN2(ret, node, invokesuperforward, ci, parent_block);
10513 }
10514 else {
10515 ADD_INSN2(ret, node, invokesuper, ci, parent_block);
10516 }
10517
10518 if (popped) {
10519 ADD_INSN(ret, node, pop);
10520 }
10521 return COMPILE_OK;
10522}
10523
10524static int
10525compile_yield(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
10526{
10527 DECL_ANCHOR(args);
10528 VALUE argc;
10529 unsigned int flag = 0;
10530 struct rb_callinfo_kwarg *keywords = NULL;
10531
10532 INIT_ANCHOR(args);
10533
10534 switch (ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq)->type) {
10535 case ISEQ_TYPE_TOP:
10536 case ISEQ_TYPE_MAIN:
10537 case ISEQ_TYPE_CLASS:
10538 COMPILE_ERROR(ERROR_ARGS "Invalid yield");
10539 return COMPILE_NG;
10540 default: /* valid */;
10541 }
10542
10543 if (RNODE_YIELD(node)->nd_head) {
10544 argc = setup_args(iseq, args, RNODE_YIELD(node)->nd_head, &flag, &keywords);
10545 CHECK(!NIL_P(argc));
10546 }
10547 else {
10548 argc = INT2FIX(0);
10549 }
10550
10551 ADD_SEQ(ret, args);
10552 ADD_INSN1(ret, node, invokeblock, new_callinfo(iseq, 0, FIX2INT(argc), flag, keywords, FALSE));
10553 iseq_set_use_block(ISEQ_BODY(iseq)->local_iseq);
10554
10555 if (popped) {
10556 ADD_INSN(ret, node, pop);
10557 }
10558
10559 int level = 0;
10560 const rb_iseq_t *tmp_iseq = iseq;
10561 for (; tmp_iseq != ISEQ_BODY(iseq)->local_iseq; level++ ) {
10562 tmp_iseq = ISEQ_BODY(tmp_iseq)->parent_iseq;
10563 }
10564 if (level > 0) access_outer_variables(iseq, level, rb_intern("yield"), true);
10565
10566 return COMPILE_OK;
10567}
10568
10569static int
10570compile_match(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped, const enum node_type type)
10571{
10572 DECL_ANCHOR(recv);
10573 DECL_ANCHOR(val);
10574
10575 INIT_ANCHOR(recv);
10576 INIT_ANCHOR(val);
10577 switch ((int)type) {
10578 case NODE_MATCH:
10579 {
10580 VALUE re = rb_node_regx_string_val(node);
10582 ADD_INSN1(recv, node, putobject, re);
10583 ADD_INSN2(val, node, getspecial, INT2FIX(0),
10584 INT2FIX(0));
10585 }
10586 break;
10587 case NODE_MATCH2:
10588 CHECK(COMPILE(recv, "receiver", RNODE_MATCH2(node)->nd_recv));
10589 CHECK(COMPILE(val, "value", RNODE_MATCH2(node)->nd_value));
10590 break;
10591 case NODE_MATCH3:
10592 CHECK(COMPILE(recv, "receiver", RNODE_MATCH3(node)->nd_value));
10593 CHECK(COMPILE(val, "value", RNODE_MATCH3(node)->nd_recv));
10594 break;
10595 }
10596
10597 ADD_SEQ(ret, recv);
10598 ADD_SEQ(ret, val);
10599 ADD_SEND(ret, node, idEqTilde, INT2FIX(1));
10600
10601 if (nd_type_p(node, NODE_MATCH2) && RNODE_MATCH2(node)->nd_args) {
10602 compile_named_capture_assign(iseq, ret, RNODE_MATCH2(node)->nd_args);
10603 }
10604
10605 if (popped) {
10606 ADD_INSN(ret, node, pop);
10607 }
10608 return COMPILE_OK;
10609}
10610
10611static int
10612compile_colon2(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
10613{
10614 if (rb_is_const_id(RNODE_COLON2(node)->nd_mid)) {
10615 /* constant */
10616 rb_const_path_t const_path;
10617 if (ISEQ_COMPILE_DATA(iseq)->option->inline_const_cache &&
10618 (const_path = compile_const_path(iseq, node))) {
10619 ISEQ_BODY(iseq)->ic_size++;
10620 ADD_INSN1(ret, node, opt_getconstant_path, (VALUE)const_path);
10621 }
10622 else {
10623 /* constant */
10624 DECL_ANCHOR(pref);
10625 DECL_ANCHOR(body);
10626
10627 INIT_ANCHOR(pref);
10628 INIT_ANCHOR(body);
10629 CHECK(compile_const_prefix(iseq, node, pref, body));
10630 if (LIST_INSN_SIZE_ZERO(pref)) {
10631 ADD_INSN(ret, node, putnil);
10632 ADD_SEQ(ret, body);
10633 }
10634 else {
10635 ADD_SEQ(ret, pref);
10636 ADD_SEQ(ret, body);
10637 }
10638 }
10639 }
10640 else {
10641 /* function call */
10642 ADD_CALL_RECEIVER(ret, node);
10643 CHECK(COMPILE(ret, "colon2#nd_head", RNODE_COLON2(node)->nd_head));
10644 ADD_CALL(ret, node, RNODE_COLON2(node)->nd_mid, INT2FIX(1));
10645 }
10646 if (popped) {
10647 ADD_INSN(ret, node, pop);
10648 }
10649 return COMPILE_OK;
10650}
10651
10652static int
10653compile_colon3(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
10654{
10655 debugi("colon3#nd_mid", RNODE_COLON3(node)->nd_mid);
10656
10657 /* add cache insn */
10658 if (ISEQ_COMPILE_DATA(iseq)->option->inline_const_cache) {
10659 ISEQ_BODY(iseq)->ic_size++;
10660 rb_const_path_t const_path = rb_const_path_from_ids(true, &RNODE_COLON3(node)->nd_mid, 1);
10661 ADD_INSN1(ret, node, opt_getconstant_path, (VALUE)const_path);
10662 }
10663 else {
10664 ADD_INSN1(ret, node, putobject, rb_cObject);
10665 ADD_INSN1(ret, node, putobject, Qtrue);
10666 ADD_INSN1(ret, node, getconstant, ID2SYM(RNODE_COLON3(node)->nd_mid));
10667 }
10668
10669 if (popped) {
10670 ADD_INSN(ret, node, pop);
10671 }
10672 return COMPILE_OK;
10673}
10674
10675static int
10676compile_dots(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped, const int excl)
10677{
10678 VALUE flag = INT2FIX(excl);
10679 const NODE *b = RNODE_DOT2(node)->nd_beg;
10680 const NODE *e = RNODE_DOT2(node)->nd_end;
10681
10682 if (optimizable_range_item_p(b) && optimizable_range_item_p(e)) {
10683 if (!popped) {
10684 VALUE bv = optimized_range_item(b);
10685 VALUE ev = optimized_range_item(e);
10686 VALUE val = rb_range_new(bv, ev, excl);
10688 ADD_INSN1(ret, node, putobject, val);
10689 RB_OBJ_WRITTEN(iseq, Qundef, val);
10690 }
10691 }
10692 else {
10693 CHECK(COMPILE_(ret, "min", b, popped));
10694 CHECK(COMPILE_(ret, "max", e, popped));
10695 if (!popped) {
10696 ADD_INSN1(ret, node, newrange, flag);
10697 }
10698 }
10699 return COMPILE_OK;
10700}
10701
10702static int
10703compile_errinfo(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
10704{
10705 if (!popped) {
10706 if (ISEQ_BODY(iseq)->type == ISEQ_TYPE_RESCUE) {
10707 ADD_GETLOCAL(ret, node, LVAR_ERRINFO, 0);
10708 }
10709 else {
10710 const rb_iseq_t *ip = iseq;
10711 int level = 0;
10712 while (ip) {
10713 if (ISEQ_BODY(ip)->type == ISEQ_TYPE_RESCUE) {
10714 break;
10715 }
10716 ip = ISEQ_BODY(ip)->parent_iseq;
10717 level++;
10718 }
10719 if (ip) {
10720 ADD_GETLOCAL(ret, node, LVAR_ERRINFO, level);
10721 }
10722 else {
10723 ADD_INSN(ret, node, putnil);
10724 }
10725 }
10726 }
10727 return COMPILE_OK;
10728}
10729
10730static int
10731compile_kw_arg(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
10732{
10733 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
10734 LABEL *end_label = NEW_LABEL(nd_line(node));
10735 const NODE *default_value = get_nd_value(RNODE_KW_ARG(node)->nd_body);
10736
10737 if (default_value == NODE_SPECIAL_REQUIRED_KEYWORD) {
10738 /* required argument. do nothing */
10739 COMPILE_ERROR(ERROR_ARGS "unreachable");
10740 return COMPILE_NG;
10741 }
10742 else if (nd_type_p(default_value, NODE_SYM) ||
10743 nd_type_p(default_value, NODE_REGX) ||
10744 nd_type_p(default_value, NODE_LINE) ||
10745 nd_type_p(default_value, NODE_INTEGER) ||
10746 nd_type_p(default_value, NODE_FLOAT) ||
10747 nd_type_p(default_value, NODE_RATIONAL) ||
10748 nd_type_p(default_value, NODE_IMAGINARY) ||
10749 nd_type_p(default_value, NODE_NIL) ||
10750 nd_type_p(default_value, NODE_TRUE) ||
10751 nd_type_p(default_value, NODE_FALSE)) {
10752 COMPILE_ERROR(ERROR_ARGS "unreachable");
10753 return COMPILE_NG;
10754 }
10755 else {
10756 /* if keywordcheck(_kw_bits, nth_keyword)
10757 * kw = default_value
10758 * end
10759 */
10760 int kw_bits_idx = body->local_table_size - body->param.keyword->bits_start;
10761 int keyword_idx = body->param.keyword->num - body->param.keyword->required_num;
10762 for (const rb_node_kw_arg_t *kwarg = RNODE_KW_ARG(node); kwarg; kwarg = kwarg->nd_next) {
10763 if (get_nd_value(kwarg->nd_body) != NODE_SPECIAL_REQUIRED_KEYWORD) {
10764 keyword_idx--;
10765 }
10766 }
10767
10768 ADD_INSN2(ret, node, checkkeyword, INT2FIX(kw_bits_idx + VM_ENV_DATA_SIZE - 1), INT2FIX(keyword_idx));
10769 ADD_INSNL(ret, node, branchif, end_label);
10770 CHECK(COMPILE_POPPED(ret, "keyword default argument", RNODE_KW_ARG(node)->nd_body));
10771 ADD_LABEL(ret, end_label);
10772 }
10773 return COMPILE_OK;
10774}
10775
10776static int
10777compile_attrasgn(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
10778{
10779 DECL_ANCHOR(recv);
10780 DECL_ANCHOR(args);
10781 unsigned int flag = 0;
10782 ID mid = RNODE_ATTRASGN(node)->nd_mid;
10783 VALUE argc;
10784 LABEL *else_label = NULL;
10785 VALUE branches = Qfalse;
10786
10787 INIT_ANCHOR(recv);
10788 INIT_ANCHOR(args);
10789 argc = setup_args(iseq, args, RNODE_ATTRASGN(node)->nd_args, &flag, NULL);
10790 CHECK(!NIL_P(argc));
10791
10792 int asgnflag = COMPILE_RECV(recv, "recv", node, RNODE_ATTRASGN(node)->nd_recv);
10793 CHECK(asgnflag != -1);
10794 flag |= (unsigned int)asgnflag;
10795
10796 debugp_param("argc", argc);
10797 debugp_param("nd_mid", ID2SYM(mid));
10798
10799 if (!rb_is_attrset_id(mid)) {
10800 /* safe nav attr */
10801 mid = rb_id_attrset(mid);
10802 else_label = qcall_branch_start(iseq, recv, &branches, node, node);
10803 }
10804 if (!popped) {
10805 ADD_INSN(ret, node, putnil);
10806 ADD_SEQ(ret, recv);
10807 ADD_SEQ(ret, args);
10808
10809 if (flag & VM_CALL_ARGS_SPLAT) {
10810 ADD_INSN(ret, node, dup);
10811 ADD_INSN1(ret, node, putobject, INT2FIX(-1));
10812 ADD_SEND_WITH_FLAG(ret, node, idAREF, INT2FIX(1), INT2FIX(asgnflag));
10813 ADD_INSN1(ret, node, setn, FIXNUM_INC(argc, 2));
10814 ADD_INSN (ret, node, pop);
10815 }
10816 else {
10817 ADD_INSN1(ret, node, setn, FIXNUM_INC(argc, 1));
10818 }
10819 }
10820 else {
10821 ADD_SEQ(ret, recv);
10822 ADD_SEQ(ret, args);
10823 }
10824 ADD_SEND_WITH_FLAG(ret, node, mid, argc, INT2FIX(flag));
10825 qcall_branch_end(iseq, ret, else_label, branches, node, node);
10826 ADD_INSN(ret, node, pop);
10827 return COMPILE_OK;
10828}
10829
10830static int
10831compile_make_shareable_node(rb_iseq_t *iseq, LINK_ANCHOR *ret, LINK_ANCHOR *sub, const NODE *value, bool copy)
10832{
10833 ADD_INSN1(ret, value, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
10834 ADD_SEQ(ret, sub);
10835
10836 if (copy) {
10837 /*
10838 * NEW_CALL(fcore, rb_intern("make_shareable_copy"),
10839 * NEW_LIST(value, loc), loc);
10840 */
10841 ADD_SEND_WITH_FLAG(ret, value, rb_intern("make_shareable_copy"), INT2FIX(1), INT2FIX(VM_CALL_ARGS_SIMPLE));
10842 }
10843 else {
10844 /*
10845 * NEW_CALL(fcore, rb_intern("make_shareable"),
10846 * NEW_LIST(value, loc), loc);
10847 */
10848 ADD_SEND_WITH_FLAG(ret, value, rb_intern("make_shareable"), INT2FIX(1), INT2FIX(VM_CALL_ARGS_SIMPLE));
10849 }
10850
10851 return COMPILE_OK;
10852}
10853
10854static VALUE
10855node_const_decl_val(const NODE *node)
10856{
10857 VALUE path;
10858 switch (nd_type(node)) {
10859 case NODE_CDECL:
10860 if (RNODE_CDECL(node)->nd_vid) {
10861 path = rb_id2str(RNODE_CDECL(node)->nd_vid);
10862 goto end;
10863 }
10864 else {
10865 node = RNODE_CDECL(node)->nd_else;
10866 }
10867 break;
10868 case NODE_COLON2:
10869 break;
10870 case NODE_COLON3:
10871 // ::Const
10872 path = rb_str_new_cstr("::");
10873 rb_str_append(path, rb_id2str(RNODE_COLON3(node)->nd_mid));
10874 goto end;
10875 default:
10876 rb_bug("unexpected node: %s", ruby_node_name(nd_type(node)));
10878 }
10879
10880 path = rb_ary_new();
10881 if (node) {
10882 for (; node && nd_type_p(node, NODE_COLON2); node = RNODE_COLON2(node)->nd_head) {
10883 rb_ary_push(path, rb_id2str(RNODE_COLON2(node)->nd_mid));
10884 }
10885 if (node && nd_type_p(node, NODE_CONST)) {
10886 // Const::Name
10887 rb_ary_push(path, rb_id2str(RNODE_CONST(node)->nd_vid));
10888 }
10889 else if (node && nd_type_p(node, NODE_COLON3)) {
10890 // ::Const::Name
10891 rb_ary_push(path, rb_id2str(RNODE_COLON3(node)->nd_mid));
10892 rb_ary_push(path, rb_str_new(0, 0));
10893 }
10894 else {
10895 // expression::Name
10896 rb_ary_push(path, rb_str_new_cstr("..."));
10897 }
10898 path = rb_ary_join(rb_ary_reverse(path), rb_str_new_cstr("::"));
10899 }
10900 end:
10901 path = rb_fstring(path);
10902 return path;
10903}
10904
10905static VALUE
10906const_decl_path(NODE *dest)
10907{
10908 VALUE path = Qnil;
10909 if (!nd_type_p(dest, NODE_CALL)) {
10910 path = node_const_decl_val(dest);
10911 }
10912 return path;
10913}
10914
10915static int
10916compile_ensure_shareable_node(rb_iseq_t *iseq, LINK_ANCHOR *ret, NODE *dest, const NODE *value)
10917{
10918 /*
10919 *. RubyVM::FrozenCore.ensure_shareable(value, const_decl_path(dest))
10920 */
10921 VALUE path = const_decl_path(dest);
10922 ADD_INSN1(ret, value, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
10923 CHECK(COMPILE(ret, "compile_ensure_shareable_node", value));
10924 ADD_INSN1(ret, value, putobject, path);
10925 RB_OBJ_WRITTEN(iseq, Qundef, path);
10926 ADD_SEND_WITH_FLAG(ret, value, rb_intern("ensure_shareable"), INT2FIX(2), INT2FIX(VM_CALL_ARGS_SIMPLE));
10927
10928 return COMPILE_OK;
10929}
10930
10931#ifndef SHAREABLE_BARE_EXPRESSION
10932#define SHAREABLE_BARE_EXPRESSION 1
10933#endif
10934
10935static int
10936compile_shareable_literal_constant(rb_iseq_t *iseq, LINK_ANCHOR *ret, enum rb_parser_shareability shareable, NODE *dest, const NODE *node, size_t level, VALUE *value_p, int *shareable_literal_p)
10937{
10938# define compile_shareable_literal_constant_next(node, anchor, value_p, shareable_literal_p) \
10939 compile_shareable_literal_constant(iseq, anchor, shareable, dest, node, level+1, value_p, shareable_literal_p)
10940 VALUE lit = Qnil;
10941 DECL_ANCHOR(anchor);
10942
10943 enum node_type type = node ? nd_type(node) : NODE_NIL;
10944 switch (type) {
10945 case NODE_TRUE:
10946 *value_p = Qtrue;
10947 goto compile;
10948 case NODE_FALSE:
10949 *value_p = Qfalse;
10950 goto compile;
10951 case NODE_NIL:
10952 *value_p = Qnil;
10953 goto compile;
10954 case NODE_SYM:
10955 *value_p = rb_node_sym_string_val(node);
10956 goto compile;
10957 case NODE_REGX:
10958 *value_p = rb_node_regx_string_val(node);
10959 goto compile;
10960 case NODE_LINE:
10961 *value_p = rb_node_line_lineno_val(node);
10962 goto compile;
10963 case NODE_INTEGER:
10964 *value_p = rb_node_integer_literal_val(node);
10965 goto compile;
10966 case NODE_FLOAT:
10967 *value_p = rb_node_float_literal_val(node);
10968 goto compile;
10969 case NODE_RATIONAL:
10970 *value_p = rb_node_rational_literal_val(node);
10971 goto compile;
10972 case NODE_IMAGINARY:
10973 *value_p = rb_node_imaginary_literal_val(node);
10974 goto compile;
10975 case NODE_ENCODING:
10976 *value_p = rb_node_encoding_val(node);
10977
10978 compile:
10979 CHECK(COMPILE(ret, "shareable_literal_constant", node));
10980 *shareable_literal_p = 1;
10981 return COMPILE_OK;
10982
10983 case NODE_DSTR:
10984 CHECK(COMPILE(ret, "shareable_literal_constant", node));
10985 if (shareable == rb_parser_shareable_literal) {
10986 /*
10987 * NEW_CALL(node, idUMinus, 0, loc);
10988 *
10989 * -"#{var}"
10990 */
10991 ADD_SEND_WITH_FLAG(ret, node, idUMinus, INT2FIX(0), INT2FIX(VM_CALL_ARGS_SIMPLE));
10992 }
10993 *value_p = Qundef;
10994 *shareable_literal_p = 1;
10995 return COMPILE_OK;
10996
10997 case NODE_STR:{
10998 VALUE lit = rb_node_str_string_val(node);
10999 ADD_INSN1(ret, node, putobject, lit);
11000 RB_OBJ_WRITTEN(iseq, Qundef, lit);
11001 *value_p = lit;
11002 *shareable_literal_p = 1;
11003
11004 return COMPILE_OK;
11005 }
11006
11007 case NODE_FILE:
11008 compile_file_path(iseq, ret, node, ISEQ_FROZEN_STRING_LITERAL_ENABLED);
11009 *value_p = Qundef;
11010 *shareable_literal_p = 1;
11011 return COMPILE_OK;
11012
11013 case NODE_ZLIST:{
11014 VALUE lit = rb_ary_new();
11015 OBJ_FREEZE(lit);
11016 ADD_INSN1(ret, node, putobject, lit);
11017 RB_OBJ_WRITTEN(iseq, Qundef, lit);
11018 *value_p = lit;
11019 *shareable_literal_p = 1;
11020
11021 return COMPILE_OK;
11022 }
11023
11024 case NODE_LIST:{
11025 INIT_ANCHOR(anchor);
11026 lit = rb_ary_new();
11027 for (NODE *n = (NODE *)node; n; n = RNODE_LIST(n)->nd_next) {
11028 VALUE val = Qundef;
11029 int shareable_literal_p2;
11030 NODE *elt = RNODE_LIST(n)->nd_head;
11031 if (elt) {
11032 CHECK(compile_shareable_literal_constant_next(elt, anchor, &val, &shareable_literal_p2));
11033 if (shareable_literal_p2) {
11034 /* noop */
11035 }
11036 else if (RTEST(lit)) {
11037 rb_ary_clear(lit);
11038 lit = Qfalse;
11039 }
11040 }
11041 if (RTEST(lit)) {
11042 if (!UNDEF_P(val)) {
11043 rb_ary_push(lit, val);
11044 }
11045 else {
11046 rb_ary_clear(lit);
11047 lit = Qnil; /* make shareable at runtime */
11048 }
11049 }
11050 }
11051 break;
11052 }
11053 case NODE_HASH:{
11054 if (!RNODE_HASH(node)->nd_brace) goto compile_shareable;
11055 for (NODE *n = RNODE_HASH(node)->nd_head; n; n = RNODE_LIST(RNODE_LIST(n)->nd_next)->nd_next) {
11056 if (!RNODE_LIST(n)->nd_head) {
11057 // If the hash node have a keyword splat, fall back to the default case.
11058 goto compile_shareable;
11059 }
11060 }
11061
11062 INIT_ANCHOR(anchor);
11063 lit = rb_hash_new();
11064 for (NODE *n = RNODE_HASH(node)->nd_head; n; n = RNODE_LIST(RNODE_LIST(n)->nd_next)->nd_next) {
11065 VALUE key_val = 0;
11066 VALUE value_val = 0;
11067 int shareable_literal_p2;
11068 NODE *key = RNODE_LIST(n)->nd_head;
11069 NODE *val = RNODE_LIST(RNODE_LIST(n)->nd_next)->nd_head;
11070 CHECK(compile_shareable_literal_constant_next(key, anchor, &key_val, &shareable_literal_p2));
11071 if (shareable_literal_p2) {
11072 /* noop */
11073 }
11074 else if (RTEST(lit)) {
11075 rb_hash_clear(lit);
11076 lit = Qfalse;
11077 }
11078 CHECK(compile_shareable_literal_constant_next(val, anchor, &value_val, &shareable_literal_p2));
11079 if (shareable_literal_p2) {
11080 /* noop */
11081 }
11082 else if (RTEST(lit)) {
11083 rb_hash_clear(lit);
11084 lit = Qfalse;
11085 }
11086 if (RTEST(lit)) {
11087 if (!UNDEF_P(key_val) && !UNDEF_P(value_val)) {
11088 rb_hash_aset(lit, key_val, value_val);
11089 }
11090 else {
11091 rb_hash_clear(lit);
11092 lit = Qnil; /* make shareable at runtime */
11093 }
11094 }
11095 }
11096 break;
11097 }
11098
11099 default:
11100
11101 compile_shareable:
11102 if (shareable == rb_parser_shareable_literal &&
11103 (SHAREABLE_BARE_EXPRESSION || level > 0)) {
11104 CHECK(compile_ensure_shareable_node(iseq, ret, dest, node));
11105 *value_p = Qundef;
11106 *shareable_literal_p = 1;
11107 return COMPILE_OK;
11108 }
11109 CHECK(COMPILE(ret, "shareable_literal_constant", node));
11110 *value_p = Qundef;
11111 *shareable_literal_p = 0;
11112 return COMPILE_OK;
11113 }
11114
11115 /* Array or Hash that does not have keyword splat */
11116 if (!lit) {
11117 if (nd_type(node) == NODE_LIST) {
11118 ADD_INSN1(anchor, node, newarray, INT2FIX(RNODE_LIST(node)->as.nd_alen));
11119 }
11120 else if (nd_type(node) == NODE_HASH) {
11121 long len = RNODE_LIST(RNODE_HASH(node)->nd_head)->as.nd_alen;
11124 ADD_INSN1(anchor, node, newhash, LONG2FIX(len));
11125 }
11126 *value_p = Qundef;
11127 *shareable_literal_p = 0;
11128 ADD_SEQ(ret, anchor);
11129 return COMPILE_OK;
11130 }
11131 if (NIL_P(lit)) {
11132 // if shareable_literal, all elements should have been ensured
11133 // as shareable
11134 if (nd_type(node) == NODE_LIST) {
11135 ADD_INSN1(anchor, node, newarray, INT2FIX(RNODE_LIST(node)->as.nd_alen));
11136 }
11137 else if (nd_type(node) == NODE_HASH) {
11138 long len = RNODE_LIST(RNODE_HASH(node)->nd_head)->as.nd_alen;
11141 ADD_INSN1(anchor, node, newhash, LONG2FIX(len));
11142 }
11143 CHECK(compile_make_shareable_node(iseq, ret, anchor, node, false));
11144 *value_p = Qundef;
11145 *shareable_literal_p = 1;
11146 }
11147 else {
11149 ADD_INSN1(ret, node, putobject, val);
11150 RB_OBJ_WRITTEN(iseq, Qundef, val);
11151 *value_p = val;
11152 *shareable_literal_p = 1;
11153 }
11154
11155 return COMPILE_OK;
11156}
11157
11158static int
11159compile_shareable_constant_value(rb_iseq_t *iseq, LINK_ANCHOR *ret, enum rb_parser_shareability shareable, const NODE *lhs, const NODE *value)
11160{
11161 int literal_p = 0;
11162 VALUE val;
11163 DECL_ANCHOR(anchor);
11164 INIT_ANCHOR(anchor);
11165
11166 switch (shareable) {
11167 case rb_parser_shareable_none:
11168 CHECK(COMPILE(ret, "compile_shareable_constant_value", value));
11169 return COMPILE_OK;
11170
11171 case rb_parser_shareable_literal:
11172 CHECK(compile_shareable_literal_constant(iseq, anchor, shareable, (NODE *)lhs, value, 0, &val, &literal_p));
11173 ADD_SEQ(ret, anchor);
11174 return COMPILE_OK;
11175
11176 case rb_parser_shareable_copy:
11177 case rb_parser_shareable_everything:
11178 CHECK(compile_shareable_literal_constant(iseq, anchor, shareable, (NODE *)lhs, value, 0, &val, &literal_p));
11179 if (!literal_p) {
11180 CHECK(compile_make_shareable_node(iseq, ret, anchor, value, shareable == rb_parser_shareable_copy));
11181 }
11182 else {
11183 ADD_SEQ(ret, anchor);
11184 }
11185 return COMPILE_OK;
11186 default:
11187 rb_bug("unexpected rb_parser_shareability: %d", shareable);
11188 }
11189}
11190
11191static int iseq_compile_each0(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped);
11199static int
11200iseq_compile_each(rb_iseq_t *iseq, LINK_ANCHOR *ret, const NODE *node, int popped)
11201{
11202 if (node == 0) {
11203 if (!popped) {
11204 debugs("node: NODE_NIL(implicit)\n");
11205 ADD_SYNTHETIC_INSN(ret, iseq_synthetic_lineno(iseq), -1, putnil);
11206 }
11207 return COMPILE_OK;
11208 }
11209 return iseq_compile_each0(iseq, ret, node, popped);
11210}
11211
11212static int
11213iseq_compile_each0(rb_iseq_t *iseq, LINK_ANCHOR *const ret, const NODE *const node, int popped)
11214{
11215 const int line = (int)nd_line(node);
11216 const enum node_type type = nd_type(node);
11217 struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
11218
11219 if (ISEQ_COMPILE_DATA(iseq)->last_line == line) {
11220 /* ignore */
11221 }
11222 else {
11223 if (nd_fl_newline(node)) {
11224 int event = RUBY_EVENT_LINE;
11225 ISEQ_COMPILE_DATA(iseq)->last_line = line;
11226 if (line > 0 && ISEQ_COVERAGE(iseq) && ISEQ_LINE_COVERAGE(iseq)) {
11227 event |= RUBY_EVENT_COVERAGE_LINE;
11228 }
11229 ADD_TRACE(ret, event);
11230 }
11231 }
11232
11233 debug_node_start(node);
11234#undef BEFORE_RETURN
11235#define BEFORE_RETURN debug_node_end()
11236
11237 switch (type) {
11238 case NODE_BLOCK:
11239 CHECK(compile_block(iseq, ret, node, popped));
11240 break;
11241 case NODE_IF:
11242 case NODE_UNLESS:
11243 CHECK(compile_if(iseq, ret, node, popped, type));
11244 break;
11245 case NODE_CASE:
11246 CHECK(compile_case(iseq, ret, node, popped));
11247 break;
11248 case NODE_CASE2:
11249 CHECK(compile_case2(iseq, ret, node, popped));
11250 break;
11251 case NODE_CASE3:
11252 CHECK(compile_case3(iseq, ret, node, popped));
11253 break;
11254 case NODE_WHILE:
11255 case NODE_UNTIL:
11256 CHECK(compile_loop(iseq, ret, node, popped, type));
11257 break;
11258 case NODE_FOR:
11259 case NODE_ITER:
11260 CHECK(compile_iter(iseq, ret, node, popped));
11261 break;
11262 case NODE_FOR_MASGN:
11263 CHECK(compile_for_masgn(iseq, ret, node, popped));
11264 break;
11265 case NODE_BREAK:
11266 CHECK(compile_break(iseq, ret, node, popped));
11267 break;
11268 case NODE_NEXT:
11269 CHECK(compile_next(iseq, ret, node, popped));
11270 break;
11271 case NODE_REDO:
11272 CHECK(compile_redo(iseq, ret, node, popped));
11273 break;
11274 case NODE_RETRY:
11275 CHECK(compile_retry(iseq, ret, node, popped));
11276 break;
11277 case NODE_BEGIN:{
11278 CHECK(COMPILE_(ret, "NODE_BEGIN", RNODE_BEGIN(node)->nd_body, popped));
11279 break;
11280 }
11281 case NODE_RESCUE:
11282 CHECK(compile_rescue(iseq, ret, node, popped));
11283 break;
11284 case NODE_RESBODY:
11285 CHECK(compile_resbody(iseq, ret, node, popped));
11286 break;
11287 case NODE_ENSURE:
11288 CHECK(compile_ensure(iseq, ret, node, popped));
11289 break;
11290
11291 case NODE_AND:
11292 case NODE_OR:{
11293 LABEL *end_label = NEW_LABEL(line);
11294 const NODE *cond = node;
11295 /* Compile a chain of the same operator (`a && b && ...`) against one
11296 * shared end label, so every branch targets it directly. Compiling
11297 * nd_2nd recursively would instead give each operator its own label,
11298 * and the peephole optimizer would rewrite that chain in quadratic
11299 * time. */
11300 while (1) {
11301 CHECK(COMPILE(ret, "nd_1st", RNODE_OR(cond)->nd_1st));
11302 if (!popped) {
11303 ADD_INSN(ret, cond, dup);
11304 }
11305 if (type == NODE_AND) {
11306 ADD_INSNL(ret, cond, branchunless, end_label);
11307 }
11308 else {
11309 ADD_INSNL(ret, cond, branchif, end_label);
11310 }
11311 if (!popped) {
11312 ADD_INSN(ret, cond, pop);
11313 }
11314 const NODE *rest = RNODE_OR(cond)->nd_2nd;
11315 if (nd_type_p(rest, type)) {
11316 cond = rest;
11317 continue;
11318 }
11319 CHECK(COMPILE_(ret, "nd_2nd", rest, popped));
11320 break;
11321 }
11322 ADD_LABEL(ret, end_label);
11323 break;
11324 }
11325
11326 case NODE_MASGN:{
11327 compile_massign(iseq, ret, node, popped);
11328 break;
11329 }
11330
11331 case NODE_LASGN:{
11332 ID id = RNODE_LASGN(node)->nd_vid;
11333 int idx = ISEQ_BODY(body->local_iseq)->local_table_size - get_local_var_idx(iseq, id);
11334
11335 debugs("lvar: %s idx: %d\n", rb_id2name(id), idx);
11336 CHECK(COMPILE(ret, "rvalue", RNODE_LASGN(node)->nd_value));
11337
11338 if (!popped) {
11339 ADD_INSN(ret, node, dup);
11340 }
11341 ADD_SETLOCAL(ret, node, idx, get_lvar_level(iseq));
11342 break;
11343 }
11344 case NODE_DASGN: {
11345 int idx, lv, ls;
11346 ID id = RNODE_DASGN(node)->nd_vid;
11347 CHECK(COMPILE(ret, "dvalue", RNODE_DASGN(node)->nd_value));
11348 debugi("dassn id", rb_id2str(id) ? id : '*');
11349
11350 if (!popped) {
11351 ADD_INSN(ret, node, dup);
11352 }
11353
11354 idx = get_dyna_var_idx(iseq, id, &lv, &ls);
11355
11356 if (idx < 0) {
11357 COMPILE_ERROR(ERROR_ARGS "NODE_DASGN: unknown id (%"PRIsVALUE")",
11358 rb_id2str(id));
11359 goto ng;
11360 }
11361 ADD_SETLOCAL(ret, node, ls - idx, lv);
11362 break;
11363 }
11364 case NODE_GASGN:{
11365 CHECK(COMPILE(ret, "lvalue", RNODE_GASGN(node)->nd_value));
11366
11367 if (!popped) {
11368 ADD_INSN(ret, node, dup);
11369 }
11370 ADD_INSN1(ret, node, setglobal, ID2SYM(RNODE_GASGN(node)->nd_vid));
11371 break;
11372 }
11373 case NODE_IASGN:{
11374 CHECK(COMPILE(ret, "lvalue", RNODE_IASGN(node)->nd_value));
11375 if (!popped) {
11376 ADD_INSN(ret, node, dup);
11377 }
11378 ADD_INSN2(ret, node, setinstancevariable,
11379 ID2SYM(RNODE_IASGN(node)->nd_vid),
11380 get_ivar_ic_value(iseq,RNODE_IASGN(node)->nd_vid));
11381 break;
11382 }
11383 case NODE_CDECL:{
11384 if (RNODE_CDECL(node)->nd_vid) {
11385 CHECK(compile_shareable_constant_value(iseq, ret, RNODE_CDECL(node)->shareability, node, RNODE_CDECL(node)->nd_value));
11386
11387 if (!popped) {
11388 ADD_INSN(ret, node, dup);
11389 }
11390
11391 ADD_INSN1(ret, node, putspecialobject,
11392 INT2FIX(VM_SPECIAL_OBJECT_CONST_BASE));
11393 ADD_INSN1(ret, node, setconstant, ID2SYM(RNODE_CDECL(node)->nd_vid));
11394 }
11395 else {
11396 compile_cpath(ret, iseq, RNODE_CDECL(node)->nd_else);
11397 CHECK(compile_shareable_constant_value(iseq, ret, RNODE_CDECL(node)->shareability, node, RNODE_CDECL(node)->nd_value));
11398 ADD_INSN(ret, node, swap);
11399
11400 if (!popped) {
11401 ADD_INSN1(ret, node, topn, INT2FIX(1));
11402 ADD_INSN(ret, node, swap);
11403 }
11404
11405 ADD_INSN1(ret, node, setconstant, ID2SYM(get_node_colon_nd_mid(RNODE_CDECL(node)->nd_else)));
11406 }
11407 break;
11408 }
11409 case NODE_CVASGN:{
11410 CHECK(COMPILE(ret, "cvasgn val", RNODE_CVASGN(node)->nd_value));
11411 if (!popped) {
11412 ADD_INSN(ret, node, dup);
11413 }
11414 ADD_INSN2(ret, node, setclassvariable,
11415 ID2SYM(RNODE_CVASGN(node)->nd_vid),
11416 get_cvar_ic_value(iseq, RNODE_CVASGN(node)->nd_vid));
11417 break;
11418 }
11419 case NODE_OP_ASGN1:
11420 CHECK(compile_op_asgn1(iseq, ret, node, popped));
11421 break;
11422 case NODE_OP_ASGN2:
11423 CHECK(compile_op_asgn2(iseq, ret, node, popped));
11424 break;
11425 case NODE_OP_CDECL:
11426 CHECK(compile_op_cdecl(iseq, ret, node, popped));
11427 break;
11428 case NODE_OP_ASGN_AND:
11429 case NODE_OP_ASGN_OR:
11430 CHECK(compile_op_log(iseq, ret, node, popped, type));
11431 break;
11432 case NODE_CALL: /* obj.foo */
11433 case NODE_OPCALL: /* foo[] */
11434 if (compile_call_precheck_freeze(iseq, ret, node, node, popped) == TRUE) {
11435 break;
11436 }
11437 case NODE_QCALL: /* obj&.foo */
11438 case NODE_FCALL: /* foo() */
11439 case NODE_VCALL: /* foo (variable or call) */
11440 if (compile_call(iseq, ret, node, type, node, popped, false) == COMPILE_NG) {
11441 goto ng;
11442 }
11443 break;
11444 case NODE_SUPER:
11445 case NODE_ZSUPER:
11446 CHECK(compile_super(iseq, ret, node, popped, type));
11447 break;
11448 case NODE_LIST:{
11449 CHECK(compile_array(iseq, ret, node, popped, TRUE) >= 0);
11450 break;
11451 }
11452 case NODE_ZLIST:{
11453 if (!popped) {
11454 ADD_INSN1(ret, node, newarray, INT2FIX(0));
11455 }
11456 break;
11457 }
11458 case NODE_HASH:
11459 CHECK(compile_hash(iseq, ret, node, FALSE, popped) >= 0);
11460 break;
11461 case NODE_RETURN:
11462 CHECK(compile_return(iseq, ret, node, popped));
11463 break;
11464 case NODE_YIELD:
11465 CHECK(compile_yield(iseq, ret, node, popped));
11466 break;
11467 case NODE_LVAR:{
11468 if (!popped) {
11469 compile_lvar(iseq, ret, node, RNODE_LVAR(node)->nd_vid);
11470 }
11471 break;
11472 }
11473 case NODE_DVAR:{
11474 int lv, idx, ls;
11475 debugi("nd_vid", RNODE_DVAR(node)->nd_vid);
11476 if (!popped) {
11477 idx = get_dyna_var_idx(iseq, RNODE_DVAR(node)->nd_vid, &lv, &ls);
11478 if (idx < 0) {
11479 COMPILE_ERROR(ERROR_ARGS "unknown dvar (%"PRIsVALUE")",
11480 rb_id2str(RNODE_DVAR(node)->nd_vid));
11481 goto ng;
11482 }
11483 ADD_GETLOCAL(ret, node, ls - idx, lv);
11484 }
11485 break;
11486 }
11487 case NODE_GVAR:{
11488 ADD_INSN1(ret, node, getglobal, ID2SYM(RNODE_GVAR(node)->nd_vid));
11489 if (popped) {
11490 ADD_INSN(ret, node, pop);
11491 }
11492 break;
11493 }
11494 case NODE_IVAR:{
11495 debugi("nd_vid", RNODE_IVAR(node)->nd_vid);
11496 if (!popped) {
11497 ADD_INSN2(ret, node, getinstancevariable,
11498 ID2SYM(RNODE_IVAR(node)->nd_vid),
11499 get_ivar_ic_value(iseq, RNODE_IVAR(node)->nd_vid));
11500 }
11501 break;
11502 }
11503 case NODE_CONST:{
11504 debugi("nd_vid", RNODE_CONST(node)->nd_vid);
11505
11506 if (ISEQ_COMPILE_DATA(iseq)->option->inline_const_cache) {
11507 body->ic_size++;
11508 rb_const_path_t const_path = rb_const_path_from_ids(false, &RNODE_CONST(node)->nd_vid, 1);
11509 ADD_INSN1(ret, node, opt_getconstant_path, (VALUE)const_path);
11510 }
11511 else {
11512 ADD_INSN(ret, node, putnil);
11513 ADD_INSN1(ret, node, putobject, Qtrue);
11514 ADD_INSN1(ret, node, getconstant, ID2SYM(RNODE_CONST(node)->nd_vid));
11515 }
11516
11517 if (popped) {
11518 ADD_INSN(ret, node, pop);
11519 }
11520 break;
11521 }
11522 case NODE_CVAR:{
11523 if (!popped) {
11524 ADD_INSN2(ret, node, getclassvariable,
11525 ID2SYM(RNODE_CVAR(node)->nd_vid),
11526 get_cvar_ic_value(iseq, RNODE_CVAR(node)->nd_vid));
11527 }
11528 break;
11529 }
11530 case NODE_NTH_REF:{
11531 if (!popped) {
11532 if (!RNODE_NTH_REF(node)->nd_nth) {
11533 ADD_INSN(ret, node, putnil);
11534 break;
11535 }
11536 ADD_INSN2(ret, node, getspecial, INT2FIX(1) /* '~' */,
11537 INT2FIX(RNODE_NTH_REF(node)->nd_nth << 1));
11538 }
11539 break;
11540 }
11541 case NODE_BACK_REF:{
11542 if (!popped) {
11543 ADD_INSN2(ret, node, getspecial, INT2FIX(1) /* '~' */,
11544 INT2FIX(0x01 | (RNODE_BACK_REF(node)->nd_nth << 1)));
11545 }
11546 break;
11547 }
11548 case NODE_MATCH:
11549 case NODE_MATCH2:
11550 case NODE_MATCH3:
11551 CHECK(compile_match(iseq, ret, node, popped, type));
11552 break;
11553 case NODE_SYM:{
11554 if (!popped) {
11555 ADD_INSN1(ret, node, putobject, rb_node_sym_string_val(node));
11556 }
11557 break;
11558 }
11559 case NODE_LINE:{
11560 if (!popped) {
11561 ADD_INSN1(ret, node, putobject, rb_node_line_lineno_val(node));
11562 }
11563 break;
11564 }
11565 case NODE_ENCODING:{
11566 if (!popped) {
11567 ADD_INSN1(ret, node, putobject, rb_node_encoding_val(node));
11568 }
11569 break;
11570 }
11571 case NODE_INTEGER:{
11572 VALUE lit = rb_node_integer_literal_val(node);
11573 if (!SPECIAL_CONST_P(lit)) RB_OBJ_SET_SHAREABLE(lit);
11574 debugp_param("integer", lit);
11575 if (!popped) {
11576 ADD_INSN1(ret, node, putobject, lit);
11577 RB_OBJ_WRITTEN(iseq, Qundef, lit);
11578 }
11579 break;
11580 }
11581 case NODE_FLOAT:{
11582 VALUE lit = rb_node_float_literal_val(node);
11583 if (!SPECIAL_CONST_P(lit)) RB_OBJ_SET_SHAREABLE(lit);
11584 debugp_param("float", lit);
11585 if (!popped) {
11586 ADD_INSN1(ret, node, putobject, lit);
11587 RB_OBJ_WRITTEN(iseq, Qundef, lit);
11588 }
11589 break;
11590 }
11591 case NODE_RATIONAL:{
11592 VALUE lit = rb_node_rational_literal_val(node);
11594 debugp_param("rational", lit);
11595 if (!popped) {
11596 ADD_INSN1(ret, node, putobject, lit);
11597 RB_OBJ_WRITTEN(iseq, Qundef, lit);
11598 }
11599 break;
11600 }
11601 case NODE_IMAGINARY:{
11602 VALUE lit = rb_node_imaginary_literal_val(node);
11604 debugp_param("imaginary", lit);
11605 if (!popped) {
11606 ADD_INSN1(ret, node, putobject, lit);
11607 RB_OBJ_WRITTEN(iseq, Qundef, lit);
11608 }
11609 break;
11610 }
11611 case NODE_FILE:
11612 if (!popped) {
11613 compile_file_path(iseq, ret, node, ISEQ_COMPILE_DATA(iseq)->option->frozen_string_literal);
11614 }
11615 break;
11616 case NODE_STR:{
11617 debugp_param("nd_lit", get_string_value(node));
11618 if (!popped) {
11619 VALUE lit = get_string_value(node);
11620 const rb_compile_option_t *option = ISEQ_COMPILE_DATA(iseq)->option;
11621 if ((option->debug_frozen_string_literal || RTEST(ruby_debug)) &&
11622 option->frozen_string_literal != ISEQ_FROZEN_STRING_LITERAL_DISABLED) {
11623 lit = rb_str_with_debug_created_info(lit, rb_iseq_path(iseq), line);
11625 }
11626 switch (option->frozen_string_literal) {
11627 case ISEQ_FROZEN_STRING_LITERAL_UNSET:
11628 ADD_INSN1(ret, node, dupchilledstring, lit);
11629 break;
11630 case ISEQ_FROZEN_STRING_LITERAL_DISABLED:
11631 ADD_INSN1(ret, node, dupstring, lit);
11632 break;
11633 case ISEQ_FROZEN_STRING_LITERAL_ENABLED:
11634 ADD_INSN1(ret, node, putobject, lit);
11635 break;
11636 default:
11637 rb_bug("invalid frozen_string_literal");
11638 }
11639 RB_OBJ_WRITTEN(iseq, Qundef, lit);
11640 }
11641 break;
11642 }
11643 case NODE_DSTR:{
11644 compile_dstr(iseq, ret, node);
11645
11646 if (popped) {
11647 ADD_INSN(ret, node, pop);
11648 }
11649 break;
11650 }
11651 case NODE_XSTR:{
11652 ADD_CALL_RECEIVER(ret, node);
11653 VALUE str = rb_node_str_string_val(node);
11654 ADD_INSN1(ret, node, putobject, str);
11655 RB_OBJ_WRITTEN(iseq, Qundef, str);
11656 ADD_CALL(ret, node, idBackquote, INT2FIX(1));
11657
11658 if (popped) {
11659 ADD_INSN(ret, node, pop);
11660 }
11661 break;
11662 }
11663 case NODE_DXSTR:{
11664 ADD_CALL_RECEIVER(ret, node);
11665 compile_dstr(iseq, ret, node);
11666 ADD_CALL(ret, node, idBackquote, INT2FIX(1));
11667
11668 if (popped) {
11669 ADD_INSN(ret, node, pop);
11670 }
11671 break;
11672 }
11673 case NODE_EVSTR:
11674 CHECK(compile_evstr(iseq, ret, RNODE_EVSTR(node)->nd_body, popped));
11675 break;
11676 case NODE_REGX:{
11677 if (!popped) {
11678 VALUE lit = rb_node_regx_string_val(node);
11680 ADD_INSN1(ret, node, putobject, lit);
11681 RB_OBJ_WRITTEN(iseq, Qundef, lit);
11682 }
11683 break;
11684 }
11685 case NODE_DREGX:
11686 compile_dregx(iseq, ret, node, popped);
11687 break;
11688 case NODE_ONCE:{
11689 const rb_iseq_t *block_iseq;
11690 block_iseq = NEW_CHILD_ISEQ(RNODE_ONCE(node)->nd_body, make_name_for_block(iseq), ISEQ_TYPE_PLAIN, line);
11691
11692 VALUE once_storage = rb_imemo_once_storage_new();
11693 ADD_INSN2(ret, node, once, block_iseq, once_storage);
11694 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)block_iseq);
11695 RB_OBJ_WRITTEN(iseq, Qundef, once_storage);
11696
11697 if (popped) {
11698 ADD_INSN(ret, node, pop);
11699 }
11700 break;
11701 }
11702 case NODE_ARGSCAT:{
11703 if (popped) {
11704 CHECK(COMPILE(ret, "argscat head", RNODE_ARGSCAT(node)->nd_head));
11705 ADD_INSN1(ret, node, splatarray, Qfalse);
11706 ADD_INSN(ret, node, pop);
11707 CHECK(COMPILE(ret, "argscat body", RNODE_ARGSCAT(node)->nd_body));
11708 ADD_INSN1(ret, node, splatarray, Qfalse);
11709 ADD_INSN(ret, node, pop);
11710 }
11711 else {
11712 CHECK(COMPILE(ret, "argscat head", RNODE_ARGSCAT(node)->nd_head));
11713 const NODE *body_node = RNODE_ARGSCAT(node)->nd_body;
11714 if (nd_type_p(body_node, NODE_LIST)) {
11715 CHECK(compile_array(iseq, ret, body_node, popped, FALSE) >= 0);
11716 }
11717 else {
11718 CHECK(COMPILE(ret, "argscat body", body_node));
11719 ADD_INSN(ret, node, concattoarray);
11720 }
11721 }
11722 break;
11723 }
11724 case NODE_ARGSPUSH:{
11725 if (popped) {
11726 CHECK(COMPILE(ret, "argspush head", RNODE_ARGSPUSH(node)->nd_head));
11727 ADD_INSN1(ret, node, splatarray, Qfalse);
11728 ADD_INSN(ret, node, pop);
11729 CHECK(COMPILE_(ret, "argspush body", RNODE_ARGSPUSH(node)->nd_body, popped));
11730 }
11731 else {
11732 CHECK(COMPILE(ret, "argspush head", RNODE_ARGSPUSH(node)->nd_head));
11733 const NODE *body_node = RNODE_ARGSPUSH(node)->nd_body;
11734 if (keyword_node_p(body_node)) {
11735 CHECK(COMPILE_(ret, "array element", body_node, FALSE));
11736 ADD_INSN(ret, node, pushtoarraykwsplat);
11737 }
11738 else if (static_literal_node_p(body_node, iseq, false)) {
11739 ADD_INSN1(ret, body_node, putobject, static_literal_value(body_node, iseq));
11740 ADD_INSN1(ret, node, pushtoarray, INT2FIX(1));
11741 }
11742 else {
11743 CHECK(COMPILE_(ret, "array element", body_node, FALSE));
11744 ADD_INSN1(ret, node, pushtoarray, INT2FIX(1));
11745 }
11746 }
11747 break;
11748 }
11749 case NODE_SPLAT:{
11750 CHECK(COMPILE(ret, "splat", RNODE_SPLAT(node)->nd_head));
11751 ADD_INSN1(ret, node, splatarray, Qtrue);
11752
11753 if (popped) {
11754 ADD_INSN(ret, node, pop);
11755 }
11756 break;
11757 }
11758 case NODE_DEFN:{
11759 ID mid = RNODE_DEFN(node)->nd_mid;
11760 const rb_iseq_t *method_iseq = NEW_ISEQ(RNODE_DEFN(node)->nd_defn,
11761 rb_id2str(mid),
11762 ISEQ_TYPE_METHOD, line);
11763
11764 debugp_param("defn/iseq", rb_iseqw_new(method_iseq));
11765 ADD_INSN2(ret, node, definemethod, ID2SYM(mid), method_iseq);
11766 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)method_iseq);
11767
11768 if (!popped) {
11769 ADD_INSN1(ret, node, putobject, ID2SYM(mid));
11770 }
11771
11772 break;
11773 }
11774 case NODE_DEFS:{
11775 ID mid = RNODE_DEFS(node)->nd_mid;
11776 const rb_iseq_t * singleton_method_iseq = NEW_ISEQ(RNODE_DEFS(node)->nd_defn,
11777 rb_id2str(mid),
11778 ISEQ_TYPE_METHOD, line);
11779
11780 debugp_param("defs/iseq", rb_iseqw_new(singleton_method_iseq));
11781 CHECK(COMPILE(ret, "defs: recv", RNODE_DEFS(node)->nd_recv));
11782 ADD_INSN2(ret, node, definesmethod, ID2SYM(mid), singleton_method_iseq);
11783 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)singleton_method_iseq);
11784
11785 if (!popped) {
11786 ADD_INSN1(ret, node, putobject, ID2SYM(mid));
11787 }
11788 break;
11789 }
11790 case NODE_ALIAS:{
11791 ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
11792 ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_CBASE));
11793 CHECK(COMPILE(ret, "alias arg1", RNODE_ALIAS(node)->nd_1st));
11794 CHECK(COMPILE(ret, "alias arg2", RNODE_ALIAS(node)->nd_2nd));
11795 ADD_SEND(ret, node, id_core_set_method_alias, INT2FIX(3));
11796
11797 if (popped) {
11798 ADD_INSN(ret, node, pop);
11799 }
11800 break;
11801 }
11802 case NODE_VALIAS:{
11803 ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
11804 ADD_INSN1(ret, node, putobject, ID2SYM(RNODE_VALIAS(node)->nd_alias));
11805 ADD_INSN1(ret, node, putobject, ID2SYM(RNODE_VALIAS(node)->nd_orig));
11806 ADD_SEND(ret, node, id_core_set_variable_alias, INT2FIX(2));
11807
11808 if (popped) {
11809 ADD_INSN(ret, node, pop);
11810 }
11811 break;
11812 }
11813 case NODE_UNDEF:{
11814 const rb_parser_ary_t *ary = RNODE_UNDEF(node)->nd_undefs;
11815
11816 for (long i = 0; i < ary->len; i++) {
11817 ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
11818 ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_CBASE));
11819 CHECK(COMPILE(ret, "undef arg", ary->data[i]));
11820 ADD_SEND(ret, node, id_core_undef_method, INT2FIX(2));
11821
11822 if (i < ary->len - 1) {
11823 ADD_INSN(ret, node, pop);
11824 }
11825 }
11826
11827 if (popped) {
11828 ADD_INSN(ret, node, pop);
11829 }
11830 break;
11831 }
11832 case NODE_CLASS:{
11833 const rb_iseq_t *class_iseq = NEW_CHILD_ISEQ(RNODE_CLASS(node)->nd_body,
11834 rb_str_freeze(rb_sprintf("<class:%"PRIsVALUE">", rb_id2str(get_node_colon_nd_mid(RNODE_CLASS(node)->nd_cpath)))),
11835 ISEQ_TYPE_CLASS, line);
11836 const int flags = VM_DEFINECLASS_TYPE_CLASS |
11837 (RNODE_CLASS(node)->nd_super ? VM_DEFINECLASS_FLAG_HAS_SUPERCLASS : 0) |
11838 compile_cpath(ret, iseq, RNODE_CLASS(node)->nd_cpath);
11839
11840 CHECK(COMPILE(ret, "super", RNODE_CLASS(node)->nd_super));
11841 ADD_INSN3(ret, node, defineclass, ID2SYM(get_node_colon_nd_mid(RNODE_CLASS(node)->nd_cpath)), class_iseq, INT2FIX(flags));
11842 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)class_iseq);
11843
11844 if (popped) {
11845 ADD_INSN(ret, node, pop);
11846 }
11847 break;
11848 }
11849 case NODE_MODULE:{
11850 const rb_iseq_t *module_iseq = NEW_CHILD_ISEQ(RNODE_MODULE(node)->nd_body,
11851 rb_str_freeze(rb_sprintf("<module:%"PRIsVALUE">", rb_id2str(get_node_colon_nd_mid(RNODE_MODULE(node)->nd_cpath)))),
11852 ISEQ_TYPE_CLASS, line);
11853 const int flags = VM_DEFINECLASS_TYPE_MODULE |
11854 compile_cpath(ret, iseq, RNODE_MODULE(node)->nd_cpath);
11855
11856 ADD_INSN (ret, node, putnil); /* dummy */
11857 ADD_INSN3(ret, node, defineclass, ID2SYM(get_node_colon_nd_mid(RNODE_MODULE(node)->nd_cpath)), module_iseq, INT2FIX(flags));
11858 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)module_iseq);
11859
11860 if (popped) {
11861 ADD_INSN(ret, node, pop);
11862 }
11863 break;
11864 }
11865 case NODE_SCLASS:{
11866 ID singletonclass;
11867 const rb_iseq_t *singleton_class = NEW_ISEQ(RNODE_SCLASS(node)->nd_body, rb_fstring_lit("singleton class"),
11868 ISEQ_TYPE_CLASS, line);
11869
11870 CHECK(COMPILE(ret, "sclass#recv", RNODE_SCLASS(node)->nd_recv));
11871 ADD_INSN (ret, node, putnil);
11872 CONST_ID(singletonclass, "singletonclass");
11873
11874 /* `class << self` in a class body and `class << Foo` (constant
11875 receiver) are stable. All other forms are potentially dynamic. */
11876 int sclass_flags = VM_DEFINECLASS_TYPE_SINGLETON_CLASS;
11877 const NODE *recv = RNODE_SCLASS(node)->nd_recv;
11878 if (!(nd_type_p(recv, NODE_SELF) &&
11879 ISEQ_BODY(iseq)->type == ISEQ_TYPE_CLASS) &&
11880 !cpath_const_p(recv)) {
11881 sclass_flags |= VM_DEFINECLASS_FLAG_DYNAMIC_CREF;
11882 }
11883
11884 ADD_INSN3(ret, node, defineclass,
11885 ID2SYM(singletonclass), singleton_class,
11886 INT2FIX(sclass_flags));
11887 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)singleton_class);
11888
11889 if (popped) {
11890 ADD_INSN(ret, node, pop);
11891 }
11892 break;
11893 }
11894 case NODE_COLON2:
11895 CHECK(compile_colon2(iseq, ret, node, popped));
11896 break;
11897 case NODE_COLON3:
11898 CHECK(compile_colon3(iseq, ret, node, popped));
11899 break;
11900 case NODE_DOT2:
11901 CHECK(compile_dots(iseq, ret, node, popped, FALSE));
11902 break;
11903 case NODE_DOT3:
11904 CHECK(compile_dots(iseq, ret, node, popped, TRUE));
11905 break;
11906 case NODE_FLIP2:
11907 case NODE_FLIP3:{
11908 LABEL *lend = NEW_LABEL(line);
11909 LABEL *ltrue = NEW_LABEL(line);
11910 LABEL *lfalse = NEW_LABEL(line);
11911 CHECK(compile_flip_flop(iseq, ret, node, type == NODE_FLIP2,
11912 ltrue, lfalse));
11913 ADD_LABEL(ret, ltrue);
11914 ADD_INSN1(ret, node, putobject, Qtrue);
11915 ADD_INSNL(ret, node, jump, lend);
11916 ADD_LABEL(ret, lfalse);
11917 ADD_INSN1(ret, node, putobject, Qfalse);
11918 ADD_LABEL(ret, lend);
11919 break;
11920 }
11921 case NODE_SELF:{
11922 if (!popped) {
11923 ADD_INSN(ret, node, putself);
11924 }
11925 break;
11926 }
11927 case NODE_NIL:{
11928 if (!popped) {
11929 ADD_INSN(ret, node, putnil);
11930 }
11931 break;
11932 }
11933 case NODE_TRUE:{
11934 if (!popped) {
11935 ADD_INSN1(ret, node, putobject, Qtrue);
11936 }
11937 break;
11938 }
11939 case NODE_FALSE:{
11940 if (!popped) {
11941 ADD_INSN1(ret, node, putobject, Qfalse);
11942 }
11943 break;
11944 }
11945 case NODE_ERRINFO:
11946 CHECK(compile_errinfo(iseq, ret, node, popped));
11947 break;
11948 case NODE_DEFINED:
11949 if (!popped) {
11950 CHECK(compile_defined_expr(iseq, ret, node, Qtrue, false));
11951 }
11952 break;
11953 case NODE_POSTEXE:{
11954 /* compiled to:
11955 * ONCE{ rb_mRubyVMFrozenCore::core#set_postexe{ ... } }
11956 */
11958 rb_iseq_new_with_callback_new_callback(build_postexe_iseq, RNODE_POSTEXE(node)->nd_body);
11959 const rb_iseq_t *once_iseq =
11960 NEW_CHILD_ISEQ_WITH_CALLBACK(ifunc, rb_fstring(make_name_for_block(iseq)), ISEQ_TYPE_BLOCK, line);
11961
11962 VALUE once_storage = rb_imemo_once_storage_new();
11963 ADD_INSN2(ret, node, once, once_iseq, once_storage);
11964 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)once_iseq);
11965 RB_OBJ_WRITTEN(iseq, Qundef, once_storage);
11966
11967 if (popped) {
11968 ADD_INSN(ret, node, pop);
11969 }
11970 break;
11971 }
11972 case NODE_KW_ARG:
11973 CHECK(compile_kw_arg(iseq, ret, node, popped));
11974 break;
11975 case NODE_DSYM:{
11976 compile_dstr(iseq, ret, node);
11977 if (!popped) {
11978 ADD_INSN(ret, node, intern);
11979 }
11980 else {
11981 ADD_INSN(ret, node, pop);
11982 }
11983 break;
11984 }
11985 case NODE_ATTRASGN:
11986 CHECK(compile_attrasgn(iseq, ret, node, popped));
11987 break;
11988 case NODE_LAMBDA:{
11989 /* compile same as lambda{...} */
11990 const rb_iseq_t *block = NEW_CHILD_ISEQ(RNODE_LAMBDA(node)->nd_body, make_name_for_block(iseq), ISEQ_TYPE_BLOCK, line);
11991 VALUE argc = INT2FIX(0);
11992
11993 ADD_INSN1(ret, node, putspecialobject, INT2FIX(VM_SPECIAL_OBJECT_VMCORE));
11994 ADD_CALL_WITH_BLOCK(ret, node, idLambda, argc, block);
11995 RB_OBJ_WRITTEN(iseq, Qundef, (VALUE)block);
11996
11997 if (popped) {
11998 ADD_INSN(ret, node, pop);
11999 }
12000 break;
12001 }
12002 default:
12003 UNKNOWN_NODE("iseq_compile_each", node, COMPILE_NG);
12004 ng:
12005 debug_node_end();
12006 return COMPILE_NG;
12007 }
12008
12009 debug_node_end();
12010 return COMPILE_OK;
12011}
12012
12013/***************************/
12014/* instruction information */
12015/***************************/
12016
12017static int
12018insn_data_length(INSN *iobj)
12019{
12020 return insn_len(iobj->insn_id);
12021}
12022
12023static int
12024calc_sp_depth(int depth, INSN *insn)
12025{
12026 return comptime_insn_stack_increase(depth, insn->insn_id, insn->operands);
12027}
12028
12029static VALUE
12030opobj_inspect(VALUE obj)
12031{
12032 if (!SPECIAL_CONST_P(obj) && !RBASIC_CLASS(obj)) {
12033 switch (BUILTIN_TYPE(obj)) {
12034 case T_STRING:
12035 obj = rb_str_resurrect(obj);
12036 break;
12037 case T_ARRAY:
12038 obj = rb_ary_resurrect(obj);
12039 break;
12040 default:
12041 break;
12042 }
12043 }
12044 return rb_inspect(obj);
12045}
12046
12047
12048
12049static VALUE
12050insn_data_to_s_detail(INSN *iobj)
12051{
12052 VALUE str = rb_sprintf("%-20s ", insn_name(iobj->insn_id));
12053
12054 if (iobj->operands) {
12055 const char *types = insn_op_types(iobj->insn_id);
12056 int j;
12057
12058 for (j = 0; types[j]; j++) {
12059 char type = types[j];
12060
12061 switch (type) {
12062 case TS_OFFSET: /* label(destination position) */
12063 {
12064 LABEL *lobj = (LABEL *)OPERAND_AT(iobj, j);
12065 rb_str_catf(str, LABEL_FORMAT, lobj->label_no);
12066 break;
12067 }
12068 break;
12069 case TS_ISEQ: /* iseq */
12070 {
12071 rb_iseq_t *iseq = (rb_iseq_t *)OPERAND_AT(iobj, j);
12072 VALUE val = Qnil;
12073 if (0 && iseq) { /* TODO: invalidate now */
12074 val = (VALUE)iseq;
12075 }
12076 rb_str_concat(str, opobj_inspect(val));
12077 }
12078 break;
12079 case TS_LINDEX:
12080 case TS_NUM: /* ulong */
12081 case TS_VALUE: /* VALUE */
12082 {
12083 VALUE v = OPERAND_AT(iobj, j);
12084 if (!CLASS_OF(v))
12085 rb_str_cat2(str, "<hidden>");
12086 else {
12087 rb_str_concat(str, opobj_inspect(v));
12088 }
12089 break;
12090 }
12091 case TS_ID: /* ID */
12092 rb_str_concat(str, opobj_inspect(OPERAND_AT(iobj, j)));
12093 break;
12094 case TS_IC: /* inline cache */
12095 rb_str_concat(str, opobj_inspect(rb_const_path_to_array((rb_const_path_t)OPERAND_AT(iobj, j))));
12096 break;
12097 case TS_IVC: /* inline ivar cache */
12098 rb_str_catf(str, "<ivc:%d>", FIX2INT(OPERAND_AT(iobj, j)));
12099 break;
12100 case TS_ICVARC: /* inline cvar cache */
12101 rb_str_catf(str, "<icvarc:%d>", FIX2INT(OPERAND_AT(iobj, j)));
12102 break;
12103 case TS_CALLDATA: /* we store these as call infos at compile time */
12104 {
12105 const struct rb_callinfo *ci = (struct rb_callinfo *)OPERAND_AT(iobj, j);
12106 rb_str_cat2(str, "<calldata:");
12107 if (vm_ci_mid(ci)) rb_str_append(str, rb_id2str(vm_ci_mid(ci)));
12108 rb_str_catf(str, ", %d>", vm_ci_argc(ci));
12109 break;
12110 }
12111 case TS_CDHASH: /* case/when condition cache */
12112 rb_str_cat2(str, "<ch>");
12113 break;
12114 case TS_FUNCPTR:
12115 {
12116 void *func = (void *)OPERAND_AT(iobj, j);
12117#ifdef HAVE_DLADDR
12118 Dl_info info;
12119 if (dladdr(func, &info) && info.dli_sname) {
12120 rb_str_cat2(str, info.dli_sname);
12121 break;
12122 }
12123#endif
12124 rb_str_catf(str, "<%p>", func);
12125 }
12126 break;
12127 case TS_BUILTIN:
12128 rb_str_cat2(str, "<TS_BUILTIN>");
12129 break;
12130 default:{
12131 rb_raise(rb_eSyntaxError, "unknown operand type: %c", type);
12132 }
12133 }
12134 if (types[j + 1]) {
12135 rb_str_cat2(str, ", ");
12136 }
12137 }
12138 }
12139 return str;
12140}
12141
12142static void
12143dump_disasm_list(const LINK_ELEMENT *link)
12144{
12145 dump_disasm_list_with_cursor(link, NULL, NULL);
12146}
12147
12148static void
12149dump_disasm_list_with_cursor(const LINK_ELEMENT *link, const LINK_ELEMENT *curr, const LABEL *dest)
12150{
12151 int pos = 0;
12152 INSN *iobj;
12153 LABEL *lobj;
12154 VALUE str;
12155
12156 printf("-- raw disasm--------\n");
12157
12158 while (link) {
12159 if (curr) printf(curr == link ? "*" : " ");
12160 switch (link->type) {
12161 case ISEQ_ELEMENT_INSN:
12162 {
12163 iobj = (INSN *)link;
12164 str = insn_data_to_s_detail(iobj);
12165 printf(" %04d %-65s(%4u)\n", pos, StringValueCStr(str), iobj->insn_info.line_no);
12166 pos += insn_data_length(iobj);
12167 break;
12168 }
12169 case ISEQ_ELEMENT_LABEL:
12170 {
12171 lobj = (LABEL *)link;
12172 printf(LABEL_FORMAT" [sp: %d, unremovable: %d, refcnt: %d]%s\n", lobj->label_no, lobj->sp, lobj->unremovable, lobj->refcnt,
12173 dest == lobj ? " <---" : "");
12174 break;
12175 }
12176 case ISEQ_ELEMENT_TRACE:
12177 {
12178 TRACE *trace = (TRACE *)link;
12179 printf(" trace: %0x\n", trace->event);
12180 break;
12181 }
12182 case ISEQ_ELEMENT_ADJUST:
12183 {
12184 ADJUST *adjust = (ADJUST *)link;
12185 printf(" adjust: [label: %d]\n", adjust->label ? adjust->label->label_no : -1);
12186 break;
12187 }
12188 default:
12189 /* ignore */
12190 rb_raise(rb_eSyntaxError, "dump_disasm_list error: %d\n", (int)link->type);
12191 }
12192 link = link->next;
12193 }
12194 printf("---------------------\n");
12195 fflush(stdout);
12196}
12197
12198int
12199rb_insn_len(VALUE insn)
12200{
12201 return insn_len(insn);
12202}
12203
12204const char *
12205rb_insns_name(int i)
12206{
12207 return insn_name(i);
12208}
12209
12210VALUE
12211rb_insns_name_array(void)
12212{
12213 VALUE ary = rb_ary_new_capa(VM_INSTRUCTION_SIZE);
12214 int i;
12215 for (i = 0; i < VM_INSTRUCTION_SIZE; i++) {
12216 rb_ary_push(ary, rb_fstring_cstr(insn_name(i)));
12217 }
12218 return rb_ary_freeze(ary);
12219}
12220
12221static LABEL *
12222register_label(rb_iseq_t *iseq, struct st_table *labels_table, VALUE obj)
12223{
12224 LABEL *label = 0;
12225 st_data_t tmp;
12226 obj = rb_to_symbol_type(obj);
12227
12228 if (st_lookup(labels_table, obj, &tmp) == 0) {
12229 label = NEW_LABEL(0);
12230 st_insert(labels_table, obj, (st_data_t)label);
12231 }
12232 else {
12233 label = (LABEL *)tmp;
12234 }
12235 LABEL_REF(label);
12236 return label;
12237}
12238
12239static VALUE
12240get_exception_sym2type(VALUE sym)
12241{
12242 static VALUE symRescue, symEnsure, symRetry;
12243 static VALUE symBreak, symRedo, symNext;
12244
12245 if (symRescue == 0) {
12246 symRescue = ID2SYM(rb_intern_const("rescue"));
12247 symEnsure = ID2SYM(rb_intern_const("ensure"));
12248 symRetry = ID2SYM(rb_intern_const("retry"));
12249 symBreak = ID2SYM(rb_intern_const("break"));
12250 symRedo = ID2SYM(rb_intern_const("redo"));
12251 symNext = ID2SYM(rb_intern_const("next"));
12252 }
12253
12254 if (sym == symRescue) return CATCH_TYPE_RESCUE;
12255 if (sym == symEnsure) return CATCH_TYPE_ENSURE;
12256 if (sym == symRetry) return CATCH_TYPE_RETRY;
12257 if (sym == symBreak) return CATCH_TYPE_BREAK;
12258 if (sym == symRedo) return CATCH_TYPE_REDO;
12259 if (sym == symNext) return CATCH_TYPE_NEXT;
12260 rb_raise(rb_eSyntaxError, "invalid exception symbol: %+"PRIsVALUE, sym);
12261 return 0;
12262}
12263
12264static int
12265iseq_build_from_ary_exception(rb_iseq_t *iseq, struct st_table *labels_table,
12266 VALUE exception)
12267{
12268 int i;
12269
12270 for (i=0; i<RARRAY_LEN(exception); i++) {
12271 const rb_iseq_t *eiseq;
12272 VALUE v, type;
12273 LABEL *lstart, *lend, *lcont;
12274 unsigned int sp;
12275
12276 v = rb_to_array_type(RARRAY_AREF(exception, i));
12277 if (RARRAY_LEN(v) != 6) {
12278 rb_raise(rb_eSyntaxError, "wrong exception entry");
12279 }
12280 type = get_exception_sym2type(RARRAY_AREF(v, 0));
12281 if (NIL_P(RARRAY_AREF(v, 1))) {
12282 eiseq = NULL;
12283 }
12284 else {
12285 eiseq = rb_iseqw_to_iseq(rb_iseq_load(RARRAY_AREF(v, 1), (VALUE)iseq, Qnil));
12286 }
12287
12288 lstart = register_label(iseq, labels_table, RARRAY_AREF(v, 2));
12289 lend = register_label(iseq, labels_table, RARRAY_AREF(v, 3));
12290 lcont = register_label(iseq, labels_table, RARRAY_AREF(v, 4));
12291 sp = NUM2UINT(RARRAY_AREF(v, 5));
12292
12293 /* TODO: Dirty Hack! Fix me */
12294 if (type == CATCH_TYPE_RESCUE ||
12295 type == CATCH_TYPE_BREAK ||
12296 type == CATCH_TYPE_NEXT) {
12297 ++sp;
12298 }
12299
12300 lcont->sp = sp;
12301
12302 ADD_CATCH_ENTRY(type, lstart, lend, eiseq, lcont);
12303
12304 RB_GC_GUARD(v);
12305 }
12306 return COMPILE_OK;
12307}
12308
12309static struct st_table *
12310insn_make_insn_table(void)
12311{
12312 struct st_table *table;
12313 int i;
12314 table = st_init_numtable_with_size(VM_INSTRUCTION_SIZE);
12315
12316 for (i=0; i<VM_INSTRUCTION_SIZE; i++) {
12317 st_insert(table, ID2SYM(rb_intern_const(insn_name(i))), i);
12318 }
12319
12320 return table;
12321}
12322
12323static const rb_iseq_t *
12324iseq_build_load_iseq(const rb_iseq_t *iseq, VALUE op)
12325{
12326 VALUE iseqw;
12327 const rb_iseq_t *loaded_iseq;
12328
12329 if (RB_TYPE_P(op, T_ARRAY)) {
12330 iseqw = rb_iseq_load(op, (VALUE)iseq, Qnil);
12331 }
12332 else if (CLASS_OF(op) == rb_cISeq) {
12333 iseqw = op;
12334 }
12335 else {
12336 rb_raise(rb_eSyntaxError, "ISEQ is required");
12337 }
12338
12339 loaded_iseq = rb_iseqw_to_iseq(iseqw);
12340 return loaded_iseq;
12341}
12342
12343static VALUE
12344iseq_build_callinfo_from_hash(rb_iseq_t *iseq, VALUE op)
12345{
12346 ID mid = 0;
12347 int orig_argc = 0;
12348 unsigned int flag = 0;
12349 struct rb_callinfo_kwarg *kw_arg = 0;
12350
12351 if (!NIL_P(op)) {
12352 VALUE vmid = rb_hash_aref(op, ID2SYM(rb_intern_const("mid")));
12353 VALUE vflag = rb_hash_aref(op, ID2SYM(rb_intern_const("flag")));
12354 VALUE vorig_argc = rb_hash_aref(op, ID2SYM(rb_intern_const("orig_argc")));
12355 VALUE vkw_arg = rb_hash_aref(op, ID2SYM(rb_intern_const("kw_arg")));
12356
12357 if (!NIL_P(vmid)) mid = SYM2ID(vmid);
12358 if (!NIL_P(vflag)) flag = NUM2UINT(vflag);
12359 if (!NIL_P(vorig_argc)) orig_argc = FIX2INT(vorig_argc);
12360
12361 if (!NIL_P(vkw_arg)) {
12362 int i;
12363 int len = RARRAY_LENINT(vkw_arg);
12364 size_t n = rb_callinfo_kwarg_bytes(len);
12365
12366 kw_arg = xmalloc(n);
12367 kw_arg->references = 0;
12368 kw_arg->keyword_len = len;
12369 for (i = 0; i < len; i++) {
12370 VALUE kw = RARRAY_AREF(vkw_arg, i);
12371 SYM2ID(kw); /* make immortal */
12372 kw_arg->keywords[i] = kw;
12373 }
12374 }
12375 }
12376
12377 const struct rb_callinfo *ci = new_callinfo(iseq, mid, orig_argc, flag, kw_arg, (flag & VM_CALL_ARGS_SIMPLE) == 0);
12378 RB_OBJ_WRITTEN(iseq, Qundef, ci);
12379 return (VALUE)ci;
12380}
12381
12382static rb_iseq_events_t
12383event_name_to_flag(VALUE sym)
12384{
12385#define CHECK_EVENT(ev) if (sym == ID2SYM(rb_intern_const(#ev))) return ev;
12386 CHECK_EVENT(RUBY_EVENT_LINE);
12387 CHECK_EVENT(RUBY_EVENT_CLASS);
12388 CHECK_EVENT(RUBY_EVENT_END);
12389 CHECK_EVENT(RUBY_EVENT_CALL);
12390 CHECK_EVENT(RUBY_EVENT_RETURN);
12391 CHECK_EVENT(RUBY_EVENT_B_CALL);
12392 CHECK_EVENT(RUBY_EVENT_B_RETURN);
12393 CHECK_EVENT(RUBY_EVENT_RESCUE);
12394#undef CHECK_EVENT
12395 return RUBY_EVENT_NONE;
12396}
12397
12398static int
12399iseq_build_from_ary_body(rb_iseq_t *iseq, LINK_ANCHOR *const anchor,
12400 VALUE body, VALUE node_ids, VALUE labels_wrapper)
12401{
12402 /* TODO: body should be frozen */
12403 rb_len_t i, len = RARRAY_LEN(body);
12404 struct st_table *labels_table = RTYPEDDATA_DATA(labels_wrapper);
12405 int j;
12406 int line_no = 0, node_id = -1, insn_idx = 0;
12407 int ret = COMPILE_OK;
12408
12409 /*
12410 * index -> LABEL *label
12411 */
12412 static struct st_table *insn_table;
12413
12414 if (insn_table == 0) {
12415 insn_table = insn_make_insn_table();
12416 }
12417
12418 for (i=0; i<len; i++) {
12419 VALUE obj = RARRAY_AREF(body, i);
12420
12421 if (SYMBOL_P(obj)) {
12422 rb_iseq_events_t event;
12423 if ((event = event_name_to_flag(obj)) != RUBY_EVENT_NONE) {
12424 ADD_TRACE(anchor, event);
12425 }
12426 else {
12427 LABEL *label = register_label(iseq, labels_table, obj);
12428 ADD_LABEL(anchor, label);
12429 }
12430 }
12431 else if (RB_INTEGER_TYPE_P(obj)) {
12432 line_no = NUM2INT(obj);
12433 }
12434 else if (RB_TYPE_P(obj, T_ARRAY)) {
12435 VALUE *argv = 0;
12436 int argc = RARRAY_LENINT(obj) - 1;
12437 st_data_t insn_id;
12438 VALUE insn;
12439
12440 if (node_ids) {
12441 node_id = NUM2INT(rb_ary_entry(node_ids, insn_idx++));
12442 }
12443
12444 insn = (argc < 0) ? Qnil : RARRAY_AREF(obj, 0);
12445 if (st_lookup(insn_table, (st_data_t)insn, &insn_id) == 0) {
12446 /* TODO: exception */
12447 COMPILE_ERROR(iseq, line_no,
12448 "unknown instruction: %+"PRIsVALUE, insn);
12449 ret = COMPILE_NG;
12450 break;
12451 }
12452
12453 if (argc != insn_len((VALUE)insn_id)-1) {
12454 COMPILE_ERROR(iseq, line_no,
12455 "operand size mismatch");
12456 ret = COMPILE_NG;
12457 break;
12458 }
12459
12460 if (argc > 0) {
12461 argv = compile_data_calloc2_type(iseq, VALUE, argc);
12462
12463 // add element before operand setup to make GC root
12464 ADD_ELEM(anchor,
12465 (LINK_ELEMENT*)new_insn_core(iseq, line_no, node_id,
12466 (enum ruby_vminsn_type)insn_id, argc, argv));
12467
12468 for (j=0; j<argc; j++) {
12469 VALUE op = rb_ary_entry(obj, j+1);
12470 switch (insn_op_type((VALUE)insn_id, j)) {
12471 case TS_OFFSET: {
12472 LABEL *label = register_label(iseq, labels_table, op);
12473 argv[j] = (VALUE)label;
12474 break;
12475 }
12476 case TS_LINDEX:
12477 case TS_NUM:
12478 (void)NUM2INT(op);
12479 argv[j] = op;
12480 break;
12481 case TS_VALUE:
12482 if (insn_id == BIN(once)) op = rb_imemo_once_storage_new();
12483 argv[j] = op;
12484 RB_OBJ_WRITTEN(iseq, Qundef, op);
12485 break;
12486 case TS_ISEQ:
12487 {
12488 if (op != Qnil) {
12489 VALUE v = (VALUE)iseq_build_load_iseq(iseq, op);
12490 argv[j] = v;
12491 RB_OBJ_WRITTEN(iseq, Qundef, v);
12492 }
12493 else {
12494 argv[j] = 0;
12495 }
12496 }
12497 break;
12498 case TS_IC:
12499 {
12500 VALUE segments = rb_ary_new();
12501 op = rb_to_array_type(op);
12502
12503 for (int i = 0; i < RARRAY_LEN(op); i++) {
12504 VALUE sym = RARRAY_AREF(op, i);
12505 sym = rb_to_symbol_type(sym);
12506 rb_ary_push(segments, sym);
12507 }
12508
12509 rb_const_path_t const_path = rb_const_path_from_array(segments);
12510 argv[j] = (VALUE)const_path;
12511 RB_GC_GUARD(op);
12512 RB_GC_GUARD(segments);
12513 ISEQ_BODY(iseq)->ic_size++;
12514 }
12515 break;
12516 case TS_IVC: /* inline ivar cache */
12517 argv[j] = op;
12518 if (NUM2UINT(op) >= ISEQ_BODY(iseq)->ivc_size) {
12519 ISEQ_BODY(iseq)->ivc_size = NUM2INT(op) + 1;
12520 }
12521 break;
12522 case TS_ICVARC: /* inline cvar cache */
12523 argv[j] = op;
12524 if (NUM2UINT(op) >= ISEQ_BODY(iseq)->icvarc_size) {
12525 ISEQ_BODY(iseq)->icvarc_size = NUM2INT(op) + 1;
12526 }
12527 break;
12528 case TS_CALLDATA:
12529 argv[j] = iseq_build_callinfo_from_hash(iseq, op);
12530 break;
12531 case TS_ID:
12532 argv[j] = rb_to_symbol_type(op);
12533 break;
12534 case TS_CDHASH:
12535 {
12536 int i;
12537 VALUE map = cdhash_new(RARRAY_LEN(op) / 2);
12538
12539 op = rb_to_array_type(op);
12540 for (i=0; i<RARRAY_LEN(op); i+=2) {
12541 VALUE key = RARRAY_AREF(op, i);
12542 VALUE sym = RARRAY_AREF(op, i+1);
12543 LABEL *label =
12544 register_label(iseq, labels_table, sym);
12545 cdhash_aset(map, key, (VALUE)label);
12546 }
12547 RB_GC_GUARD(op);
12548 RB_OBJ_SET_SHAREABLE(map); // allow mutation while compiling
12549 argv[j] = map;
12550 RB_OBJ_WRITTEN(iseq, Qundef, map);
12551 }
12552 break;
12553 case TS_FUNCPTR:
12554 {
12555#if SIZEOF_VALUE <= SIZEOF_LONG
12556 long funcptr = NUM2LONG(op);
12557#else
12558 LONG_LONG funcptr = NUM2LL(op);
12559#endif
12560 argv[j] = (VALUE)funcptr;
12561 }
12562 break;
12563 default:
12564 rb_raise(rb_eSyntaxError, "unknown operand: %c", insn_op_type((VALUE)insn_id, j));
12565 }
12566 }
12567 }
12568 else {
12569 ADD_ELEM(anchor,
12570 (LINK_ELEMENT*)new_insn_core(iseq, line_no, node_id,
12571 (enum ruby_vminsn_type)insn_id, argc, NULL));
12572 }
12573 }
12574 else {
12575 rb_raise(rb_eTypeError, "unexpected object for instruction");
12576 }
12577 }
12578 RTYPEDDATA_DATA(labels_wrapper) = 0;
12579 RB_GC_GUARD(labels_wrapper);
12580 validate_labels(iseq, labels_table);
12581 if (!ret) return ret;
12582 return iseq_setup(iseq, anchor);
12583}
12584
12585#define CHECK_ARRAY(v) rb_to_array_type(v)
12586#define CHECK_SYMBOL(v) rb_to_symbol_type(v)
12587
12588static int
12589int_param(int *dst, VALUE param, VALUE sym)
12590{
12591 VALUE val = rb_hash_aref(param, sym);
12592 if (FIXNUM_P(val)) {
12593 *dst = FIX2INT(val);
12594 return TRUE;
12595 }
12596 else if (!NIL_P(val)) {
12597 rb_raise(rb_eTypeError, "invalid %+"PRIsVALUE" Fixnum: %+"PRIsVALUE,
12598 sym, val);
12599 }
12600 return FALSE;
12601}
12602
12603static const struct rb_iseq_param_keyword *
12604iseq_build_kw(rb_iseq_t *iseq, VALUE params, VALUE keywords)
12605{
12606 int i, j;
12607 int len = RARRAY_LENINT(keywords);
12608 int default_len;
12609 VALUE key, sym, default_val;
12610 VALUE *dvs;
12611 ID *ids;
12612 struct rb_iseq_param_keyword *keyword = ZALLOC(struct rb_iseq_param_keyword);
12613
12614 ISEQ_BODY(iseq)->param.flags.has_kw = TRUE;
12615
12616 keyword->num = len;
12617#define SYM(s) ID2SYM(rb_intern_const(#s))
12618 (void)int_param(&keyword->bits_start, params, SYM(kwbits));
12619 i = keyword->bits_start - keyword->num;
12620 ids = (ID *)&ISEQ_BODY(iseq)->local_table[i];
12621#undef SYM
12622
12623 /* required args */
12624 for (i = 0; i < len; i++) {
12625 VALUE val = RARRAY_AREF(keywords, i);
12626
12627 if (!SYMBOL_P(val)) {
12628 goto default_values;
12629 }
12630 ids[i] = SYM2ID(val);
12631 keyword->required_num++;
12632 }
12633
12634 default_values: /* note: we intentionally preserve `i' from previous loop */
12635 default_len = len - i;
12636 if (default_len == 0) {
12637 keyword->table = ids;
12638 return keyword;
12639 }
12640 else if (default_len < 0) {
12642 }
12643
12644 dvs = ALLOC_N(VALUE, (unsigned int)default_len);
12645
12646 for (j = 0; i < len; i++, j++) {
12647 key = RARRAY_AREF(keywords, i);
12648 CHECK_ARRAY(key);
12649
12650 switch (RARRAY_LEN(key)) {
12651 case 1:
12652 sym = RARRAY_AREF(key, 0);
12653 default_val = Qundef;
12654 break;
12655 case 2:
12656 sym = RARRAY_AREF(key, 0);
12657 default_val = RARRAY_AREF(key, 1);
12658 break;
12659 default:
12660 rb_raise(rb_eTypeError, "keyword default has unsupported len %+"PRIsVALUE, key);
12661 }
12662 ids[i] = SYM2ID(sym);
12663 RB_OBJ_WRITE(iseq, &dvs[j], default_val);
12664 }
12665
12666 keyword->table = ids;
12667 keyword->default_values = dvs;
12668
12669 return keyword;
12670}
12671
12672static void
12673iseq_insn_each_object_mark_and_move(VALUE * obj, VALUE _)
12674{
12675 rb_gc_mark_and_move(obj);
12676}
12677
12678void
12679rb_iseq_mark_and_move_insn_storage(struct iseq_compile_data_storage *storage)
12680{
12681 INSN *iobj = 0;
12682 size_t size = sizeof(INSN);
12683 size_t align = ALIGNMENT_SIZE_OF(INSN);
12684 unsigned int pos = 0;
12685
12686 while (storage) {
12687 size_t padding = calc_padding((void *)&storage->buff[pos], align);
12688 size_t offset = pos + size + padding;
12689 if (offset > storage->size || offset > storage->pos) {
12690 pos = 0;
12691 storage = storage->next;
12692 }
12693 else {
12694 pos += (int)padding;
12695
12696 iobj = (INSN *)&storage->buff[pos];
12697
12698 if (iobj->operands) {
12699 iseq_insn_each_markable_object(iobj, iseq_insn_each_object_mark_and_move, (VALUE)0);
12700 }
12701 pos += (int)size;
12702 }
12703 }
12704}
12705
12706static const rb_data_type_t labels_wrapper_type = {
12707 .wrap_struct_name = "compiler/labels_wrapper",
12708 .function = {
12709 .dmark = (RUBY_DATA_FUNC)rb_mark_set,
12710 .dfree = (RUBY_DATA_FUNC)st_free_table,
12711 },
12712 .flags = RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED,
12713};
12714
12715void
12716rb_iseq_build_from_ary(rb_iseq_t *iseq, VALUE misc, VALUE locals, VALUE params,
12717 VALUE exception, VALUE body)
12718{
12719#define SYM(s) ID2SYM(rb_intern_const(#s))
12720 int i, len;
12721 unsigned int arg_size, local_size, stack_max;
12722 ID *tbl;
12723 struct st_table *labels_table = st_init_numtable();
12724 VALUE labels_wrapper = TypedData_Wrap_Struct(0, &labels_wrapper_type, labels_table);
12725 VALUE arg_opt_labels = rb_hash_aref(params, SYM(opt));
12726 VALUE keywords = rb_hash_aref(params, SYM(keyword));
12727 VALUE sym_arg_rest = ID2SYM(rb_intern_const("#arg_rest"));
12728 DECL_ANCHOR(anchor);
12729 INIT_ANCHOR(anchor);
12730
12731 len = RARRAY_LENINT(locals);
12732 ISEQ_BODY(iseq)->local_table_size = len;
12733 ISEQ_BODY(iseq)->local_table = tbl = len > 0 ? (ID *)ALLOC_N(ID, ISEQ_BODY(iseq)->local_table_size) : NULL;
12734
12735 for (i = 0; i < len; i++) {
12736 VALUE lv = RARRAY_AREF(locals, i);
12737
12738 if (sym_arg_rest == lv) {
12739 tbl[i] = 0;
12740 }
12741 else {
12742 tbl[i] = FIXNUM_P(lv) ? (ID)FIX2LONG(lv) : SYM2ID(CHECK_SYMBOL(lv));
12743 }
12744 }
12745
12746#define INT_PARAM(F) int_param(&ISEQ_BODY(iseq)->param.F, params, SYM(F))
12747 if (INT_PARAM(lead_num)) {
12748 ISEQ_BODY(iseq)->param.flags.has_lead = TRUE;
12749 }
12750 if (INT_PARAM(post_num)) ISEQ_BODY(iseq)->param.flags.has_post = TRUE;
12751 if (INT_PARAM(block_start)) ISEQ_BODY(iseq)->param.flags.has_block = TRUE;
12752#undef INT_PARAM
12753 if (Qtrue == rb_hash_aref(params, SYM(rest))) ISEQ_BODY(iseq)->param.flags.has_rest = TRUE;
12754 {
12755#define INT_PARAM(F) F = (int_param(&x, misc, SYM(F)) ? (unsigned int)x : 0)
12756 int x;
12757 INT_PARAM(arg_size);
12758 INT_PARAM(local_size);
12759 INT_PARAM(stack_max);
12760#undef INT_PARAM
12761 }
12762
12763 VALUE source_hash = rb_hash_aref(misc, ID2SYM(rb_intern("source_hash")));
12764 if (!NIL_P(source_hash)) {
12765 ISEQ_BODY(iseq)->source_hash = NUM2ULL(source_hash);
12766 }
12767
12768 VALUE node_ids = Qfalse;
12769 node_ids = rb_hash_aref(misc, ID2SYM(rb_intern("node_ids")));
12770 if (!RB_TYPE_P(node_ids, T_ARRAY)) {
12771 rb_raise(rb_eTypeError, "node_ids is not an array");
12772 }
12773
12774 if (RB_TYPE_P(arg_opt_labels, T_ARRAY)) {
12775 len = RARRAY_LENINT(arg_opt_labels);
12776 ISEQ_BODY(iseq)->param.flags.has_opt = !!(len - 1 >= 0);
12777
12778 if (ISEQ_BODY(iseq)->param.flags.has_opt) {
12779 VALUE *opt_table = ALLOC_N(VALUE, len);
12780
12781 for (i = 0; i < len; i++) {
12782 VALUE ent = RARRAY_AREF(arg_opt_labels, i);
12783 LABEL *label = register_label(iseq, labels_table, ent);
12784 opt_table[i] = (VALUE)label;
12785 }
12786
12787 ISEQ_BODY(iseq)->param.opt_num = len - 1;
12788 ISEQ_BODY(iseq)->param.opt_table = opt_table;
12789 }
12790 }
12791 else if (!NIL_P(arg_opt_labels)) {
12792 rb_raise(rb_eTypeError, ":opt param is not an array: %+"PRIsVALUE,
12793 arg_opt_labels);
12794 }
12795
12796 if (RB_TYPE_P(keywords, T_ARRAY)) {
12797 ISEQ_BODY(iseq)->param.keyword = iseq_build_kw(iseq, params, keywords);
12798 }
12799 else if (!NIL_P(keywords)) {
12800 rb_raise(rb_eTypeError, ":keywords param is not an array: %+"PRIsVALUE,
12801 keywords);
12802 }
12803
12804 if (Qtrue == rb_hash_aref(params, SYM(ambiguous_param0))) {
12805 ISEQ_BODY(iseq)->param.flags.ambiguous_param0 = TRUE;
12806 }
12807
12808 if (Qtrue == rb_hash_aref(params, SYM(use_block))) {
12809 ISEQ_BODY(iseq)->param.flags.use_block = TRUE;
12810 }
12811
12812 if (int_param(&i, params, SYM(kwrest))) {
12813 struct rb_iseq_param_keyword *keyword = (struct rb_iseq_param_keyword *)ISEQ_BODY(iseq)->param.keyword;
12814 if (keyword == NULL) {
12815 ISEQ_BODY(iseq)->param.keyword = keyword = ZALLOC(struct rb_iseq_param_keyword);
12816 }
12817 keyword->rest_start = i;
12818 ISEQ_BODY(iseq)->param.flags.has_kwrest = TRUE;
12819 }
12820#undef SYM
12821 iseq_calc_param_size(iseq);
12822
12823 /* exception */
12824 iseq_build_from_ary_exception(iseq, labels_table, exception);
12825
12826 /* body */
12827 iseq_build_from_ary_body(iseq, anchor, body, node_ids, labels_wrapper);
12828
12829 ISEQ_BODY(iseq)->param.size = arg_size;
12830 ISEQ_BODY(iseq)->local_table_size = local_size;
12831 ISEQ_BODY(iseq)->stack_max = stack_max;
12832}
12833
12834/* for parser */
12835
12836int
12837rb_dvar_defined(ID id, const rb_iseq_t *iseq)
12838{
12839 if (iseq) {
12840 const struct rb_iseq_constant_body *body = ISEQ_BODY(iseq);
12841 while (body->type == ISEQ_TYPE_BLOCK ||
12842 body->type == ISEQ_TYPE_RESCUE ||
12843 body->type == ISEQ_TYPE_ENSURE ||
12844 body->type == ISEQ_TYPE_EVAL ||
12845 body->type == ISEQ_TYPE_MAIN
12846 ) {
12847 unsigned int i;
12848
12849 for (i = 0; i < body->local_table_size; i++) {
12850 if (body->local_table[i] == id) {
12851 return 1;
12852 }
12853 }
12854 iseq = body->parent_iseq;
12855 body = ISEQ_BODY(iseq);
12856 }
12857 }
12858 return 0;
12859}
12860
12861int
12862rb_local_defined(ID id, const rb_iseq_t *iseq)
12863{
12864 if (iseq) {
12865 unsigned int i;
12866 const struct rb_iseq_constant_body *const body = ISEQ_BODY(ISEQ_BODY(iseq)->local_iseq);
12867
12868 for (i=0; i<body->local_table_size; i++) {
12869 if (body->local_table[i] == id) {
12870 return 1;
12871 }
12872 }
12873 }
12874 return 0;
12875}
12876
12877/* ISeq binary format */
12878
12879#ifndef IBF_ISEQ_DEBUG
12880#define IBF_ISEQ_DEBUG 0
12881#endif
12882
12883#ifndef IBF_ISEQ_ENABLE_LOCAL_BUFFER
12884#define IBF_ISEQ_ENABLE_LOCAL_BUFFER 0
12885#endif
12886
12887typedef uint32_t ibf_offset_t;
12888#define IBF_OFFSET(ptr) ((ibf_offset_t)(VALUE)(ptr))
12889
12890#define IBF_MAJOR_VERSION ISEQ_MAJOR_VERSION
12891#ifdef RUBY_DEVEL
12892#define IBF_DEVEL_VERSION 21
12893#define IBF_MINOR_VERSION (ISEQ_MINOR_VERSION * 10000 + IBF_DEVEL_VERSION)
12894#else
12895#define IBF_MINOR_VERSION ISEQ_MINOR_VERSION
12896#endif
12897
12898static const char IBF_ENDIAN_MARK =
12899#ifdef WORDS_BIGENDIAN
12900 'b'
12901#else
12902 'l'
12903#endif
12904 ;
12905
12907 char magic[4]; /* YARB */
12908 uint32_t major_version;
12909 uint32_t minor_version;
12910 uint32_t size;
12911 uint32_t extra_size;
12912
12913 uint32_t iseq_list_size;
12914 uint32_t global_object_list_size;
12915 ibf_offset_t iseq_list_offset;
12916 ibf_offset_t global_object_list_offset;
12917 uint32_t source_hash_hi;
12918 uint32_t source_hash_lo;
12919 uint8_t endian;
12920 uint8_t wordsize; /* assume no 2048-bit CPU */
12921};
12922
12924 VALUE str;
12925 st_table *obj_table; /* obj -> obj number */
12926};
12927
12928struct ibf_dump {
12929 st_table *iseq_table; /* iseq -> iseq number */
12930 struct ibf_dump_buffer global_buffer;
12931 struct ibf_dump_buffer *current_buffer;
12932};
12933
12935 const char *buff;
12936 ibf_offset_t size;
12937
12938 VALUE obj_list; /* [obj0, ...] */
12939 unsigned int obj_list_size;
12940 ibf_offset_t obj_list_offset;
12941 ibf_offset_t *obj_offsets;
12942};
12943
12944struct ibf_load {
12945 const struct ibf_header *header;
12946 VALUE iseq_list; /* [iseq0, ...] */
12947 struct ibf_load_buffer global_buffer;
12948 VALUE loader_obj;
12949 rb_iseq_t *iseq;
12950 VALUE str;
12951 VALUE path_override;
12952 VALUE realpath_override;
12953 VALUE pathobj;
12954 VALUE pathobj_index;
12955 struct ibf_load_buffer *current_buffer;
12956};
12957
12959 long size;
12960 VALUE buffer[1];
12961};
12962
12963static void
12964pinned_list_mark(void *ptr)
12965{
12966 long i;
12967 struct pinned_list *list = (struct pinned_list *)ptr;
12968 for (i = 0; i < list->size; i++) {
12969 if (list->buffer[i]) {
12970 rb_gc_mark(list->buffer[i]);
12971 }
12972 }
12973}
12974
12975static const rb_data_type_t pinned_list_type = {
12976 "pinned_list",
12977 {
12978 pinned_list_mark,
12980 NULL, // No external memory to report,
12981 },
12982 0, 0, RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_EMBEDDABLE
12983};
12984
12985static VALUE
12986pinned_list_fetch(VALUE list, long offset)
12987{
12988 struct pinned_list * ptr;
12989
12990 TypedData_Get_Struct(list, struct pinned_list, &pinned_list_type, ptr);
12991
12992 if (offset < 0 || offset >= ptr->size) {
12993 rb_raise(rb_eIndexError, "object index out of range: %ld", offset);
12994 }
12995
12996 return ptr->buffer[offset];
12997}
12998
12999static void
13000pinned_list_store(VALUE list, long offset, VALUE object)
13001{
13002 struct pinned_list * ptr;
13003
13004 TypedData_Get_Struct(list, struct pinned_list, &pinned_list_type, ptr);
13005
13006 if (offset < 0 || offset >= ptr->size) {
13007 rb_raise(rb_eIndexError, "object index out of range: %ld", offset);
13008 }
13009
13010 RB_OBJ_WRITE(list, &ptr->buffer[offset], object);
13011}
13012
13013static VALUE
13014pinned_list_new(long size)
13015{
13016 size_t memsize = offsetof(struct pinned_list, buffer) + size * sizeof(VALUE);
13017 VALUE obj_list = rb_data_typed_object_zalloc(0, memsize, &pinned_list_type);
13018 struct pinned_list * ptr = RTYPEDDATA_GET_DATA(obj_list);
13019 ptr->size = size;
13020 return obj_list;
13021}
13022
13023static ibf_offset_t
13024ibf_dump_pos(struct ibf_dump *dump)
13025{
13026 rb_len_t pos = RSTRING_LEN(dump->current_buffer->str);
13027#if SIZEOF_RB_LEN_T > SIZEOF_INT
13028 if (pos >= UINT_MAX) {
13029 rb_raise(rb_eRuntimeError, "dump size exceeds");
13030 }
13031#endif
13032 return (unsigned int)pos;
13033}
13034
13035static void
13036ibf_dump_align(struct ibf_dump *dump, size_t align)
13037{
13038 ibf_offset_t pos = ibf_dump_pos(dump);
13039 if (pos % align) {
13040 static const char padding[sizeof(VALUE)];
13041 size_t size = align - ((size_t)pos % align);
13042#if SIZEOF_RB_LEN_T > SIZEOF_INT
13043 if (pos + size >= UINT_MAX) {
13044 rb_raise(rb_eRuntimeError, "dump size exceeds");
13045 }
13046#endif
13047 for (; size > sizeof(padding); size -= sizeof(padding)) {
13048 rb_str_cat(dump->current_buffer->str, padding, sizeof(padding));
13049 }
13050 rb_str_cat(dump->current_buffer->str, padding, size);
13051 }
13052}
13053
13054static ibf_offset_t
13055ibf_dump_write(struct ibf_dump *dump, const void *buff, size_t size)
13056{
13057 ibf_offset_t pos = ibf_dump_pos(dump);
13058#if SIZEOF_RB_LEN_T > SIZEOF_INT
13059 /* ensure the resulting dump does not exceed UINT_MAX */
13060 if (size >= UINT_MAX || pos + size >= UINT_MAX) {
13061 rb_raise(rb_eRuntimeError, "dump size exceeds");
13062 }
13063#endif
13064 rb_str_cat(dump->current_buffer->str, (const char *)buff, size);
13065 return pos;
13066}
13067
13068static ibf_offset_t
13069ibf_dump_write_byte(struct ibf_dump *dump, unsigned char byte)
13070{
13071 return ibf_dump_write(dump, &byte, sizeof(unsigned char));
13072}
13073
13074static void
13075ibf_dump_overwrite(struct ibf_dump *dump, void *buff, unsigned int size, rb_len_t offset)
13076{
13077 VALUE str = dump->current_buffer->str;
13078 char *ptr = RSTRING_PTR(str);
13079 if ((rb_ulen_t)(size + offset) > (rb_ulen_t)RSTRING_LEN(str))
13080 rb_bug("ibf_dump_overwrite: overflow");
13081 memcpy(ptr + offset, buff, size);
13082}
13083
13084static const void *
13085ibf_load_ptr(const struct ibf_load *load, ibf_offset_t *offset, int size)
13086{
13087 ibf_offset_t beg = *offset;
13088 *offset += size;
13089 return load->current_buffer->buff + beg;
13090}
13091
13092static void *
13093ibf_load_alloc(const struct ibf_load *load, ibf_offset_t offset, size_t x, size_t y)
13094{
13095 void *buff = ruby_xmalloc2(x, y);
13096 size_t size = x * y;
13097 memcpy(buff, load->current_buffer->buff + offset, size);
13098 return buff;
13099}
13100
13101#define IBF_W_ALIGN(type) (RUBY_ALIGNOF(type) > 1 ? ibf_dump_align(dump, RUBY_ALIGNOF(type)) : (void)0)
13102
13103#define IBF_W(b, type, n) (IBF_W_ALIGN(type), (type *)(VALUE)IBF_WP(b, type, n))
13104#define IBF_WV(variable) ibf_dump_write(dump, &(variable), sizeof(variable))
13105#define IBF_WP(b, type, n) ibf_dump_write(dump, (b), sizeof(type) * (n))
13106#define IBF_R(val, type, n) (type *)ibf_load_alloc(load, IBF_OFFSET(val), sizeof(type), (n))
13107#define IBF_ZERO(variable) memset(&(variable), 0, sizeof(variable))
13108
13109static int
13110ibf_table_lookup(struct st_table *table, st_data_t key)
13111{
13112 st_data_t val;
13113
13114 if (st_lookup(table, key, &val)) {
13115 return (int)val;
13116 }
13117 else {
13118 return -1;
13119 }
13120}
13121
13122static int
13123ibf_table_find_or_insert(struct st_table *table, st_data_t key)
13124{
13125 int index = ibf_table_lookup(table, key);
13126
13127 if (index < 0) { /* not found */
13128 index = (int)table->num_entries;
13129 st_insert(table, key, (st_data_t)index);
13130 }
13131
13132 return index;
13133}
13134
13135/* dump/load generic */
13136
13137static void ibf_dump_object_list(struct ibf_dump *dump, ibf_offset_t *obj_list_offset, unsigned int *obj_list_size);
13138
13139static VALUE ibf_load_object(const struct ibf_load *load, VALUE object_index);
13140static rb_iseq_t *ibf_load_iseq(const struct ibf_load *load, const rb_iseq_t *index_iseq);
13141
13142static st_table *
13143ibf_dump_object_table_new(void)
13144{
13145 st_table *obj_table = st_init_numtable(); /* need free */
13146 st_insert(obj_table, (st_data_t)Qnil, (st_data_t)0); /* 0th is nil */
13147
13148 return obj_table;
13149}
13150
13151static VALUE
13152ibf_dump_object(struct ibf_dump *dump, VALUE obj)
13153{
13154 return ibf_table_find_or_insert(dump->current_buffer->obj_table, (st_data_t)obj);
13155}
13156
13157static VALUE
13158ibf_dump_id(struct ibf_dump *dump, ID id)
13159{
13160 if (id == 0 || rb_id2name(id) == NULL) {
13161 return 0;
13162 }
13163 return ibf_dump_object(dump, rb_id2sym(id));
13164}
13165
13166static ID
13167ibf_load_id(const struct ibf_load *load, const ID id_index)
13168{
13169 if (id_index == 0) {
13170 return 0;
13171 }
13172 VALUE sym = ibf_load_object(load, id_index);
13173 if (rb_integer_type_p(sym)) {
13174 /* Load hidden local variables as indexes */
13175 return NUM2ULONG(sym);
13176 }
13177 return rb_sym2id(sym);
13178}
13179
13180/* dump/load: code */
13181
13182static ibf_offset_t ibf_dump_iseq_each(struct ibf_dump *dump, const rb_iseq_t *iseq);
13183
13184static int
13185ibf_dump_iseq(struct ibf_dump *dump, const rb_iseq_t *iseq)
13186{
13187 if (iseq == NULL) {
13188 return -1;
13189 }
13190 else {
13191 return ibf_table_find_or_insert(dump->iseq_table, (st_data_t)iseq);
13192 }
13193}
13194
13195static unsigned char
13196ibf_load_byte(const struct ibf_load *load, ibf_offset_t *offset)
13197{
13198 if (*offset >= load->current_buffer->size) { rb_raise(rb_eRuntimeError, "invalid bytecode"); }
13199 return (unsigned char)load->current_buffer->buff[(*offset)++];
13200}
13201
13202/*
13203 * Small uint serialization
13204 * 0x00000000_00000000 - 0x00000000_0000007f: 1byte | XXXX XXX1 |
13205 * 0x00000000_00000080 - 0x00000000_00003fff: 2byte | XXXX XX10 | XXXX XXXX |
13206 * 0x00000000_00004000 - 0x00000000_001fffff: 3byte | XXXX X100 | XXXX XXXX | XXXX XXXX |
13207 * 0x00000000_00020000 - 0x00000000_0fffffff: 4byte | XXXX 1000 | XXXX XXXX | XXXX XXXX | XXXX XXXX |
13208 * ...
13209 * 0x00010000_00000000 - 0x00ffffff_ffffffff: 8byte | 1000 0000 | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX |
13210 * 0x01000000_00000000 - 0xffffffff_ffffffff: 9byte | 0000 0000 | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX | XXXX XXXX |
13211 */
13212static void
13213ibf_dump_write_small_value(struct ibf_dump *dump, VALUE x)
13214{
13215 if (sizeof(VALUE) > 8 || CHAR_BIT != 8) {
13216 ibf_dump_write(dump, &x, sizeof(VALUE));
13217 return;
13218 }
13219
13220 enum { max_byte_length = sizeof(VALUE) + 1 };
13221
13222 unsigned char bytes[max_byte_length];
13223 ibf_offset_t n;
13224
13225 for (n = 0; n < sizeof(VALUE) && (x >> (7 - n)); n++, x >>= 8) {
13226 bytes[max_byte_length - 1 - n] = (unsigned char)x;
13227 }
13228
13229 x <<= 1;
13230 x |= 1;
13231 x <<= n;
13232 bytes[max_byte_length - 1 - n] = (unsigned char)x;
13233 n++;
13234
13235 ibf_dump_write(dump, bytes + max_byte_length - n, n);
13236}
13237
13238static VALUE
13239ibf_load_small_value(const struct ibf_load *load, ibf_offset_t *offset)
13240{
13241 if (sizeof(VALUE) > 8 || CHAR_BIT != 8) {
13242 union { char s[sizeof(VALUE)]; VALUE v; } x;
13243
13244 memcpy(x.s, load->current_buffer->buff + *offset, sizeof(VALUE));
13245 *offset += sizeof(VALUE);
13246
13247 return x.v;
13248 }
13249
13250 enum { max_byte_length = sizeof(VALUE) + 1 };
13251
13252 const unsigned char *buffer = (const unsigned char *)load->current_buffer->buff;
13253 const unsigned char c = buffer[*offset];
13254
13255 ibf_offset_t n =
13256 c & 1 ? 1 :
13257 c == 0 ? 9 : ntz_int32(c) + 1;
13258 VALUE x = (VALUE)c >> n;
13259
13260 if (*offset + n > load->current_buffer->size) {
13261 rb_raise(rb_eRuntimeError, "invalid byte sequence");
13262 }
13263
13264 ibf_offset_t i;
13265 for (i = 1; i < n; i++) {
13266 x <<= 8;
13267 x |= (VALUE)buffer[*offset + i];
13268 }
13269
13270 *offset += n;
13271 return x;
13272}
13273
13274/* For values that are -1 when absent, which would otherwise take the longest
13275 * small value encoding: they are written shifted by one. */
13276static void
13277ibf_dump_write_small_value_nullable(struct ibf_dump *dump, VALUE x)
13278{
13279 ibf_dump_write_small_value(dump, x + 1);
13280}
13281
13282static VALUE
13283ibf_load_small_value_nullable(const struct ibf_load *load, ibf_offset_t *offset)
13284{
13285 return ibf_load_small_value(load, offset) - 1;
13286}
13287
13288static void
13289ibf_dump_write_small_int32(struct ibf_dump *dump, int32_t x)
13290{
13291 ibf_dump_write_small_value(dump, ((uint32_t)x << 1) ^ (x < 0 ? 0xffffffff : 0)); // zigzag encoding.
13292}
13293
13294static int32_t
13295ibf_load_small_int32(const struct ibf_load *load, ibf_offset_t *offset)
13296{
13297 VALUE x = ibf_load_small_value(load, offset);
13298 return (int32_t)((x >> 1) ^ (x & 1 ? 0xffffffff : 0));
13299}
13300
13301static void
13302ibf_dump_builtin(struct ibf_dump *dump, const struct rb_builtin_function *bf)
13303{
13304 // short: index
13305 // short: name.length
13306 // bytes: name
13307 // // omit argc (only verify with name)
13308 ibf_dump_write_small_value(dump, (VALUE)bf->index);
13309
13310 size_t len = strlen(bf->name);
13311 ibf_dump_write_small_value(dump, (VALUE)len);
13312 ibf_dump_write(dump, bf->name, len);
13313}
13314
13315static const struct rb_builtin_function *
13316ibf_load_builtin(const struct ibf_load *load, ibf_offset_t *offset)
13317{
13318 int i = (int)ibf_load_small_value(load, offset);
13319 int len = (int)ibf_load_small_value(load, offset);
13320 const char *name = (char *)ibf_load_ptr(load, offset, len);
13321
13322 if (0) {
13323 fprintf(stderr, "%.*s!!\n", len, name);
13324 }
13325
13326 const struct rb_builtin_function *table = GET_VM()->builtin_function_table;
13327 if (table == NULL) rb_raise(rb_eArgError, "builtin function table is not provided");
13328 if (strncmp(table[i].name, name, len) != 0) {
13329 rb_raise(rb_eArgError, "builtin function index (%d) mismatch (expect %.*s but %s)",
13330 i, len, name, table[i].name);
13331 }
13332 // fprintf(stderr, "load-builtin: name:%s(%d)\n", table[i].name, table[i].argc);
13333
13334 return &table[i];
13335}
13336
13337static int
13338ibf_dump_insn_header(struct ibf_dump *dump, const rb_iseq_t *iseq, unsigned int pos, VALUE insn, int prev_line)
13339{
13340 struct iseq_insn_info_entry info = rb_iseq_insn_info_at(iseq, pos);
13341 bool changed = info.events || info.line_no != prev_line;
13342
13343 // Most instructions have no events and stay on the same line, so we use
13344 // the opcode LSB to saves writing isns_info for most ops.
13345 ibf_dump_write_small_value(dump, (insn << 1) | changed);
13346
13347 if (changed) {
13348 if (info.line_no == prev_line) {
13349 ibf_dump_write_small_value(dump, info.events << 1);
13350 }
13351 else {
13352 ibf_dump_write_small_value(dump, (info.events << 1) | 1);
13353 ibf_dump_write_small_int32(dump, info.line_no - prev_line);
13354 }
13355 }
13356 return info.line_no;
13357}
13358
13359static ibf_offset_t
13360ibf_dump_code(struct ibf_dump *dump, const rb_iseq_t *iseq)
13361{
13362 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
13363 const int iseq_size = body->iseq_size;
13364 int code_index;
13365 const VALUE *orig_code = rb_iseq_original_iseq(iseq);
13366 int prev_line = body->location.first_lineno;
13367
13368 ibf_offset_t offset = ibf_dump_pos(dump);
13369
13370 for (code_index=0; code_index<iseq_size;) {
13371 const VALUE insn = orig_code[code_index];
13372 const char *types = insn_op_types(insn);
13373 int op_index;
13374
13375 if (insn >= 0x100) { rb_raise(rb_eRuntimeError, "invalid instruction"); }
13376 prev_line = ibf_dump_insn_header(dump, iseq, code_index, insn, prev_line);
13377 code_index++;
13378
13379 /* operands */
13380 for (op_index=0; types[op_index]; op_index++, code_index++) {
13381 VALUE op = orig_code[code_index];
13382 VALUE wv;
13383
13384 switch (types[op_index]) {
13385 case TS_CDHASH:
13386 case TS_VALUE:
13387 wv = ibf_dump_object(dump, op);
13388 break;
13389 case TS_ISEQ:
13390 ibf_dump_write_small_value_nullable(dump, (VALUE)ibf_dump_iseq(dump, (const rb_iseq_t *)op));
13391 goto skip_wv;
13392 case TS_IC:
13393 case TS_IVC:
13394 case TS_ICVARC:
13395 {
13397 wv = is - ISEQ_IS_ENTRY_START(body, types[op_index]);
13398 }
13399 break;
13400 case TS_CALLDATA:
13401 {
13402 goto skip_wv;
13403 }
13404 case TS_ID:
13405 wv = ibf_dump_id(dump, (ID)op);
13406 break;
13407 case TS_FUNCPTR:
13408 rb_raise(rb_eRuntimeError, "TS_FUNCPTR is not supported");
13409 goto skip_wv;
13410 case TS_BUILTIN:
13411 ibf_dump_builtin(dump, (const struct rb_builtin_function *)op);
13412 goto skip_wv;
13413 default:
13414 wv = op;
13415 break;
13416 }
13417 ibf_dump_write_small_value(dump, wv);
13418 skip_wv:;
13419 }
13420 RUBY_ASSERT(insn_len(insn) == op_index+1);
13421 }
13422
13423 return offset;
13424}
13425
13426static rb_const_path_t
13427ibf_load_const_path(const struct ibf_load *load, ibf_offset_t *reading_pos)
13428{
13429 size_t header = (size_t)ibf_load_small_value(load, reading_pos);
13430 bool absolute = header & 1;
13431 size_t size = header >> 1;
13432 if (size == 0) {
13433 rb_raise(rb_eRuntimeError, "broken binary format");
13434 }
13435
13436 VALUE buf_v = 0;
13437 ID *ids = ALLOCV_N(ID, buf_v, size);
13438 for (size_t i = 0; i < size; i++) {
13439 ids[i] = ibf_load_id(load, (ID)ibf_load_small_value(load, reading_pos));
13440 if (!is_notop_id(ids[i]) || !is_const_id(ids[i])) {
13441 rb_raise(rb_eRuntimeError, "broken binary format");
13442 }
13443 }
13444
13445 rb_const_path_t const_path = rb_const_path_from_ids(absolute, ids, size);
13446 ALLOCV_END(buf_v);
13447 return const_path;
13448}
13449
13450/* The run-length insns_info entries rebuilt while loading the bytecode. */
13452 struct iseq_insn_info_entry *entries;
13453 unsigned int *positions;
13454 unsigned int size;
13455 int line;
13456};
13457
13458static VALUE
13459ibf_load_insn_header(const struct ibf_load *load, ibf_offset_t *reading_pos, unsigned int pos,
13460 struct ibf_insn_info_builder *info)
13461{
13462 rb_iseq_events_t events = 0;
13463 VALUE opcode = ibf_load_small_value(load, reading_pos);
13464 bool has_events = opcode & 1;
13465 opcode >>= 1;
13466
13467 if (has_events) {
13468 VALUE header = ibf_load_small_value(load, reading_pos);
13469 bool has_line = header & 1;
13470 events = (rb_iseq_events_t)(header >> 1);
13471 if (has_line) {
13472 info->line += ibf_load_small_int32(load, reading_pos);
13473 }
13474 }
13475
13476 const struct iseq_insn_info_entry *last = info->size ? &info->entries[info->size - 1] : NULL;
13477 if (!last || last->line_no != info->line || last->events != events) {
13478 info->entries[info->size].line_no = info->line;
13479 info->entries[info->size].events = events;
13480 info->positions[info->size] = pos;
13481 info->size++;
13482 }
13483 return opcode;
13484}
13485
13486static void
13487ibf_load_insns_info(const struct ibf_load *load, struct rb_iseq_constant_body *body, ibf_offset_t body_offset,
13488 const struct ibf_insn_info_builder *info)
13489{
13490 ibf_offset_t reading_pos = body_offset;
13491 const unsigned int node_ids_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
13492 if (node_ids_size == 0 || node_ids_size > load->current_buffer->size - reading_pos) {
13493 rb_raise(rb_eRuntimeError, "invalid byte sequence");
13494 }
13495 const uint8_t *node_ids = (const uint8_t *)load->current_buffer->buff + reading_pos;
13496
13497 rb_iseq_insn_info_setup(body, info->entries, info->positions, info->size, node_ids, node_ids_size);
13498}
13499
13500static VALUE *
13501ibf_load_code(const struct ibf_load *load, rb_iseq_t *iseq, ibf_offset_t bytecode_offset, ibf_offset_t bytecode_size, unsigned int iseq_size,
13502 ibf_offset_t insns_info_body_offset)
13503{
13504 VALUE iseqv = (VALUE)iseq;
13505 unsigned int code_index;
13506 ibf_offset_t reading_pos = bytecode_offset;
13507 VALUE *code = ZALLOC_N(VALUE, iseq_size);
13508
13509 struct rb_iseq_constant_body *load_body = ISEQ_BODY(iseq);
13510 struct rb_call_data *cd_entries = load_body->call_data;
13511
13512 load_body->iseq_encoded = code;
13513 load_body->iseq_size = iseq_size;
13514
13515 iseq_bits_t * mark_offset_bits;
13516 if (ISEQ_MBITS_BUFLEN(iseq_size) == 1) {
13517 load_body->mark_bits.single = 0;
13518 mark_offset_bits = &load_body->mark_bits.single;
13519 }
13520 else {
13521 load_body->mark_bits.list = ZALLOC_N(iseq_bits_t, ISEQ_MBITS_BUFLEN(iseq_size));
13522 mark_offset_bits = load_body->mark_bits.list;
13523 }
13524 bool needs_bitmap = false;
13525
13526 VALUE entries_buf, positions_buf;
13527 struct ibf_insn_info_builder insns_info = {
13528 .entries = ALLOCV_N(struct iseq_insn_info_entry, entries_buf, iseq_size),
13529 .positions = ALLOCV_N(unsigned int, positions_buf, iseq_size),
13530 .line = load_body->location.first_lineno,
13531 };
13532
13533 for (code_index=0; code_index<iseq_size;) {
13534 const VALUE insn = code[code_index] = ibf_load_insn_header(load, &reading_pos, code_index, &insns_info);
13535 const char *types = insn_op_types(insn);
13536 int op_index;
13537
13538 code_index++;
13539
13540 /* operands */
13541 for (op_index=0; types[op_index]; op_index++, code_index++) {
13542 const char operand_type = types[op_index];
13543 switch (operand_type) {
13544 case TS_VALUE:
13545 {
13546 VALUE op = ibf_load_small_value(load, &reading_pos);
13547 VALUE v = ibf_load_object(load, op);
13548 code[code_index] = v;
13549 if (!SPECIAL_CONST_P(v)) {
13550 RB_OBJ_WRITTEN(iseqv, Qundef, v);
13551 ISEQ_MBITS_SET(mark_offset_bits, code_index);
13552 needs_bitmap = true;
13553 }
13554 break;
13555 }
13556 case TS_CDHASH:
13557 {
13558 VALUE op = ibf_load_small_value(load, &reading_pos);
13559 VALUE v = ibf_load_object(load, op);
13560
13561 // Overwrite the existing hash in the object list. This
13562 // is to keep the object alive during load time.
13563 // [Bug #17984] [ruby-core:104259]
13564 pinned_list_store(load->current_buffer->obj_list, (long)op, v);
13565
13566 code[code_index] = v;
13567 ISEQ_MBITS_SET(mark_offset_bits, code_index);
13568 RB_OBJ_WRITTEN(iseqv, Qundef, v);
13569 needs_bitmap = true;
13570 break;
13571 }
13572 case TS_ISEQ:
13573 {
13574 VALUE op = ibf_load_small_value_nullable(load, &reading_pos);
13575 VALUE v = (VALUE)ibf_load_iseq(load, (const rb_iseq_t *)op);
13576 code[code_index] = v;
13577 if (!SPECIAL_CONST_P(v)) {
13578 RB_OBJ_WRITTEN(iseqv, Qundef, v);
13579 ISEQ_MBITS_SET(mark_offset_bits, code_index);
13580 needs_bitmap = true;
13581 }
13582 break;
13583 }
13584 case TS_IC:
13585 case TS_ICVARC:
13586 case TS_IVC:
13587 {
13588 unsigned int op = (unsigned int)ibf_load_small_value(load, &reading_pos);
13589
13590 union iseq_inline_storage_entry *ic = ISEQ_IS_ENTRY_START(load_body, operand_type) + op;
13591 code[code_index] = (VALUE)ic;
13592
13593 if (operand_type == TS_IVC) {
13594 IVC cache = (IVC)ic;
13595
13596 if (insn == BIN(setinstancevariable)) {
13597 ID iv_name = (ID)code[code_index - 1];
13598 cache->iv_set_name = iv_name;
13599 cache->value = IVAR_CACHE_INIT;
13600 }
13601 else {
13602 cache->iv_set_name = 0;
13603 cache->value = rb_getivar_cache_pack(ROOT_SHAPE_ID, ATTR_INDEX_NOT_SET);
13604 }
13605 }
13606
13607 }
13608 break;
13609 case TS_CALLDATA:
13610 {
13611 code[code_index] = (VALUE)cd_entries++;
13612 }
13613 break;
13614 case TS_ID:
13615 {
13616 VALUE op = ibf_load_small_value(load, &reading_pos);
13617 code[code_index] = ibf_load_id(load, (ID)(VALUE)op);
13618 }
13619 break;
13620 case TS_FUNCPTR:
13621 rb_raise(rb_eRuntimeError, "TS_FUNCPTR is not supported");
13622 break;
13623 case TS_BUILTIN:
13624 code[code_index] = (VALUE)ibf_load_builtin(load, &reading_pos);
13625 break;
13626 default:
13627 code[code_index] = ibf_load_small_value(load, &reading_pos);
13628 continue;
13629 }
13630 }
13631 if (insn_len(insn) != op_index+1) {
13632 rb_raise(rb_eRuntimeError, "operand size mismatch");
13633 }
13634 }
13635
13636 if (!needs_bitmap) {
13637 SIZED_FREE_N(load_body->mark_bits.list, ISEQ_MBITS_BUFLEN(iseq_size));
13638 load_body->mark_bits.list = NULL;
13639 }
13640
13641 RUBY_ASSERT(code_index == iseq_size);
13642 RUBY_ASSERT(reading_pos == bytecode_offset + bytecode_size);
13643
13644 ibf_load_insns_info(load, load_body, insns_info_body_offset, &insns_info);
13645 ALLOCV_END(entries_buf);
13646 ALLOCV_END(positions_buf);
13647
13648 return code;
13649}
13650
13651static ibf_offset_t
13652ibf_dump_param_opt_table(struct ibf_dump *dump, const rb_iseq_t *iseq)
13653{
13654 int opt_num = ISEQ_BODY(iseq)->param.opt_num;
13655
13656 if (opt_num > 0) {
13657 IBF_W_ALIGN(VALUE);
13658 return ibf_dump_write(dump, ISEQ_BODY(iseq)->param.opt_table, sizeof(VALUE) * (opt_num + 1));
13659 }
13660 else {
13661 return ibf_dump_pos(dump);
13662 }
13663}
13664
13665static VALUE *
13666ibf_load_param_opt_table(const struct ibf_load *load, ibf_offset_t opt_table_offset, int opt_num)
13667{
13668 if (opt_num > 0) {
13669 VALUE *table = ALLOC_N(VALUE, opt_num+1);
13670 MEMCPY(table, load->current_buffer->buff + opt_table_offset, VALUE, opt_num+1);
13671 return table;
13672 }
13673 else {
13674 return NULL;
13675 }
13676}
13677
13678static ibf_offset_t
13679ibf_dump_param_keyword(struct ibf_dump *dump, const rb_iseq_t *iseq)
13680{
13681 const struct rb_iseq_param_keyword *kw = ISEQ_BODY(iseq)->param.keyword;
13682
13683 if (kw) {
13684 struct rb_iseq_param_keyword dump_kw = *kw;
13685 int dv_num = kw->num - kw->required_num;
13686 ID *ids = kw->num > 0 ? ALLOCA_N(ID, kw->num) : NULL;
13687 VALUE *dvs = dv_num > 0 ? ALLOCA_N(VALUE, dv_num) : NULL;
13688 int i;
13689
13690 for (i=0; i<kw->num; i++) ids[i] = (ID)ibf_dump_id(dump, kw->table[i]);
13691 for (i=0; i<dv_num; i++) dvs[i] = (VALUE)ibf_dump_object(dump, kw->default_values[i]);
13692
13693 dump_kw.table = IBF_W(ids, ID, kw->num);
13694 dump_kw.default_values = IBF_W(dvs, VALUE, dv_num);
13695 IBF_W_ALIGN(struct rb_iseq_param_keyword);
13696 return ibf_dump_write(dump, &dump_kw, sizeof(struct rb_iseq_param_keyword) * 1);
13697 }
13698 else {
13699 return 0;
13700 }
13701}
13702
13703static const struct rb_iseq_param_keyword *
13704ibf_load_param_keyword(const struct ibf_load *load, ibf_offset_t param_keyword_offset)
13705{
13706 if (param_keyword_offset) {
13707 struct rb_iseq_param_keyword *kw = IBF_R(param_keyword_offset, struct rb_iseq_param_keyword, 1);
13708 int dv_num = kw->num - kw->required_num;
13709 VALUE *dvs = dv_num ? IBF_R(kw->default_values, VALUE, dv_num) : NULL;
13710
13711 int i;
13712 for (i=0; i<dv_num; i++) {
13713 dvs[i] = ibf_load_object(load, dvs[i]);
13714 }
13715
13716 // Will be set once the local table is loaded.
13717 kw->table = NULL;
13718
13719 kw->default_values = dvs;
13720 return kw;
13721 }
13722 else {
13723 return NULL;
13724 }
13725}
13726
13727static ibf_offset_t
13728ibf_dump_insns_info_body(struct ibf_dump *dump, const rb_iseq_t *iseq)
13729{
13730 ibf_offset_t offset = ibf_dump_pos(dump);
13731 const struct iseq_insn_info *info = ISEQ_BODY(iseq)->insns_info;
13732
13733 ibf_dump_write_small_value(dump, info->node_ids_size);
13734 ibf_dump_write(dump, rb_iseq_insn_info_node_ids(info), info->node_ids_size);
13735
13736 return offset;
13737}
13738
13739static ibf_offset_t
13740ibf_dump_local_table(struct ibf_dump *dump, const rb_iseq_t *iseq)
13741{
13742 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
13743 const int size = body->local_table_size;
13744 ibf_offset_t offset = ibf_dump_pos(dump);
13745 int i;
13746
13747 for (i=0; i<size; i++) {
13748 VALUE v = ibf_dump_id(dump, body->local_table[i]);
13749 if (v == 0) {
13750 /* Dump hidden local variables as indexes, so load_from_binary will work with them */
13751 v = ibf_dump_object(dump, ULONG2NUM(body->local_table[i]));
13752 }
13753 ibf_dump_write_small_value(dump, v);
13754 }
13755 return offset;
13756}
13757
13758static const ID *
13759ibf_load_local_table(const struct ibf_load *load, ibf_offset_t local_table_offset, int size)
13760{
13761 if (size > 0) {
13762 ID *table = ALLOC_N(ID, size);
13763 ibf_offset_t reading_pos = local_table_offset;
13764 int i;
13765
13766 for (i=0; i<size; i++) {
13767 table[i] = ibf_load_id(load, ibf_load_small_value(load, &reading_pos));
13768 }
13769
13770 if (size == 1 && table[0] == idERROR_INFO) {
13771 ruby_xfree_sized(table, sizeof(ID) * size);
13772 return rb_iseq_shared_exc_local_tbl;
13773 }
13774 else {
13775 return table;
13776 }
13777 }
13778 else {
13779 return NULL;
13780 }
13781}
13782
13783static ibf_offset_t
13784ibf_dump_lvar_states(struct ibf_dump *dump, const rb_iseq_t *iseq)
13785{
13786 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
13787 const int size = ISEQ_LVAR_STATES_BUFLEN(body->local_table_size);
13788 IBF_W_ALIGN(uint8_t);
13789 if (iseq_has_lvar_states_p(body)) {
13790 return ibf_dump_write(dump, iseq_lvar_states(body), sizeof(uint8_t) * size);
13791 }
13792 else {
13793 return ibf_dump_write(dump, NULL, 0);
13794 }
13795}
13796
13797static void
13798ibf_load_lvar_states(const struct ibf_load *load, struct rb_iseq_constant_body *load_body, ibf_offset_t lvar_states_offset, int size, const ID *local_table)
13799{
13800 if (local_table == rb_iseq_shared_exc_local_tbl ||
13801 size <= 0) {
13802 load_body->lvar_states.list = NULL;
13803 }
13804 else if (ISEQ_LVAR_STATES_EMBED_P((unsigned int)size)) {
13805 ibf_offset_t pos = lvar_states_offset;
13806 const int len = sizeof(uint8_t) * ISEQ_LVAR_STATES_BUFLEN(size);
13807 memcpy(load_body->lvar_states.single, ibf_load_ptr(load, &pos, len), len);
13808 }
13809 else {
13810 load_body->lvar_states.list = IBF_R(lvar_states_offset, uint8_t, ISEQ_LVAR_STATES_BUFLEN(size));
13811 }
13812}
13813
13814static ibf_offset_t
13815ibf_dump_catch_table(struct ibf_dump *dump, const rb_iseq_t *iseq)
13816{
13817 const struct iseq_catch_table *table = ISEQ_BODY(iseq)->catch_table;
13818
13819 if (table) {
13820 int *iseq_indices = ALLOCA_N(int, table->size);
13821 unsigned int i;
13822
13823 for (i=0; i<table->size; i++) {
13824 iseq_indices[i] = ibf_dump_iseq(dump, table->entries[i].iseq);
13825 }
13826
13827 const ibf_offset_t offset = ibf_dump_pos(dump);
13828
13829 for (i=0; i<table->size; i++) {
13830 ibf_dump_write_small_value_nullable(dump, (VALUE)iseq_indices[i]);
13831 ibf_dump_write_small_value(dump, table->entries[i].type);
13832 ibf_dump_write_small_value(dump, table->entries[i].start);
13833 ibf_dump_write_small_value(dump, table->entries[i].end);
13834 ibf_dump_write_small_value(dump, table->entries[i].cont);
13835 ibf_dump_write_small_value(dump, table->entries[i].sp);
13836 }
13837 return offset;
13838 }
13839 else {
13840 return ibf_dump_pos(dump);
13841 }
13842}
13843
13844static void
13845ibf_load_catch_table(const struct ibf_load *load, ibf_offset_t catch_table_offset, unsigned int size, const rb_iseq_t *parent_iseq)
13846{
13847 if (size) {
13848 struct iseq_catch_table *table = ruby_xcalloc(1, iseq_catch_table_bytes(size));
13849 table->size = size;
13850 ISEQ_BODY(parent_iseq)->catch_table = table;
13851
13852 ibf_offset_t reading_pos = catch_table_offset;
13853
13854 unsigned int i;
13855 for (i=0; i<table->size; i++) {
13856 int iseq_index = (int)ibf_load_small_value_nullable(load, &reading_pos);
13857 table->entries[i].type = (enum rb_catch_type)ibf_load_small_value(load, &reading_pos);
13858 table->entries[i].start = (unsigned int)ibf_load_small_value(load, &reading_pos);
13859 table->entries[i].end = (unsigned int)ibf_load_small_value(load, &reading_pos);
13860 table->entries[i].cont = (unsigned int)ibf_load_small_value(load, &reading_pos);
13861 table->entries[i].sp = (unsigned int)ibf_load_small_value(load, &reading_pos);
13862
13863 rb_iseq_t *catch_iseq = (rb_iseq_t *)ibf_load_iseq(load, (const rb_iseq_t *)(VALUE)iseq_index);
13864 RB_OBJ_WRITE(parent_iseq, UNALIGNED_MEMBER_PTR(&table->entries[i], iseq), catch_iseq);
13865 }
13866 }
13867 else {
13868 ISEQ_BODY(parent_iseq)->catch_table = NULL;
13869 }
13870}
13871
13872static ibf_offset_t
13873ibf_dump_ci_entries(struct ibf_dump *dump, const rb_iseq_t *iseq)
13874{
13875 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
13876 const unsigned int ci_size = body->ci_size;
13877 const struct rb_call_data *cds = body->call_data;
13878
13879 ibf_offset_t offset = ibf_dump_pos(dump);
13880
13881 unsigned int i;
13882
13883 for (i = 0; i < ci_size; i++) {
13884 const struct rb_callinfo *ci = cds[i].ci;
13885 if (ci != NULL) {
13886 ibf_dump_write_small_value_nullable(dump, ibf_dump_id(dump, vm_ci_mid(ci)));
13887 ibf_dump_write_small_value(dump, vm_ci_flag(ci));
13888 ibf_dump_write_small_value(dump, vm_ci_argc(ci));
13889
13890 const struct rb_callinfo_kwarg *kwarg = vm_ci_kwarg(ci);
13891 if (kwarg) {
13892 int len = kwarg->keyword_len;
13893 ibf_dump_write_small_value(dump, len);
13894 for (int j=0; j<len; j++) {
13895 VALUE keyword = ibf_dump_object(dump, kwarg->keywords[j]);
13896 ibf_dump_write_small_value(dump, keyword);
13897 }
13898 }
13899 else {
13900 ibf_dump_write_small_value(dump, 0);
13901 }
13902 }
13903 else {
13904 // TODO: truncate NULL ci from call_data.
13905 ibf_dump_write_small_value_nullable(dump, (VALUE)-1);
13906 }
13907 }
13908
13909 return offset;
13910}
13911
13913 ID id;
13914 VALUE name;
13915 VALUE val;
13916};
13917
13919 size_t num;
13920 struct outer_variable_pair pairs[1];
13921};
13922
13923static enum rb_id_table_iterator_result
13924store_outer_variable(ID id, VALUE val, void *dump)
13925{
13926 struct outer_variable_list *ovlist = dump;
13927 struct outer_variable_pair *pair = &ovlist->pairs[ovlist->num++];
13928 pair->id = id;
13929 pair->name = rb_id2str(id);
13930 pair->val = val;
13931 return ID_TABLE_CONTINUE;
13932}
13933
13934static int
13935outer_variable_cmp(const void *a, const void *b, void *arg)
13936{
13937 const struct outer_variable_pair *ap = (const struct outer_variable_pair *)a;
13938 const struct outer_variable_pair *bp = (const struct outer_variable_pair *)b;
13939
13940 if (!ap->name) {
13941 return -1;
13942 }
13943 else if (!bp->name) {
13944 return 1;
13945 }
13946
13947 return rb_str_cmp(ap->name, bp->name);
13948}
13949
13950static ibf_offset_t
13951ibf_dump_outer_variables(struct ibf_dump *dump, const rb_iseq_t *iseq)
13952{
13953 struct rb_id_table * ovs = ISEQ_BODY(iseq)->outer_variables;
13954
13955 ibf_offset_t offset = ibf_dump_pos(dump);
13956
13957 size_t size = ovs ? rb_id_table_size(ovs) : 0;
13958 ibf_dump_write_small_value(dump, (VALUE)size);
13959 if (size > 0) {
13960 VALUE buff;
13961 size_t buffsize =
13962 rb_size_mul_add_or_raise(sizeof(struct outer_variable_pair), size,
13963 offsetof(struct outer_variable_list, pairs),
13964 rb_eArgError);
13965 struct outer_variable_list *ovlist = RB_ALLOCV(buff, buffsize);
13966 ovlist->num = 0;
13967 rb_id_table_foreach(ovs, store_outer_variable, ovlist);
13968 ruby_qsort(ovlist->pairs, size, sizeof(struct outer_variable_pair), outer_variable_cmp, NULL);
13969 for (size_t i = 0; i < size; ++i) {
13970 ID id = ovlist->pairs[i].id;
13971 ID val = ovlist->pairs[i].val;
13972 ibf_dump_write_small_value(dump, ibf_dump_id(dump, id));
13973 ibf_dump_write_small_value(dump, val);
13974 }
13975 ALLOCV_END(buff);
13976 }
13977
13978 return offset;
13979}
13980
13981static ibf_offset_t
13982ibf_dump_ic_entries(struct ibf_dump *dump, const rb_iseq_t *iseq)
13983{
13984 const struct rb_iseq_constant_body *const body = ISEQ_BODY(iseq);
13985 ibf_offset_t offset = ibf_dump_pos(dump);
13986
13987 for (unsigned int i = 0; i < body->ic_size; i++) {
13988 const struct iseq_inline_constant_cache *ic = &ISEQ_IS_IC_ENTRY(body, i);
13989 const rb_const_path_t const_path = ic->const_path;
13990 size_t size = const_path_size(const_path);
13991 ibf_dump_write_small_value(dump, (size << 1) | (const_path_absolute_p(const_path) ? 1 : 0));
13992 for (size_t j = 0; j < size; j++) {
13993 ibf_dump_write_small_value(dump, ibf_dump_id(dump, const_path_aref(const_path, j)));
13994 }
13995 }
13996
13997 return offset;
13998}
13999
14000static void
14001ibf_load_ic_entries(const struct ibf_load *load, ibf_offset_t ic_entries_offset, struct rb_iseq_constant_body *load_body)
14002{
14003 ibf_offset_t reading_pos = ic_entries_offset;
14004
14005 for (unsigned int i = 0; i < load_body->ic_size; i++) {
14006 IC ic = &ISEQ_IS_IC_ENTRY(load_body, i);
14007 ic->const_path = ibf_load_const_path(load, &reading_pos);
14008 }
14009}
14010
14011/* note that we dump out rb_call_info but load back rb_call_data */
14012static void
14013ibf_load_ci_entries(const struct ibf_load *load,
14014 ibf_offset_t ci_entries_offset,
14015 unsigned int ci_size,
14016 struct rb_call_data **cd_ptr)
14017{
14018 if (!ci_size) {
14019 *cd_ptr = NULL;
14020 return;
14021 }
14022
14023 ibf_offset_t reading_pos = ci_entries_offset;
14024
14025 unsigned int i;
14026
14027 struct rb_call_data *cds = ZALLOC_N(struct rb_call_data, ci_size);
14028 *cd_ptr = cds;
14029
14030 for (i = 0; i < ci_size; i++) {
14031 VALUE mid_index = ibf_load_small_value_nullable(load, &reading_pos);
14032 if (mid_index != (VALUE)-1) {
14033 ID mid = ibf_load_id(load, mid_index);
14034 unsigned int flag = (unsigned int)ibf_load_small_value(load, &reading_pos);
14035 unsigned int argc = (unsigned int)ibf_load_small_value(load, &reading_pos);
14036
14037 struct rb_callinfo_kwarg *kwarg = NULL;
14038 int kwlen = (int)ibf_load_small_value(load, &reading_pos);
14039 if (kwlen > 0) {
14040 kwarg = rb_xmalloc_mul_add(kwlen, sizeof(VALUE), sizeof(struct rb_callinfo_kwarg));
14041 kwarg->references = 0;
14042 kwarg->keyword_len = kwlen;
14043 for (int j=0; j<kwlen; j++) {
14044 VALUE keyword = ibf_load_small_value(load, &reading_pos);
14045 kwarg->keywords[j] = ibf_load_object(load, keyword);
14046 }
14047 }
14048
14049 cds[i].ci = vm_ci_new(mid, flag, argc, kwarg);
14050 RB_OBJ_WRITTEN(load->iseq, Qundef, cds[i].ci);
14051 cds[i].cc = vm_cc_empty();
14052 }
14053 else {
14054 // NULL ci
14055 cds[i].ci = NULL;
14056 cds[i].cc = NULL;
14057 }
14058 }
14059}
14060
14061static struct rb_id_table *
14062ibf_load_outer_variables(const struct ibf_load * load, ibf_offset_t outer_variables_offset)
14063{
14064 ibf_offset_t reading_pos = outer_variables_offset;
14065
14066 struct rb_id_table *tbl = NULL;
14067
14068 size_t table_size = (size_t)ibf_load_small_value(load, &reading_pos);
14069
14070 if (table_size > 0) {
14071 tbl = rb_id_table_create(table_size);
14072 }
14073
14074 for (size_t i = 0; i < table_size; i++) {
14075 ID key = ibf_load_id(load, (ID)ibf_load_small_value(load, &reading_pos));
14076 VALUE value = ibf_load_small_value(load, &reading_pos);
14077 if (!key) key = rb_make_temporary_id(i);
14078 rb_id_table_insert(tbl, key, value);
14079 }
14080
14081 return tbl;
14082}
14083
14084static ibf_offset_t
14085ibf_dump_iseq_each(struct ibf_dump *dump, const rb_iseq_t *iseq)
14086{
14087 RUBY_ASSERT(dump->current_buffer == &dump->global_buffer);
14088
14089 const struct rb_iseq_constant_body *body = ISEQ_BODY(iseq);
14090
14091 const VALUE location_pathobj_index = ibf_dump_object(dump, body->location.pathobj); /* TODO: freeze */
14092 const VALUE location_label_index = ibf_dump_object(dump, body->location.label);
14093
14094#if IBF_ISEQ_ENABLE_LOCAL_BUFFER
14095 ibf_offset_t iseq_start = ibf_dump_pos(dump);
14096
14097 struct ibf_dump_buffer *saved_buffer = dump->current_buffer;
14098 struct ibf_dump_buffer buffer;
14099 buffer.str = rb_str_new(0, 0);
14100 buffer.obj_table = ibf_dump_object_table_new();
14101 dump->current_buffer = &buffer;
14102#endif
14103
14104 const ibf_offset_t bytecode_offset = ibf_dump_code(dump, iseq);
14105 const ibf_offset_t bytecode_size = ibf_dump_pos(dump) - bytecode_offset;
14106 const ibf_offset_t param_opt_table_offset = ibf_dump_param_opt_table(dump, iseq);
14107 const ibf_offset_t param_keyword_offset = ibf_dump_param_keyword(dump, iseq);
14108 const ibf_offset_t insns_info_body_offset = ibf_dump_insns_info_body(dump, iseq);
14109
14110 const ibf_offset_t local_table_offset = ibf_dump_local_table(dump, iseq);
14111 const ibf_offset_t lvar_states_offset = ibf_dump_lvar_states(dump, iseq);
14112 const unsigned int catch_table_size = body->catch_table ? body->catch_table->size : 0;
14113 const ibf_offset_t catch_table_offset = ibf_dump_catch_table(dump, iseq);
14114 /* a NULL parent (persisted root) and references outside a Proc#refined subtree dump come out absent (-1) */
14115 const int parent_iseq_index = ibf_table_lookup(dump->iseq_table, (st_data_t)ISEQ_BODY(iseq)->parent_iseq);
14116 const int local_iseq_index = ibf_table_lookup(dump->iseq_table, (st_data_t)ISEQ_BODY(iseq)->local_iseq);
14117 const int mandatory_only_iseq_index = ibf_dump_iseq(dump, ISEQ_MANDATORY_ONLY_ISEQ(iseq));
14118 const ibf_offset_t ci_entries_offset = ibf_dump_ci_entries(dump, iseq);
14119 const ibf_offset_t outer_variables_offset = ibf_dump_outer_variables(dump, iseq);
14120 const ibf_offset_t ic_entries_offset = ibf_dump_ic_entries(dump, iseq);
14121
14122#if IBF_ISEQ_ENABLE_LOCAL_BUFFER
14123 ibf_offset_t local_obj_list_offset;
14124 unsigned int local_obj_list_size;
14125
14126 ibf_dump_object_list(dump, &local_obj_list_offset, &local_obj_list_size);
14127#endif
14128
14129 ibf_offset_t body_offset = ibf_dump_pos(dump);
14130
14131 /* dump the constant body */
14132 unsigned int param_flags =
14133 (body->param.flags.has_lead << 0) |
14134 (body->param.flags.has_opt << 1) |
14135 (body->param.flags.has_rest << 2) |
14136 (body->param.flags.has_post << 3) |
14137 (body->param.flags.has_kw << 4) |
14138 (body->param.flags.has_kwrest << 5) |
14139 (body->param.flags.has_block << 6) |
14140 (body->param.flags.ambiguous_param0 << 7) |
14141 (body->param.flags.accepts_no_kwarg << 8) |
14142 (body->param.flags.ruby2_keywords << 9) |
14143 (body->param.flags.anon_rest << 10) |
14144 (body->param.flags.anon_kwrest << 11) |
14145 (body->param.flags.use_block << 12) |
14146 (body->param.flags.forwardable << 13) |
14147 (body->param.flags.accepts_no_block << 14);
14148
14149#if IBF_ISEQ_ENABLE_LOCAL_BUFFER
14150# define IBF_BODY_OFFSET(x) (x)
14151#else
14152# define IBF_BODY_OFFSET(x) (body_offset - (x))
14153#endif
14154
14155 ibf_dump_write_small_value(dump, body->type);
14156 ibf_dump_write_small_value(dump, body->iseq_size);
14157 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(bytecode_offset));
14158 ibf_dump_write_small_value(dump, bytecode_size);
14159 ibf_dump_write_small_value(dump, param_flags);
14160 ibf_dump_write_small_value(dump, body->param.size);
14161 ibf_dump_write_small_value(dump, body->param.lead_num);
14162 ibf_dump_write_small_value(dump, body->param.opt_num);
14163 ibf_dump_write_small_value(dump, body->param.post_num);
14164 ibf_dump_write_small_value(dump, body->param.block_start);
14165 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(param_opt_table_offset));
14166 ibf_dump_write_small_value(dump, param_keyword_offset);
14167 ibf_dump_write_small_value(dump, location_pathobj_index);
14168 ibf_dump_write_small_value(dump, body->no_realpath);
14169 ibf_dump_write_small_value(dump, location_label_index);
14170 ibf_dump_write_small_value(dump, body->location.first_lineno);
14171 ibf_dump_write_small_value(dump, body->location.node_id);
14172 ibf_dump_write_small_value(dump, body->location.code_location.beg_pos.lineno);
14173 ibf_dump_write_small_value(dump, body->location.code_location.beg_pos.column);
14174 ibf_dump_write_small_value(dump, body->location.code_location.end_pos.lineno);
14175 ibf_dump_write_small_value(dump, body->location.code_location.end_pos.column);
14176 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(insns_info_body_offset));
14177 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(local_table_offset));
14178 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(lvar_states_offset));
14179 ibf_dump_write_small_value(dump, catch_table_size);
14180 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(catch_table_offset));
14181 ibf_dump_write_small_value_nullable(dump, (VALUE)parent_iseq_index);
14182 ibf_dump_write_small_value_nullable(dump, (VALUE)local_iseq_index);
14183 ibf_dump_write_small_value_nullable(dump, (VALUE)mandatory_only_iseq_index);
14184 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(ci_entries_offset));
14185 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(outer_variables_offset));
14186 ibf_dump_write_small_value(dump, ISEQ_FLIP_CNT(iseq));
14187 ibf_dump_write_small_value(dump, body->local_table_size);
14188 ibf_dump_write_small_value(dump, body->ivc_size);
14189 ibf_dump_write_small_value(dump, body->icvarc_size);
14190 ibf_dump_write_small_value(dump, body->ic_size);
14191 if (body->ic_size) {
14192 ibf_dump_write_small_value(dump, IBF_BODY_OFFSET(ic_entries_offset));
14193 }
14194 ibf_dump_write_small_value(dump, body->ci_size);
14195 ibf_dump_write_small_value(dump, body->stack_max);
14196 ibf_dump_write_small_value(dump, body->builtin_attrs);
14197 ibf_dump_write_small_value(dump, body->prism ? 1 : 0);
14198
14199#undef IBF_BODY_OFFSET
14200
14201#if IBF_ISEQ_ENABLE_LOCAL_BUFFER
14202 ibf_offset_t iseq_length_bytes = ibf_dump_pos(dump);
14203
14204 dump->current_buffer = saved_buffer;
14205 ibf_dump_write(dump, RSTRING_PTR(buffer.str), iseq_length_bytes);
14206
14207 ibf_offset_t offset = ibf_dump_pos(dump);
14208 ibf_dump_write_small_value(dump, iseq_start);
14209 ibf_dump_write_small_value(dump, iseq_length_bytes);
14210 ibf_dump_write_small_value(dump, body_offset);
14211
14212 ibf_dump_write_small_value(dump, local_obj_list_offset);
14213 ibf_dump_write_small_value(dump, local_obj_list_size);
14214
14215 st_free_table(buffer.obj_table); // TODO: this leaks in case of exception
14216
14217 return offset;
14218#else
14219 return body_offset;
14220#endif
14221}
14222
14223static VALUE
14224ibf_load_location_str(const struct ibf_load *load, VALUE str_index)
14225{
14226 VALUE str = ibf_load_object(load, str_index);
14227 if (str != Qnil) {
14228 str = rb_fstring(str);
14229 }
14230 return str;
14231}
14232
14233static void
14234ibf_load_iseq_each(struct ibf_load *load, rb_iseq_t *iseq, ibf_offset_t offset)
14235{
14236 struct rb_iseq_constant_body *load_body = ISEQ_BODY(iseq) = rb_iseq_constant_body_alloc();
14237
14238 ibf_offset_t reading_pos = offset;
14239
14240#if IBF_ISEQ_ENABLE_LOCAL_BUFFER
14241 struct ibf_load_buffer *saved_buffer = load->current_buffer;
14242 load->current_buffer = &load->global_buffer;
14243
14244 const ibf_offset_t iseq_start = (ibf_offset_t)ibf_load_small_value(load, &reading_pos);
14245 const ibf_offset_t iseq_length_bytes = (ibf_offset_t)ibf_load_small_value(load, &reading_pos);
14246 const ibf_offset_t body_offset = (ibf_offset_t)ibf_load_small_value(load, &reading_pos);
14247
14248 struct ibf_load_buffer buffer;
14249 buffer.buff = load->global_buffer.buff + iseq_start;
14250 buffer.size = iseq_length_bytes;
14251 buffer.obj_list_offset = (ibf_offset_t)ibf_load_small_value(load, &reading_pos);
14252 buffer.obj_list_size = (ibf_offset_t)ibf_load_small_value(load, &reading_pos);
14253 buffer.obj_list = pinned_list_new(buffer.obj_list_size);
14254 VALUE obj_offsets_tmp;
14255
14256 load->current_buffer = &buffer;
14257 ibf_load_object_offsets(load, ALLOCV_N(ibf_offset_t, obj_offsets_tmp, buffer.obj_list_size));
14258 reading_pos = body_offset;
14259#endif
14260
14261#if IBF_ISEQ_ENABLE_LOCAL_BUFFER
14262# define IBF_BODY_OFFSET(x) (x)
14263#else
14264# define IBF_BODY_OFFSET(x) (offset - (x))
14265#endif
14266
14267 const unsigned int type = (unsigned int)ibf_load_small_value(load, &reading_pos);
14268 const unsigned int iseq_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
14269 const ibf_offset_t bytecode_offset = (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos));
14270 const ibf_offset_t bytecode_size = (ibf_offset_t)ibf_load_small_value(load, &reading_pos);
14271 const unsigned int param_flags = (unsigned int)ibf_load_small_value(load, &reading_pos);
14272 const unsigned int param_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
14273 const int param_lead_num = (int)ibf_load_small_value(load, &reading_pos);
14274 const int param_opt_num = (int)ibf_load_small_value(load, &reading_pos);
14275 const int param_post_num = (int)ibf_load_small_value(load, &reading_pos);
14276 const int param_block_start = (int)ibf_load_small_value(load, &reading_pos);
14277 const ibf_offset_t param_opt_table_offset = (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos));
14278 const ibf_offset_t param_keyword_offset = (ibf_offset_t)ibf_load_small_value(load, &reading_pos);
14279 const VALUE location_pathobj_index = ibf_load_small_value(load, &reading_pos);
14280 const bool no_realpath = (bool)ibf_load_small_value(load, &reading_pos);
14281 const VALUE location_label_index = ibf_load_small_value(load, &reading_pos);
14282 const int location_first_lineno = (int)ibf_load_small_value(load, &reading_pos);
14283 const int location_node_id = (int)ibf_load_small_value(load, &reading_pos);
14284 const int location_code_location_beg_pos_lineno = (int)ibf_load_small_value(load, &reading_pos);
14285 const int location_code_location_beg_pos_column = (int)ibf_load_small_value(load, &reading_pos);
14286 const int location_code_location_end_pos_lineno = (int)ibf_load_small_value(load, &reading_pos);
14287 const int location_code_location_end_pos_column = (int)ibf_load_small_value(load, &reading_pos);
14288 const ibf_offset_t insns_info_body_offset = (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos));
14289 const ibf_offset_t local_table_offset = (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos));
14290 const ibf_offset_t lvar_states_offset = (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos));
14291 const unsigned int catch_table_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
14292 const ibf_offset_t catch_table_offset = (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos));
14293 const int parent_iseq_index = (int)ibf_load_small_value_nullable(load, &reading_pos);
14294 const int local_iseq_index = (int)ibf_load_small_value_nullable(load, &reading_pos);
14295 const int mandatory_only_iseq_index = (int)ibf_load_small_value_nullable(load, &reading_pos);
14296 const ibf_offset_t ci_entries_offset = (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos));
14297 const ibf_offset_t outer_variables_offset = (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos));
14298 const rb_snum_t variable_flip_count = (rb_snum_t)ibf_load_small_value(load, &reading_pos);
14299 const unsigned int local_table_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
14300
14301 const unsigned int ivc_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
14302 const unsigned int icvarc_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
14303 const unsigned int ic_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
14304 const ibf_offset_t ic_entries_offset = ic_size ? (ibf_offset_t)IBF_BODY_OFFSET(ibf_load_small_value(load, &reading_pos)) : 0;
14305
14306 const unsigned int ci_size = (unsigned int)ibf_load_small_value(load, &reading_pos);
14307 const unsigned int stack_max = (unsigned int)ibf_load_small_value(load, &reading_pos);
14308 const unsigned int builtin_attrs = (unsigned int)ibf_load_small_value(load, &reading_pos);
14309 const bool prism = (bool)ibf_load_small_value(load, &reading_pos);
14310
14311 // setup fname and dummy frame
14312 if (load->pathobj && load->pathobj_index == location_pathobj_index) {
14313 rb_iseq_pathobj_set(iseq, load->pathobj, Qnil);
14314 }
14315 else {
14316 VALUE path = ibf_load_object(load, location_pathobj_index);
14317 VALUE realpath = Qnil;
14318
14319 if (RB_TYPE_P(path, T_STRING)) {
14320 path = rb_fstring(path);
14321 realpath = no_realpath ? Qnil : path;
14322 }
14323 else if (RB_TYPE_P(path, T_ARRAY)) {
14324 VALUE pathobj = path;
14325 if (RARRAY_LEN(pathobj) != 2) {
14326 rb_raise(rb_eRuntimeError, "path object size mismatch");
14327 }
14328 path = rb_fstring(RARRAY_AREF(pathobj, 0));
14329 realpath = RARRAY_AREF(pathobj, 1);
14330 if (!NIL_P(realpath)) {
14331 if (!RB_TYPE_P(realpath, T_STRING)) {
14332 rb_raise(rb_eArgError, "unexpected realpath %"PRIxVALUE
14333 "(%x), path=%+"PRIsVALUE,
14334 realpath, TYPE(realpath), path);
14335 }
14336 realpath = rb_fstring(realpath);
14337 }
14338 }
14339 else {
14340 rb_raise(rb_eRuntimeError, "unexpected path object");
14341 }
14342 if (RTEST(load->path_override)) {
14343 path = load->path_override;
14344 realpath = load->realpath_override;
14345 }
14346 rb_iseq_pathobj_set(iseq, path, realpath);
14347
14348 VALUE pathobj = ISEQ_BODY(iseq)->location.pathobj;
14349 if (RB_TYPE_P(pathobj, T_ARRAY)) {
14350 RB_OBJ_WRITE(load->loader_obj, &load->pathobj, pathobj);
14351 load->pathobj_index = location_pathobj_index;
14352 }
14353 }
14354
14355 // push dummy frame
14356 rb_execution_context_t *ec = GET_EC();
14357 VALUE dummy_frame = rb_vm_push_frame_fname(ec, rb_iseq_path(iseq));
14358
14359#undef IBF_BODY_OFFSET
14360
14361 load_body->type = type;
14362 load_body->stack_max = stack_max;
14363 load_body->param.flags.has_lead = (param_flags >> 0) & 1;
14364 load_body->param.flags.has_opt = (param_flags >> 1) & 1;
14365 load_body->param.flags.has_rest = (param_flags >> 2) & 1;
14366 load_body->param.flags.has_post = (param_flags >> 3) & 1;
14367 load_body->param.flags.has_kw = FALSE;
14368 load_body->param.flags.has_kwrest = (param_flags >> 5) & 1;
14369 load_body->param.flags.has_block = (param_flags >> 6) & 1;
14370 load_body->param.flags.ambiguous_param0 = (param_flags >> 7) & 1;
14371 load_body->param.flags.accepts_no_kwarg = (param_flags >> 8) & 1;
14372 load_body->param.flags.ruby2_keywords = (param_flags >> 9) & 1;
14373 load_body->param.flags.anon_rest = (param_flags >> 10) & 1;
14374 load_body->param.flags.anon_kwrest = (param_flags >> 11) & 1;
14375 load_body->param.flags.use_block = (param_flags >> 12) & 1;
14376 load_body->param.flags.forwardable = (param_flags >> 13) & 1;
14377 load_body->param.flags.accepts_no_block = (param_flags >> 14) & 1;
14378 load_body->param.size = param_size;
14379 load_body->param.lead_num = param_lead_num;
14380 load_body->param.opt_num = param_opt_num;
14381 load_body->param.post_num = param_post_num;
14382 load_body->param.block_start = param_block_start;
14383 load_body->local_table_size = local_table_size;
14384 load_body->ci_size = ci_size;
14385
14386 // variable is NULL from ZALLOC; only allocate if flip_count is non-zero.
14387 ISEQ_ORIGINAL_ISEQ_CLEAR(iseq);
14388 if (variable_flip_count) {
14389 struct rb_iseq_variable *v = rb_iseq_variable_ensure(iseq);
14390 v->flip_count = variable_flip_count;
14391 }
14392
14393 load_body->location.first_lineno = location_first_lineno;
14394 load_body->location.node_id = location_node_id;
14395 load_body->source_hash = ((uint64_t)load->header->source_hash_hi << 32) | load->header->source_hash_lo;
14396 load_body->location.code_location.beg_pos.lineno = location_code_location_beg_pos_lineno;
14397 load_body->location.code_location.beg_pos.column = location_code_location_beg_pos_column;
14398 load_body->location.code_location.end_pos.lineno = location_code_location_end_pos_lineno;
14399 load_body->location.code_location.end_pos.column = location_code_location_end_pos_column;
14400 load_body->builtin_attrs = builtin_attrs;
14401 load_body->prism = prism;
14402
14403 load_body->ivc_size = ivc_size;
14404 load_body->icvarc_size = icvarc_size;
14405 load_body->ic_size = ic_size;
14406
14407 if (ISEQ_IS_SIZE(load_body)) {
14408 load_body->is_entries = ZALLOC_N(union iseq_inline_storage_entry, ISEQ_IS_SIZE(load_body));
14409 }
14410 else {
14411 load_body->is_entries = NULL;
14412 }
14413 ibf_load_ci_entries(load, ci_entries_offset, ci_size, &load_body->call_data);
14414 load_body->outer_variables = ibf_load_outer_variables(load, outer_variables_offset);
14415 ibf_load_ic_entries(load, ic_entries_offset, load_body);
14416 load_body->param.opt_table = ibf_load_param_opt_table(load, param_opt_table_offset, param_opt_num);
14417 load_body->param.keyword = ibf_load_param_keyword(load, param_keyword_offset);
14418 load_body->param.flags.has_kw = (param_flags >> 4) & 1;
14419 load_body->local_table = ibf_load_local_table(load, local_table_offset, local_table_size);
14420 ibf_load_lvar_states(load, load_body, lvar_states_offset, local_table_size, load_body->local_table);
14421 ibf_load_catch_table(load, catch_table_offset, catch_table_size, iseq);
14422
14423 const rb_iseq_t *parent_iseq = ibf_load_iseq(load, (const rb_iseq_t *)(VALUE)parent_iseq_index);
14424 const rb_iseq_t *local_iseq = ibf_load_iseq(load, (const rb_iseq_t *)(VALUE)local_iseq_index);
14425 const rb_iseq_t *mandatory_only_iseq = ibf_load_iseq(load, (const rb_iseq_t *)(VALUE)mandatory_only_iseq_index);
14426
14427 RB_OBJ_WRITE(iseq, &load_body->parent_iseq, parent_iseq);
14428 RB_OBJ_WRITE(iseq, &load_body->local_iseq, local_iseq);
14429 rb_iseq_mandatory_only_iseq_set(iseq, mandatory_only_iseq);
14430
14431 // This must be done after the local table is loaded.
14432 if (load_body->param.keyword != NULL) {
14433 RUBY_ASSERT(load_body->local_table);
14434 struct rb_iseq_param_keyword *keyword = (struct rb_iseq_param_keyword *) load_body->param.keyword;
14435 keyword->table = &load_body->local_table[keyword->bits_start - keyword->num];
14436 }
14437
14438 ibf_load_code(load, iseq, bytecode_offset, bytecode_size, iseq_size, insns_info_body_offset);
14439
14440 rb_iseq_translate_threaded_code(iseq);
14441
14442#if IBF_ISEQ_ENABLE_LOCAL_BUFFER
14443 load->current_buffer = &load->global_buffer;
14444#endif
14445
14446 RB_OBJ_WRITE(iseq, &load_body->location.label, ibf_load_location_str(load, location_label_index));
14447
14448#if IBF_ISEQ_ENABLE_LOCAL_BUFFER
14449 load->current_buffer = saved_buffer;
14450 ALLOCV_END(obj_offsets_tmp);
14451#endif
14452 verify_call_cache(iseq);
14453
14454 RB_GC_GUARD(dummy_frame);
14455 rb_vm_pop_frame_no_int(ec);
14456}
14457
14459{
14460 struct ibf_dump *dump;
14461 VALUE offset_list;
14462};
14463
14464static int
14465ibf_dump_iseq_list_i(st_data_t key, st_data_t val, st_data_t ptr)
14466{
14467 const rb_iseq_t *iseq = (const rb_iseq_t *)key;
14468 struct ibf_dump_iseq_list_arg *args = (struct ibf_dump_iseq_list_arg *)ptr;
14469
14470 ibf_offset_t offset = ibf_dump_iseq_each(args->dump, iseq);
14471 rb_ary_push(args->offset_list, UINT2NUM(offset));
14472
14473 return ST_CONTINUE;
14474}
14475
14476static void
14477ibf_dump_iseq_list(struct ibf_dump *dump, struct ibf_header *header)
14478{
14479 VALUE offset_list = rb_ary_hidden_new(dump->iseq_table->num_entries);
14480
14481 struct ibf_dump_iseq_list_arg args;
14482 args.dump = dump;
14483 args.offset_list = offset_list;
14484
14485 st_foreach(dump->iseq_table, ibf_dump_iseq_list_i, (st_data_t)&args);
14486
14487 st_index_t i;
14488 st_index_t size = dump->iseq_table->num_entries;
14489 ibf_offset_t *offsets = ALLOCA_N(ibf_offset_t, size);
14490
14491 for (i = 0; i < size; i++) {
14492 offsets[i] = NUM2UINT(RARRAY_AREF(offset_list, i));
14493 }
14494
14495 ibf_dump_align(dump, sizeof(ibf_offset_t));
14496 header->iseq_list_offset = ibf_dump_write(dump, offsets, sizeof(ibf_offset_t) * size);
14497 header->iseq_list_size = (unsigned int)size;
14498}
14499
14500/*
14501 * Binary format
14502 * - ibf_object_header
14503 * - ibf_object_xxx (xxx is type)
14504 */
14505
14507 unsigned int type: 5;
14508 unsigned int special_const: 1;
14509 unsigned int frozen: 1;
14510 unsigned int internal: 1;
14511};
14512
14513enum ibf_object_class_index {
14514 IBF_OBJECT_CLASS_OBJECT,
14515 IBF_OBJECT_CLASS_ARRAY,
14516 IBF_OBJECT_CLASS_STANDARD_ERROR,
14517 IBF_OBJECT_CLASS_NO_MATCHING_PATTERN_ERROR,
14518 IBF_OBJECT_CLASS_TYPE_ERROR,
14519 IBF_OBJECT_CLASS_NO_MATCHING_PATTERN_KEY_ERROR,
14520};
14521
14523 long srcstr;
14524 char option;
14525};
14526
14528 long len;
14529 long keyval[FLEX_ARY_LEN];
14530};
14531
14533 long class_index;
14534 long len;
14535 long beg;
14536 long end;
14537 int excl;
14538};
14539
14541 ssize_t slen;
14542 BDIGIT digits[FLEX_ARY_LEN];
14543};
14544
14545enum ibf_object_data_type {
14546 IBF_OBJECT_DATA_ENCODING,
14547};
14548
14550 long a, b;
14551};
14552
14554 long str;
14555};
14556
14557#define IBF_ALIGNED_OFFSET(align, offset) /* offset > 0 */ \
14558 ((((offset) - 1) / (align) + 1) * (align))
14559/* No cast, since it's UB to create an unaligned pointer.
14560 * Leave as void* for use with memcpy in those cases.
14561 * We align the offset, but the buffer pointer is only VALUE aligned,
14562 * so the returned pointer may be unaligned for `type` .*/
14563#define IBF_OBJBODY(type, offset) \
14564 ibf_load_check_offset(load, IBF_ALIGNED_OFFSET(RUBY_ALIGNOF(type), offset))
14565
14566static const void *
14567ibf_load_check_offset(const struct ibf_load *load, size_t offset)
14568{
14569 if (offset >= load->current_buffer->size) {
14570 rb_raise(rb_eIndexError, "object offset out of range: %"PRIdSIZE, offset);
14571 }
14572 return load->current_buffer->buff + offset;
14573}
14574
14575NORETURN(static void ibf_dump_object_unsupported(struct ibf_dump *dump, VALUE obj));
14576
14577static void
14578ibf_dump_object_unsupported(struct ibf_dump *dump, VALUE obj)
14579{
14580 char buff[0x100];
14581 rb_raw_obj_info(buff, sizeof(buff), obj);
14582 rb_raise(rb_eNotImpError, "ibf_dump_object_unsupported: %s", buff);
14583}
14584
14585NORETURN(static VALUE ibf_load_object_unsupported(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset));
14586
14587static VALUE
14588ibf_load_object_unsupported(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14589{
14590 rb_raise(rb_eArgError, "unsupported");
14592}
14593
14594static void
14595ibf_dump_object_class(struct ibf_dump *dump, VALUE obj)
14596{
14597 enum ibf_object_class_index cindex;
14598 if (obj == rb_cObject) {
14599 cindex = IBF_OBJECT_CLASS_OBJECT;
14600 }
14601 else if (obj == rb_cArray) {
14602 cindex = IBF_OBJECT_CLASS_ARRAY;
14603 }
14604 else if (obj == rb_eStandardError) {
14605 cindex = IBF_OBJECT_CLASS_STANDARD_ERROR;
14606 }
14607 else if (obj == rb_eNoMatchingPatternError) {
14608 cindex = IBF_OBJECT_CLASS_NO_MATCHING_PATTERN_ERROR;
14609 }
14610 else if (obj == rb_eTypeError) {
14611 cindex = IBF_OBJECT_CLASS_TYPE_ERROR;
14612 }
14613 else if (obj == rb_eNoMatchingPatternKeyError) {
14614 cindex = IBF_OBJECT_CLASS_NO_MATCHING_PATTERN_KEY_ERROR;
14615 }
14616 else {
14617 rb_obj_info_dump(obj);
14618 rb_p(obj);
14619 rb_bug("unsupported class");
14620 }
14621 ibf_dump_write_small_value(dump, (VALUE)cindex);
14622}
14623
14624static VALUE
14625ibf_load_object_class(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14626{
14627 enum ibf_object_class_index cindex = (enum ibf_object_class_index)ibf_load_small_value(load, &offset);
14628
14629 switch (cindex) {
14630 case IBF_OBJECT_CLASS_OBJECT:
14631 return rb_cObject;
14632 case IBF_OBJECT_CLASS_ARRAY:
14633 return rb_cArray;
14634 case IBF_OBJECT_CLASS_STANDARD_ERROR:
14635 return rb_eStandardError;
14636 case IBF_OBJECT_CLASS_NO_MATCHING_PATTERN_ERROR:
14638 case IBF_OBJECT_CLASS_TYPE_ERROR:
14639 return rb_eTypeError;
14640 case IBF_OBJECT_CLASS_NO_MATCHING_PATTERN_KEY_ERROR:
14642 }
14643
14644 rb_raise(rb_eArgError, "ibf_load_object_class: unknown class (%d)", (int)cindex);
14645}
14646
14647
14648static void
14649ibf_dump_object_float(struct ibf_dump *dump, VALUE obj)
14650{
14651 double dbl = RFLOAT_VALUE(obj);
14652 (void)IBF_W(&dbl, double, 1);
14653}
14654
14655static VALUE
14656ibf_load_object_float(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14657{
14658 double d;
14659 /* Avoid unaligned VFP load on ARMv7; IBF payload may be unaligned (C99 6.3.2.3 p7). */
14660 memcpy(&d, IBF_OBJBODY(double, offset), sizeof(d));
14661 VALUE f = DBL2NUM(d);
14662 if (!FLONUM_P(f)) RB_OBJ_SET_SHAREABLE(f);
14663 return f;
14664}
14665
14666static void
14667ibf_dump_object_string(struct ibf_dump *dump, VALUE obj)
14668{
14669 long encindex = (long)rb_enc_get_index(obj);
14670 rb_len_t len = RSTRING_LEN(obj);
14671 const char *ptr = RSTRING_PTR(obj);
14672
14673 if (encindex > RUBY_ENCINDEX_BUILTIN_MAX) {
14674 rb_encoding *enc = rb_enc_from_index((int)encindex);
14675 const char *enc_name = rb_enc_name(enc);
14676 encindex = RUBY_ENCINDEX_BUILTIN_MAX + ibf_dump_object(dump, rb_str_new2(enc_name));
14677 }
14678
14679 ibf_dump_write_small_value(dump, encindex);
14680 ibf_dump_write_small_value(dump, len);
14681 IBF_WP(ptr, char, len);
14682}
14683
14684static VALUE
14685ibf_load_object_string(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14686{
14687 ibf_offset_t reading_pos = offset;
14688
14689 int encindex = (int)ibf_load_small_value(load, &reading_pos);
14690 const rb_len_t len = (rb_len_t)ibf_load_small_value(load, &reading_pos);
14691 const char *ptr = load->current_buffer->buff + reading_pos;
14692
14693 if (encindex > RUBY_ENCINDEX_BUILTIN_MAX) {
14694 VALUE enc_name_str = ibf_load_object(load, encindex - RUBY_ENCINDEX_BUILTIN_MAX);
14695 encindex = rb_enc_find_index(RSTRING_PTR(enc_name_str));
14696 }
14697
14698 VALUE str;
14699 if (header->frozen && !header->internal) {
14700 str = rb_enc_literal_str(ptr, len, rb_enc_from_index(encindex));
14701 }
14702 else {
14703 str = rb_enc_str_new(ptr, len, rb_enc_from_index(encindex));
14704
14705 if (header->internal) rb_obj_hide(str);
14706 if (header->frozen) str = rb_fstring(str);
14707 }
14708 return str;
14709}
14710
14711static void
14712ibf_dump_object_regexp(struct ibf_dump *dump, VALUE obj)
14713{
14714 VALUE srcstr = RREGEXP_SRC(obj);
14715 struct ibf_object_regexp regexp;
14716 regexp.option = (char)rb_reg_options(obj);
14717 regexp.srcstr = (long)ibf_dump_object(dump, srcstr);
14718
14719 ibf_dump_write_byte(dump, (unsigned char)regexp.option);
14720 ibf_dump_write_small_value(dump, regexp.srcstr);
14721}
14722
14723static VALUE
14724ibf_load_object_regexp(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14725{
14726 struct ibf_object_regexp regexp;
14727 regexp.option = ibf_load_byte(load, &offset);
14728 regexp.srcstr = ibf_load_small_value(load, &offset);
14729
14730 VALUE srcstr = ibf_load_object(load, regexp.srcstr);
14731 VALUE reg = rb_reg_compile(srcstr, (int)regexp.option, NULL, 0);
14732
14733 if (header->internal) rb_obj_hide(reg);
14734 if (header->frozen) RB_OBJ_SET_SHAREABLE(rb_obj_freeze(reg));
14735
14736 return reg;
14737}
14738
14739static void
14740ibf_dump_object_array(struct ibf_dump *dump, VALUE obj)
14741{
14742 rb_len_t i, len = RARRAY_LEN(obj);
14743 ibf_dump_write_small_value(dump, len);
14744 for (i=0; i<len; i++) {
14745 long index = (long)ibf_dump_object(dump, RARRAY_AREF(obj, i));
14746 ibf_dump_write_small_value(dump, index);
14747 }
14748}
14749
14750static VALUE
14751ibf_load_object_array(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14752{
14753 ibf_offset_t reading_pos = offset;
14754
14755 const rb_len_t len = (rb_len_t)ibf_load_small_value(load, &reading_pos);
14756
14757 VALUE ary = header->internal ? rb_ary_hidden_new(len) : rb_ary_new_capa(len);
14758 int i;
14759
14760 for (i=0; i<len; i++) {
14761 const VALUE index = ibf_load_small_value(load, &reading_pos);
14762 rb_ary_push(ary, ibf_load_object(load, index));
14763 }
14764
14765 if (header->frozen) {
14766 rb_ary_freeze(ary);
14767 rb_ractor_make_shareable(ary); // TODO: check elements
14768 }
14769
14770 return ary;
14771}
14772
14773static int
14774ibf_dump_object_hash_i(st_data_t key, st_data_t val, st_data_t ptr)
14775{
14776 struct ibf_dump *dump = (struct ibf_dump *)ptr;
14777
14778 VALUE key_index = ibf_dump_object(dump, (VALUE)key);
14779 VALUE val_index = ibf_dump_object(dump, (VALUE)val);
14780
14781 ibf_dump_write_small_value(dump, key_index);
14782 ibf_dump_write_small_value(dump, val_index);
14783 return ST_CONTINUE;
14784}
14785
14786static void
14787ibf_dump_object_hash(struct ibf_dump *dump, VALUE obj)
14788{
14789 long len = RHASH_SIZE(obj);
14790 ibf_dump_write_small_value(dump, (VALUE)len);
14791
14792 if (len > 0) rb_hash_foreach(obj, ibf_dump_object_hash_i, (VALUE)dump);
14793}
14794
14795static VALUE
14796ibf_load_object_hash(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14797{
14798 long len = (long)ibf_load_small_value(load, &offset);
14799 VALUE obj = header->frozen ? rb_hash_alloc_fixed_size(rb_cHash, len) : rb_hash_new_capa(len);
14800 int i;
14801
14802 for (i = 0; i < len; i++) {
14803 VALUE key_index = ibf_load_small_value(load, &offset);
14804 VALUE val_index = ibf_load_small_value(load, &offset);
14805
14806 VALUE key = ibf_load_object(load, key_index);
14807 VALUE val = ibf_load_object(load, val_index);
14808 rb_hash_aset(obj, key, val);
14809 }
14810
14811 if (header->internal) rb_obj_hide(obj);
14812 if (header->frozen) {
14813 RB_OBJ_SET_FROZEN_SHAREABLE(obj);
14814 }
14815
14816 return obj;
14817}
14818
14819static int
14820ibf_dump_cdhash_i(st_data_t key, st_data_t val, st_data_t ptr)
14821{
14822 struct ibf_dump *dump = (struct ibf_dump *)ptr;
14823
14824 VALUE key_index = ibf_dump_object(dump, (VALUE)key);
14825
14826 ibf_dump_write_small_value(dump, key_index);
14827 ibf_dump_write_small_value(dump, val);
14828 return ST_CONTINUE;
14829}
14830
14831static void
14832ibf_dump_object_imemo(struct ibf_dump *dump, VALUE obj)
14833{
14834 ibf_dump_write_small_value(dump, (VALUE)imemo_type(obj));
14835 switch (imemo_type(obj)) {
14836 case imemo_once_storage:
14837 break;
14838 case imemo_cdhash: {
14839 st_table *tbl = rb_imemo_cdhash_tbl(obj);
14840
14841 long len = tbl->num_entries;
14842 ibf_dump_write_small_value(dump, (VALUE)len);
14843 if (len > 0) st_foreach(tbl, ibf_dump_cdhash_i, (VALUE)dump);
14844 break;
14845 }
14846 default:
14847 ibf_dump_object_unsupported(dump, obj);
14848 break;
14849 }
14850}
14851
14852static VALUE
14853ibf_load_object_imemo(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14854{
14855 enum imemo_type type = (enum imemo_type)ibf_load_small_value(load, &offset);
14856 switch (type) {
14857 case imemo_once_storage:
14858 return rb_imemo_once_storage_new();
14859 case imemo_cdhash: {
14860 long len = (long)ibf_load_small_value(load, &offset);
14861 VALUE obj = cdhash_new(len);
14862
14863 for (long i = 0; i < len; i++) {
14864 VALUE key_index = ibf_load_small_value(load, &offset);
14865 VALUE val = ibf_load_small_value(load, &offset);
14866
14867 VALUE key = ibf_load_object(load, key_index);
14868 cdhash_aset(obj, key, val);
14869 }
14870
14871 return obj;
14872 }
14873 default:
14874 return ibf_load_object_unsupported(load, header, offset);
14875 }
14876}
14877
14878static void
14879ibf_dump_object_struct(struct ibf_dump *dump, VALUE obj)
14880{
14881 if (rb_obj_is_kind_of(obj, rb_cRange)) {
14882 struct ibf_object_struct_range range;
14883 VALUE beg, end;
14884 IBF_ZERO(range);
14885 range.len = 3;
14886 range.class_index = 0;
14887
14888 rb_range_values(obj, &beg, &end, &range.excl);
14889 range.beg = (long)ibf_dump_object(dump, beg);
14890 range.end = (long)ibf_dump_object(dump, end);
14891
14892 IBF_W_ALIGN(struct ibf_object_struct_range);
14893 IBF_WV(range);
14894 }
14895 else {
14896 rb_raise(rb_eNotImpError, "ibf_dump_object_struct: unsupported class %"PRIsVALUE,
14897 rb_class_name(CLASS_OF(obj)));
14898 }
14899}
14900
14901static VALUE
14902ibf_load_object_struct(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14903{
14904 const struct ibf_object_struct_range *range = IBF_OBJBODY(struct ibf_object_struct_range, offset);
14905 VALUE beg = ibf_load_object(load, range->beg);
14906 VALUE end = ibf_load_object(load, range->end);
14907 VALUE obj = rb_range_new(beg, end, range->excl);
14908 if (header->internal) rb_obj_hide(obj);
14909 if (header->frozen) RB_OBJ_SET_FROZEN_SHAREABLE(obj);
14910 return obj;
14911}
14912
14913static void
14914ibf_dump_object_bignum(struct ibf_dump *dump, VALUE obj)
14915{
14916 ssize_t len = BIGNUM_LEN(obj);
14917 ssize_t slen = BIGNUM_SIGN(obj) > 0 ? len : len * -1;
14918 BDIGIT *d = BIGNUM_DIGITS(obj);
14919
14920 (void)IBF_W(&slen, ssize_t, 1);
14921 IBF_WP(d, BDIGIT, len);
14922}
14923
14924static VALUE
14925ibf_load_object_bignum(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14926{
14927 const struct ibf_object_bignum *bignum = IBF_OBJBODY(struct ibf_object_bignum, offset);
14928 int sign = bignum->slen > 0;
14929 ssize_t len = sign > 0 ? bignum->slen : -1 * bignum->slen;
14930 const int big_unpack_flags = /* c.f. rb_big_unpack() */
14933 VALUE obj = rb_integer_unpack(bignum->digits, len, sizeof(BDIGIT), 0,
14934 big_unpack_flags |
14935 (sign == 0 ? INTEGER_PACK_NEGATIVE : 0));
14936 if (header->internal) rb_obj_hide(obj);
14937 if (header->frozen) RB_OBJ_SET_FROZEN_SHAREABLE(obj);
14938 return obj;
14939}
14940
14941static void
14942ibf_dump_object_data(struct ibf_dump *dump, VALUE obj)
14943{
14944 if (rb_data_is_encoding(obj)) {
14945 rb_encoding *enc = rb_to_encoding(obj);
14946 const char *name = rb_enc_name(enc);
14947 long len = strlen(name) + 1;
14948 long data[2];
14949 data[0] = IBF_OBJECT_DATA_ENCODING;
14950 data[1] = len;
14951 (void)IBF_W(data, long, 2);
14952 IBF_WP(name, char, len);
14953 }
14954 else {
14955 ibf_dump_object_unsupported(dump, obj);
14956 }
14957}
14958
14959static VALUE
14960ibf_load_object_data(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14961{
14962 const long *body = IBF_OBJBODY(long, offset);
14963 const enum ibf_object_data_type type = (enum ibf_object_data_type)body[0];
14964 /* const long len = body[1]; */
14965 const char *data = (const char *)&body[2];
14966
14967 switch (type) {
14968 case IBF_OBJECT_DATA_ENCODING:
14969 {
14970 VALUE encobj = rb_enc_from_encoding(rb_enc_find(data));
14971 return encobj;
14972 }
14973 }
14974
14975 return ibf_load_object_unsupported(load, header, offset);
14976}
14977
14978static void
14979ibf_dump_object_complex_rational(struct ibf_dump *dump, VALUE obj)
14980{
14981 long data[2];
14982 data[0] = (long)ibf_dump_object(dump, RCOMPLEX(obj)->real);
14983 data[1] = (long)ibf_dump_object(dump, RCOMPLEX(obj)->imag);
14984
14985 (void)IBF_W(data, long, 2);
14986}
14987
14988static VALUE
14989ibf_load_object_complex_rational(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
14990{
14991 const struct ibf_object_complex_rational *nums = IBF_OBJBODY(struct ibf_object_complex_rational, offset);
14992 VALUE a = ibf_load_object(load, nums->a);
14993 VALUE b = ibf_load_object(load, nums->b);
14994 VALUE obj = header->type == T_COMPLEX ?
14995 rb_complex_new(a, b) : rb_rational_new(a, b);
14996
14997 if (header->internal) rb_obj_hide(obj);
14998 if (header->frozen) rb_ractor_make_shareable(rb_obj_freeze(obj));
14999 return obj;
15000}
15001
15002static void
15003ibf_dump_object_symbol(struct ibf_dump *dump, VALUE obj)
15004{
15005 ibf_dump_object_string(dump, rb_sym2str(obj));
15006}
15007
15008static VALUE
15009ibf_load_object_symbol(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset)
15010{
15011 ibf_offset_t reading_pos = offset;
15012
15013 int encindex = (int)ibf_load_small_value(load, &reading_pos);
15014 const rb_len_t len = (rb_len_t)ibf_load_small_value(load, &reading_pos);
15015 const char *ptr = load->current_buffer->buff + reading_pos;
15016
15017 if (encindex > RUBY_ENCINDEX_BUILTIN_MAX) {
15018 VALUE enc_name_str = ibf_load_object(load, encindex - RUBY_ENCINDEX_BUILTIN_MAX);
15019 encindex = rb_enc_find_index(RSTRING_PTR(enc_name_str));
15020 }
15021
15022 ID id = rb_intern3(ptr, len, rb_enc_from_index(encindex));
15023 return ID2SYM(id);
15024}
15025
15026typedef void (*ibf_dump_object_function)(struct ibf_dump *dump, VALUE obj);
15027static const ibf_dump_object_function dump_object_functions[RUBY_T_MASK+1] = {
15028 ibf_dump_object_unsupported, /* T_NONE */
15029 ibf_dump_object_unsupported, /* T_OBJECT */
15030 ibf_dump_object_class, /* T_CLASS */
15031 ibf_dump_object_unsupported, /* T_MODULE */
15032 ibf_dump_object_float, /* T_FLOAT */
15033 ibf_dump_object_string, /* T_STRING */
15034 ibf_dump_object_regexp, /* T_REGEXP */
15035 ibf_dump_object_array, /* T_ARRAY */
15036 ibf_dump_object_hash, /* T_HASH */
15037 ibf_dump_object_struct, /* T_STRUCT */
15038 ibf_dump_object_bignum, /* T_BIGNUM */
15039 ibf_dump_object_unsupported, /* T_FILE */
15040 ibf_dump_object_data, /* T_DATA */
15041 ibf_dump_object_unsupported, /* T_MATCH */
15042 ibf_dump_object_complex_rational, /* T_COMPLEX */
15043 ibf_dump_object_complex_rational, /* T_RATIONAL */
15044 ibf_dump_object_unsupported, /* 0x10 */
15045 ibf_dump_object_unsupported, /* 0x11 T_NIL */
15046 ibf_dump_object_unsupported, /* 0x12 T_TRUE */
15047 ibf_dump_object_unsupported, /* 0x13 T_FALSE */
15048 ibf_dump_object_symbol, /* 0x14 T_SYMBOL */
15049 ibf_dump_object_unsupported, /* T_FIXNUM */
15050 ibf_dump_object_unsupported, /* T_UNDEF */
15051 ibf_dump_object_unsupported, /* 0x17 */
15052 ibf_dump_object_unsupported, /* 0x18 */
15053 ibf_dump_object_unsupported, /* 0x19 */
15054 ibf_dump_object_imemo, /* T_IMEMO 0x1a */
15055 ibf_dump_object_unsupported, /* T_NODE 0x1b */
15056 ibf_dump_object_unsupported, /* T_ICLASS 0x1c */
15057 ibf_dump_object_unsupported, /* T_ZOMBIE 0x1d */
15058 ibf_dump_object_unsupported, /* 0x1e */
15059 ibf_dump_object_unsupported, /* 0x1f */
15060};
15061
15062static void
15063ibf_dump_object_object_header(struct ibf_dump *dump, const struct ibf_object_header header)
15064{
15065 unsigned char byte =
15066 (header.type << 0) |
15067 (header.special_const << 5) |
15068 (header.frozen << 6) |
15069 (header.internal << 7);
15070
15071 IBF_WV(byte);
15072}
15073
15074static struct ibf_object_header
15075ibf_load_object_object_header(const struct ibf_load *load, ibf_offset_t *offset)
15076{
15077 unsigned char byte = ibf_load_byte(load, offset);
15078
15079 struct ibf_object_header header;
15080 header.type = (byte >> 0) & 0x1f;
15081 header.special_const = (byte >> 5) & 0x01;
15082 header.frozen = (byte >> 6) & 0x01;
15083 header.internal = (byte >> 7) & 0x01;
15084
15085 return header;
15086}
15087
15088static ibf_offset_t
15089ibf_dump_object_object(struct ibf_dump *dump, VALUE obj)
15090{
15091 struct ibf_object_header obj_header;
15092 ibf_offset_t current_offset;
15093 IBF_ZERO(obj_header);
15094 obj_header.type = TYPE(obj);
15095
15096 IBF_W_ALIGN(ibf_offset_t);
15097 current_offset = ibf_dump_pos(dump);
15098
15099 if (SPECIAL_CONST_P(obj) &&
15100 ! (SYMBOL_P(obj) ||
15101 RB_FLOAT_TYPE_P(obj))) {
15102 obj_header.special_const = TRUE;
15103 obj_header.frozen = TRUE;
15104 obj_header.internal = TRUE;
15105 ibf_dump_object_object_header(dump, obj_header);
15106 ibf_dump_write_small_value(dump, obj);
15107 }
15108 else {
15109 obj_header.internal = SPECIAL_CONST_P(obj) ? FALSE : (RBASIC_CLASS(obj) == 0) ? TRUE : FALSE;
15110 obj_header.special_const = FALSE;
15111 obj_header.frozen = OBJ_FROZEN(obj) ? TRUE : FALSE;
15112 ibf_dump_object_object_header(dump, obj_header);
15113 (*dump_object_functions[obj_header.type])(dump, obj);
15114 }
15115
15116 return current_offset;
15117}
15118
15119typedef VALUE (*ibf_load_object_function)(const struct ibf_load *load, const struct ibf_object_header *header, ibf_offset_t offset);
15120static const ibf_load_object_function load_object_functions[RUBY_T_MASK+1] = {
15121 ibf_load_object_unsupported, /* T_NONE */
15122 ibf_load_object_unsupported, /* T_OBJECT */
15123 ibf_load_object_class, /* T_CLASS */
15124 ibf_load_object_unsupported, /* T_MODULE */
15125 ibf_load_object_float, /* T_FLOAT */
15126 ibf_load_object_string, /* T_STRING */
15127 ibf_load_object_regexp, /* T_REGEXP */
15128 ibf_load_object_array, /* T_ARRAY */
15129 ibf_load_object_hash, /* T_HASH */
15130 ibf_load_object_struct, /* T_STRUCT */
15131 ibf_load_object_bignum, /* T_BIGNUM */
15132 ibf_load_object_unsupported, /* T_FILE */
15133 ibf_load_object_data, /* T_DATA */
15134 ibf_load_object_unsupported, /* T_MATCH */
15135 ibf_load_object_complex_rational, /* T_COMPLEX */
15136 ibf_load_object_complex_rational, /* T_RATIONAL */
15137 ibf_load_object_unsupported, /* 0x10 */
15138 ibf_load_object_unsupported, /* T_NIL */
15139 ibf_load_object_unsupported, /* T_TRUE */
15140 ibf_load_object_unsupported, /* T_FALSE */
15141 ibf_load_object_symbol,
15142 ibf_load_object_unsupported, /* T_FIXNUM */
15143 ibf_load_object_unsupported, /* T_UNDEF */
15144 ibf_load_object_unsupported, /* 0x17 */
15145 ibf_load_object_unsupported, /* 0x18 */
15146 ibf_load_object_unsupported, /* 0x19 */
15147 ibf_load_object_imemo, /* T_IMEMO 0x1a */
15148 ibf_load_object_unsupported, /* T_NODE 0x1b */
15149 ibf_load_object_unsupported, /* T_ICLASS 0x1c */
15150 ibf_load_object_unsupported, /* T_ZOMBIE 0x1d */
15151 ibf_load_object_unsupported, /* 0x1e */
15152 ibf_load_object_unsupported, /* 0x1f */
15153};
15154
15155#if USE_LAZY_LOAD
15156/* Lazily loaded iseqs are completed after the entry point returns, so the
15157 * loader owns the offsets and frees them along with itself. */
15158# define IBF_LOAD_ALLOC_OBJ_OFFSETS(load, ptr) \
15159 VALUE ptr##_tmp = 0; \
15160 ibf_offset_t *ptr = ALLOC_N(ibf_offset_t, (load)->current_buffer->obj_list_size)
15161# define IBF_LOAD_FREE_OBJ_OFFSETS(load, ptr) ((void)(ptr##_tmp))
15162#else
15163# define IBF_LOAD_ALLOC_OBJ_OFFSETS(load, ptr) \
15164 VALUE ptr##_tmp; \
15165 ibf_offset_t *ptr = ALLOCV_N(ibf_offset_t, ptr##_tmp, (load)->current_buffer->obj_list_size)
15166# define IBF_LOAD_FREE_OBJ_OFFSETS(load, ptr) \
15167 ((load)->current_buffer->obj_offsets = NULL, ALLOCV_END(ptr##_tmp))
15168#endif
15169
15170static void
15171ibf_load_object_offsets(const struct ibf_load *load, ibf_offset_t *offsets)
15172{
15173 struct ibf_load_buffer *buffer = load->current_buffer;
15174 ibf_offset_t reading_pos = buffer->obj_list_offset;
15175 buffer->obj_offsets = offsets;
15176 ibf_offset_t offset = 0;
15177
15178 for (unsigned int i = 0; i < buffer->obj_list_size; i++) {
15179 VALUE delta = ibf_load_small_value(load, &reading_pos);
15180 if (delta >= buffer->size - offset) {
15181 rb_raise(rb_eIndexError, "object offset out of range");
15182 }
15183 offset += (ibf_offset_t)delta;
15184 offsets[i] = offset;
15185 }
15186}
15187
15188static VALUE
15189ibf_load_object(const struct ibf_load *load, VALUE object_index)
15190{
15191 if (object_index == 0) {
15192 return Qnil;
15193 }
15194 else {
15195 VALUE obj = pinned_list_fetch(load->current_buffer->obj_list, (long)object_index);
15196 if (!obj) {
15197 ibf_offset_t offset = load->current_buffer->obj_offsets[object_index];
15198 const struct ibf_object_header header = ibf_load_object_object_header(load, &offset);
15199
15200#if IBF_ISEQ_DEBUG
15201 fprintf(stderr, "ibf_load_object: list=%#x offset=%#x\n",
15202 load->current_buffer->obj_list_offset, offset);
15203 fprintf(stderr, "ibf_load_object: type=%#x special=%d frozen=%d internal=%d\n",
15204 header.type, header.special_const, header.frozen, header.internal);
15205#endif
15206 if (offset >= load->current_buffer->size) {
15207 rb_raise(rb_eIndexError, "object offset out of range: %u", offset);
15208 }
15209
15210 if (header.special_const) {
15211 ibf_offset_t reading_pos = offset;
15212
15213 obj = ibf_load_small_value(load, &reading_pos);
15214 }
15215 else {
15216 obj = (*load_object_functions[header.type])(load, &header, offset);
15217 }
15218
15219 pinned_list_store(load->current_buffer->obj_list, (long)object_index, obj);
15220 }
15221#if IBF_ISEQ_DEBUG
15222 fprintf(stderr, "ibf_load_object: index=%#"PRIxVALUE" obj=%#"PRIxVALUE"\n",
15223 object_index, obj);
15224#endif
15225 return obj;
15226 }
15227}
15228
15230{
15231 struct ibf_dump *dump;
15232 VALUE offset_list;
15233};
15234
15235static int
15236ibf_dump_object_list_i(st_data_t key, st_data_t val, st_data_t ptr)
15237{
15238 VALUE obj = (VALUE)key;
15239 struct ibf_dump_object_list_arg *args = (struct ibf_dump_object_list_arg *)ptr;
15240
15241 ibf_offset_t offset = ibf_dump_object_object(args->dump, obj);
15242 rb_ary_push(args->offset_list, UINT2NUM(offset));
15243
15244 return ST_CONTINUE;
15245}
15246
15247static void
15248ibf_dump_object_list(struct ibf_dump *dump, ibf_offset_t *obj_list_offset, unsigned int *obj_list_size)
15249{
15250 st_table *obj_table = dump->current_buffer->obj_table;
15251 VALUE offset_list = rb_ary_hidden_new(obj_table->num_entries);
15252
15253 struct ibf_dump_object_list_arg args;
15254 args.dump = dump;
15255 args.offset_list = offset_list;
15256
15257 st_foreach(obj_table, ibf_dump_object_list_i, (st_data_t)&args);
15258
15259 *obj_list_offset = ibf_dump_pos(dump);
15260
15261 st_index_t size = obj_table->num_entries;
15262 st_index_t i;
15263 ibf_offset_t prev_offset = 0;
15264
15265 // Objects are dumped in list order, so offsets are monotonically increasing.
15266 // So we store individual objects sizes instead, which is enough information
15267 // to rebuild the offset list, but is more compact.
15268 // The tradeoff is that it can't directly be indexed, it has to be decoded
15269 // first.
15270 for (i=0; i<size; i++) {
15271 ibf_offset_t offset = NUM2UINT(RARRAY_AREF(offset_list, i));
15272 ibf_dump_write_small_value(dump, offset - prev_offset);
15273 prev_offset = offset;
15274 }
15275
15276 *obj_list_size = (unsigned int)size;
15277}
15278
15279static void
15280ibf_dump_mark(void *ptr)
15281{
15282 struct ibf_dump *dump = (struct ibf_dump *)ptr;
15283 rb_gc_mark(dump->global_buffer.str);
15284
15285 rb_mark_set(dump->global_buffer.obj_table);
15286 rb_mark_set(dump->iseq_table);
15287}
15288
15289static void
15290ibf_dump_free(void *ptr)
15291{
15292 struct ibf_dump *dump = (struct ibf_dump *)ptr;
15293 if (dump->global_buffer.obj_table) {
15294 st_free_table(dump->global_buffer.obj_table);
15295 dump->global_buffer.obj_table = 0;
15296 }
15297 if (dump->iseq_table) {
15298 st_free_table(dump->iseq_table);
15299 dump->iseq_table = 0;
15300 }
15301}
15302
15303static size_t
15304ibf_dump_memsize(const void *ptr)
15305{
15306 struct ibf_dump *dump = (struct ibf_dump *)ptr;
15307 size_t size = 0;
15308 if (dump->iseq_table) size += st_memsize(dump->iseq_table);
15309 if (dump->global_buffer.obj_table) size += st_memsize(dump->global_buffer.obj_table);
15310 return size;
15311}
15312
15313static const rb_data_type_t ibf_dump_type = {
15314 "ibf_dump",
15315 {ibf_dump_mark, ibf_dump_free, ibf_dump_memsize,},
15316 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_EMBEDDABLE
15317};
15318
15319static void
15320ibf_dump_setup(struct ibf_dump *dump, VALUE dumper_obj)
15321{
15322 dump->global_buffer.obj_table = NULL; // GC may run before a value is assigned
15323 dump->iseq_table = NULL;
15324
15325 RB_OBJ_WRITE(dumper_obj, &dump->global_buffer.str, rb_str_new(0, 0));
15326 dump->global_buffer.obj_table = ibf_dump_object_table_new();
15327 dump->iseq_table = st_init_numtable(); /* need free */
15328
15329 dump->current_buffer = &dump->global_buffer;
15330}
15331
15332static VALUE
15333iseq_ibf_dump_0(struct ibf_dump *dump, const rb_iseq_t *iseq, VALUE opt)
15334{
15335 struct ibf_header header = {{0}};
15336
15337 ibf_dump_write(dump, &header, sizeof(header));
15338 ibf_dump_iseq(dump, iseq);
15339
15340 header.magic[0] = 'Y'; /* YARB */
15341 header.magic[1] = 'A';
15342 header.magic[2] = 'R';
15343 header.magic[3] = 'B';
15344 header.major_version = IBF_MAJOR_VERSION;
15345 header.minor_version = IBF_MINOR_VERSION;
15346 header.endian = IBF_ENDIAN_MARK;
15347 header.wordsize = (uint8_t)SIZEOF_VALUE;
15348 header.source_hash_hi = (uint32_t)(ISEQ_BODY(iseq)->source_hash >> 32);
15349 header.source_hash_lo = (uint32_t)ISEQ_BODY(iseq)->source_hash;
15350 ibf_dump_iseq_list(dump, &header);
15351 ibf_dump_object_list(dump, &header.global_object_list_offset, &header.global_object_list_size);
15352 header.size = ibf_dump_pos(dump);
15353
15354 if (RTEST(opt)) {
15355 VALUE opt_str = opt;
15356 const char *ptr = StringValuePtr(opt_str);
15357 header.extra_size = RSTRING_LENINT(opt_str);
15358 ibf_dump_write(dump, ptr, header.extra_size);
15359 }
15360 else {
15361 header.extra_size = 0;
15362 }
15363
15364 ibf_dump_overwrite(dump, &header, sizeof(header), 0);
15365
15366 return dump->global_buffer.str;
15367}
15368
15369VALUE
15370rb_iseq_ibf_dump(const rb_iseq_t *iseq, VALUE opt)
15371{
15372 struct ibf_dump *dump;
15373 VALUE dump_obj;
15374 VALUE str;
15375
15376 if (ISEQ_BODY(iseq)->parent_iseq != NULL ||
15377 ISEQ_BODY(iseq)->local_iseq != iseq) {
15378 rb_raise(rb_eRuntimeError, "should be top of iseq");
15379 }
15380 if (RTEST(ISEQ_COVERAGE(iseq))) {
15381 rb_raise(rb_eRuntimeError, "should not compile with coverage");
15382 }
15383
15384 dump_obj = TypedData_Make_Struct(0, struct ibf_dump, &ibf_dump_type, dump);
15385 ibf_dump_setup(dump, dump_obj);
15386
15387 str = iseq_ibf_dump_0(dump, iseq, opt);
15388 RB_GC_GUARD(dump_obj);
15389 return str;
15390}
15391
15392static const ibf_offset_t *
15393ibf_iseq_list(const struct ibf_load *load)
15394{
15395 return (const ibf_offset_t *)(load->global_buffer.buff + load->header->iseq_list_offset);
15396}
15397
15398void
15399rb_ibf_load_iseq_complete(rb_iseq_t *iseq)
15400{
15401 struct ibf_load *load = RTYPEDDATA_DATA(iseq->aux.loader.obj);
15402 rb_iseq_t *prev_src_iseq = load->iseq;
15403 ibf_offset_t offset = ibf_iseq_list(load)[iseq->aux.loader.index];
15404 load->iseq = iseq;
15405#if IBF_ISEQ_DEBUG
15406 fprintf(stderr, "rb_ibf_load_iseq_complete: index=%#x offset=%#x size=%#x\n",
15407 iseq->aux.loader.index, offset,
15408 load->header->size);
15409#endif
15410 ibf_load_iseq_each(load, iseq, offset);
15411 ISEQ_COMPILE_DATA_CLEAR(iseq);
15412 FL_UNSET((VALUE)iseq, ISEQ_NOT_LOADED_YET);
15413 rb_iseq_init_trace(iseq);
15414 load->iseq = prev_src_iseq;
15415}
15416
15417#if USE_LAZY_LOAD
15418const rb_iseq_t *
15419rb_iseq_complete(const rb_iseq_t *iseq)
15420{
15421 rb_ibf_load_iseq_complete((rb_iseq_t *)iseq);
15422 return iseq;
15423}
15424#endif
15425
15426static rb_iseq_t *
15427ibf_load_iseq(const struct ibf_load *load, const rb_iseq_t *index_iseq)
15428{
15429 int iseq_index = (int)(VALUE)index_iseq;
15430
15431#if IBF_ISEQ_DEBUG
15432 fprintf(stderr, "ibf_load_iseq: index_iseq=%p iseq_list=%p\n",
15433 (void *)index_iseq, (void *)load->iseq_list);
15434#endif
15435 if (iseq_index == -1) {
15436 return NULL;
15437 }
15438 else {
15439 VALUE iseqv = pinned_list_fetch(load->iseq_list, iseq_index);
15440
15441#if IBF_ISEQ_DEBUG
15442 fprintf(stderr, "ibf_load_iseq: iseqv=%p\n", (void *)iseqv);
15443#endif
15444 if (iseqv) {
15445 return (rb_iseq_t *)iseqv;
15446 }
15447 else {
15448 rb_iseq_t *iseq = iseq_imemo_alloc();
15449#if IBF_ISEQ_DEBUG
15450 fprintf(stderr, "ibf_load_iseq: new iseq=%p\n", (void *)iseq);
15451#endif
15452 FL_SET((VALUE)iseq, ISEQ_NOT_LOADED_YET);
15453 RB_OBJ_WRITE((VALUE)iseq, &iseq->aux.loader.obj, load->loader_obj);
15454 iseq->aux.loader.index = iseq_index;
15455#if IBF_ISEQ_DEBUG
15456 fprintf(stderr, "ibf_load_iseq: iseq=%p loader_obj=%p index=%d\n",
15457 (void *)iseq, (void *)load->loader_obj, iseq_index);
15458#endif
15459 pinned_list_store(load->iseq_list, iseq_index, (VALUE)iseq);
15460
15461 if (!USE_LAZY_LOAD || GET_VM()->builtin_function_table) {
15462#if IBF_ISEQ_DEBUG
15463 fprintf(stderr, "ibf_load_iseq: loading iseq=%p\n", (void *)iseq);
15464#endif
15465 rb_ibf_load_iseq_complete(iseq);
15466 }
15467
15468#if IBF_ISEQ_DEBUG
15469 fprintf(stderr, "ibf_load_iseq: iseq=%p loaded %p\n",
15470 (void *)iseq, (void *)load->iseq);
15471#endif
15472 return iseq;
15473 }
15474 }
15475}
15476
15477static void
15478ibf_load_setup_bytes(struct ibf_load *load, VALUE loader_obj, const char *bytes, size_t size)
15479{
15480 struct ibf_header *header = (struct ibf_header *)bytes;
15481 load->loader_obj = loader_obj;
15482 load->global_buffer.buff = bytes;
15483 load->header = header;
15484 load->global_buffer.size = header->size;
15485 load->global_buffer.obj_list_offset = header->global_object_list_offset;
15486 load->global_buffer.obj_list_size = header->global_object_list_size;
15487 RB_OBJ_WRITE(loader_obj, &load->iseq_list, pinned_list_new(header->iseq_list_size));
15488 RB_OBJ_WRITE(loader_obj, &load->global_buffer.obj_list, pinned_list_new(load->global_buffer.obj_list_size));
15489 load->iseq = NULL;
15490
15491 load->current_buffer = &load->global_buffer;
15492
15493 if (size < header->size) {
15494 rb_raise(rb_eRuntimeError, "broken binary format");
15495 }
15496 if (strncmp(header->magic, "YARB", 4) != 0) {
15497 rb_raise(rb_eRuntimeError, "unknown binary format");
15498 }
15499 if (header->major_version != IBF_MAJOR_VERSION ||
15500 header->minor_version != IBF_MINOR_VERSION) {
15501 rb_raise(rb_eRuntimeError, "unmatched version file (%u.%u for %u.%u)",
15502 header->major_version, header->minor_version, IBF_MAJOR_VERSION, IBF_MINOR_VERSION);
15503 }
15504 if (header->endian != IBF_ENDIAN_MARK) {
15505 rb_raise(rb_eRuntimeError, "unmatched endian: %c", header->endian);
15506 }
15507 if (header->wordsize != SIZEOF_VALUE) {
15508 rb_raise(rb_eRuntimeError, "unmatched word size: %d", header->wordsize);
15509 }
15510 if (header->iseq_list_offset % RUBY_ALIGNOF(ibf_offset_t)) {
15511 rb_raise(rb_eArgError, "unaligned iseq list offset: %u",
15512 header->iseq_list_offset);
15513 }
15514 if (load->global_buffer.obj_list_offset >= load->global_buffer.size) {
15515 rb_raise(rb_eArgError, "object list offset out of range: %u",
15516 load->global_buffer.obj_list_offset);
15517 }
15518}
15519
15520static void
15521ibf_load_setup(struct ibf_load *load, VALUE loader_obj, VALUE str)
15522{
15523 StringValue(str);
15524
15525 if (RSTRING_LENINT(str) < (int)sizeof(struct ibf_header)) {
15526 rb_raise(rb_eRuntimeError, "broken binary format");
15527 }
15528
15529 if (USE_LAZY_LOAD) {
15530 str = rb_str_new(RSTRING_PTR(str), RSTRING_LEN(str));
15531 }
15532
15533 ibf_load_setup_bytes(load, loader_obj, RSTRING_PTR(str), RSTRING_LEN(str));
15534 RB_OBJ_WRITE(loader_obj, &load->str, str);
15535}
15536
15537static void
15538ibf_loader_mark(void *ptr)
15539{
15540 struct ibf_load *load = (struct ibf_load *)ptr;
15541 rb_gc_mark(load->str);
15542 rb_gc_mark(load->path_override);
15543 rb_gc_mark(load->realpath_override);
15544 rb_gc_mark(load->pathobj);
15545 rb_gc_mark(load->iseq_list);
15546 rb_gc_mark(load->global_buffer.obj_list);
15547}
15548
15549static void
15550ibf_loader_free(void *ptr)
15551{
15552 struct ibf_load *load = (struct ibf_load *)ptr;
15553#if USE_LAZY_LOAD
15554 if (load->global_buffer.obj_offsets) {
15555 SIZED_FREE_N(load->global_buffer.obj_offsets, load->global_buffer.obj_list_size);
15556 }
15557#endif
15558 SIZED_FREE(load);
15559}
15560
15561static size_t
15562ibf_loader_memsize(const void *ptr)
15563{
15564 size_t size = sizeof(struct ibf_load);
15565#if USE_LAZY_LOAD
15566 const struct ibf_load *load = (const struct ibf_load *)ptr;
15567 if (load->global_buffer.obj_offsets) {
15568 size += load->global_buffer.obj_list_size * sizeof(ibf_offset_t);
15569 }
15570#endif
15571 return size;
15572}
15573
15574static const rb_data_type_t ibf_load_type = {
15575 "ibf_loader",
15576 {ibf_loader_mark, ibf_loader_free, ibf_loader_memsize,},
15577 0, 0, RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_THREAD_SAFE_FREE
15578};
15579
15580static void
15581ibf_load_set_path(struct ibf_load *load, VALUE path, VALUE realpath)
15582{
15583 if (NIL_P(path)) return;
15584 if (NIL_P(realpath)) realpath = path;
15585 RB_OBJ_WRITE(load->loader_obj, &load->path_override, rb_fstring(path));
15586 RB_OBJ_WRITE(load->loader_obj, &load->realpath_override, rb_fstring(realpath));
15587}
15588
15589static const rb_iseq_t *
15590iseq_ibf_load(struct ibf_load *load, VALUE fname, VALUE path)
15591{
15592 IBF_LOAD_ALLOC_OBJ_OFFSETS(load, obj_offsets);
15593 ibf_load_object_offsets(load, obj_offsets);
15594 ibf_load_set_path(load, fname, path);
15595 rb_iseq_t *iseq = ibf_load_iseq(load, 0);
15596 IBF_LOAD_FREE_OBJ_OFFSETS(load, obj_offsets);
15597 return iseq;
15598}
15599
15600const rb_iseq_t *
15601rb_iseq_ibf_load(VALUE str, VALUE fname, VALUE path)
15602{
15603 struct ibf_load *load;
15604 VALUE loader_obj = TypedData_Make_Struct(0, struct ibf_load, &ibf_load_type, load);
15605 ibf_load_setup(load, loader_obj, str);
15606
15607 const rb_iseq_t *iseq = iseq_ibf_load(load, fname, path);
15608
15609 RB_GC_GUARD(loader_obj);
15610 return iseq;
15611}
15612
15613const rb_iseq_t *
15614rb_iseq_ibf_load_bytes(const char *bytes, size_t size, VALUE fname, VALUE path)
15615{
15616 struct ibf_load *load;
15617 VALUE loader_obj = TypedData_Make_Struct(0, struct ibf_load, &ibf_load_type, load);
15618 ibf_load_setup_bytes(load, loader_obj, bytes, size);
15619
15620 const rb_iseq_t *iseq = iseq_ibf_load(load, fname, path);
15621
15622 RB_GC_GUARD(loader_obj);
15623 return iseq;
15624}
15625
15626/* collect the iseq table into an array indexed by iseq-list index */
15627static int
15628ibf_dump_iseq_table_collect_i(st_data_t key, st_data_t val, st_data_t arg)
15629{
15630 const rb_iseq_t **srcs = (const rb_iseq_t **)arg;
15631 srcs[(int)val] = (const rb_iseq_t *)key;
15632 return ST_CONTINUE;
15633}
15634
15635/* pc2branchindex (branch coverage) is per-iseq, so pair each copy with its
15636 * source by list index */
15637static void
15638iseq_subtree_copy_pc2branchindex(const struct ibf_dump *dump, const struct ibf_load *load)
15639{
15640 unsigned int iseq_count = (unsigned int)dump->iseq_table->num_entries;
15641 VALUE srcs_buf;
15642 const rb_iseq_t **srcs = ALLOCV_N(const rb_iseq_t *, srcs_buf, iseq_count);
15643 st_foreach(dump->iseq_table, ibf_dump_iseq_table_collect_i, (st_data_t)srcs);
15644
15645 for (unsigned int i = 0; i < iseq_count; i++) {
15646 rb_iseq_t *copy = ibf_load_iseq(load, (const rb_iseq_t *)(VALUE)i);
15647 VALUE pc2branchindex = ISEQ_PC2BRANCHINDEX(srcs[i]);
15648 if (pc2branchindex != Qnil) {
15649 ISEQ_PC2BRANCHINDEX_SET(copy, pc2branchindex);
15650 }
15651 }
15652
15653 ALLOCV_END(srcs_buf);
15654}
15655
15656/* Deep-copy an iseq subtree with independent inline caches for Proc#refined */
15657const rb_iseq_t *
15658rb_iseq_dup_with_independent_caches(const rb_iseq_t *src_root)
15659{
15660 struct ibf_dump *dump;
15661 VALUE dump_obj;
15662 VALUE str;
15663
15664 /* --- dump the subtree --- */
15665 dump_obj = TypedData_Make_Struct(0, struct ibf_dump, &ibf_dump_type, dump);
15666 ibf_dump_setup(dump, dump_obj);
15667
15668 str = iseq_ibf_dump_0(dump, src_root, Qnil);
15669
15670 /* --- load it back --- */
15671 struct ibf_load *load;
15672 VALUE loader_obj = TypedData_Make_Struct(0, struct ibf_load, &ibf_load_type, load);
15673 ibf_load_setup(load, loader_obj, str);
15674 IBF_LOAD_ALLOC_OBJ_OFFSETS(load, obj_offsets);
15675 ibf_load_object_offsets(load, obj_offsets);
15676
15677 /* What the loader could not reconstruct is the same for every iseq in
15678 * the subtree: the only absent parent is the top's, every absent
15679 * local_iseq is the source's local root (runtime walks compare it
15680 * against the original frames, so a copy must not stand in), and
15681 * pathobj/script_lines/coverage are per-file values. */
15682 const struct rb_iseq_constant_body *sb = ISEQ_BODY(src_root);
15683 unsigned int iseq_count = (unsigned int)dump->iseq_table->num_entries;
15684 const rb_iseq_t *result = NULL;
15685 for (unsigned int i = 0; i < iseq_count; i++) {
15686 rb_iseq_t *copy = ibf_load_iseq(load, (const rb_iseq_t *)(VALUE)i);
15687 /* force completion even under USE_LAZY_LOAD */
15688 if (FL_TEST((VALUE)copy, ISEQ_NOT_LOADED_YET)) {
15689 rb_ibf_load_iseq_complete(copy);
15690 }
15691
15692 FL_SET((VALUE)copy, ISEQ_REFINED_COPY);
15693
15694 struct rb_iseq_constant_body *cb = ISEQ_BODY(copy);
15695 if (!cb->local_iseq) RB_OBJ_WRITE(copy, &cb->local_iseq, sb->local_iseq);
15696 RB_OBJ_WRITE(copy, &cb->location.pathobj, sb->location.pathobj);
15697 cb->no_realpath = sb->no_realpath;
15698 VALUE sl = ISEQ_SCRIPT_LINES(src_root);
15699 VALUE cov = ISEQ_COVERAGE(src_root);
15700 if (!NIL_P(sl) || !NIL_P(cov)) {
15701 struct rb_iseq_variable *v = rb_iseq_variable_ensure(copy);
15702 RB_OBJ_WRITE(copy, &v->script_lines, sl);
15703 RB_OBJ_WRITE(copy, &v->coverage, cov);
15704 }
15705
15706 if (i == 0) {
15707 RB_OBJ_WRITE(copy, &cb->parent_iseq, sb->parent_iseq);
15708 result = copy;
15709 }
15710
15711 /* Shared across Ractors through the Proc#refined memo; the duplicated
15712 * subtree is self-contained, so mark each copy shareable. */
15714 }
15715
15716 if (ISEQ_PC2BRANCHINDEX(src_root) != Qnil) {
15717 iseq_subtree_copy_pc2branchindex(dump, load);
15718 }
15719 IBF_LOAD_FREE_OBJ_OFFSETS(load, obj_offsets);
15720
15721 RB_GC_GUARD(dump_obj);
15722 RB_GC_GUARD(loader_obj);
15723 return result;
15724}
15725
15726VALUE
15727rb_iseq_ibf_load_extra_data(VALUE str)
15728{
15729 struct ibf_load *load;
15730 VALUE loader_obj = TypedData_Make_Struct(0, struct ibf_load, &ibf_load_type, load);
15731 VALUE extra_str;
15732
15733 ibf_load_setup(load, loader_obj, str);
15734 extra_str = rb_str_new(load->global_buffer.buff + load->header->size, load->header->extra_size);
15735 RB_GC_GUARD(loader_obj);
15736 return extra_str;
15737}
15738
15739#include "prism_compile.c"
#define RUBY_ATOMIC_PTR_LOAD(var)
Identical to RUBY_ATOMIC_LOAD, except it expects its arguments are void*.
Definition atomic.h:348
#define LONG_LONG
Definition long_long.h:38
#define RUBY_ALIGNOF
Wraps (or simulates) alignof.
Definition stdalign.h:28
#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_NONE
No events.
Definition event.h:37
#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
#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
#define RBIMPL_ATTR_FORMAT(x, y, z)
Wraps (or simulates) __attribute__((format)).
Definition format.h:33
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1700
#define T_COMPLEX
Old name of RUBY_T_COMPLEX.
Definition value_type.h:59
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
#define NUM2ULONG
Old name of RB_NUM2ULONG.
Definition long.h:52
#define NUM2LL
Old name of RB_NUM2LL.
Definition long_long.h:34
#define ALLOCV
Old name of RB_ALLOCV.
Definition memory.h:407
#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 OBJ_FROZEN
Old name of RB_OBJ_FROZEN.
Definition fl_type.h:133
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1708
#define T_NIL
Old name of RUBY_T_NIL.
Definition value_type.h:72
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
Definition assume.h:28
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
#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 OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define ULONG2NUM
Old name of RB_ULONG2NUM.
Definition long.h:60
#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 FIX2UINT
Old name of RB_FIX2UINT.
Definition int.h:42
#define ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:405
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define FIXABLE
Old name of RB_FIXABLE.
Definition fixnum.h:25
#define xmalloc
Old name of ruby_xmalloc.
Definition xmalloc.h:53
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define NUM2UINT
Old name of RB_NUM2UINT.
Definition int.h:45
#define ZALLOC_N
Old name of RB_ZALLOC_N.
Definition memory.h:404
#define ASSUME
Old name of RBIMPL_ASSUME.
Definition assume.h:27
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition value_type.h:76
#define T_HASH
Old name of RUBY_T_HASH.
Definition value_type.h:65
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:402
#define FL_SET
Old name of RB_FL_SET.
Definition fl_type.h:125
#define FLONUM_P
Old name of RB_FLONUM_P.
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#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 NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:408
#define NUM2ULL
Old name of RB_NUM2ULL.
Definition long_long.h:35
#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 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 NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FL_UNSET
Old name of RB_FL_UNSET.
Definition fl_type.h:129
#define UINT2NUM
Old name of RB_UINT2NUM.
Definition int.h:46
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:409
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
#define T_REGEXP
Old name of RUBY_T_REGEXP.
Definition value_type.h:77
#define ruby_debug
This variable controls whether the interpreter is in debug mode.
Definition error.h:487
VALUE rb_eNotImpError
NotImplementedError exception.
Definition error.c:1467
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1454
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
VALUE rb_eNoMatchingPatternError
NoMatchingPatternError exception.
Definition error.c:1470
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
VALUE rb_eNoMatchingPatternKeyError
NoMatchingPatternKeyError exception.
Definition error.c:1471
VALUE rb_eIndexError
IndexError exception.
Definition error.c:1459
VALUE rb_errinfo(void)
This is the same as $! in Ruby.
Definition eval.c:2133
VALUE rb_eSyntaxError
SyntaxError exception.
Definition error.c:1474
@ RB_WARN_CATEGORY_STRICT_UNUSED_BLOCK
Warning is for checking unused block strictly.
Definition error.h:57
VALUE rb_obj_reveal(VALUE obj, VALUE klass)
Make a hidden object visible again.
Definition object.c:103
VALUE rb_cArray
Array class.
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:94
VALUE rb_cHash
Hash class.
Definition hash.c:123
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:665
VALUE rb_cRange
Range class.
Definition range.c:35
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_obj_freeze(VALUE obj)
Same as RB_OBJ_FREEZE(), but returns the given object.
Definition object.c:1305
#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 RBIMPL_ASSERT_OR_ASSUME(...)
This is either RUBY_ASSERT or RBIMPL_ASSUME, depending on RUBY_DEBUG.
Definition assert.h:311
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#define RB_POSFIXABLE(_)
Checks if the passed value is in range of fixnum, assuming it is a positive number.
Definition fixnum.h:43
#define RBIMPL_ATTR_NORETURN()
Wraps (or simulates) [[noreturn]].
Definition noreturn.h:38
void rb_memerror(void)
Triggers out-of-memory error.
Definition gc.c:6685
VALUE rb_ary_reverse(VALUE ary)
Destructively reverses the passed array in-place.
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_new_capa(rb_len_t capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
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_new(void)
Allocates a new, empty array.
VALUE rb_ary_clear(VALUE ary)
Destructively removes everything form an array.
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_freeze(VALUE obj)
Freeze an array, preventing further modifications.
VALUE rb_ary_cat(VALUE ary, const VALUE *train, rb_len_t len)
Destructively appends multiple elements at the end of the array.
VALUE rb_ary_join(VALUE ary, VALUE sep)
Recursively stringises the elements of the passed array, flattens that result, then joins the sequenc...
#define INTEGER_PACK_NATIVE_BYTE_ORDER
Means either INTEGER_PACK_MSBYTE_FIRST or INTEGER_PACK_LSBYTE_FIRST, depending on the host processor'...
Definition bignum.h:550
#define INTEGER_PACK_NEGATIVE
Interprets the input as a signed negative number (unpack only).
Definition bignum.h:568
#define INTEGER_PACK_LSWORD_FIRST
Stores/interprets the least significant word as the first word.
Definition bignum.h:532
VALUE rb_hash_new(void)
Creates a new, empty hash object.
Definition hash.c:1656
int rb_is_const_id(ID id)
Classifies the given ID, then sees if it is a constant.
Definition symbol.c:1249
int rb_is_attrset_id(ID id)
Classifies the given ID, then sees if it is an attribute writer.
Definition symbol.c:1273
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Deconstructs a range into its components.
Definition range.c:1857
VALUE rb_range_new(VALUE beg, VALUE end, int excl)
Creates a new Range.
Definition range.c:77
VALUE rb_rational_new(VALUE num, VALUE den)
Constructs a Rational, with reduction.
Definition rational.c:2006
int rb_reg_options(VALUE re)
Queries the options of the passed regular expression.
Definition re.c:5338
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:4020
VALUE rb_str_tmp_new(rb_len_t len)
Allocates a "temporary" string.
Definition string.c:1845
int rb_str_hash_cmp(VALUE str1, VALUE str2)
Compares two strings.
Definition string.c:4403
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1523
st_index_t rb_str_hash(VALUE str)
Calculates a hash value of a string.
Definition string.c:4389
VALUE rb_str_cat(VALUE dst, const char *src, rb_len_t srclen)
Destructively appends the passed contents to the string.
Definition string.c:3786
VALUE rb_str_resurrect(VALUE str)
Like rb_str_dup(), but always create an instance of rb_cString regardless of the given object's class...
Definition string.c:2104
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:3984
int rb_str_cmp(VALUE lhs, VALUE rhs)
Compares two strings, as in strcmp(3).
Definition string.c:4475
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:4269
VALUE rb_str_freeze(VALUE str)
This is the implementation of String#freeze.
Definition string.c:3455
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1539
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:517
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
VALUE rb_id2sym(ID id)
Allocates an instance of rb_cSymbol that has the given id.
Definition symbol.c:1142
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1162
ID rb_sym2id(VALUE obj)
Converts an instance of rb_cSymbol into an ID.
Definition symbol.c:1104
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
#define RB_OBJ_SHAREABLE_P(obj)
Queries if the passed object has previously classified as shareable or not.
Definition ractor.h:255
static VALUE RB_OBJ_SET_FROZEN_SHAREABLE(VALUE obj)
Freezes and marks the object as shareable.
Definition ractor.h:301
VALUE rb_ractor_make_shareable(VALUE obj)
Destructively transforms the passed object so that multiple Ractors can share it.
Definition ractor.c:2078
#define DECIMAL_SIZE_OF(expr)
An approximation of decimal representation size.
Definition util.h:48
void ruby_qsort(void *, const size_t, const size_t, int(*)(const void *, const void *, void *), void *)
Reentrant implementation of quick sort.
#define rb_long2int
Just another name of rb_long2int_inline.
Definition long.h:62
#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 MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:363
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
#define RB_ALLOCV(v, n)
Identical to RB_ALLOCV_N(), except that it allocates a number of bytes and returns a void* .
Definition memory.h:307
VALUE type(ANYARGS)
ANYARGS-ed function type.
int st_foreach(st_table *q, int_type *w, st_data_t e)
Iteration over the given table.
void rb_hash_foreach(VALUE q, int_type *w, VALUE e)
Iteration over the given hash.
#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
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:398
static void RARRAY_ASET(VALUE ary, rb_len_t i, VALUE v)
Assigns an object in an array.
Definition rarray.h:362
#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 RUBY_DEFAULT_FREE
This is a value you can set to RData::dfree.
Definition rdata.h:56
void(* RUBY_DATA_FUNC)(void *)
This is the type of callbacks registered to RData.
Definition rdata.h:69
#define RHASH_SIZE(h)
Queries the size of the hash.
Definition rhash.h:57
static VALUE RREGEXP_SRC(VALUE rexp)
Convenient getter function.
Definition rregexp.h:93
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
#define StringValuePtr(v)
Identical to StringValue, except it returns a char*.
Definition rstring.h:76
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 RTYPEDDATA_DATA(v)
Convenient getter macro.
Definition rtypeddata.h:106
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:773
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition rtypeddata.h:557
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:239
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:604
void rb_p(VALUE obj)
Inspects an object.
Definition io.c:9336
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 _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
Definition proc.c:31
Internal header for Complex.
Definition complex.h:13
Internal header for Rational.
Definition rational.h:16
Definition iseq.h:369
Definition vm_core.h:415
Definition st.h:79
Definition vm_core.h:277
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
unsigned long rb_ulen_t
An unsigned integer type that has the same width with rb_len_t.
Definition value.h:145
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 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_integer_type_p(VALUE obj)
Queries if the object is an instance of rb_cInteger.
Definition value_type.h:204
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
@ RUBY_T_MASK
Bitmask of ruby_value_type.
Definition value_type.h:145