1 /*
2 * Copyright (c) 2017, 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 "cds/archiveUtils.hpp"
26 #include "cds/cdsConfig.hpp"
27 #include "classfile/vmSymbols.hpp"
28 #include "code/codeCache.hpp"
29 #include "gc/shared/barrierSet.hpp"
30 #include "gc/shared/collectedHeap.inline.hpp"
31 #include "gc/shared/gcLocker.inline.hpp"
32 #include "interpreter/interpreter.hpp"
33 #include "logging/log.hpp"
34 #include "memory/metadataFactory.hpp"
35 #include "memory/metaspaceClosure.hpp"
36 #include "oops/access.hpp"
37 #include "oops/arrayKlass.hpp"
38 #include "oops/compressedOops.inline.hpp"
39 #include "oops/fieldStreams.inline.hpp"
40 #include "oops/flatArrayKlass.hpp"
41 #include "oops/inlineKlass.inline.hpp"
42 #include "oops/instanceKlass.inline.hpp"
43 #include "oops/layoutKind.hpp"
44 #include "oops/method.hpp"
45 #include "oops/objArrayKlass.hpp"
46 #include "oops/oop.inline.hpp"
47 #include "oops/oopsHierarchy.hpp"
48 #include "oops/refArrayKlass.hpp"
49 #include "runtime/fieldDescriptor.inline.hpp"
50 #include "runtime/handles.inline.hpp"
51 #include "runtime/interfaceSupport.inline.hpp"
52 #include "runtime/registerMap.hpp"
53 #include "runtime/safepointVerifiers.hpp"
54 #include "runtime/sharedRuntime.hpp"
55 #include "runtime/signature.hpp"
56 #include "runtime/thread.inline.hpp"
57 #include "utilities/copy.hpp"
58 #include "utilities/stringUtils.hpp"
59
60 InlineKlass::Members::Members()
61 : _extended_sig(nullptr),
62 _return_regs(nullptr),
63 _pack_handler(nullptr),
64 _pack_handler_jobject(nullptr),
65 _unpack_handler(nullptr),
66 _null_reset_value_offset(0),
67 _payload_offset(-1),
68 _payload_size_in_bytes(-1),
69 _payload_alignment(-1),
70 _null_free_non_atomic_size_in_bytes(-1),
71 _null_free_non_atomic_alignment(-1),
72 _null_free_atomic_size_in_bytes(-1),
73 _nullable_atomic_size_in_bytes(-1),
74 _nullable_non_atomic_size_in_bytes(-1),
75 _null_marker_offset(-1) {
76 }
77
78 InlineKlass::InlineKlass() {
79 assert(CDSConfig::is_dumping_archive() || UseSharedSpaces, "only for CDS");
80 }
81
82 // Constructor
83 InlineKlass::InlineKlass(const ClassFileParser& parser)
84 : InstanceKlass(parser, InlineKlass::Kind, markWord::inline_type_prototype()) {
85 assert(is_inline_klass(), "sanity");
86 assert(prototype_header().is_inline_type(), "sanity");
87
88 // Set up the offset to the members of this klass
89 _adr_inline_klass_members = calculate_members_address();
90
91 // Placement install the members
92 new (_adr_inline_klass_members) Members();
93
94 // Sanity check construction of the members
95 assert(pack_handler() == nullptr, "pack handler not null");
96 }
97
98 address InlineKlass::calculate_members_address() const {
99 // The members are placed after all other contents inherited from the InstanceKlass
100 return end_of_instance_klass();
101 }
102
103 oop InlineKlass::null_reset_value() const {
104 assert(is_initialized() || is_being_initialized() || is_in_error_state(), "null reset value is set at the beginning of initialization");
105 oop val = java_mirror()->obj_field_acquire(null_reset_value_offset());
106 assert(val != nullptr, "Sanity check");
107 return val;
108 }
109
110 void InlineKlass::set_null_reset_value(oop val) {
111 assert(val != nullptr, "Sanity check");
112 assert(oopDesc::is_oop(val), "Sanity check");
113 assert(val->is_inline_type(), "Sanity check");
114 assert(val->klass() == this, "sanity check");
115 java_mirror()->obj_field_put(null_reset_value_offset(), val);
116 }
117
118 inlineOop InlineKlass::allocate_instance(TRAPS) {
119 inlineOop oop = (inlineOop)InstanceKlass::allocate_instance(CHECK_NULL);
120 assert(oop->mark().is_inline_type(), "Expected inline type");
121 return oop;
122 }
123
124 int InlineKlass::nonstatic_oop_count() {
125 int oops = 0;
126 int map_count = nonstatic_oop_map_count();
127 OopMapBlock* block = start_of_nonstatic_oop_maps();
128 OopMapBlock* end = block + map_count;
129 while (block != end) {
130 oops += block->count();
131 block++;
132 }
133 return oops;
134 }
135
136 // Arrays of...
137
138 bool InlineKlass::maybe_flat_in_array() {
139 if (!UseArrayFlattening) {
140 return false;
141 }
142 // Too many embedded oops
143 if ((FlatArrayElementMaxOops >= 0) && (nonstatic_oop_count() > FlatArrayElementMaxOops)) {
144 return false;
145 }
146 // No flat layout?
147 if (!has_nullable_atomic_layout() && !has_null_free_atomic_layout() && !has_null_free_non_atomic_layout()) {
148 return false;
149 }
150 return true;
151 }
152
153 bool InlineKlass::is_always_flat_in_array() {
154 if (!UseArrayFlattening) {
155 return false;
156 }
157 // Too many embedded oops
158 if ((FlatArrayElementMaxOops >= 0) && (nonstatic_oop_count() > FlatArrayElementMaxOops)) {
159 return false;
160 }
161
162 // An instance is always flat in an array if we have all layouts. Note that this could change in the future when the
163 // flattening policies are updated or if new APIs are added that allow the creation of reference arrays directly.
164 return has_nullable_atomic_layout() && has_null_free_atomic_layout() && has_null_free_non_atomic_layout();
165 }
166
167 // Inline type arguments are not passed by reference, instead each
168 // field of the inline type is passed as an argument. This helper
169 // function collects the flat field (recursively)
170 // in a list. Included with the field's type is
171 // the offset of each field in the inline type: i2c and c2i adapters
172 // need that to load or store fields. Finally, the list of fields is
173 // sorted in order of increasing offsets: the adapters and the
174 // compiled code need to agree upon the order of fields.
175 //
176 // The list of basic types that is returned starts with a T_METADATA
177 // and ends with an extra T_VOID. T_METADATA/T_VOID pairs are used as
178 // delimiters. Every entry between the two is a field of the inline
179 // type. If there's an embedded inline type in the list, it also starts
180 // with a T_METADATA and ends with a T_VOID. This is so we can
181 // generate a unique fingerprint for the method's adapters and we can
182 // generate the list of basic types from the interpreter point of view
183 // (inline types passed as reference: iterate on the list until a
184 // T_METADATA, drop everything until and including the closing
185 // T_VOID) or the compiler point of view (each field of the inline
186 // types is an argument: drop all T_METADATA/T_VOID from the list).
187 //
188 // Value classes could also have fields in abstract super value classes.
189 // Use a HierarchicalFieldStream to get them as well.
190 int InlineKlass::collect_fields(GrowableArray<SigEntry>* sig, int base_off, int null_marker_offset) {
191 int count = 0;
192 SigEntry::add_entry(sig, T_METADATA, name(), base_off);
193 for (TopDownHierarchicalNonStaticFieldStreamBase fs(this); !fs.done(); fs.next()) {
194 assert(!fs.access_flags().is_static(), "TopDownHierarchicalNonStaticFieldStreamBase should not let static fields pass.");
195 int offset = base_off + fs.offset() - (base_off > 0 ? payload_offset() : 0);
196 InstanceKlass* field_holder = fs.field_descriptor().field_holder();
197 // TODO 8284443 Use different heuristic to decide what should be scalarized in the calling convention
198 if (fs.is_flat()) {
199 // Resolve klass of flat field and recursively collect fields
200 int field_null_marker_offset = -1;
201 if (!fs.is_null_free_inline_type()) {
202 field_null_marker_offset = base_off + fs.null_marker_offset() - (base_off > 0 ? payload_offset() : 0);
203 }
204 Klass* vk = field_holder->get_inline_type_field_klass(fs.index());
205 count += InlineKlass::cast(vk)->collect_fields(sig, offset, field_null_marker_offset);
206 } else {
207 BasicType bt = Signature::basic_type(fs.signature());
208 SigEntry::add_entry(sig, bt, fs.name(), offset);
209 count += type2size[bt];
210 }
211 }
212 int offset = base_off + size_helper()*HeapWordSize - (base_off > 0 ? payload_offset() : 0);
213 // Null markers are no real fields, add them manually at the end (C2 relies on this) of the flat fields
214 if (null_marker_offset != -1) {
215 SigEntry::add_null_marker(sig, name(), null_marker_offset);
216 count++;
217 }
218 SigEntry::add_entry(sig, T_VOID, name(), offset);
219 assert(sig->at(0)._bt == T_METADATA && sig->at(sig->length()-1)._bt == T_VOID, "broken structure");
220 return count;
221 }
222
223 void InlineKlass::initialize_calling_convention(TRAPS) {
224 // Because the pack and unpack handler addresses need to be loadable from generated code,
225 // they are stored at a fixed offset in the klass metadata. Since inline type klasses do
226 // not have a vtable, the vtable offset is used to store these addresses.
227 if (InlineTypeReturnedAsFields || InlineTypePassFieldsAsArgs) {
228 ResourceMark rm;
229 GrowableArray<SigEntry> sig_vk;
230 int nb_fields = collect_fields(&sig_vk);
231 if (*PrintInlineKlassFields != '\0') {
232 const char* class_name_str = _name->as_C_string();
233 if (StringUtils::class_list_match(PrintInlineKlassFields, class_name_str)) {
234 ttyLocker ttyl;
235 tty->print_cr("Fields of InlineKlass: %s", class_name_str);
236 for (const SigEntry& entry : sig_vk) {
237 tty->print(" %s: %s+%d", entry._name->as_C_string(), type2name(entry._bt), entry._offset);
238 if (entry._null_marker) {
239 tty->print(" (null marker)");
240 }
241 tty->print_cr("");
242 }
243 }
244 }
245 Array<SigEntry>* extended_sig = MetadataFactory::new_array<SigEntry>(class_loader_data(), sig_vk.length(), CHECK);
246 set_extended_sig(extended_sig);
247 for (int i = 0; i < sig_vk.length(); i++) {
248 extended_sig->at_put(i, sig_vk.at(i));
249 }
250 if (can_be_returned_as_fields(/* init= */ true)) {
251 nb_fields++;
252 BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, nb_fields);
253 sig_bt[0] = T_METADATA;
254 SigEntry::fill_sig_bt(&sig_vk, sig_bt+1);
255 VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, nb_fields);
256 int total = SharedRuntime::java_return_convention(sig_bt, regs, nb_fields);
257
258 if (total > 0) {
259 Array<VMRegPair>* return_regs = MetadataFactory::new_array<VMRegPair>(class_loader_data(), nb_fields, CHECK);
260 set_return_regs(return_regs);
261 for (int i = 0; i < nb_fields; i++) {
262 return_regs->at_put(i, regs[i]);
263 }
264
265 BufferedInlineTypeBlob* buffered_blob = SharedRuntime::generate_buffered_inline_type_adapter(this);
266 if (buffered_blob == nullptr) {
267 THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "Out of space in CodeCache for adapters");
268 }
269 set_pack_handler(buffered_blob->pack_fields());
270 set_pack_handler_jobject(buffered_blob->pack_fields_jobject());
271 set_unpack_handler(buffered_blob->unpack_fields());
272 assert(CodeCache::find_blob(pack_handler()) == buffered_blob, "lost track of blob");
273 assert(can_be_returned_as_fields(), "sanity");
274 }
275 }
276 if (!can_be_returned_as_fields() && !can_be_passed_as_fields()) {
277 MetadataFactory::free_array<SigEntry>(class_loader_data(), extended_sig);
278 assert(return_regs() == nullptr, "sanity");
279 }
280 }
281 }
282
283 void InlineKlass::deallocate_contents(ClassLoaderData* loader_data) {
284 if (extended_sig() != nullptr) {
285 MetadataFactory::free_array<SigEntry>(loader_data, members()._extended_sig);
286 set_extended_sig(nullptr);
287 }
288 if (return_regs() != nullptr) {
289 MetadataFactory::free_array<VMRegPair>(loader_data, members()._return_regs);
290 set_return_regs(nullptr);
291 }
292 cleanup_blobs();
293 InstanceKlass::deallocate_contents(loader_data);
294 }
295
296 void InlineKlass::cleanup(InlineKlass* ik) {
297 ik->cleanup_blobs();
298 }
299
300 void InlineKlass::cleanup_blobs() {
301 if (pack_handler() != nullptr) {
302 CodeBlob* buffered_blob = CodeCache::find_blob(pack_handler());
303 assert(buffered_blob->is_buffered_inline_type_blob(), "bad blob type");
304 BufferBlob::free((BufferBlob*)buffered_blob);
305 set_pack_handler(nullptr);
306 set_pack_handler_jobject(nullptr);
307 set_unpack_handler(nullptr);
308 }
309 }
310
311 // Can this inline type be passed as multiple values?
312 bool InlineKlass::can_be_passed_as_fields() const {
313 return InlineTypePassFieldsAsArgs;
314 }
315
316 // Can this inline type be returned as multiple values?
317 bool InlineKlass::can_be_returned_as_fields(bool init) const {
318 return InlineTypeReturnedAsFields && (init || return_regs() != nullptr);
319 }
320
321 // Create handles for all oop fields returned in registers that are going to be live across a safepoint
322 void InlineKlass::save_oop_fields(const RegisterMap& reg_map, GrowableArray<Handle>& handles) const {
323 Thread* thread = Thread::current();
324 const Array<SigEntry>* sig_vk = extended_sig();
325 const Array<VMRegPair>* regs = return_regs();
326 int j = 1;
327
328 for (int i = 0; i < sig_vk->length(); i++) {
329 BasicType bt = sig_vk->at(i)._bt;
330 if (bt == T_OBJECT || bt == T_ARRAY) {
331 VMRegPair pair = regs->at(j);
332 oop* loc = (oop*)reg_map.location(pair.first(), nullptr);
333 guarantee(loc != nullptr, "bad register save location");
334 oop o = *loc;
335 assert(oopDesc::is_oop_or_null(o), "Bad oop value: " PTR_FORMAT, p2i(o));
336 handles.push(Handle(thread, o));
337 }
338 if (bt == T_METADATA) {
339 continue;
340 }
341 if (bt == T_VOID &&
342 sig_vk->at(i-1)._bt != T_LONG &&
343 sig_vk->at(i-1)._bt != T_DOUBLE) {
344 continue;
345 }
346 j++;
347 }
348 assert(j == regs->length(), "missed a field?");
349 }
350
351 // Update oop fields in registers from handles after a safepoint
352 void InlineKlass::restore_oop_results(RegisterMap& reg_map, GrowableArray<Handle>& handles) const {
353 assert(InlineTypeReturnedAsFields, "Inline types should never be returned as fields");
354 const Array<SigEntry>* sig_vk = extended_sig();
355 const Array<VMRegPair>* regs = return_regs();
356 assert(regs != nullptr, "inconsistent");
357
358 int j = 1;
359 int k = 0;
360 for (int i = 0; i < sig_vk->length(); i++) {
361 BasicType bt = sig_vk->at(i)._bt;
362 if (bt == T_OBJECT || bt == T_ARRAY) {
363 VMRegPair pair = regs->at(j);
364 oop* loc = (oop*)reg_map.location(pair.first(), nullptr);
365 guarantee(loc != nullptr, "bad register save location");
366 *loc = handles.at(k++)();
367 }
368 if (bt == T_METADATA) {
369 continue;
370 }
371 if (bt == T_VOID &&
372 sig_vk->at(i-1)._bt != T_LONG &&
373 sig_vk->at(i-1)._bt != T_DOUBLE) {
374 continue;
375 }
376 j++;
377 }
378 assert(k == handles.length(), "missed a handle?");
379 assert(j == regs->length(), "missed a field?");
380 }
381
382 // Fields are in registers. Create an instance of the inline type and
383 // initialize it with the values of the fields.
384 oop InlineKlass::realloc_result(const RegisterMap& reg_map, const GrowableArray<Handle>& handles, TRAPS) {
385 oop new_vt = allocate_instance(CHECK_NULL);
386 const Array<SigEntry>* sig_vk = extended_sig();
387 const Array<VMRegPair>* regs = return_regs();
388
389 int j = 1;
390 int k = 0;
391 for (int i = 0; i < sig_vk->length(); i++) {
392 BasicType bt = sig_vk->at(i)._bt;
393 if (bt == T_METADATA) {
394 continue;
395 }
396 if (bt == T_VOID) {
397 if (sig_vk->at(i-1)._bt == T_LONG ||
398 sig_vk->at(i-1)._bt == T_DOUBLE) {
399 j++;
400 }
401 continue;
402 }
403 int off = sig_vk->at(i)._offset;
404 assert(off > 0, "offset in object should be positive");
405 VMRegPair pair = regs->at(j);
406 address loc = reg_map.location(pair.first(), nullptr);
407 guarantee(loc != nullptr, "bad register save location");
408 switch(bt) {
409 case T_BOOLEAN: {
410 new_vt->bool_field_put(off, *(jboolean*)loc);
411 break;
412 }
413 case T_CHAR: {
414 new_vt->char_field_put(off, *(jchar*)loc);
415 break;
416 }
417 case T_BYTE: {
418 new_vt->byte_field_put(off, *(jbyte*)loc);
419 break;
420 }
421 case T_SHORT: {
422 new_vt->short_field_put(off, *(jshort*)loc);
423 break;
424 }
425 case T_INT: {
426 new_vt->int_field_put(off, *(jint*)loc);
427 break;
428 }
429 case T_LONG: {
430 #ifdef _LP64
431 new_vt->double_field_put(off, *(jdouble*)loc);
432 #else
433 Unimplemented();
434 #endif
435 break;
436 }
437 case T_OBJECT:
438 case T_ARRAY: {
439 Handle handle = handles.at(k++);
440 new_vt->obj_field_put(off, handle());
441 break;
442 }
443 case T_FLOAT: {
444 new_vt->float_field_put(off, *(jfloat*)loc);
445 break;
446 }
447 case T_DOUBLE: {
448 new_vt->double_field_put(off, *(jdouble*)loc);
449 break;
450 }
451 default:
452 ShouldNotReachHere();
453 }
454 *(intptr_t*)loc = 0xDEAD;
455 j++;
456 }
457 assert(j == regs->length(), "missed a field?");
458 assert(k == handles.length(), "missed an oop?");
459 return new_vt;
460 }
461
462 // Check if we return an inline type in scalarized form, i.e. check if either
463 // - The return value is a tagged InlineKlass pointer, or
464 // - The return value is an inline type oop that is also returned in scalarized form
465 InlineKlass* InlineKlass::returned_inline_klass(const RegisterMap& map, bool* return_oop, Method* method) {
466 BasicType bt = T_METADATA;
467 VMRegPair pair;
468 int nb = SharedRuntime::java_return_convention(&bt, &pair, 1);
469 assert(nb == 1, "broken");
470
471 intptr_t* loc = (intptr_t*)map.location(pair.first(), nullptr);
472 guarantee(loc != nullptr, "bad register save location");
473 intptr_t ptr = *loc;
474 if (is_set_nth_bit(ptr, 0)) {
475 // Return value is tagged, must be an InlineKlass pointer
476 clear_nth_bit(ptr, 0);
477 assert(Metaspace::contains((void*)ptr), "should be klass");
478 InlineKlass* vk = (InlineKlass*)ptr;
479 assert(vk->can_be_returned_as_fields(), "must be able to return as fields");
480 if (return_oop != nullptr) {
481 // Not returning an oop
482 *return_oop = false;
483 }
484 return vk;
485 }
486 // Return value is not tagged, must be a valid oop
487 oop o = cast_to_oop(ptr);
488 assert(oopDesc::is_oop_or_null(o), "Bad oop return: " PTR_FORMAT, ptr);
489 if (return_oop != nullptr && o != nullptr && o->is_inline_type()) {
490 // Check if inline type is also returned in scalarized form
491 InlineKlass* vk_val = InlineKlass::cast(o->klass());
492 InlineKlass* vk_sig = method->returns_inline_type();
493 if (vk_val->can_be_returned_as_fields() && vk_sig != nullptr) {
494 assert(vk_val == vk_sig, "Unexpected return value");
495 return vk_val;
496 }
497 }
498 return nullptr;
499 }
500
501 // CDS support
502 #if INCLUDE_CDS
503
504 void InlineKlass::remove_unshareable_info() {
505 InstanceKlass::remove_unshareable_info();
506
507 // update it to point to the "buffered" copy of this class.
508 _adr_inline_klass_members = calculate_members_address();
509 ArchivePtrMarker::mark_pointer(&_adr_inline_klass_members);
510
511 set_extended_sig(nullptr);
512 set_return_regs(nullptr);
513 set_pack_handler(nullptr);
514 set_pack_handler_jobject(nullptr);
515 set_unpack_handler(nullptr);
516
517 assert(pack_handler() == nullptr, "pack handler not null");
518 }
519
520 #endif // CDS
521
522 void InlineKlass::print_on(outputStream* st) const {
523 InstanceKlass::print_on(st);
524 st->print_cr("- ---- LayoutKinds:");
525 auto print_layout_kind = [&](LayoutKind lk) {
526 if (is_layout_supported(lk)) {
527 st->print_cr("- %s layout: %d/%d",
528 LayoutKindHelper::layout_kind_as_string(lk),
529 layout_size_in_bytes(lk), layout_alignment(lk));
530 } else {
531 st->print_cr("- %s layout: -/-",
532 LayoutKindHelper::layout_kind_as_string(lk));
533 }
534 };
535 print_layout_kind(LayoutKind::BUFFERED);
536 print_layout_kind(LayoutKind::NULL_FREE_NON_ATOMIC_FLAT);
537 print_layout_kind(LayoutKind::NULL_FREE_ATOMIC_FLAT);
538 print_layout_kind(LayoutKind::NULLABLE_ATOMIC_FLAT);
539 print_layout_kind(LayoutKind::NULLABLE_NON_ATOMIC_FLAT);
540 }
541
542 // Verification
543
544 void InlineKlass::verify_on(outputStream* st) {
545 InstanceKlass::verify_on(st);
546 guarantee(prototype_header().is_inline_type(), "Prototype header is not inline type");
547 }
548
549 void InlineKlass::oop_verify_on(oop obj, outputStream* st) {
550 InstanceKlass::oop_verify_on(obj, st);
551 guarantee(obj->mark().is_inline_type(), "Header is not inline type");
552 }