1 /*
  2  * Copyright (c) 1999, 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/ciField.hpp"
 26 #include "ci/ciInlineKlass.hpp"
 27 #include "ci/ciInstance.hpp"
 28 #include "ci/ciInstanceKlass.hpp"
 29 #include "ci/ciUtilities.inline.hpp"
 30 #include "classfile/javaClasses.hpp"
 31 #include "classfile/systemDictionary.hpp"
 32 #include "classfile/vmClasses.hpp"
 33 #include "memory/allocation.hpp"
 34 #include "memory/allocation.inline.hpp"
 35 #include "memory/resourceArea.hpp"
 36 #include "oops/fieldStreams.inline.hpp"
 37 #include "oops/inlineKlass.inline.hpp"
 38 #include "oops/instanceKlass.inline.hpp"
 39 #include "oops/klass.inline.hpp"
 40 #include "oops/oop.inline.hpp"
 41 #include "runtime/arguments.hpp"
 42 #include "runtime/fieldDescriptor.inline.hpp"
 43 #include "runtime/handles.inline.hpp"
 44 #include "runtime/jniHandles.inline.hpp"
 45 
 46 // ciInstanceKlass
 47 //
 48 // This class represents a Klass* in the HotSpot virtual machine
 49 // whose Klass part in an InstanceKlass.
 50 
 51 
 52 // ------------------------------------------------------------------
 53 // ciInstanceKlass::ciInstanceKlass
 54 //
 55 // Loaded instance klass.
 56 ciInstanceKlass::ciInstanceKlass(Klass* k) :
 57   ciKlass(k)
 58 {
 59   assert(get_Klass()->is_instance_klass(), "wrong type");
 60   assert(get_instanceKlass()->is_loaded(), "must be at least loaded");
 61   InstanceKlass* ik = get_instanceKlass();
 62 
 63   AccessFlags access_flags = ik->access_flags();
 64   _flags = ciFlags(access_flags);
 65   _has_finalizer = ik->has_finalizer();
 66   _has_subklass = flags().is_final() ? subklass_false : subklass_unknown;
 67   _init_state = ik->init_state();
 68   _has_nonstatic_fields = ik->has_nonstatic_fields();
 69   _has_nonstatic_concrete_methods = ik->has_nonstatic_concrete_methods();
 70   _is_hidden = ik->is_hidden();
 71   _is_record = ik->is_record();
 72   _declared_nonstatic_fields = nullptr; // initialized lazily by compute_nonstatic_fields
 73   _nonstatic_fields = nullptr;          // initialized lazily by compute_nonstatic_fields
 74   _trust_final_fields = ik->trust_final_fields();
 75   _has_injected_fields = -1;
 76   _implementor = nullptr;               // we will fill these lazily
 77   _transitive_interfaces = nullptr;
 78 
 79   // Ensure that the metadata wrapped by the ciMetadata is kept alive by GC.
 80   // This is primarily useful for metadata which is considered as weak roots
 81   // by the GC but need to be strong roots if reachable from a current compilation.
 82   // InstanceKlass are created for both weak and strong metadata.  Ensuring this metadata
 83   // alive covers the cases where there are weak roots without performance cost.
 84   oop holder = ik->klass_holder();
 85   if (ik->class_loader_data()->has_class_mirror_holder()) {
 86     // Though ciInstanceKlass records class loader oop, it's not enough to keep
 87     // non-strong hidden classes alive (loader == nullptr). Klass holder should
 88     // be used instead. It is enough to record a ciObject, since cached elements are never removed
 89     // during ciObjectFactory lifetime. ciObjectFactory itself is created for
 90     // every compilation and lives for the whole duration of the compilation.
 91     assert(holder != nullptr, "holder of hidden class is the mirror which is never null");
 92     (void)CURRENT_ENV->get_object(holder);
 93   }
 94 
 95   JavaThread *thread = JavaThread::current();
 96   if (ciObjectFactory::is_initialized()) {
 97     _loader = JNIHandles::make_local(thread, ik->class_loader());
 98     _is_shared = false;
 99   } else {
100     Handle h_loader(thread, ik->class_loader());
101     _loader = JNIHandles::make_global(h_loader);
102     _is_shared = true;
103   }
104 
105   _has_trusted_loader = compute_has_trusted_loader();
106 
107   // Lazy fields get filled in only upon request.
108   _super  = nullptr;
109   _java_mirror = nullptr;
110 
111   if (is_shared()) {
112     if (k != vmClasses::Object_klass()) {
113       super();
114     }
115     //compute_nonstatic_fields();  // done outside of constructor
116   }
117 
118   _field_cache = nullptr;
119 }
120 
121 // Version for unloaded classes:
122 ciInstanceKlass::ciInstanceKlass(ciSymbol* name,
123                                  jobject loader,
124                                  BasicType bt)
125   : ciKlass(name, bt)
126 {
127   assert(name->char_at(0) != JVM_SIGNATURE_ARRAY, "not an instance klass");
128   _init_state = (InstanceKlass::ClassState)0;
129   _has_nonstatic_fields = false;
130   _declared_nonstatic_fields = nullptr; // initialized lazily by compute_nonstatic_fields
131   _nonstatic_fields = nullptr;          // initialized lazily by compute_nonstatic_fields
132   _has_injected_fields = -1;
133   _is_hidden = false;
134   _is_record = false;
135   _loader = loader;
136   _is_shared = false;
137   _super = nullptr;
138   _java_mirror = nullptr;
139   _field_cache = nullptr;
140   _has_trusted_loader = compute_has_trusted_loader();
141 }
142 
143 
144 
145 // ------------------------------------------------------------------
146 // ciInstanceKlass::compute_shared_is_initialized
147 void ciInstanceKlass::compute_shared_init_state() {
148   GUARDED_VM_ENTRY(
149     InstanceKlass* ik = get_instanceKlass();
150     _init_state = ik->init_state();
151   )
152 }
153 
154 // ------------------------------------------------------------------
155 // ciInstanceKlass::compute_shared_has_subklass
156 bool ciInstanceKlass::compute_shared_has_subklass() {
157   GUARDED_VM_ENTRY(
158     InstanceKlass* ik = get_instanceKlass();
159     _has_subklass = ik->subklass() != nullptr ? subklass_true : subklass_false;
160     return _has_subklass == subklass_true;
161   )
162 }
163 
164 // ------------------------------------------------------------------
165 // ciInstanceKlass::loader
166 oop ciInstanceKlass::loader() {
167   ASSERT_IN_VM;
168   return JNIHandles::resolve(_loader);
169 }
170 
171 // ------------------------------------------------------------------
172 // ciInstanceKlass::loader_handle
173 jobject ciInstanceKlass::loader_handle() {
174   return _loader;
175 }
176 
177 // ------------------------------------------------------------------
178 // ciInstanceKlass::field_cache
179 //
180 // Get the field cache associated with this klass.
181 ciConstantPoolCache* ciInstanceKlass::field_cache() {
182   if (is_shared()) {
183     return nullptr;
184   }
185   if (_field_cache == nullptr) {
186     assert(!is_java_lang_Object(), "Object has no fields");
187     Arena* arena = CURRENT_ENV->arena();
188     _field_cache = new (arena) ciConstantPoolCache(arena, 5);
189   }
190   return _field_cache;
191 }
192 
193 // ------------------------------------------------------------------
194 // ciInstanceKlass::get_canonical_holder
195 //
196 ciInstanceKlass* ciInstanceKlass::get_canonical_holder(int offset) {
197   #ifdef ASSERT
198   if (!(offset >= 0 && offset < layout_helper_size_in_bytes())) {
199     tty->print("*** get_canonical_holder(%d) on ", offset);
200     this->print();
201     tty->print_cr(" ***");
202   };
203   assert(offset >= 0 && offset < layout_helper_size_in_bytes(), "offset must be tame");
204   #endif
205 
206   if (offset < instanceOopDesc::base_offset_in_bytes()) {
207     // All header offsets belong properly to java/lang/Object.
208     return CURRENT_ENV->Object_klass();
209   }
210 
211   ciInstanceKlass* self = this;
212   assert(self->is_loaded(), "must be loaded to access field info");
213   ciField* field = self->get_field_by_offset(offset, false);
214   if (field != nullptr) {
215     return field->holder();
216   } else {
217     for (;;) {
218       assert(self->is_loaded(), "must be loaded to have size");
219       ciInstanceKlass* super = self->super();
220       if (super == nullptr ||
221           super->nof_nonstatic_fields() == 0 ||
222           super->layout_helper_size_in_bytes() <= offset) {
223         return self;
224       } else {
225         self = super;  // return super->get_canonical_holder(offset)
226       }
227     }
228   }
229 }
230 
231 // ------------------------------------------------------------------
232 // ciInstanceKlass::is_java_lang_Object
233 //
234 // Is this klass java.lang.Object?
235 bool ciInstanceKlass::is_java_lang_Object() const {
236   return equals(CURRENT_ENV->Object_klass());
237 }
238 
239 // ------------------------------------------------------------------
240 // ciInstanceKlass::uses_default_loader
241 bool ciInstanceKlass::uses_default_loader() const {
242   // Note:  We do not need to resolve the handle or enter the VM
243   // in order to test null-ness.
244   return _loader == nullptr;
245 }
246 
247 // ------------------------------------------------------------------
248 
249 /**
250  * Return basic type of boxed value for box klass or T_OBJECT if not.
251  */
252 BasicType ciInstanceKlass::box_klass_type() const {
253   if (uses_default_loader() && is_loaded()) {
254     return vmClasses::box_klass_type(get_Klass());
255   } else {
256     return T_OBJECT;
257   }
258 }
259 
260 /**
261  * Is this boxing klass?
262  */
263 bool ciInstanceKlass::is_box_klass() const {
264   return is_java_primitive(box_klass_type());
265 }
266 
267 /**
268  *  Is this boxed value offset?
269  */
270 bool ciInstanceKlass::is_boxed_value_offset(int offset) const {
271   BasicType bt = box_klass_type();
272   return is_java_primitive(bt) &&
273          (offset == java_lang_boxing_object::value_offset(bt));
274 }
275 
276 // ------------------------------------------------------------------
277 // ciInstanceKlass::is_in_package
278 //
279 // Is this klass in the given package?
280 bool ciInstanceKlass::is_in_package(const char* packagename, int len) {
281   // To avoid class loader mischief, this test always rejects application classes.
282   if (!uses_default_loader())
283     return false;
284   GUARDED_VM_ENTRY(
285     return is_in_package_impl(packagename, len);
286   )
287 }
288 
289 bool ciInstanceKlass::is_in_package_impl(const char* packagename, int len) {
290   ASSERT_IN_VM;
291 
292   // If packagename contains trailing '/' exclude it from the
293   // prefix-test since we test for it explicitly.
294   if (packagename[len - 1] == '/')
295     len--;
296 
297   if (!name()->starts_with(packagename, len))
298     return false;
299 
300   // Test if the class name is something like "java/lang".
301   if ((len + 1) > name()->utf8_length())
302     return false;
303 
304   // Test for trailing '/'
305   if (name()->char_at(len) != '/')
306     return false;
307 
308   // Make sure it's not actually in a subpackage:
309   if (name()->index_of_at(len+1, "/", 1) >= 0)
310     return false;
311 
312   return true;
313 }
314 
315 // ------------------------------------------------------------------
316 // ciInstanceKlass::print_impl
317 //
318 // Implementation of the print method.
319 void ciInstanceKlass::print_impl(outputStream* st) {
320   ciKlass::print_impl(st);
321   GUARDED_VM_ENTRY(st->print(" loader=" INTPTR_FORMAT, p2i(loader()));)
322   if (is_loaded()) {
323     st->print(" initialized=%s finalized=%s subklass=%s size=%d flags=",
324               bool_to_str(is_initialized()),
325               bool_to_str(has_finalizer()),
326               bool_to_str(has_subklass()),
327               layout_helper());
328 
329     _flags.print_klass_flags(st);
330 
331     if (_super) {
332       st->print(" super=");
333       _super->print_name_on(st);
334     }
335     if (_java_mirror) {
336       st->print(" mirror=PRESENT");
337     }
338   }
339 }
340 
341 // ------------------------------------------------------------------
342 // ciInstanceKlass::super
343 //
344 // Get the superklass of this klass.
345 ciInstanceKlass* ciInstanceKlass::super() {
346   assert(is_loaded(), "must be loaded");
347   if (_super == nullptr && !is_java_lang_Object()) {
348     GUARDED_VM_ENTRY(
349       Klass* super_klass = get_instanceKlass()->super();
350       _super = CURRENT_ENV->get_instance_klass(super_klass);
351     )
352   }
353   return _super;
354 }
355 
356 // ------------------------------------------------------------------
357 // ciInstanceKlass::java_mirror
358 //
359 // Get the instance of java.lang.Class corresponding to this klass.
360 // Cache it on this->_java_mirror.
361 ciInstance* ciInstanceKlass::java_mirror() {
362   if (is_shared()) {
363     return ciKlass::java_mirror();
364   }
365   if (_java_mirror == nullptr) {
366     _java_mirror = ciKlass::java_mirror();
367   }
368   return _java_mirror;
369 }
370 
371 // ------------------------------------------------------------------
372 // ciInstanceKlass::unique_concrete_subklass
373 ciInstanceKlass* ciInstanceKlass::unique_concrete_subklass() {
374   if (!is_loaded())     return nullptr; // No change if class is not loaded
375   if (!is_abstract())   return nullptr; // Only applies to abstract classes.
376   if (!has_subklass())  return nullptr; // Must have at least one subklass.
377   VM_ENTRY_MARK;
378   InstanceKlass* ik = get_instanceKlass();
379   Klass* up = ik->up_cast_abstract();
380   assert(up->is_instance_klass(), "must be InstanceKlass");
381   if (ik == up) {
382     return nullptr;
383   }
384   return CURRENT_THREAD_ENV->get_instance_klass(up);
385 }
386 
387 // ------------------------------------------------------------------
388 // ciInstanceKlass::has_finalizable_subclass
389 bool ciInstanceKlass::has_finalizable_subclass() {
390   if (!is_loaded())     return true;
391   VM_ENTRY_MARK;
392   return Dependencies::find_finalizable_subclass(get_instanceKlass()) != nullptr;
393 }
394 
395 // ------------------------------------------------------------------
396 // ciInstanceKlass::contains_field_offset
397 bool ciInstanceKlass::contains_field_offset(int offset) {
398   VM_ENTRY_MARK;
399   return get_instanceKlass()->contains_field_offset(offset);
400 }
401 
402 ciField* ciInstanceKlass::get_nonstatic_field_by_offset(const int field_offset) {
403   for (int i = 0, len = nof_nonstatic_fields(); i < len; i++) {
404     ciField* field = nonstatic_field_at(i);
405     int field_off = field->offset_in_bytes();
406     if (field_off == field_offset) {
407       return field;
408     }
409   }
410   return nullptr;
411 }
412 
413 // ------------------------------------------------------------------
414 // ciInstanceKlass::get_field_by_offset
415 ciField* ciInstanceKlass::get_field_by_offset(int field_offset, bool is_static) {
416   if (!is_static) {
417     return get_nonstatic_field_by_offset(field_offset);
418   }
419 
420   VM_ENTRY_MARK;
421   InstanceKlass* k = get_instanceKlass();
422   fieldDescriptor fd;
423   if (!k->find_field_from_offset(field_offset, is_static, &fd)) {
424     return nullptr;
425   }
426   ciField* field = new (CURRENT_THREAD_ENV->arena()) ciField(&fd);
427   return field;
428 }
429 
430 ciField* ciInstanceKlass::get_non_flat_field_by_offset(int field_offset) {
431   for (int i = 0, len = nof_declared_nonstatic_fields(); i < len; i++) {
432     ciField* field = declared_nonstatic_field_at(i);
433     int field_off = field->offset_in_bytes();
434     if (field_off == field_offset) {
435       return field;
436     }
437   }
438   return nullptr;
439 }
440 
441 int ciInstanceKlass::field_index_by_offset(int offset) {
442   int best_offset = 0;
443   int best_index = -1;
444   // Search the field with the given offset
445   for (int i = 0; i < nof_declared_nonstatic_fields(); ++i) {
446     int field_offset = declared_nonstatic_field_at(i)->offset_in_bytes();
447     if (field_offset == offset) {
448       // Exact match
449       return i;
450     } else if (field_offset < offset && field_offset > best_offset) {
451       // No exact match. Save the index of the field with the closest offset that
452       // is smaller than the given field offset. This index corresponds to the
453       // flat field that holds the field we are looking for.
454       best_offset = field_offset;
455       best_index = i;
456     }
457   }
458   assert(best_index >= 0, "field not found");
459   assert(best_offset == offset || declared_nonstatic_field_at(best_index)->type()->is_inlinetype(), "offset should match for non-inline types");
460   return best_index;
461 }
462 
463 // ------------------------------------------------------------------
464 // ciInstanceKlass::get_field_by_name
465 ciField* ciInstanceKlass::get_field_by_name(ciSymbol* name, ciSymbol* signature, bool is_static) {
466   VM_ENTRY_MARK;
467   InstanceKlass* k = get_instanceKlass();
468   fieldDescriptor fd;
469   Klass* def = k->find_field(name->get_symbol(), signature->get_symbol(), is_static, &fd);
470   if (def == nullptr) {
471     return nullptr;
472   }
473   ciField* field = new (CURRENT_THREAD_ENV->arena()) ciField(&fd);
474   return field;
475 }
476 
477 const GrowableArray<ciField*> empty_field_array(0, MemTag::mtCompiler);
478 
479 // This is essentially a shortcut for:
480 //   get_field_by_offset(field_offset, is_static)->layout_type()
481 // except this does not require allocating memory for a new ciField
482 BasicType ciInstanceKlass::get_field_type_by_offset(const int field_offset, const bool is_static) {
483   if (!is_static) {
484     ciField* field = get_nonstatic_field_by_offset(field_offset);
485     return field != nullptr ? field->layout_type() : T_ILLEGAL;
486   }
487 
488   // Avoid allocating a new ciField by obtaining the field type directly
489   VM_ENTRY_MARK;
490   InstanceKlass* k = get_instanceKlass();
491   fieldDescriptor fd;
492   if (!k->find_field_from_offset(field_offset, is_static, &fd)) {
493     return T_ILLEGAL;
494   }
495 
496   // Reproduce the behavior of ciField::layout_type
497   BasicType field_type = fd.field_type();
498   if (is_reference_type(field_type)) {
499     return T_OBJECT;
500   }
501   return type2field[make(field_type)->basic_type()];
502 }
503 
504 void ciInstanceKlass::compute_nonstatic_fields() {
505   assert(is_loaded(), "must be loaded");
506 
507   if (_nonstatic_fields != nullptr) {
508     assert(_declared_nonstatic_fields != nullptr, "must be initialized at the same time, class %s", name()->as_utf8());
509     return;
510   }
511 
512   if (!has_nonstatic_fields()) {
513     _declared_nonstatic_fields = &empty_field_array;
514     _nonstatic_fields = &empty_field_array;
515     return;
516   }
517   assert(!is_java_lang_Object(), "bootstrap OK");
518 
519   ciInstanceKlass* super = this->super();
520   assert(super != nullptr, "must have a super class, current class: %s", name()->as_utf8());
521   super->compute_nonstatic_fields();
522   const GrowableArray<ciField*>* super_declared_fields = super->_declared_nonstatic_fields;;
523   const GrowableArray<ciField*>* super_fields = super->_nonstatic_fields;
524   assert(super_declared_fields != nullptr && super_fields != nullptr, "must have been initialized, current class: %s, super class: %s", name()->as_utf8(), super->name()->as_utf8());
525 
526   GUARDED_VM_ENTRY({
527     compute_nonstatic_fields_impl(super_declared_fields, super_fields);
528   });
529 }
530 
531 void ciInstanceKlass::compute_nonstatic_fields_impl(const GrowableArray<ciField*>* super_declared_fields, const GrowableArray<ciField*>* super_fields) {
532   assert(_declared_nonstatic_fields == nullptr && _nonstatic_fields == nullptr, "initialized already");
533   ASSERT_IN_VM;
534   Arena* arena = CURRENT_ENV->arena();
535 
536   InstanceKlass* this_klass = get_instanceKlass();
537   int declared_field_num = 0;
538   int field_num = 0;
539   for (JavaFieldStream fs(this_klass); !fs.done(); fs.next()) {
540     if (fs.access_flags().is_static()) {
541       continue;
542     }
543 
544     declared_field_num++;
545 
546     fieldDescriptor& fd = fs.field_descriptor();
547     if (fd.is_flat()) {
548       InlineKlass* k = this_klass->get_inline_type_field_klass(fd.index());
549       ciInlineKlass* vk = CURRENT_ENV->get_klass(k)->as_inline_klass();
550       field_num += vk->nof_nonstatic_fields();
551       field_num += fd.has_null_marker() ? 1 : 0;
552     } else {
553       field_num++;
554     }
555   }
556 
557   GrowableArray<ciField*>* tmp_declared_fields = nullptr;
558   if (declared_field_num != 0) {
559     tmp_declared_fields = new (arena) GrowableArray<ciField*>(arena, declared_field_num + super_declared_fields->length(), 0, nullptr);
560     tmp_declared_fields->appendAll(super_declared_fields);
561   }
562 
563   GrowableArray<ciField*>* tmp_fields = nullptr;
564   if (field_num != 0) {
565     tmp_fields = new (arena) GrowableArray<ciField*>(arena, field_num + super_fields->length(), 0, nullptr);
566     tmp_fields->appendAll(super_fields);
567   }
568 
569   // For later assertion
570   declared_field_num += super_declared_fields->length();
571   field_num += super_fields->length();
572 
573   for (JavaFieldStream fs(this_klass); !fs.done(); fs.next()) {
574     if (fs.access_flags().is_static()) {
575       continue;
576     }
577 
578     fieldDescriptor& fd = fs.field_descriptor();
579     ciField* declared_field = new (arena) ciField(&fd);
580     assert(tmp_declared_fields != nullptr, "should be initialized");
581     tmp_declared_fields->append(declared_field);
582 
583     if (fd.is_flat()) {
584       // Flat fields are embedded
585       Klass* k = get_instanceKlass()->get_inline_type_field_klass(fd.index());
586       ciInlineKlass* vk = CURRENT_ENV->get_klass(k)->as_inline_klass();
587       // Iterate over fields of the flat inline type and copy them to 'this'
588       for (int i = 0; i < vk->nof_nonstatic_fields(); ++i) {
589         assert(tmp_fields != nullptr, "should be initialized");
590         tmp_fields->append(new (arena) ciField(declared_field, vk->nonstatic_field_at(i)));
591       }
592       if (fd.has_null_marker()) {
593         assert(tmp_fields != nullptr, "should be initialized");
594         tmp_fields->append(new (arena) ciField(declared_field));
595       }
596     } else {
597       assert(tmp_fields != nullptr, "should be initialized");
598       tmp_fields->append(declared_field);
599     }
600   }
601 
602   // Now sort them by offset, ascending. In principle, they could mix with superclass fields.
603   if (tmp_declared_fields != nullptr) {
604     assert(tmp_declared_fields->length() == declared_field_num, "sanity check failed for class: %s, number of declared fields: %d, expected: %d",
605            name()->as_utf8(), tmp_declared_fields->length(), declared_field_num);
606     _declared_nonstatic_fields = tmp_declared_fields;
607   } else {
608     _declared_nonstatic_fields = super_declared_fields;
609   }
610 
611   if (tmp_fields != nullptr) {
612     assert(tmp_fields->length() == field_num, "sanity check failed for class: %s, number of fields: %d, expected: %d",
613            name()->as_utf8(), tmp_fields->length(), field_num);
614     _nonstatic_fields = tmp_fields;
615   } else {
616     _nonstatic_fields = super_fields;
617   }
618 }
619 
620 bool ciInstanceKlass::compute_injected_fields_helper() {
621   ASSERT_IN_VM;
622   InstanceKlass* k = get_instanceKlass();
623 
624   for (InternalFieldStream fs(k); !fs.done(); fs.next()) {
625     if (fs.access_flags().is_static())  continue;
626     return true;
627   }
628   return false;
629 }
630 
631 void ciInstanceKlass::compute_injected_fields() {
632   assert(is_loaded(), "must be loaded");
633 
634   int has_injected_fields = 0;
635   if (super() != nullptr && super()->has_injected_fields()) {
636     has_injected_fields = 1;
637   } else {
638     GUARDED_VM_ENTRY({
639         has_injected_fields = compute_injected_fields_helper() ? 1 : 0;
640       });
641   }
642   // may be concurrently initialized for shared ciInstanceKlass objects
643   assert(_has_injected_fields == -1 || _has_injected_fields == has_injected_fields, "broken concurrent initialization");
644   _has_injected_fields = has_injected_fields;
645 }
646 
647 bool ciInstanceKlass::has_object_fields() const {
648   GUARDED_VM_ENTRY(
649       return get_instanceKlass()->nonstatic_oop_map_size() > 0;
650     );
651 }
652 
653 bool ciInstanceKlass::compute_has_trusted_loader() {
654   ASSERT_IN_VM;
655   oop loader_oop = loader();
656   if (loader_oop == nullptr) {
657     return true; // bootstrap class loader
658   }
659   return java_lang_ClassLoader::is_trusted_loader(loader_oop);
660 }
661 
662 bool ciInstanceKlass::has_class_initializer() {
663   VM_ENTRY_MARK;
664   return get_instanceKlass()->class_initializer() != nullptr;
665 }
666 
667 // ------------------------------------------------------------------
668 // ciInstanceKlass::find_method
669 //
670 // Find a method in this klass.
671 ciMethod* ciInstanceKlass::find_method(ciSymbol* name, ciSymbol* signature) {
672   VM_ENTRY_MARK;
673   InstanceKlass* k = get_instanceKlass();
674   Symbol* name_sym = name->get_symbol();
675   Symbol* sig_sym= signature->get_symbol();
676 
677   Method* m = k->find_method(name_sym, sig_sym);
678   if (m == nullptr)  return nullptr;
679 
680   return CURRENT_THREAD_ENV->get_method(m);
681 }
682 
683 // ------------------------------------------------------------------
684 // ciInstanceKlass::is_leaf_type
685 bool ciInstanceKlass::is_leaf_type() {
686   assert(is_loaded(), "must be loaded");
687   if (is_shared()) {
688     return is_final();  // approximately correct
689   } else {
690     return !has_subklass() && (!is_interface() || nof_implementors() == 0);
691   }
692 }
693 
694 // ------------------------------------------------------------------
695 // ciInstanceKlass::implementor
696 //
697 // Report an implementor of this interface.
698 // Note that there are various races here, since my copy
699 // of _nof_implementors might be out of date with respect
700 // to results returned by InstanceKlass::implementor.
701 // This is OK, since any dependencies we decide to assert
702 // will be checked later under the Compile_lock.
703 ciInstanceKlass* ciInstanceKlass::implementor() {
704   assert(is_interface(), "required");
705   ciInstanceKlass* impl = _implementor;
706   if (impl == nullptr) {
707     if (is_shared()) {
708       impl = this; // assume a well-known interface never has a unique implementor
709     } else {
710       // Go into the VM to fetch the implementor.
711       VM_ENTRY_MARK;
712       InstanceKlass* ik = get_instanceKlass();
713       Klass* implk = ik->implementor();
714       if (implk != nullptr) {
715         if (implk == ik) {
716           // More than one implementors. Use 'this' in this case.
717           impl = this;
718         } else {
719           impl = CURRENT_THREAD_ENV->get_instance_klass(implk);
720         }
721       }
722     }
723     // Memoize this result.
724     _implementor = impl;
725   }
726   return impl;
727 }
728 
729 bool ciInstanceKlass::can_be_inline_klass(bool is_exact) {
730   if (!Arguments::is_valhalla_enabled()) {
731     return false;
732   }
733   if (!is_loaded() || is_inlinetype()) {
734     // Not loaded or known to be an inline klass
735     return true;
736   }
737   if (!is_exact) {
738     // Not exact, check if this is a valid super for an inline klass
739     GUARDED_VM_ENTRY(
740       return !get_instanceKlass()->access_flags().is_identity_class() || is_java_lang_Object();
741     )
742   }
743   return false;
744 }
745 
746 // Utility class for printing of the contents of the static fields for
747 // use by compilation replay.  It only prints out the information that
748 // could be consumed by the compiler, so for primitive types it prints
749 // out the actual value.  For Strings it's the actual string value.
750 // For array types it it's first level array size since that's the
751 // only value which statically unchangeable.  For all other reference
752 // types it simply prints out the dynamic type.
753 
754 class StaticFieldPrinter : public FieldClosure {
755 protected:
756   outputStream* _out;
757 public:
758   StaticFieldPrinter(outputStream* out) :
759     _out(out) {
760   }
761   void do_field_helper(fieldDescriptor* fd, oop obj, bool is_flat);
762 };
763 
764 class StaticFinalFieldPrinter : public StaticFieldPrinter {
765   const char*   _holder;
766  public:
767   StaticFinalFieldPrinter(outputStream* out, const char* holder) :
768     StaticFieldPrinter(out), _holder(holder) {
769   }
770   void do_field(fieldDescriptor* fd) {
771     if (fd->is_final() && !fd->has_initial_value()) {
772       ResourceMark rm;
773       InstanceKlass* holder = fd->field_holder();
774       oop mirror = holder->java_mirror();
775       _out->print("staticfield %s %s ", _holder, fd->name()->as_quoted_ascii());
776       BasicType bt = fd->field_type();
777       if (bt != T_OBJECT && bt != T_ARRAY) {
778         _out->print("%s ", fd->signature()->as_quoted_ascii());
779       }
780       do_field_helper(fd, mirror, false);
781       _out->cr();
782     }
783   }
784 };
785 
786 class InlineTypeFieldPrinter : public StaticFieldPrinter {
787   oop _obj;
788 public:
789   InlineTypeFieldPrinter(outputStream* out, oop obj) :
790     StaticFieldPrinter(out), _obj(obj) {
791   }
792   void do_field(fieldDescriptor* fd) {
793     do_field_helper(fd, _obj, true);
794     _out->print(" ");
795   }
796 };
797 
798 void StaticFieldPrinter::do_field_helper(fieldDescriptor* fd, oop mirror, bool is_flat) {
799   BasicType field_type = fd->field_type();
800   switch (field_type) {
801     case T_BYTE:    _out->print("%d", mirror->byte_field(fd->offset()));   break;
802     case T_BOOLEAN: _out->print("%d", mirror->bool_field(fd->offset()));   break;
803     case T_SHORT:   _out->print("%d", mirror->short_field(fd->offset()));  break;
804     case T_CHAR:    _out->print("%d", mirror->char_field(fd->offset()));   break;
805     case T_INT:     _out->print("%d", mirror->int_field(fd->offset()));    break;
806     case T_LONG:    _out->print(INT64_FORMAT, (int64_t)(mirror->long_field(fd->offset())));   break;
807     case T_FLOAT: {
808       float f = mirror->float_field(fd->offset());
809       _out->print("%d", *(int*)&f);
810       break;
811     }
812     case T_DOUBLE: {
813       double d = mirror->double_field(fd->offset());
814       _out->print(INT64_FORMAT, *(int64_t*)&d);
815       break;
816     }
817     case T_ARRAY:  // fall-through
818     case T_OBJECT:
819       if (!fd->is_null_free_inline_type()) {
820         _out->print("%s ", fd->signature()->as_quoted_ascii());
821         oop value =  mirror->obj_field_acquire(fd->offset());
822         if (value == nullptr) {
823           if (field_type == T_ARRAY) {
824             _out->print("%d", -1);
825           }
826           _out->cr();
827         } else if (value->is_instance()) {
828           assert(field_type == T_OBJECT, "");
829           if (value->is_a(vmClasses::String_klass())) {
830             const char* ascii_value = java_lang_String::as_quoted_ascii(value);
831             _out->print("\"%s\"", (ascii_value != nullptr) ? ascii_value : "");
832           } else {
833             const char* klass_name  = value->klass()->name()->as_quoted_ascii();
834             _out->print("%s", klass_name);
835           }
836         } else if (value->is_array()) {
837           typeArrayOop ta = (typeArrayOop)value;
838           _out->print("%d", ta->length());
839           if (value->is_objArray() || value->is_flatArray()) {
840             objArrayOop oa = (objArrayOop)value;
841             const char* klass_name  = value->klass()->name()->as_quoted_ascii();
842             _out->print(" %s", klass_name);
843           }
844         } else {
845           ShouldNotReachHere();
846         }
847         break;
848       } else {
849         // handling of null free inline type
850         ResetNoHandleMark rnhm;
851         Thread* THREAD = Thread::current();
852         SignatureStream ss(fd->signature(), false);
853         Symbol* name = ss.as_symbol();
854         assert(!HAS_PENDING_EXCEPTION, "can resolve klass?");
855         InstanceKlass* holder = fd->field_holder();
856         InstanceKlass* k = SystemDictionary::find_instance_klass(THREAD, name,
857                                                                  Handle(THREAD, holder->class_loader()));
858         guarantee(k != nullptr && !HAS_PENDING_EXCEPTION, "can resolve klass?");
859         InlineKlass* vk = InlineKlass::cast(k);
860         oop obj;
861         if (is_flat) {
862           int field_offset = fd->offset() - vk->payload_offset();
863           obj = cast_to_oop(cast_from_oop<address>(mirror) + field_offset);
864         } else {
865           obj = mirror->obj_field_acquire(fd->offset());
866         }
867         InlineTypeFieldPrinter print_field(_out, obj);
868         vk->do_nonstatic_fields(&print_field);
869         break;
870       }
871     default:
872       ShouldNotReachHere();
873   }
874 }
875 
876 const char *ciInstanceKlass::replay_name() const {
877   return CURRENT_ENV->replay_name(get_instanceKlass());
878 }
879 
880 void ciInstanceKlass::dump_replay_instanceKlass(outputStream* out, InstanceKlass* ik) {
881   if (ik->is_hidden()) {
882     const char *name = CURRENT_ENV->dyno_name(ik);
883     if (name != nullptr) {
884       out->print_cr("instanceKlass %s # %s", name, ik->name()->as_quoted_ascii());
885     } else {
886       out->print_cr("# instanceKlass %s", ik->name()->as_quoted_ascii());
887     }
888   } else {
889     out->print_cr("instanceKlass %s", ik->name()->as_quoted_ascii());
890   }
891 }
892 
893 GrowableArray<ciInstanceKlass*>* ciInstanceKlass::transitive_interfaces() const{
894   if (_transitive_interfaces == nullptr) {
895     const_cast<ciInstanceKlass*>(this)->compute_transitive_interfaces();
896   }
897   return _transitive_interfaces;
898 }
899 
900 void ciInstanceKlass::compute_transitive_interfaces() {
901   GUARDED_VM_ENTRY(
902           InstanceKlass* ik = get_instanceKlass();
903           Array<InstanceKlass*>* interfaces = ik->transitive_interfaces();
904           int orig_length = interfaces->length();
905           Arena* arena = CURRENT_ENV->arena();
906           int transitive_interfaces_len = orig_length + (is_interface() ? 1 : 0);
907           GrowableArray<ciInstanceKlass*>* transitive_interfaces = new(arena)GrowableArray<ciInstanceKlass*>(arena, transitive_interfaces_len,
908                                                                                                              0, nullptr);
909           for (int i = 0; i < orig_length; i++) {
910             transitive_interfaces->append(CURRENT_ENV->get_instance_klass(interfaces->at(i)));
911           }
912           if (is_interface()) {
913             transitive_interfaces->append(this);
914           }
915           _transitive_interfaces = transitive_interfaces;
916   );
917 }
918 
919 void ciInstanceKlass::dump_replay_data(outputStream* out) {
920   ResourceMark rm;
921 
922   InstanceKlass* ik = get_instanceKlass();
923   ConstantPool*  cp = ik->constants();
924 
925   // Try to record related loaded classes
926   Klass* sub = ik->subklass();
927   while (sub != nullptr) {
928     if (sub->is_instance_klass()) {
929       InstanceKlass *isub = InstanceKlass::cast(sub);
930       dump_replay_instanceKlass(out, isub);
931     }
932     sub = sub->next_sibling();
933   }
934 
935   // Dump out the state of the constant pool tags.  During replay the
936   // tags will be validated for things which shouldn't change and
937   // classes will be resolved if the tags indicate that they were
938   // resolved at compile time.
939   const char *name = replay_name();
940   out->print("ciInstanceKlass %s %d %d %d", name,
941              is_linked(), is_initialized(), cp->length());
942   for (int index = 1; index < cp->length(); index++) {
943     out->print(" %d", cp->tags()->at(index));
944   }
945   out->cr();
946   if (is_initialized()) {
947     //  Dump out the static final fields in case the compilation relies
948     //  on their value for correct replay.
949     StaticFinalFieldPrinter sffp(out, name);
950     ik->do_local_static_fields(&sffp);
951   }
952 }
953 
954 #ifdef ASSERT
955 bool ciInstanceKlass::debug_final_field_at(int offset) {
956   GUARDED_VM_ENTRY(
957     InstanceKlass* ik = get_instanceKlass();
958     fieldDescriptor fd;
959     if (ik->find_field_from_offset(offset, false, &fd)) {
960       return fd.is_final();
961     }
962   );
963   return false;
964 }
965 
966 bool ciInstanceKlass::debug_stable_field_at(int offset) {
967   GUARDED_VM_ENTRY(
968     InstanceKlass* ik = get_instanceKlass();
969     fieldDescriptor fd;
970     if (ik->find_field_from_offset(offset, false, &fd)) {
971       return fd.is_stable();
972     }
973   );
974   return false;
975 }
976 #endif