1 /*
2 * Copyright (c) 1998, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "ci/ciInstanceKlass.hpp"
26 #include "compiler/compileLog.hpp"
27 #include "interpreter/linkResolver.hpp"
28 #include "memory/universe.hpp"
29 #include "oops/accessDecorators.hpp"
30 #include "oops/flatArrayKlass.hpp"
31 #include "oops/objArrayKlass.hpp"
32 #include "opto/addnode.hpp"
33 #include "opto/castnode.hpp"
34 #include "opto/inlinetypenode.hpp"
35 #include "opto/memnode.hpp"
36 #include "opto/parse.hpp"
37 #include "opto/rootnode.hpp"
38 #include "opto/runtime.hpp"
39 #include "opto/subnode.hpp"
40 #include "runtime/deoptimization.hpp"
41 #include "runtime/handles.inline.hpp"
42
43 //=============================================================================
44 // Helper methods for _get* and _put* bytecodes
45 //=============================================================================
46
47 void Parse::do_field_access(bool is_get, bool is_field) {
48 bool will_link;
49 ciField* field = iter().get_field(will_link);
50 assert(will_link, "getfield: typeflow responsibility");
51
52 if (is_field == field->is_static()) {
53 // Interpreter will throw java_lang_IncompatibleClassChangeError
54 // Check this before allowing <clinit> methods to access static fields
55 uncommon_trap(Deoptimization::Reason_unhandled,
56 Deoptimization::Action_none);
57 return;
58 }
59
60 // Deoptimize on putfield writes to call site target field outside of CallSite ctor.
61 ciInstanceKlass* field_holder = field->holder();
62 if (!is_get && field->is_call_site_target() &&
63 !(method()->holder() == field_holder && method()->is_object_constructor())) {
64 uncommon_trap(Deoptimization::Reason_unhandled,
65 Deoptimization::Action_reinterpret,
66 nullptr, "put to call site target field");
67 return;
68 }
69
70 if (C->needs_clinit_barrier(field, method())) {
71 clinit_barrier(field_holder, method());
72 if (stopped()) return;
73 }
74
75 assert(field->will_link(method(), bc()), "getfield: typeflow responsibility");
76
77 // Note: We do not check for an unloaded field type here any more.
78
79 // Generate code for the object pointer.
80 Node* obj;
81 if (is_field) {
82 int obj_depth = is_get ? 0 : field->type()->size();
83 obj = null_check(peek(obj_depth));
84 // Compile-time detect of null-exception?
85 if (stopped()) return;
86
87 #ifdef ASSERT
88 const TypeInstPtr *tjp = TypeInstPtr::make(TypePtr::NotNull, iter().get_declared_field_holder());
89 assert(_gvn.type(obj)->higher_equal(tjp), "cast_up is no longer needed");
90 #endif
91
92 if (is_get) {
93 do_get_xxx(obj, field);
94 } else {
95 do_put_xxx(obj, field, is_field);
96 if (stopped()) {
97 return;
98 }
99 (void) pop(); // pop receiver after putting
100 }
101 } else {
102 const TypeInstPtr* tip = TypeInstPtr::make(field_holder->java_mirror());
103 obj = _gvn.makecon(tip);
104 if (is_get) {
105 do_get_xxx(obj, field);
106 } else {
107 do_put_xxx(obj, field, is_field);
108 }
109 }
110 }
111
112 void Parse::do_get_xxx(Node* obj, ciField* field) {
113 BasicType bt = field->layout_type();
114 // Does this field have a constant value? If so, just push the value.
115 if (field->is_constant() && !field->is_flat() &&
116 // Keep consistent with types found by ciTypeFlow: for an
117 // unloaded field type, ciTypeFlow::StateVector::do_getstatic()
118 // speculates the field is null. The code in the rest of this
119 // method does the same. We must not bypass it and use a non
120 // null constant here.
121 (bt != T_OBJECT || field->type()->is_loaded())) {
122 // final or stable field
123 Node* con = make_constant_from_field(field, obj);
124 if (con != nullptr) {
125 if (!field->is_static()) {
126 pop();
127 }
128 push_node(field->layout_type(), con);
129 return;
130 }
131 }
132
133 if (obj->is_InlineType()) {
134 assert(!field->is_static(), "must not be a static field");
135 InlineTypeNode* vt = obj->as_InlineType();
136 Node* value = vt->field_value_by_offset(field->offset_in_bytes(), false);
137 const Type* value_type = _gvn.type(value);
138 if (value->is_InlineType()) {
139 value = value->as_InlineType()->adjust_scalarization_depth(this);
140 } else if (value_type->is_inlinetypeptr()) {
141 value = InlineTypeNode::make_from_oop(this, value, value_type->inline_klass());
142 }
143 pop();
144 push_node(field->layout_type(), value);
145 return;
146 }
147
148 ciType* field_klass = field->type();
149 field_klass = improve_abstract_inline_type_klass(field_klass);
150 int offset = field->offset_in_bytes();
151 bool must_assert_null = false;
152 Node* adr = basic_plus_adr(obj, obj, offset);
153 assert(C->get_alias_index(C->alias_type(field)->adr_type()) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
154 "slice of address and input slice don't match");
155
156 Node* ld = nullptr;
157 if (field->is_null_free() && field_klass->as_inline_klass()->is_empty()) {
158 // Loading from a field of an empty inline type. Just return the default instance.
159 ld = InlineTypeNode::make_all_zero(_gvn, field_klass->as_inline_klass());
160 } else if (field->is_flat()) {
161 // Loading from a flat inline type field.
162 ciInlineKlass* vk = field->type()->as_inline_klass();
163 bool is_immutable = field->is_final() && field->is_strict();
164 bool atomic = field->is_atomic();
165 ld = InlineTypeNode::make_from_flat(this, field_klass->as_inline_klass(), obj, adr, atomic, is_immutable, field->is_null_free(), IN_HEAP | MO_UNORDERED);
166 } else {
167 // Build the resultant type of the load
168 const Type* type;
169 if (is_reference_type(bt)) {
170 if (!field_klass->is_loaded()) {
171 type = TypeInstPtr::BOTTOM;
172 must_assert_null = true;
173 } else if (field->is_static_constant()) {
174 // This can happen if the constant oop is non-perm.
175 ciObject* con = field->constant_value().as_object();
176 // Do not "join" in the previous type; it doesn't add value,
177 // and may yield a vacuous result if the field is of interface type.
178 if (con->is_null_object()) {
179 type = TypePtr::NULL_PTR;
180 } else {
181 type = TypeOopPtr::make_from_constant(con)->isa_oopptr();
182 }
183 assert(type != nullptr, "field singleton type must be consistent");
184 } else {
185 type = TypeOopPtr::make_from_klass(field_klass->as_klass());
186 if (field->is_null_free()) {
187 type = type->join_speculative(TypePtr::NOTNULL);
188 }
189 }
190 } else {
191 type = Type::get_const_basic_type(bt);
192 }
193
194 const TypePtr* adr_type = C->alias_type(field)->adr_type();
195 DecoratorSet decorators = IN_HEAP;
196 decorators |= field->is_volatile() ? MO_SEQ_CST : MO_UNORDERED;
197 ld = access_load_at(obj, adr, adr_type, type, bt, decorators);
198 if (field_klass->is_inlinetype()) {
199 // Load a non-flattened inline type from memory
200 ld = InlineTypeNode::make_from_oop(this, ld, field_klass->as_inline_klass());
201 }
202 }
203
204 // Adjust Java stack
205 if (!field->is_static()) {
206 pop();
207 }
208 if (type2size[bt] == 1) {
209 push(ld);
210 } else {
211 push_pair(ld);
212 }
213
214 if (must_assert_null) {
215 // Do not take a trap here. It's possible that the program
216 // will never load the field's class, and will happily see
217 // null values in this field forever. Don't stumble into a
218 // trap for such a program, or we might get a long series
219 // of useless recompilations. (Or, we might load a class
220 // which should not be loaded.) If we ever see a non-null
221 // value, we will then trap and recompile. (The trap will
222 // not need to mention the class index, since the class will
223 // already have been loaded if we ever see a non-null value.)
224 // uncommon_trap(iter().get_field_signature_index());
225 if (PrintOpto && (Verbose || WizardMode)) {
226 method()->print_name(); tty->print_cr(" asserting nullness of field at bci: %d", bci());
227 }
228 if (C->log() != nullptr) {
229 C->log()->elem("assert_null reason='field' klass='%d'",
230 C->log()->identify(field_klass));
231 }
232 // If there is going to be a trap, put it at the next bytecode:
233 set_bci(iter().next_bci());
234 null_assert(peek());
235 set_bci(iter().cur_bci()); // put it back
236 }
237 }
238
239 // If the field klass is an abstract value klass (for which we do not know the layout, yet), it could have a unique
240 // concrete sub klass for which we have a fixed layout. This allows us to use InlineTypeNodes instead.
241 ciType* Parse::improve_abstract_inline_type_klass(ciType* field_klass) {
242 Dependencies* dependencies = C->dependencies();
243 if (UseUniqueSubclasses && dependencies != nullptr && field_klass->is_instance_klass()) {
244 ciInstanceKlass* instance_klass = field_klass->as_instance_klass();
245 if (instance_klass->is_loaded() && instance_klass->is_abstract_value_klass()) {
246 ciInstanceKlass* sub_klass = instance_klass->unique_concrete_subklass();
247 if (sub_klass != nullptr && sub_klass != field_klass) {
248 field_klass = sub_klass;
249 dependencies->assert_abstract_with_unique_concrete_subtype(instance_klass, sub_klass);
250 }
251 }
252 }
253 return field_klass;
254 }
255
256 void Parse::do_put_xxx(Node* obj, ciField* field, bool is_field) {
257 bool is_vol = field->is_volatile();
258 int offset = field->offset_in_bytes();
259
260 BasicType bt = field->layout_type();
261 Node* val = type2size[bt] == 1 ? pop() : pop_pair();
262 if (field->is_null_free()) {
263 PreserveReexecuteState preexecs(this);
264 jvms()->set_should_reexecute(true);
265 inc_sp(1);
266 val = null_check(val);
267 if (stopped()) {
268 return;
269 }
270 }
271
272 Node* adr = basic_plus_adr(obj, obj, offset);
273
274 // We cannot store into a non-larval object, so obj must not be an InlineTypeNode
275 assert(!obj->is_InlineType(), "InlineTypeNodes are non-larval value objects");
276 if (field->is_null_free() && field->type()->as_inline_klass()->is_empty() && (!method()->is_object_constructor() || field->is_flat())) {
277 // Storing to a field of an empty, null-free inline type that is already initialized. Ignore.
278 return;
279 } else if (field->is_flat()) {
280 // Storing to a flat inline type field.
281 ciInlineKlass* vk = field->type()->as_inline_klass();
282 if (!val->is_InlineType()) {
283 assert(gvn().type(val) == TypePtr::NULL_PTR, "Unexpected value");
284 val = InlineTypeNode::make_null(gvn(), vk);
285 }
286 inc_sp(1);
287 bool is_immutable = field->is_final() && field->is_strict();
288 bool atomic = field->is_atomic();
289 val->as_InlineType()->store_flat(this, obj, adr, atomic, is_immutable, field->is_null_free(), IN_HEAP | MO_UNORDERED);
290 dec_sp(1);
291 } else {
292 // Store the value.
293 const Type* field_type;
294 if (!field->type()->is_loaded()) {
295 field_type = TypeInstPtr::BOTTOM;
296 } else {
297 if (is_reference_type(bt)) {
298 field_type = TypeOopPtr::make_from_klass(field->type()->as_klass());
299 } else {
300 field_type = Type::BOTTOM;
301 }
302 }
303
304 const TypePtr* adr_type = C->alias_type(field)->adr_type();
305 assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
306 "slice of address and input slice don't match");
307 DecoratorSet decorators = IN_HEAP;
308 decorators |= is_vol ? MO_SEQ_CST : MO_UNORDERED;
309 inc_sp(1);
310 access_store_at(obj, adr, adr_type, val, field_type, bt, decorators);
311 dec_sp(1);
312 }
313
314 if (is_field) {
315 // Remember we wrote a volatile field.
316 // For not multiple copy atomic cpu (ppc64) a barrier should be issued
317 // in constructors which have such stores. See do_exits() in parse1.cpp.
318 if (is_vol) {
319 set_wrote_volatile(true);
320 }
321 set_wrote_fields(true);
322
323 // If the field is final, the rules of Java say we are in <init> or <clinit>.
324 // If the field is @Stable, we can be in any method, but we only care about
325 // constructors at this point.
326 //
327 // Note the presence of writes to final/@Stable non-static fields, so that we
328 // can insert a memory barrier later on to keep the writes from floating
329 // out of the constructor.
330 if (field->is_final() || field->is_stable()) {
331 if (field->is_final()) {
332 set_wrote_final(true);
333 }
334 if (field->is_stable()) {
335 set_wrote_stable(true);
336 }
337 if (AllocateNode::Ideal_allocation(obj) != nullptr) {
338 // Preserve allocation ptr to create precedent edge to it in membar
339 // generated on exit from constructor.
340 set_alloc_with_final_or_stable(obj);
341 }
342 }
343 }
344 }
345
346 //=============================================================================
347
348 void Parse::do_newarray() {
349 bool will_link;
350 ciKlass* klass = iter().get_klass(will_link);
351
352 // Uncommon Trap when class that array contains is not loaded
353 // we need the loaded class for the rest of graph; do not
354 // initialize the container class (see Java spec)!!!
355 assert(will_link, "newarray: typeflow responsibility");
356
357 ciArrayKlass* array_klass = ciArrayKlass::make(klass);
358
359 // Check that array_klass object is loaded
360 if (!array_klass->is_loaded()) {
361 // Generate uncommon_trap for unloaded array_class
362 uncommon_trap(Deoptimization::Reason_unloaded,
363 Deoptimization::Action_reinterpret,
364 array_klass);
365 return;
366 } else if (array_klass->element_klass() != nullptr &&
367 array_klass->element_klass()->is_inlinetype() &&
368 !array_klass->element_klass()->as_inline_klass()->is_initialized()) {
369 uncommon_trap(Deoptimization::Reason_uninitialized,
370 Deoptimization::Action_reinterpret,
371 nullptr);
372 return;
373 }
374
375 kill_dead_locals();
376
377 const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
378 array_klass_type = array_klass_type->cast_to_refined_array_klass_ptr();
379 Node* count_val = pop();
380 Node* obj = new_array(makecon(array_klass_type), count_val, 1);
381 push(obj);
382 }
383
384
385 void Parse::do_newarray(BasicType elem_type) {
386 kill_dead_locals();
387
388 Node* count_val = pop();
389 const TypeKlassPtr* array_klass = TypeKlassPtr::make(ciTypeArrayKlass::make(elem_type));
390 Node* obj = new_array(makecon(array_klass), count_val, 1);
391 // Push resultant oop onto stack
392 push(obj);
393 }
394
395 // Expand simple expressions like new int[3][5] and new Object[2][nonConLen].
396 // Also handle the degenerate 1-dimensional case of anewarray.
397 Node* Parse::expand_multianewarray(ciArrayKlass* array_klass, Node* *lengths, int ndimensions, int nargs) {
398 Node* length = lengths[0];
399 assert(length != nullptr, "");
400 const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
401 array_klass_type = array_klass_type->cast_to_refined_array_klass_ptr();
402 Node* array = new_array(makecon(array_klass_type), length, nargs);
403 if (ndimensions > 1) {
404 jint length_con = find_int_con(length, -1);
405 guarantee(length_con >= 0, "non-constant multianewarray");
406 ciArrayKlass* array_klass_1 = array_klass->as_obj_array_klass()->element_klass()->as_array_klass();
407 const TypePtr* adr_type = TypeAryPtr::OOPS;
408 const TypeOopPtr* elemtype = _gvn.type(array)->is_aryptr()->elem()->make_oopptr();
409 const intptr_t header = arrayOopDesc::base_offset_in_bytes(T_OBJECT);
410 for (jint i = 0; i < length_con; i++) {
411 Node* elem = expand_multianewarray(array_klass_1, &lengths[1], ndimensions-1, nargs);
412 intptr_t offset = header + ((intptr_t)i << LogBytesPerHeapOop);
413 Node* eaddr = basic_plus_adr(array, offset);
414 access_store_at(array, eaddr, adr_type, elem, elemtype, T_OBJECT, IN_HEAP | IS_ARRAY);
415 }
416 }
417 return array;
418 }
419
420 void Parse::do_multianewarray() {
421 int ndimensions = iter().get_dimensions();
422
423 // the m-dimensional array
424 bool will_link;
425 ciArrayKlass* array_klass = iter().get_klass(will_link)->as_array_klass();
426 assert(will_link, "multianewarray: typeflow responsibility");
427
428 // Note: Array classes are always initialized; no is_initialized check.
429
430 kill_dead_locals();
431
432 // get the lengths from the stack (first dimension is on top)
433 Node** length = NEW_RESOURCE_ARRAY(Node*, ndimensions + 1);
434 length[ndimensions] = nullptr; // terminating null for make_runtime_call
435 int j;
436 ciKlass* elem_klass = array_klass;
437 for (j = ndimensions-1; j >= 0; j--) {
438 length[j] = pop();
439 elem_klass = elem_klass->as_array_klass()->element_klass();
440 }
441 if (elem_klass != nullptr && elem_klass->is_inlinetype() && !elem_klass->as_inline_klass()->is_initialized()) {
442 inc_sp(ndimensions);
443 uncommon_trap(Deoptimization::Reason_uninitialized,
444 Deoptimization::Action_reinterpret,
445 nullptr);
446 return;
447 }
448
449 // The original expression was of this form: new T[length0][length1]...
450 // It is often the case that the lengths are small (except the last).
451 // If that happens, use the fast 1-d creator a constant number of times.
452 const int expand_limit = MIN2((int)MultiArrayExpandLimit, 100);
453 int64_t expand_count = 1; // count of allocations in the expansion
454 int64_t expand_fanout = 1; // running total fanout
455 for (j = 0; j < ndimensions-1; j++) {
456 int dim_con = find_int_con(length[j], -1);
457 // To prevent overflow, we use 64-bit values. Alternatively,
458 // we could clamp dim_con like so:
459 // dim_con = MIN2(dim_con, expand_limit);
460 expand_fanout *= dim_con;
461 expand_count += expand_fanout; // count the level-J sub-arrays
462 if (dim_con <= 0
463 || dim_con > expand_limit
464 || expand_count > expand_limit) {
465 expand_count = 0;
466 break;
467 }
468 }
469
470 // Can use multianewarray instead of [a]newarray if only one dimension,
471 // or if all non-final dimensions are small constants.
472 if (ndimensions == 1 || (1 <= expand_count && expand_count <= expand_limit)) {
473 Node* obj = nullptr;
474 // Set the original stack and the reexecute bit for the interpreter
475 // to reexecute the multianewarray bytecode if deoptimization happens.
476 // Do it unconditionally even for one dimension multianewarray.
477 // Note: the reexecute bit will be set in GraphKit::add_safepoint_edges()
478 // when AllocateArray node for newarray is created.
479 { PreserveReexecuteState preexecs(this);
480 inc_sp(ndimensions);
481 // Pass 0 as nargs since uncommon trap code does not need to restore stack.
482 obj = expand_multianewarray(array_klass, &length[0], ndimensions, 0);
483 } //original reexecute and sp are set back here
484 push(obj);
485 return;
486 }
487
488 address fun = nullptr;
489 switch (ndimensions) {
490 case 1: ShouldNotReachHere(); break;
491 case 2: fun = OptoRuntime::multianewarray2_Java(); break;
492 case 3: fun = OptoRuntime::multianewarray3_Java(); break;
493 case 4: fun = OptoRuntime::multianewarray4_Java(); break;
494 case 5: fun = OptoRuntime::multianewarray5_Java(); break;
495 };
496 Node* c = nullptr;
497
498 if (fun != nullptr) {
499 c = make_runtime_call(RC_NO_LEAF | RC_NO_IO,
500 OptoRuntime::multianewarray_Type(ndimensions),
501 fun, nullptr, TypeRawPtr::BOTTOM,
502 makecon(TypeKlassPtr::make(array_klass, Type::trust_interfaces)),
503 length[0], length[1], length[2],
504 (ndimensions > 2) ? length[3] : nullptr,
505 (ndimensions > 3) ? length[4] : nullptr);
506 } else {
507 // Create a java array for dimension sizes
508 Node* dims = nullptr;
509 { PreserveReexecuteState preexecs(this);
510 inc_sp(ndimensions);
511 Node* dims_array_klass = makecon(TypeKlassPtr::make(ciArrayKlass::make(ciType::make(T_INT))));
512 dims = new_array(dims_array_klass, intcon(ndimensions), 0);
513
514 // Fill-in it with values
515 for (j = 0; j < ndimensions; j++) {
516 Node *dims_elem = array_element_address(dims, intcon(j), T_INT);
517 store_to_memory(control(), dims_elem, length[j], T_INT, MemNode::unordered);
518 }
519 }
520
521 c = make_runtime_call(RC_NO_LEAF | RC_NO_IO,
522 OptoRuntime::multianewarrayN_Type(),
523 OptoRuntime::multianewarrayN_Java(), nullptr, TypeRawPtr::BOTTOM,
524 makecon(TypeKlassPtr::make(array_klass, Type::trust_interfaces)),
525 dims);
526 }
527 make_slow_call_ex(c, env()->Throwable_klass(), false);
528
529 Node* res = _gvn.transform(new ProjNode(c, TypeFunc::Parms));
530
531 const Type* type = TypeOopPtr::make_from_klass_raw(array_klass, Type::trust_interfaces);
532
533 // Improve the type: We know it's not null, exact, and of a given length.
534 type = type->is_ptr()->cast_to_ptr_type(TypePtr::NotNull);
535 type = type->is_aryptr()->cast_to_exactness(true);
536
537 const TypeInt* ltype = _gvn.find_int_type(length[0]);
538 if (ltype != nullptr)
539 type = type->is_aryptr()->cast_to_size(ltype);
540
541 // We cannot sharpen the nested sub-arrays, since the top level is mutable.
542
543 Node* cast = _gvn.transform( new CheckCastPPNode(control(), res, type) );
544 push(cast);
545
546 // Possible improvements:
547 // - Make a fast path for small multi-arrays. (W/ implicit init. loops.)
548 // - Issue CastII against length[*] values, to TypeInt::POS.
549 }