1 /*
   2  * Copyright (c) 1999, 2023, 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 "precompiled.hpp"
  26 #include "cds/archiveBuilder.hpp"
  27 #include "cds/cdsConfig.hpp"
  28 #include "ci/ciConstant.hpp"
  29 #include "ci/ciEnv.hpp"
  30 #include "ci/ciField.hpp"
  31 #include "ci/ciInstance.hpp"
  32 #include "ci/ciInstanceKlass.hpp"
  33 #include "ci/ciMethod.hpp"
  34 #include "ci/ciNullObject.hpp"
  35 #include "ci/ciReplay.hpp"
  36 #include "ci/ciSymbols.hpp"
  37 #include "ci/ciUtilities.inline.hpp"
  38 #include "classfile/javaClasses.hpp"
  39 #include "classfile/javaClasses.inline.hpp"
  40 #include "classfile/systemDictionary.hpp"
  41 #include "classfile/vmClasses.hpp"
  42 #include "classfile/vmSymbols.hpp"
  43 #include "code/codeCache.hpp"
  44 #include "code/scopeDesc.hpp"
  45 #include "code/SCCache.hpp"
  46 #include "compiler/compilationLog.hpp"
  47 #include "compiler/compilationPolicy.hpp"
  48 #include "compiler/compileBroker.hpp"
  49 #include "compiler/compilerEvent.hpp"
  50 #include "compiler/compileLog.hpp"
  51 #include "compiler/compileTask.hpp"
  52 #include "compiler/disassembler.hpp"
  53 #include "gc/shared/collectedHeap.inline.hpp"
  54 #include "gc/shared/barrierSetNMethod.hpp"
  55 #include "interpreter/bytecodeStream.hpp"
  56 #include "interpreter/linkResolver.hpp"
  57 #include "jfr/jfrEvents.hpp"
  58 #include "jvm.h"
  59 #include "logging/log.hpp"
  60 #include "memory/allocation.inline.hpp"
  61 #include "memory/oopFactory.hpp"
  62 #include "memory/resourceArea.hpp"
  63 #include "memory/universe.hpp"
  64 #include "oops/constantPool.inline.hpp"
  65 #include "oops/cpCache.inline.hpp"
  66 #include "oops/method.inline.hpp"
  67 #include "oops/methodData.hpp"
  68 #include "oops/objArrayKlass.hpp"
  69 #include "oops/objArrayOop.inline.hpp"
  70 #include "oops/oop.inline.hpp"
  71 #include "oops/resolvedIndyEntry.hpp"
  72 #include "oops/symbolHandle.hpp"
  73 #include "oops/trainingData.hpp"
  74 #include "prims/jvmtiExport.hpp"
  75 #include "prims/methodHandles.hpp"
  76 #include "runtime/fieldDescriptor.inline.hpp"
  77 #include "runtime/flags/flagSetting.hpp"
  78 #include "runtime/handles.inline.hpp"
  79 #include "runtime/init.hpp"
  80 #include "runtime/javaThread.hpp"
  81 #include "runtime/jniHandles.inline.hpp"
  82 #include "runtime/reflection.hpp"
  83 #include "runtime/safepointVerifiers.hpp"
  84 #include "runtime/sharedRuntime.hpp"
  85 #include "utilities/dtrace.hpp"
  86 #include "utilities/macros.hpp"
  87 #ifdef COMPILER1
  88 #include "c1/c1_Runtime1.hpp"
  89 #endif
  90 #ifdef COMPILER2
  91 #include "opto/runtime.hpp"
  92 #endif
  93 
  94 // ciEnv
  95 //
  96 // This class is the top level broker for requests from the compiler
  97 // to the VM.
  98 
  99 ciObject*              ciEnv::_null_object_instance;
 100 
 101 #define VM_CLASS_DEFN(name, ignore_s) ciInstanceKlass* ciEnv::_##name = nullptr;
 102 VM_CLASSES_DO(VM_CLASS_DEFN)
 103 #undef VM_CLASS_DEFN
 104 
 105 ciSymbol*        ciEnv::_unloaded_cisymbol = nullptr;
 106 ciInstanceKlass* ciEnv::_unloaded_ciinstance_klass = nullptr;
 107 ciObjArrayKlass* ciEnv::_unloaded_ciobjarrayklass = nullptr;
 108 
 109 jobject ciEnv::_ArrayIndexOutOfBoundsException_handle = nullptr;
 110 jobject ciEnv::_ArrayStoreException_handle = nullptr;
 111 jobject ciEnv::_ClassCastException_handle = nullptr;
 112 
 113 #ifndef PRODUCT
 114 static bool firstEnv = true;
 115 #endif /* PRODUCT */
 116 
 117 // ------------------------------------------------------------------
 118 // ciEnv::ciEnv
 119 ciEnv::ciEnv(CompileTask* task)
 120   : _ciEnv_arena(mtCompiler) {
 121   VM_ENTRY_MARK;
 122 
 123   // Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc.
 124   thread->set_env(this);
 125   assert(ciEnv::current() == this, "sanity");
 126 
 127   _oop_recorder = nullptr;
 128   _debug_info = nullptr;
 129   _dependencies = nullptr;
 130   _failure_reason = nullptr;
 131   _inc_decompile_count_on_failure = true;
 132   _compilable = MethodCompilable;
 133   _break_at_compile = false;
 134   _compiler_data = nullptr;
 135 #ifndef PRODUCT
 136   assert(!firstEnv, "not initialized properly");
 137 #endif /* !PRODUCT */
 138 
 139   _num_inlined_bytecodes = 0;
 140   assert(task == nullptr || thread->task() == task, "sanity");
 141   if (task != nullptr) {
 142     task->mark_started(os::elapsed_counter());
 143   }
 144   _task = task;
 145   _log = nullptr;
 146 
 147   // Temporary buffer for creating symbols and such.
 148   _name_buffer = nullptr;
 149   _name_buffer_len = 0;
 150 
 151   _arena   = &_ciEnv_arena;
 152   _factory = new (_arena) ciObjectFactory(_arena, 128);
 153 
 154   // Preload commonly referenced system ciObjects.
 155 
 156   // During VM initialization, these instances have not yet been created.
 157   // Assertions ensure that these instances are not accessed before
 158   // their initialization.
 159 
 160   assert(Universe::is_fully_initialized(), "should be complete");
 161 
 162   oop o = Universe::null_ptr_exception_instance();
 163   assert(o != nullptr, "should have been initialized");
 164   _NullPointerException_instance = get_object(o)->as_instance();
 165   o = Universe::arithmetic_exception_instance();
 166   assert(o != nullptr, "should have been initialized");
 167   _ArithmeticException_instance = get_object(o)->as_instance();
 168 
 169   _ArrayIndexOutOfBoundsException_instance = nullptr;
 170   _ArrayStoreException_instance = nullptr;
 171   _ClassCastException_instance = nullptr;
 172   _the_null_string = nullptr;
 173   _the_min_jint_string = nullptr;
 174 
 175   _jvmti_redefinition_count = 0;
 176   _jvmti_can_hotswap_or_post_breakpoint = false;
 177   _jvmti_can_access_local_variables = false;
 178   _jvmti_can_post_on_exceptions = false;
 179   _jvmti_can_pop_frame = false;
 180 
 181   _scc_clinit_barriers_entry = nullptr;
 182 
 183   _dyno_klasses = nullptr;
 184   _dyno_locs = nullptr;
 185   _dyno_name[0] = '\0';
 186 }
 187 
 188 // Record components of a location descriptor string.  Components are appended by the constructor and
 189 // removed by the destructor, like a stack, so scope matters.  These location descriptors are used to
 190 // locate dynamic classes, and terminate at a Method* or oop field associated with dynamic/hidden class.
 191 //
 192 // Example use:
 193 //
 194 // {
 195 //   RecordLocation fp(this, "field1");
 196 //   // location: "field1"
 197 //   { RecordLocation fp(this, " field2"); // location: "field1 field2" }
 198 //   // location: "field1"
 199 //   { RecordLocation fp(this, " field3"); // location: "field1 field3" }
 200 //   // location: "field1"
 201 // }
 202 // // location: ""
 203 //
 204 // Examples of actual locations
 205 // @bci compiler/ciReplay/CiReplayBase$TestMain test (I)V 1 <appendix> argL0 ;
 206 // // resolve invokedynamic at bci 1 of TestMain.test, then read field "argL0" from appendix
 207 // @bci compiler/ciReplay/CiReplayBase$TestMain main ([Ljava/lang/String;)V 0 <appendix> form vmentry <vmtarget> ;
 208 // // resolve invokedynamic at bci 0 of TestMain.main, then read field "form.vmentry.method.vmtarget" from appendix
 209 // @cpi compiler/ciReplay/CiReplayBase$TestMain 56 form vmentry <vmtarget> ;
 210 // // resolve MethodHandle at cpi 56 of TestMain, then read field "vmentry.method.vmtarget" from resolved MethodHandle
 211 class RecordLocation {
 212 private:
 213   char* end;
 214 
 215   ATTRIBUTE_PRINTF(3, 4)
 216   void push(ciEnv* ci, const char* fmt, ...) {
 217     va_list args;
 218     va_start(args, fmt);
 219     push_va(ci, fmt, args);
 220     va_end(args);
 221   }
 222 
 223 public:
 224   ATTRIBUTE_PRINTF(3, 0)
 225   void push_va(ciEnv* ci, const char* fmt, va_list args) {
 226     char *e = ci->_dyno_name + strlen(ci->_dyno_name);
 227     char *m = ci->_dyno_name + ARRAY_SIZE(ci->_dyno_name) - 1;
 228     os::vsnprintf(e, m - e, fmt, args);
 229     assert(strlen(ci->_dyno_name) < (ARRAY_SIZE(ci->_dyno_name) - 1), "overflow");
 230   }
 231 
 232   // append a new component
 233   ATTRIBUTE_PRINTF(3, 4)
 234   RecordLocation(ciEnv* ci, const char* fmt, ...) {
 235     end = ci->_dyno_name + strlen(ci->_dyno_name);
 236     va_list args;
 237     va_start(args, fmt);
 238     push(ci, " ");
 239     push_va(ci, fmt, args);
 240     va_end(args);
 241   }
 242 
 243   // reset to previous state
 244   ~RecordLocation() {
 245     *end = '\0';
 246   }
 247 };
 248 
 249 ciEnv::ciEnv(Arena* arena) : _ciEnv_arena(mtCompiler) {
 250   ASSERT_IN_VM;
 251 
 252   // Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc.
 253   CompilerThread* current_thread = CompilerThread::current();
 254   assert(current_thread->env() == nullptr, "must be");
 255   current_thread->set_env(this);
 256   assert(ciEnv::current() == this, "sanity");
 257 
 258   _oop_recorder = nullptr;
 259   _debug_info = nullptr;
 260   _dependencies = nullptr;
 261   _failure_reason = nullptr;
 262   _inc_decompile_count_on_failure = true;
 263   _compilable = MethodCompilable_never;
 264   _break_at_compile = false;
 265   _compiler_data = nullptr;
 266 #ifndef PRODUCT
 267   assert(firstEnv, "must be first");
 268   firstEnv = false;
 269 #endif /* !PRODUCT */
 270 
 271   _num_inlined_bytecodes = 0;
 272   _task = nullptr;
 273   _log = nullptr;
 274 
 275   // Temporary buffer for creating symbols and such.
 276   _name_buffer = nullptr;
 277   _name_buffer_len = 0;
 278 
 279   _arena   = arena;
 280   _factory = new (_arena) ciObjectFactory(_arena, 128);
 281 
 282   // Preload commonly referenced system ciObjects.
 283 
 284   // During VM initialization, these instances have not yet been created.
 285   // Assertions ensure that these instances are not accessed before
 286   // their initialization.
 287 
 288   assert(Universe::is_fully_initialized(), "must be");
 289 
 290   _NullPointerException_instance = nullptr;
 291   _ArithmeticException_instance = nullptr;
 292   _ArrayIndexOutOfBoundsException_instance = nullptr;
 293   _ArrayStoreException_instance = nullptr;
 294   _ClassCastException_instance = nullptr;
 295   _the_null_string = nullptr;
 296   _the_min_jint_string = nullptr;
 297 
 298   _jvmti_redefinition_count = 0;
 299   _jvmti_can_hotswap_or_post_breakpoint = false;
 300   _jvmti_can_access_local_variables = false;
 301   _jvmti_can_post_on_exceptions = false;
 302   _jvmti_can_pop_frame = false;
 303 
 304   _scc_clinit_barriers_entry = nullptr;
 305 
 306   _dyno_klasses = nullptr;
 307   _dyno_locs = nullptr;
 308 }
 309 
 310 ciEnv::~ciEnv() {
 311   GUARDED_VM_ENTRY(
 312       CompilerThread* current_thread = CompilerThread::current();
 313       _factory->remove_symbols();
 314       // Need safepoint to clear the env on the thread.  RedefineClasses might
 315       // be reading it.
 316       current_thread->set_env(nullptr);
 317   )
 318 }
 319 
 320 // ------------------------------------------------------------------
 321 // Cache Jvmti state
 322 bool ciEnv::cache_jvmti_state() {
 323   VM_ENTRY_MARK;
 324   // Get Jvmti capabilities under lock to get consistent values.
 325   MutexLocker mu(JvmtiThreadState_lock);
 326   _jvmti_redefinition_count             = JvmtiExport::redefinition_count();
 327   _jvmti_can_hotswap_or_post_breakpoint = JvmtiExport::can_hotswap_or_post_breakpoint();
 328   _jvmti_can_access_local_variables     = JvmtiExport::can_access_local_variables();
 329   _jvmti_can_post_on_exceptions         = JvmtiExport::can_post_on_exceptions();
 330   _jvmti_can_pop_frame                  = JvmtiExport::can_pop_frame();
 331   _jvmti_can_get_owned_monitor_info     = JvmtiExport::can_get_owned_monitor_info();
 332   _jvmti_can_walk_any_space             = JvmtiExport::can_walk_any_space();
 333   return _task != nullptr && _task->method()->is_old();
 334 }
 335 
 336 bool ciEnv::jvmti_state_changed() const {
 337   // Some classes were redefined
 338   if (_jvmti_redefinition_count != JvmtiExport::redefinition_count()) {
 339     return true;
 340   }
 341 
 342   if (!_jvmti_can_access_local_variables &&
 343       JvmtiExport::can_access_local_variables()) {
 344     return true;
 345   }
 346   if (!_jvmti_can_hotswap_or_post_breakpoint &&
 347       JvmtiExport::can_hotswap_or_post_breakpoint()) {
 348     return true;
 349   }
 350   if (!_jvmti_can_post_on_exceptions &&
 351       JvmtiExport::can_post_on_exceptions()) {
 352     return true;
 353   }
 354   if (!_jvmti_can_pop_frame &&
 355       JvmtiExport::can_pop_frame()) {
 356     return true;
 357   }
 358   if (!_jvmti_can_get_owned_monitor_info &&
 359       JvmtiExport::can_get_owned_monitor_info()) {
 360     return true;
 361   }
 362   if (!_jvmti_can_walk_any_space &&
 363       JvmtiExport::can_walk_any_space()) {
 364     return true;
 365   }
 366 
 367   return false;
 368 }
 369 
 370 // ------------------------------------------------------------------
 371 // Cache DTrace flags
 372 void ciEnv::cache_dtrace_flags() {
 373   // Need lock?
 374   _dtrace_method_probes = DTraceMethodProbes;
 375   _dtrace_alloc_probes  = DTraceAllocProbes;
 376 }
 377 
 378 ciInstanceKlass* ciEnv::get_box_klass_for_primitive_type(BasicType type) {
 379   switch (type) {
 380     case T_BOOLEAN: return Boolean_klass();
 381     case T_BYTE   : return Byte_klass();
 382     case T_CHAR   : return Character_klass();
 383     case T_SHORT  : return Short_klass();
 384     case T_INT    : return Integer_klass();
 385     case T_LONG   : return Long_klass();
 386     case T_FLOAT  : return Float_klass();
 387     case T_DOUBLE : return Double_klass();
 388 
 389     default:
 390       assert(false, "not a primitive: %s", type2name(type));
 391       return nullptr;
 392   }
 393 }
 394 
 395 ciInstance* ciEnv::ArrayIndexOutOfBoundsException_instance() {
 396   if (_ArrayIndexOutOfBoundsException_instance == nullptr) {
 397     VM_ENTRY_MARK;
 398     _ArrayIndexOutOfBoundsException_instance = get_object(Universe::array_index_oob_exception_instance())->as_instance();
 399   }
 400   return _ArrayIndexOutOfBoundsException_instance;
 401 }
 402 ciInstance* ciEnv::ArrayStoreException_instance() {
 403   if (_ArrayStoreException_instance == nullptr) {
 404     VM_ENTRY_MARK;
 405     _ArrayStoreException_instance = get_object(Universe::array_store_exception_instance())->as_instance();
 406   }
 407   return _ArrayStoreException_instance;
 408 }
 409 ciInstance* ciEnv::ClassCastException_instance() {
 410   if (_ClassCastException_instance == nullptr) {
 411     VM_ENTRY_MARK;
 412     _ClassCastException_instance = get_object(Universe::class_cast_exception_instance())->as_instance();
 413   }
 414   return _ClassCastException_instance;
 415 }
 416 
 417 ciInstance* ciEnv::the_null_string() {
 418   if (_the_null_string == nullptr) {
 419     VM_ENTRY_MARK;
 420     _the_null_string = get_object(Universe::the_null_string())->as_instance();
 421   }
 422   return _the_null_string;
 423 }
 424 
 425 ciInstance* ciEnv::the_min_jint_string() {
 426   if (_the_min_jint_string == nullptr) {
 427     VM_ENTRY_MARK;
 428     _the_min_jint_string = get_object(Universe::the_min_jint_string())->as_instance();
 429   }
 430   return _the_min_jint_string;
 431 }
 432 
 433 // ------------------------------------------------------------------
 434 // ciEnv::get_method_from_handle
 435 ciMethod* ciEnv::get_method_from_handle(Method* method) {
 436   VM_ENTRY_MARK;
 437   return get_metadata(method)->as_method();
 438 }
 439 
 440 // ------------------------------------------------------------------
 441 // ciEnv::check_klass_accessiblity
 442 //
 443 // Note: the logic of this method should mirror the logic of
 444 // ConstantPool::verify_constant_pool_resolve.
 445 bool ciEnv::check_klass_accessibility(ciKlass* accessing_klass,
 446                                       Klass* resolved_klass) {
 447   if (accessing_klass == nullptr || !accessing_klass->is_loaded()) {
 448     return true;
 449   }
 450   if (accessing_klass->is_obj_array_klass()) {
 451     accessing_klass = accessing_klass->as_obj_array_klass()->base_element_klass();
 452   }
 453   if (!accessing_klass->is_instance_klass()) {
 454     return true;
 455   }
 456 
 457   if (resolved_klass->is_objArray_klass()) {
 458     // Find the element klass, if this is an array.
 459     resolved_klass = ObjArrayKlass::cast(resolved_klass)->bottom_klass();
 460   }
 461   if (resolved_klass->is_instance_klass()) {
 462     return (Reflection::verify_class_access(accessing_klass->get_Klass(),
 463                                             InstanceKlass::cast(resolved_klass),
 464                                             true) == Reflection::ACCESS_OK);
 465   }
 466   return true;
 467 }
 468 
 469 // ------------------------------------------------------------------
 470 // ciEnv::get_klass_by_name_impl
 471 ciKlass* ciEnv::get_klass_by_name_impl(ciKlass* accessing_klass,
 472                                        const constantPoolHandle& cpool,
 473                                        ciSymbol* name,
 474                                        bool require_local) {
 475   ASSERT_IN_VM;
 476   Thread* current = Thread::current();
 477 
 478   // Now we need to check the SystemDictionary
 479   Symbol* sym = name->get_symbol();
 480   if (Signature::has_envelope(sym)) {
 481     // This is a name from a signature.  Strip off the trimmings.
 482     // Call recursive to keep scope of strippedsym.
 483     TempNewSymbol strippedsym = Signature::strip_envelope(sym);
 484     ciSymbol* strippedname = get_symbol(strippedsym);
 485     return get_klass_by_name_impl(accessing_klass, cpool, strippedname, require_local);
 486   }
 487 
 488   // Check for prior unloaded klass.  The SystemDictionary's answers
 489   // can vary over time but the compiler needs consistency.
 490   ciKlass* unloaded_klass = check_get_unloaded_klass(accessing_klass, name);
 491   if (unloaded_klass != nullptr) {
 492     if (require_local)  return nullptr;
 493     return unloaded_klass;
 494   }
 495 
 496   Handle loader;
 497   Handle domain;
 498   if (accessing_klass != nullptr) {
 499     loader = Handle(current, accessing_klass->loader());
 500     domain = Handle(current, accessing_klass->protection_domain());
 501   }
 502 
 503   Klass* found_klass = require_local ?
 504                          SystemDictionary::find_instance_or_array_klass(current, sym, loader, domain) :
 505                          SystemDictionary::find_constrained_instance_or_array_klass(current, sym, loader);
 506 
 507   // If we fail to find an array klass, look again for its element type.
 508   // The element type may be available either locally or via constraints.
 509   // In either case, if we can find the element type in the system dictionary,
 510   // we must build an array type around it.  The CI requires array klasses
 511   // to be loaded if their element klasses are loaded, except when memory
 512   // is exhausted.
 513   if (Signature::is_array(sym) &&
 514       (sym->char_at(1) == JVM_SIGNATURE_ARRAY || sym->char_at(1) == JVM_SIGNATURE_CLASS)) {
 515     // We have an unloaded array.
 516     // Build it on the fly if the element class exists.
 517     SignatureStream ss(sym, false);
 518     ss.skip_array_prefix(1);
 519     // Get element ciKlass recursively.
 520     ciKlass* elem_klass =
 521       get_klass_by_name_impl(accessing_klass,
 522                              cpool,
 523                              get_symbol(ss.as_symbol()),
 524                              require_local);
 525     if (elem_klass != nullptr && elem_klass->is_loaded()) {
 526       // Now make an array for it
 527       return ciObjArrayKlass::make_impl(elem_klass);
 528     }
 529   }
 530 
 531   if (found_klass == nullptr && !cpool.is_null() && cpool->has_preresolution()) {
 532     // Look inside the constant pool for pre-resolved class entries.
 533     for (int i = cpool->length() - 1; i >= 1; i--) {
 534       if (cpool->tag_at(i).is_klass()) {
 535         Klass* kls = cpool->resolved_klass_at(i);
 536         if (kls->name() == sym) {
 537           found_klass = kls;
 538           break;
 539         }
 540       }
 541     }
 542   }
 543 
 544   if (found_klass != nullptr) {
 545     // Found it.  Build a CI handle.
 546     return get_klass(found_klass);
 547   }
 548 
 549   if (require_local)  return nullptr;
 550 
 551   // Not yet loaded into the VM, or not governed by loader constraints.
 552   // Make a CI representative for it.
 553   return get_unloaded_klass(accessing_klass, name);
 554 }
 555 
 556 // ------------------------------------------------------------------
 557 // ciEnv::get_klass_by_name
 558 ciKlass* ciEnv::get_klass_by_name(ciKlass* accessing_klass,
 559                                   ciSymbol* klass_name,
 560                                   bool require_local) {
 561   GUARDED_VM_ENTRY(return get_klass_by_name_impl(accessing_klass,
 562                                                  constantPoolHandle(),
 563                                                  klass_name,
 564                                                  require_local);)
 565 }
 566 
 567 // ------------------------------------------------------------------
 568 // ciEnv::get_klass_by_index_impl
 569 //
 570 // Implementation of get_klass_by_index.
 571 ciKlass* ciEnv::get_klass_by_index_impl(const constantPoolHandle& cpool,
 572                                         int index,
 573                                         bool& is_accessible,
 574                                         ciInstanceKlass* accessor) {
 575   Klass* klass = nullptr;
 576   Symbol* klass_name = nullptr;
 577 
 578   if (cpool->tag_at(index).is_symbol()) {
 579     klass_name = cpool->symbol_at(index);
 580   } else {
 581     // Check if it's resolved if it's not a symbol constant pool entry.
 582     klass = ConstantPool::klass_at_if_loaded(cpool, index);
 583     // Try to look it up by name.
 584     if (klass == nullptr) {
 585       klass_name = cpool->klass_name_at(index);
 586     }
 587   }
 588 
 589   if (klass == nullptr) {
 590     // Not found in constant pool.  Use the name to do the lookup.
 591     ciKlass* k = get_klass_by_name_impl(accessor,
 592                                         cpool,
 593                                         get_symbol(klass_name),
 594                                         false);
 595     // Calculate accessibility the hard way.
 596     if (!k->is_loaded()) {
 597       is_accessible = false;
 598     } else if (k->loader() != accessor->loader() &&
 599                get_klass_by_name_impl(accessor, cpool, k->name(), true) == nullptr) {
 600       // Loaded only remotely.  Not linked yet.
 601       is_accessible = false;
 602     } else {
 603       // Linked locally, and we must also check public/private, etc.
 604       is_accessible = check_klass_accessibility(accessor, k->get_Klass());
 605     }
 606     return k;
 607   }
 608 
 609   // Check for prior unloaded klass.  The SystemDictionary's answers
 610   // can vary over time but the compiler needs consistency.
 611   ciSymbol* name = get_symbol(klass->name());
 612   ciKlass* unloaded_klass = check_get_unloaded_klass(accessor, name);
 613   if (unloaded_klass != nullptr) {
 614     is_accessible = false;
 615     return unloaded_klass;
 616   }
 617 
 618   // It is known to be accessible, since it was found in the constant pool.
 619   ciKlass* ciKlass = get_klass(klass);
 620   is_accessible = true;
 621   if (ReplayCompiles && ciKlass == _unloaded_ciinstance_klass) {
 622     // Klass was unresolved at replay dump time and therefore not accessible.
 623     is_accessible = false;
 624   }
 625   return ciKlass;
 626 }
 627 
 628 // ------------------------------------------------------------------
 629 // ciEnv::get_klass_by_index
 630 //
 631 // Get a klass from the constant pool.
 632 ciKlass* ciEnv::get_klass_by_index(const constantPoolHandle& cpool,
 633                                    int index,
 634                                    bool& is_accessible,
 635                                    ciInstanceKlass* accessor) {
 636   GUARDED_VM_ENTRY(return get_klass_by_index_impl(cpool, index, is_accessible, accessor);)
 637 }
 638 
 639 // ------------------------------------------------------------------
 640 // ciEnv::unbox_primitive_value
 641 //
 642 // Unbox a primitive and return it as a ciConstant.
 643 ciConstant ciEnv::unbox_primitive_value(ciObject* cibox, BasicType expected_bt) {
 644   jvalue value;
 645   BasicType bt = java_lang_boxing_object::get_value(cibox->get_oop(), &value);
 646   if (bt != expected_bt && expected_bt != T_ILLEGAL) {
 647     assert(false, "type mismatch: %s vs %s", type2name(expected_bt), cibox->klass()->name()->as_klass_external_name());
 648     return ciConstant();
 649   }
 650   switch (bt) {
 651     case T_BOOLEAN: return ciConstant(bt, value.z);
 652     case T_BYTE:    return ciConstant(bt, value.b);
 653     case T_SHORT:   return ciConstant(bt, value.s);
 654     case T_CHAR:    return ciConstant(bt, value.c);
 655     case T_INT:     return ciConstant(bt, value.i);
 656     case T_LONG:    return ciConstant(value.j);
 657     case T_FLOAT:   return ciConstant(value.f);
 658     case T_DOUBLE:  return ciConstant(value.d);
 659 
 660     default:
 661       assert(false, "not a primitive type: %s", type2name(bt));
 662       return ciConstant();
 663   }
 664 }
 665 
 666 // ------------------------------------------------------------------
 667 // ciEnv::get_resolved_constant
 668 //
 669 ciConstant ciEnv::get_resolved_constant(const constantPoolHandle& cpool, int obj_index) {
 670   assert(obj_index >= 0, "");
 671   oop obj = cpool->resolved_reference_at(obj_index);
 672   if (obj == nullptr) {
 673     // Unresolved constant. It is resolved when the corresponding slot contains a non-null reference.
 674     // Null constant is represented as a sentinel (non-null) value.
 675     return ciConstant();
 676   } else if (obj == Universe::the_null_sentinel()) {
 677     return ciConstant(T_OBJECT, get_object(nullptr));
 678   } else {
 679     ciObject* ciobj = get_object(obj);
 680     if (ciobj->is_array()) {
 681       return ciConstant(T_ARRAY, ciobj);
 682     } else {
 683       int cp_index = cpool->object_to_cp_index(obj_index);
 684       BasicType bt = cpool->basic_type_for_constant_at(cp_index);
 685       if (is_java_primitive(bt)) {
 686         assert(cpool->tag_at(cp_index).is_dynamic_constant(), "sanity");
 687         return unbox_primitive_value(ciobj, bt);
 688       } else {
 689         assert(ciobj->is_instance(), "should be an instance");
 690         return ciConstant(T_OBJECT, ciobj);
 691       }
 692     }
 693   }
 694 }
 695 
 696 // ------------------------------------------------------------------
 697 // ciEnv::get_constant_by_index_impl
 698 //
 699 // Implementation of get_constant_by_index().
 700 ciConstant ciEnv::get_constant_by_index_impl(const constantPoolHandle& cpool,
 701                                              int index, int obj_index,
 702                                              ciInstanceKlass* accessor) {
 703   if (obj_index >= 0) {
 704     ciConstant con = get_resolved_constant(cpool, obj_index);
 705     if (con.is_valid()) {
 706       return con;
 707     }
 708   }
 709   constantTag tag = cpool->tag_at(index);
 710   if (tag.is_int()) {
 711     return ciConstant(T_INT, (jint)cpool->int_at(index));
 712   } else if (tag.is_long()) {
 713     return ciConstant((jlong)cpool->long_at(index));
 714   } else if (tag.is_float()) {
 715     return ciConstant((jfloat)cpool->float_at(index));
 716   } else if (tag.is_double()) {
 717     return ciConstant((jdouble)cpool->double_at(index));
 718   } else if (tag.is_string()) {
 719     EXCEPTION_CONTEXT;
 720     assert(obj_index >= 0, "should have an object index");
 721     oop string = cpool->string_at(index, obj_index, THREAD);
 722     if (HAS_PENDING_EXCEPTION) {
 723       CLEAR_PENDING_EXCEPTION;
 724       record_out_of_memory_failure();
 725       return ciConstant();
 726     }
 727     ciInstance* constant = get_object(string)->as_instance();
 728     return ciConstant(T_OBJECT, constant);
 729   } else if (tag.is_unresolved_klass_in_error()) {
 730     return ciConstant(T_OBJECT, get_unloaded_klass_mirror(nullptr));
 731   } else if (tag.is_klass() || tag.is_unresolved_klass()) {
 732     bool will_link;
 733     ciKlass* klass = get_klass_by_index_impl(cpool, index, will_link, accessor);
 734     ciInstance* mirror = (will_link ? klass->java_mirror() : get_unloaded_klass_mirror(klass));
 735     return ciConstant(T_OBJECT, mirror);
 736   } else if (tag.is_method_type() || tag.is_method_type_in_error()) {
 737     // must execute Java code to link this CP entry into cache[i].f1
 738     assert(obj_index >= 0, "should have an object index");
 739     ciSymbol* signature = get_symbol(cpool->method_type_signature_at(index));
 740     ciObject* ciobj = get_unloaded_method_type_constant(signature);
 741     return ciConstant(T_OBJECT, ciobj);
 742   } else if (tag.is_method_handle() || tag.is_method_handle_in_error()) {
 743     // must execute Java code to link this CP entry into cache[i].f1
 744     assert(obj_index >= 0, "should have an object index");
 745     bool ignore_will_link;
 746     int ref_kind        = cpool->method_handle_ref_kind_at(index);
 747     int callee_index    = cpool->method_handle_klass_index_at(index);
 748     ciKlass* callee     = get_klass_by_index_impl(cpool, callee_index, ignore_will_link, accessor);
 749     ciSymbol* name      = get_symbol(cpool->method_handle_name_ref_at(index));
 750     ciSymbol* signature = get_symbol(cpool->method_handle_signature_ref_at(index));
 751     ciObject* ciobj     = get_unloaded_method_handle_constant(callee, name, signature, ref_kind);
 752     return ciConstant(T_OBJECT, ciobj);
 753   } else if (tag.is_dynamic_constant() || tag.is_dynamic_constant_in_error()) {
 754     assert(obj_index >= 0, "should have an object index");
 755     return ciConstant(T_OBJECT, unloaded_ciinstance()); // unresolved dynamic constant
 756   } else {
 757     assert(false, "unknown tag: %d (%s)", tag.value(), tag.internal_name());
 758     return ciConstant();
 759   }
 760 }
 761 
 762 // ------------------------------------------------------------------
 763 // ciEnv::get_constant_by_index
 764 //
 765 // Pull a constant out of the constant pool.  How appropriate.
 766 //
 767 // Implementation note: this query is currently in no way cached.
 768 ciConstant ciEnv::get_constant_by_index(const constantPoolHandle& cpool,
 769                                         int pool_index, int cache_index,
 770                                         ciInstanceKlass* accessor) {
 771   GUARDED_VM_ENTRY(return get_constant_by_index_impl(cpool, pool_index, cache_index, accessor);)
 772 }
 773 
 774 // ------------------------------------------------------------------
 775 // ciEnv::get_field_by_index_impl
 776 //
 777 // Implementation of get_field_by_index.
 778 //
 779 // Implementation note: the results of field lookups are cached
 780 // in the accessor klass.
 781 ciField* ciEnv::get_field_by_index_impl(ciInstanceKlass* accessor,
 782                                         int index, Bytecodes::Code bc) {
 783   ciConstantPoolCache* cache = accessor->field_cache();
 784   if (cache == nullptr) {
 785     ciField* field = new (arena()) ciField(accessor, index, bc);
 786     return field;
 787   } else {
 788     ciField* field = (ciField*)cache->get(index);
 789     if (field == nullptr) {
 790       field = new (arena()) ciField(accessor, index, bc);
 791       cache->insert(index, field);
 792     }
 793     return field;
 794   }
 795 }
 796 
 797 // ------------------------------------------------------------------
 798 // ciEnv::get_field_by_index
 799 //
 800 // Get a field by index from a klass's constant pool.
 801 ciField* ciEnv::get_field_by_index(ciInstanceKlass* accessor,
 802                                    int index, Bytecodes::Code bc) {
 803   GUARDED_VM_ENTRY(return get_field_by_index_impl(accessor, index, bc);)
 804 }
 805 
 806 // ------------------------------------------------------------------
 807 // ciEnv::lookup_method
 808 //
 809 // Perform an appropriate method lookup based on accessor, holder,
 810 // name, signature, and bytecode.
 811 Method* ciEnv::lookup_method(ciInstanceKlass* accessor,
 812                              ciKlass*         holder,
 813                              Symbol*          name,
 814                              Symbol*          sig,
 815                              Bytecodes::Code  bc,
 816                              constantTag      tag) {
 817   InstanceKlass* accessor_klass = accessor->get_instanceKlass();
 818   Klass* holder_klass = holder->get_Klass();
 819 
 820   // Accessibility checks are performed in ciEnv::get_method_by_index_impl.
 821   assert(check_klass_accessibility(accessor, holder_klass), "holder not accessible");
 822 
 823   LinkInfo link_info(holder_klass, name, sig, accessor_klass,
 824                      LinkInfo::AccessCheck::required,
 825                      LinkInfo::LoaderConstraintCheck::required,
 826                      tag);
 827   switch (bc) {
 828     case Bytecodes::_invokestatic:
 829       return LinkResolver::resolve_static_call_or_null(link_info);
 830     case Bytecodes::_invokespecial:
 831       return LinkResolver::resolve_special_call_or_null(link_info);
 832     case Bytecodes::_invokeinterface:
 833       return LinkResolver::linktime_resolve_interface_method_or_null(link_info);
 834     case Bytecodes::_invokevirtual:
 835       return LinkResolver::linktime_resolve_virtual_method_or_null(link_info);
 836     default:
 837       fatal("Unhandled bytecode: %s", Bytecodes::name(bc));
 838       return nullptr; // silence compiler warnings
 839   }
 840 }
 841 
 842 
 843 // ------------------------------------------------------------------
 844 // ciEnv::get_method_by_index_impl
 845 ciMethod* ciEnv::get_method_by_index_impl(const constantPoolHandle& cpool,
 846                                           int index, Bytecodes::Code bc,
 847                                           ciInstanceKlass* accessor) {
 848   assert(cpool.not_null(), "need constant pool");
 849   assert(accessor != nullptr, "need origin of access");
 850   if (bc == Bytecodes::_invokedynamic) {
 851     // FIXME: code generation could allow for null (unlinked) call site
 852     // The call site could be made patchable as follows:
 853     // Load the appendix argument from the constant pool.
 854     // Test the appendix argument and jump to a known deopt routine if it is null.
 855     // Jump through a patchable call site, which is initially a deopt routine.
 856     // Patch the call site to the nmethod entry point of the static compiled lambda form.
 857     // As with other two-component call sites, both values must be independently verified.
 858     int indy_index = cpool->decode_invokedynamic_index(index);
 859     assert (indy_index >= 0, "should be");
 860     assert(indy_index < cpool->cache()->resolved_indy_entries_length(), "impossible");
 861     Method* adapter = cpool->resolved_indy_entry_at(indy_index)->method();
 862     // Resolved if the adapter is non null.
 863     if (adapter != nullptr) {
 864       return get_method(adapter);
 865     }
 866 
 867     // Fake a method that is equivalent to a declared method.
 868     ciInstanceKlass* holder    = get_instance_klass(vmClasses::MethodHandle_klass());
 869     ciSymbol*        name      = ciSymbols::invokeBasic_name();
 870     ciSymbol*        signature = get_symbol(cpool->signature_ref_at(index, bc));
 871     return get_unloaded_method(holder, name, signature, accessor);
 872   } else {
 873     const int holder_index = cpool->klass_ref_index_at(index, bc);
 874     bool holder_is_accessible;
 875     ciKlass* holder = get_klass_by_index_impl(cpool, holder_index, holder_is_accessible, accessor);
 876 
 877     // Get the method's name and signature.
 878     Symbol* name_sym = cpool->name_ref_at(index, bc);
 879     Symbol* sig_sym  = cpool->signature_ref_at(index, bc);
 880 
 881     if (cpool->has_preresolution()
 882         || ((holder == ciEnv::MethodHandle_klass() || holder == ciEnv::VarHandle_klass()) &&
 883             MethodHandles::is_signature_polymorphic_name(holder->get_Klass(), name_sym))) {
 884       // Short-circuit lookups for JSR 292-related call sites.
 885       // That is, do not rely only on name-based lookups, because they may fail
 886       // if the names are not resolvable in the boot class loader (7056328).
 887       switch (bc) {
 888       case Bytecodes::_invokevirtual:
 889       case Bytecodes::_invokeinterface:
 890       case Bytecodes::_invokespecial:
 891       case Bytecodes::_invokestatic:
 892         {
 893           Method* m = ConstantPool::method_at_if_loaded(cpool, index);
 894           if (m != nullptr) {
 895             return get_method(m);
 896           }
 897         }
 898         break;
 899       default:
 900         break;
 901       }
 902     }
 903 
 904     if (holder_is_accessible) {  // Our declared holder is loaded.
 905       constantTag tag = cpool->tag_ref_at(index, bc);
 906       assert(accessor->get_instanceKlass() == cpool->pool_holder(), "not the pool holder?");
 907       Method* m = lookup_method(accessor, holder, name_sym, sig_sym, bc, tag);
 908       if (m != nullptr &&
 909           (bc == Bytecodes::_invokestatic
 910            ?  m->method_holder()->is_not_initialized()
 911            : !m->method_holder()->is_loaded())) {
 912         m = nullptr;
 913       }
 914       if (m != nullptr && ReplayCompiles && !ciReplay::is_loaded(m)) {
 915         m = nullptr;
 916       }
 917       if (m != nullptr) {
 918         // We found the method.
 919         return get_method(m);
 920       }
 921     }
 922 
 923     // Either the declared holder was not loaded, or the method could
 924     // not be found.  Create a dummy ciMethod to represent the failed
 925     // lookup.
 926     ciSymbol* name      = get_symbol(name_sym);
 927     ciSymbol* signature = get_symbol(sig_sym);
 928     return get_unloaded_method(holder, name, signature, accessor);
 929   }
 930 }
 931 
 932 
 933 // ------------------------------------------------------------------
 934 // ciEnv::get_instance_klass_for_declared_method_holder
 935 ciInstanceKlass* ciEnv::get_instance_klass_for_declared_method_holder(ciKlass* method_holder) {
 936   // For the case of <array>.clone(), the method holder can be a ciArrayKlass
 937   // instead of a ciInstanceKlass.  For that case simply pretend that the
 938   // declared holder is Object.clone since that's where the call will bottom out.
 939   // A more correct fix would trickle out through many interfaces in CI,
 940   // requiring ciInstanceKlass* to become ciKlass* and many more places would
 941   // require checks to make sure the expected type was found.  Given that this
 942   // only occurs for clone() the more extensive fix seems like overkill so
 943   // instead we simply smear the array type into Object.
 944   guarantee(method_holder != nullptr, "no method holder");
 945   if (method_holder->is_instance_klass()) {
 946     return method_holder->as_instance_klass();
 947   } else if (method_holder->is_array_klass()) {
 948     return current()->Object_klass();
 949   } else {
 950     ShouldNotReachHere();
 951   }
 952   return nullptr;
 953 }
 954 
 955 
 956 // ------------------------------------------------------------------
 957 // ciEnv::get_method_by_index
 958 ciMethod* ciEnv::get_method_by_index(const constantPoolHandle& cpool,
 959                                      int index, Bytecodes::Code bc,
 960                                      ciInstanceKlass* accessor) {
 961   GUARDED_VM_ENTRY(return get_method_by_index_impl(cpool, index, bc, accessor);)
 962 }
 963 
 964 
 965 // ------------------------------------------------------------------
 966 // ciEnv::name_buffer
 967 char *ciEnv::name_buffer(int req_len) {
 968   if (_name_buffer_len < req_len) {
 969     if (_name_buffer == nullptr) {
 970       _name_buffer = (char*)arena()->Amalloc(sizeof(char)*req_len);
 971       _name_buffer_len = req_len;
 972     } else {
 973       _name_buffer =
 974         (char*)arena()->Arealloc(_name_buffer, _name_buffer_len, req_len);
 975       _name_buffer_len = req_len;
 976     }
 977   }
 978   return _name_buffer;
 979 }
 980 
 981 // ------------------------------------------------------------------
 982 // ciEnv::is_in_vm
 983 bool ciEnv::is_in_vm() {
 984   return JavaThread::current()->thread_state() == _thread_in_vm;
 985 }
 986 
 987 // ------------------------------------------------------------------
 988 // ciEnv::validate_compile_task_dependencies
 989 //
 990 // Check for changes during compilation (e.g. class loads, evolution,
 991 // breakpoints, call site invalidation).
 992 void ciEnv::validate_compile_task_dependencies(ciMethod* target) {
 993   assert(!failing(), "should not call this when failing");
 994 
 995   Dependencies::DepType result = dependencies()->validate_dependencies(_task);
 996   if (result != Dependencies::end_marker) {
 997     if (result == Dependencies::call_site_target_value) {
 998       _inc_decompile_count_on_failure = false;
 999       record_failure("call site target change");
1000     } else if (Dependencies::is_klass_type(result)) {
1001       record_failure("concurrent class loading");
1002     } else {
1003       record_failure("invalid non-klass dependency");
1004     }
1005   }
1006 }
1007 
1008 // ------------------------------------------------------------------
1009 // ciEnv::register_method
1010 void ciEnv::register_method(ciMethod* target,
1011                             int entry_bci,
1012                             CodeOffsets* offsets,
1013                             int orig_pc_offset,
1014                             CodeBuffer* code_buffer,
1015                             int frame_words,
1016                             OopMapSet* oop_map_set,
1017                             ExceptionHandlerTable* handler_table,
1018                             ImplicitExceptionTable* inc_table,
1019                             AbstractCompiler* compiler,
1020                             bool has_clinit_barriers,
1021                             bool for_preload,
1022                             bool has_unsafe_access,
1023                             bool has_wide_vectors,
1024                             bool has_monitors,
1025                             int immediate_oops_patched,
1026                             bool install_code,
1027                             RTMState  rtm_state,
1028                             SCCEntry* scc_entry) {
1029   VM_ENTRY_MARK;
1030   nmethod* nm = nullptr;
1031   {
1032     methodHandle method(THREAD, target->get_Method());
1033     bool preload = task()->preload(); // Code is preloaded before Java method execution
1034 
1035     // We require method counters to store some method state (max compilation levels) required by the compilation policy.
1036     if (!preload && method->get_method_counters(THREAD) == nullptr) {
1037       record_failure("can't create method counters");
1038       // All buffers in the CodeBuffer are allocated in the CodeCache.
1039       // If the code buffer is created on each compile attempt
1040       // as in C2, then it must be freed.
1041       // But keep shared code.
1042       code_buffer->free_blob();
1043       return;
1044     }
1045 
1046     // Check if memory should be freed before allocation
1047     CodeCache::gc_on_allocation();
1048 
1049     // To prevent compile queue updates.
1050     MutexLocker locker(THREAD, MethodCompileQueue_lock);
1051 
1052     // Prevent InstanceKlass::add_to_hierarchy from running
1053     // and invalidating our dependencies until we install this method.
1054     // No safepoints are allowed. Otherwise, class redefinition can occur in between.
1055     MutexLocker ml(Compile_lock);
1056     NoSafepointVerifier nsv;
1057 
1058     if (scc_entry != nullptr && scc_entry->not_entrant()) {
1059       // This shared code was marked invalid while it was loaded
1060       code_buffer->free_blob();
1061       return;
1062     }
1063 
1064     // Change in Jvmti state may invalidate compilation.
1065     if (!failing() && jvmti_state_changed()) {
1066       record_failure("Jvmti state change invalidated dependencies");
1067     }
1068 
1069     // Change in DTrace flags may invalidate compilation.
1070     if (!failing() &&
1071         ( (!dtrace_method_probes() && DTraceMethodProbes) ||
1072           (!dtrace_alloc_probes() && DTraceAllocProbes) )) {
1073       record_failure("DTrace flags change invalidated dependencies");
1074     }
1075 
1076     if (!preload && !failing() && target->needs_clinit_barrier() &&
1077         target->holder()->is_in_error_state()) {
1078       record_failure("method holder is in error state");
1079     }
1080 
1081     if (!failing() && (scc_entry == nullptr)) {
1082       if (log() != nullptr) {
1083         // Log the dependencies which this compilation declares.
1084         dependencies()->log_all_dependencies();
1085       }
1086 
1087       // Encode the dependencies now, so we can check them right away.
1088       dependencies()->encode_content_bytes();
1089     }
1090     // Check for {class loads, evolution, breakpoints, ...} during compilation
1091     if (!failing() && install_code) {
1092       // Check for {class loads, evolution, breakpoints, ...} during compilation
1093       validate_compile_task_dependencies(target);
1094       if (failing() && preload) {
1095         ResourceMark rm;
1096         char *method_name = method->name_and_sig_as_C_string();
1097         log_warning(scc)("preload code for '%s' failed dependency check", method_name);
1098       }
1099     }
1100 #if INCLUDE_RTM_OPT
1101     if (!failing() && (rtm_state != NoRTM) &&
1102         (method()->method_data() != nullptr) &&
1103         (method()->method_data()->rtm_state() != rtm_state)) {
1104       // Preemptive decompile if rtm state was changed.
1105       record_failure("RTM state change invalidated rtm code");
1106     }
1107 #endif
1108 
1109     if (failing()) {
1110       // While not a true deoptimization, it is a preemptive decompile.
1111       MethodData* mdo = method()->method_data();
1112       if (mdo != nullptr && _inc_decompile_count_on_failure) {
1113         mdo->inc_decompile_count();
1114       }
1115 
1116       // All buffers in the CodeBuffer are allocated in the CodeCache.
1117       // If the code buffer is created on each compile attempt
1118       // as in C2, then it must be freed.
1119       code_buffer->free_blob();
1120       return;
1121     }
1122 
1123     assert(offsets->value(CodeOffsets::Deopt) != -1, "must have deopt entry");
1124     assert(offsets->value(CodeOffsets::Exceptions) != -1, "must have exception entry");
1125 
1126     if (rtm_state == NoRTM && scc_entry == nullptr) {
1127       scc_entry = SCCache::store_nmethod(method,
1128                              compile_id(),
1129                              entry_bci,
1130                              offsets,
1131                              orig_pc_offset,
1132                              debug_info(), dependencies(), code_buffer,
1133                              frame_words, oop_map_set,
1134                              handler_table, inc_table,
1135                              compiler,
1136                              CompLevel(task()->comp_level()),
1137                              has_clinit_barriers,
1138                              for_preload,
1139                              has_unsafe_access,
1140                              has_wide_vectors,
1141                              has_monitors);
1142       if (scc_entry != nullptr) {
1143         scc_entry->set_inlined_bytecodes(num_inlined_bytecodes());
1144         if (has_clinit_barriers) {
1145           set_scc_clinit_barriers_entry(scc_entry); // Record it
1146           // Build second version of code without class initialization barriers
1147           code_buffer->free_blob();
1148           return;
1149         } else if (!for_preload) {
1150           SCCEntry* previous_entry = scc_clinit_barriers_entry();
1151           scc_entry->set_next(previous_entry); // Link it for case of deoptimization
1152         }
1153       }
1154     }
1155     if (install_code) {
1156       nm =  nmethod::new_nmethod(method,
1157                                  compile_id(),
1158                                  entry_bci,
1159                                  offsets,
1160                                  orig_pc_offset,
1161                                  debug_info(), dependencies(), code_buffer,
1162                                  frame_words, oop_map_set,
1163                                  handler_table, inc_table,
1164                                  compiler, CompLevel(task()->comp_level()),
1165                                  scc_entry);
1166     }
1167     // Free codeBlobs
1168     code_buffer->free_blob();
1169 
1170     if (nm != nullptr) {
1171       nm->set_has_unsafe_access(has_unsafe_access);
1172       nm->set_has_wide_vectors(has_wide_vectors);
1173       nm->set_has_monitors(has_monitors);
1174       nm->set_preloaded(preload);
1175       nm->set_has_clinit_barriers(has_clinit_barriers);
1176       assert(!method->is_synchronized() || nm->has_monitors(), "");
1177 #if INCLUDE_RTM_OPT
1178       nm->set_rtm_state(rtm_state);
1179 #endif
1180 
1181       if (entry_bci == InvocationEntryBci) {
1182         if (TieredCompilation || SCCache::is_on_for_read()) {
1183           // If there is an old version we're done with it
1184           CompiledMethod* old = method->code();
1185           if (TraceMethodReplacement && old != nullptr) {
1186             ResourceMark rm;
1187             char *method_name = method->name_and_sig_as_C_string();
1188             tty->print_cr("Replacing method %s", method_name);
1189           }
1190           if (old != nullptr) {
1191             old->make_not_used();
1192           }
1193         }
1194 
1195         LogTarget(Info, nmethod, install) lt;
1196         if (lt.is_enabled()) {
1197           ResourceMark rm;
1198           char *method_name = method->name_and_sig_as_C_string();
1199           lt.print("Installing method (L%d) %s id=%d scc=%s%s%u",
1200                     task()->comp_level(), method_name, compile_id(),
1201                     task()->is_scc() ? "A" : "", preload ? "P" : "",
1202                     (scc_entry != nullptr ? scc_entry->offset() : 0));
1203         }
1204         // Allow the code to be executed
1205         MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
1206         if (nm->make_in_use()) {
1207 #ifdef ASSERT
1208           BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
1209           if (bs_nm != nullptr && bs_nm->supports_entry_barrier(nm)) {
1210             if (!bs_nm->is_armed(nm)) {
1211               log_info(init)("nmethod %d %d not armed", nm->compile_id(), nm->comp_level());
1212             }
1213           }
1214 #endif // ASSERT
1215           if (preload) {
1216             method->set_preload_code(nm);
1217           }
1218           if (!preload || target->holder()->is_linked()) {
1219             method->set_code(method, nm);
1220           }
1221         }
1222       } else {
1223         LogTarget(Info, nmethod, install) lt;
1224         if (lt.is_enabled()) {
1225           ResourceMark rm;
1226           char *method_name = method->name_and_sig_as_C_string();
1227           lt.print("Installing osr method (L%d) %s @ %d id=%u scc=%s%u",
1228                    task()->comp_level(), method_name, entry_bci, compile_id(),
1229                    task()->is_scc() ? "A" : "",
1230                    (scc_entry != nullptr ? scc_entry->offset() : 0));
1231         }
1232         MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
1233         if (nm->make_in_use()) {
1234           method->method_holder()->add_osr_nmethod(nm);
1235         }
1236       }
1237     }
1238   }
1239 
1240   NoSafepointVerifier nsv;
1241   if (nm != nullptr) {
1242     // Compilation succeeded, post what we know about it
1243     nm->post_compiled_method(task());
1244     task()->set_num_inlined_bytecodes(num_inlined_bytecodes());
1245   } else if (install_code) {
1246     // The CodeCache is full.
1247     record_failure("code cache is full");
1248   } else {
1249     task()->set_num_inlined_bytecodes(num_inlined_bytecodes());
1250   }
1251 
1252   // safepoints are allowed again
1253 }
1254 
1255 // ------------------------------------------------------------------
1256 // ciEnv::find_system_klass
1257 ciKlass* ciEnv::find_system_klass(ciSymbol* klass_name) {
1258   VM_ENTRY_MARK;
1259   return get_klass_by_name_impl(nullptr, constantPoolHandle(), klass_name, false);
1260 }
1261 
1262 // ------------------------------------------------------------------
1263 // ciEnv::comp_level
1264 int ciEnv::comp_level() {
1265   if (task() == nullptr)  return CompilationPolicy::highest_compile_level();
1266   return task()->comp_level();
1267 }
1268 
1269 // ------------------------------------------------------------------
1270 // ciEnv::compile_id
1271 int ciEnv::compile_id() {
1272   if (task() == nullptr)  return 0;
1273   return task()->compile_id();
1274 }
1275 
1276 // ------------------------------------------------------------------
1277 // ciEnv::notice_inlined_method()
1278 void ciEnv::notice_inlined_method(ciMethod* method) {
1279   _num_inlined_bytecodes += method->code_size_for_inlining();
1280   CompileTrainingData* tdata = task()->training_data();
1281   if (tdata != nullptr) {
1282     GUARDED_VM_ENTRY({
1283       methodHandle mh(Thread::current(), method->get_Method());
1284       tdata->notice_inlined_method(task(), mh);
1285     });
1286   }
1287 }
1288 
1289 // ------------------------------------------------------------------
1290 // ciEnv::num_inlined_bytecodes()
1291 int ciEnv::num_inlined_bytecodes() const {
1292   return _num_inlined_bytecodes;
1293 }
1294 
1295 // ------------------------------------------------------------------
1296 // ciEnv::record_failure()
1297 void ciEnv::record_failure(const char* reason) {
1298   if (_failure_reason == nullptr) {
1299     // Record the first failure reason.
1300     _failure_reason = reason;
1301   }
1302 }
1303 
1304 void ciEnv::report_failure(const char* reason) {
1305   EventCompilationFailure event;
1306   if (event.should_commit()) {
1307     CompilerEvent::CompilationFailureEvent::post(event, compile_id(), reason);
1308   }
1309 }
1310 
1311 // ------------------------------------------------------------------
1312 // ciEnv::record_method_not_compilable()
1313 void ciEnv::record_method_not_compilable(const char* reason, bool all_tiers) {
1314   int new_compilable =
1315     all_tiers ? MethodCompilable_never : MethodCompilable_not_at_tier ;
1316 
1317   // Only note transitions to a worse state
1318   if (new_compilable > _compilable) {
1319     if (log() != nullptr) {
1320       if (all_tiers) {
1321         log()->elem("method_not_compilable");
1322       } else {
1323         log()->elem("method_not_compilable_at_tier level='%d'",
1324                     current()->task()->comp_level());
1325       }
1326     }
1327     _compilable = new_compilable;
1328 
1329     // Reset failure reason; this one is more important.
1330     _failure_reason = nullptr;
1331     record_failure(reason);
1332   }
1333 }
1334 
1335 // ------------------------------------------------------------------
1336 // ciEnv::record_out_of_memory_failure()
1337 void ciEnv::record_out_of_memory_failure() {
1338   // If memory is low, we stop compiling methods.
1339   record_method_not_compilable("out of memory");
1340 }
1341 
1342 ciInstance* ciEnv::unloaded_ciinstance() {
1343   GUARDED_VM_ENTRY(return _factory->get_unloaded_object_constant();)
1344 }
1345 
1346 // ------------------------------------------------------------------
1347 // Replay support
1348 
1349 
1350 // Lookup location descriptor for the class, if any.
1351 // Returns false if not found.
1352 bool ciEnv::dyno_loc(const InstanceKlass* ik, const char *&loc) const {
1353   bool found = false;
1354   int pos = _dyno_klasses->find_sorted<const InstanceKlass*, klass_compare>(ik, found);
1355   if (!found) {
1356     return false;
1357   }
1358   loc = _dyno_locs->at(pos);
1359   return found;
1360 }
1361 
1362 // Associate the current location descriptor with the given class and record for later lookup.
1363 void ciEnv::set_dyno_loc(const InstanceKlass* ik) {
1364   const char *loc = os::strdup(_dyno_name);
1365   bool found = false;
1366   int pos = _dyno_klasses->find_sorted<const InstanceKlass*, klass_compare>(ik, found);
1367   if (found) {
1368     _dyno_locs->at_put(pos, loc);
1369   } else {
1370     _dyno_klasses->insert_before(pos, ik);
1371     _dyno_locs->insert_before(pos, loc);
1372   }
1373 }
1374 
1375 // Associate the current location descriptor with the given class and record for later lookup.
1376 // If it turns out that there are multiple locations for the given class, that conflict should
1377 // be handled here.  Currently we choose the first location found.
1378 void ciEnv::record_best_dyno_loc(const InstanceKlass* ik) {
1379   if (!ik->is_hidden()) {
1380     return;
1381   }
1382   const char *loc0;
1383   if (!dyno_loc(ik, loc0)) {
1384     set_dyno_loc(ik);
1385   }
1386 }
1387 
1388 // Look up the location descriptor for the given class and print it to the output stream.
1389 bool ciEnv::print_dyno_loc(outputStream* out, const InstanceKlass* ik) const {
1390   const char *loc;
1391   if (dyno_loc(ik, loc)) {
1392     out->print("%s", loc);
1393     return true;
1394   } else {
1395     return false;
1396   }
1397 }
1398 
1399 // Look up the location descriptor for the given class and return it as a string.
1400 // Returns null if no location is found.
1401 const char *ciEnv::dyno_name(const InstanceKlass* ik) const {
1402   if (ik->is_hidden()) {
1403     stringStream ss;
1404     if (print_dyno_loc(&ss, ik)) {
1405       ss.print(" ;"); // add terminator
1406       const char* call_site = ss.as_string();
1407       return call_site;
1408     }
1409   }
1410   return nullptr;
1411 }
1412 
1413 // Look up the location descriptor for the given class and return it as a string.
1414 // Returns the class name as a fallback if no location is found.
1415 const char *ciEnv::replay_name(ciKlass* k) const {
1416   if (k->is_instance_klass()) {
1417     return replay_name(k->as_instance_klass()->get_instanceKlass());
1418   }
1419   return k->name()->as_quoted_ascii();
1420 }
1421 
1422 // Look up the location descriptor for the given class and return it as a string.
1423 // Returns the class name as a fallback if no location is found.
1424 const char *ciEnv::replay_name(const InstanceKlass* ik) const {
1425   const char* name = dyno_name(ik);
1426   if (name != nullptr) {
1427       return name;
1428   }
1429   return ik->name()->as_quoted_ascii();
1430 }
1431 
1432 // Process a java.lang.invoke.MemberName object and record any dynamic locations.
1433 void ciEnv::record_member(Thread* thread, oop member) {
1434   assert(java_lang_invoke_MemberName::is_instance(member), "!");
1435   // Check MemberName.clazz field
1436   oop clazz = java_lang_invoke_MemberName::clazz(member);
1437   if (clazz->klass()->is_instance_klass()) {
1438     RecordLocation fp(this, "clazz");
1439     InstanceKlass* ik = InstanceKlass::cast(clazz->klass());
1440     record_best_dyno_loc(ik);
1441   }
1442   // Check MemberName.method.vmtarget field
1443   Method* vmtarget = java_lang_invoke_MemberName::vmtarget(member);
1444   if (vmtarget != nullptr) {
1445     RecordLocation fp2(this, "<vmtarget>");
1446     InstanceKlass* ik = vmtarget->method_holder();
1447     record_best_dyno_loc(ik);
1448   }
1449 }
1450 
1451 // Read an object field.  Lookup is done by name only.
1452 static inline oop obj_field(oop obj, const char* name) {
1453     return ciReplay::obj_field(obj, name);
1454 }
1455 
1456 // Process a java.lang.invoke.LambdaForm object and record any dynamic locations.
1457 void ciEnv::record_lambdaform(Thread* thread, oop form) {
1458   assert(java_lang_invoke_LambdaForm::is_instance(form), "!");
1459 
1460   {
1461     // Check LambdaForm.vmentry field
1462     oop member = java_lang_invoke_LambdaForm::vmentry(form);
1463     RecordLocation fp0(this, "vmentry");
1464     record_member(thread, member);
1465   }
1466 
1467   // Check LambdaForm.names array
1468   objArrayOop names = (objArrayOop)obj_field(form, "names");
1469   if (names != nullptr) {
1470     RecordLocation lp0(this, "names");
1471     int len = names->length();
1472     for (int i = 0; i < len; ++i) {
1473       oop name = names->obj_at(i);
1474       RecordLocation lp1(this, "%d", i);
1475      // Check LambdaForm.names[i].function field
1476       RecordLocation lp2(this, "function");
1477       oop function = obj_field(name, "function");
1478       if (function != nullptr) {
1479         // Check LambdaForm.names[i].function.member field
1480         oop member = obj_field(function, "member");
1481         if (member != nullptr) {
1482           RecordLocation lp3(this, "member");
1483           record_member(thread, member);
1484         }
1485         // Check LambdaForm.names[i].function.resolvedHandle field
1486         oop mh = obj_field(function, "resolvedHandle");
1487         if (mh != nullptr) {
1488           RecordLocation lp3(this, "resolvedHandle");
1489           record_mh(thread, mh);
1490         }
1491         // Check LambdaForm.names[i].function.invoker field
1492         oop invoker = obj_field(function, "invoker");
1493         if (invoker != nullptr) {
1494           RecordLocation lp3(this, "invoker");
1495           record_mh(thread, invoker);
1496         }
1497       }
1498     }
1499   }
1500 }
1501 
1502 // Process a java.lang.invoke.MethodHandle object and record any dynamic locations.
1503 void ciEnv::record_mh(Thread* thread, oop mh) {
1504   {
1505     // Check MethodHandle.form field
1506     oop form = java_lang_invoke_MethodHandle::form(mh);
1507     RecordLocation fp(this, "form");
1508     record_lambdaform(thread, form);
1509   }
1510   // Check DirectMethodHandle.member field
1511   if (java_lang_invoke_DirectMethodHandle::is_instance(mh)) {
1512     oop member = java_lang_invoke_DirectMethodHandle::member(mh);
1513     RecordLocation fp(this, "member");
1514     record_member(thread, member);
1515   } else {
1516     // Check <MethodHandle subclass>.argL<n> fields
1517     // Probably BoundMethodHandle.Species_L*, but we only care if the field exists
1518     char arg_name[] = "argLXX";
1519     int max_arg = 99;
1520     for (int index = 0; index <= max_arg; ++index) {
1521       jio_snprintf(arg_name, sizeof (arg_name), "argL%d", index);
1522       oop arg = obj_field(mh, arg_name);
1523       if (arg != nullptr) {
1524         RecordLocation fp(this, "%s", arg_name);
1525         if (arg->klass()->is_instance_klass()) {
1526           InstanceKlass* ik2 = InstanceKlass::cast(arg->klass());
1527           record_best_dyno_loc(ik2);
1528           record_call_site_obj(thread, arg);
1529         }
1530       } else {
1531         break;
1532       }
1533     }
1534   }
1535 }
1536 
1537 // Process an object found at an invokedynamic/invokehandle call site and record any dynamic locations.
1538 // Types currently supported are MethodHandle and CallSite.
1539 // The object is typically the "appendix" object, or Bootstrap Method (BSM) object.
1540 void ciEnv::record_call_site_obj(Thread* thread, oop obj)
1541 {
1542   if (obj != nullptr) {
1543     if (java_lang_invoke_MethodHandle::is_instance(obj)) {
1544         record_mh(thread, obj);
1545     } else if (java_lang_invoke_ConstantCallSite::is_instance(obj)) {
1546       oop target = java_lang_invoke_CallSite::target(obj);
1547       if (target->klass()->is_instance_klass()) {
1548         RecordLocation fp(this, "target");
1549         InstanceKlass* ik = InstanceKlass::cast(target->klass());
1550         record_best_dyno_loc(ik);
1551       }
1552     }
1553   }
1554 }
1555 
1556 // Process an adapter Method* found at an invokedynamic/invokehandle call site and record any dynamic locations.
1557 void ciEnv::record_call_site_method(Thread* thread, Method* adapter) {
1558   InstanceKlass* holder = adapter->method_holder();
1559   if (!holder->is_hidden()) {
1560     return;
1561   }
1562   RecordLocation fp(this, "<adapter>");
1563   record_best_dyno_loc(holder);
1564 }
1565 
1566 // Process an invokedynamic call site and record any dynamic locations.
1567 void ciEnv::process_invokedynamic(const constantPoolHandle &cp, int indy_index, JavaThread* thread) {
1568   int index = cp->decode_invokedynamic_index(indy_index);
1569   ResolvedIndyEntry* indy_info = cp->resolved_indy_entry_at(index);
1570   if (indy_info->method() != nullptr) {
1571     // process the adapter
1572     Method* adapter = indy_info->method();
1573     record_call_site_method(thread, adapter);
1574     // process the appendix
1575     oop appendix = cp->resolved_reference_from_indy(index);
1576     {
1577       RecordLocation fp(this, "<appendix>");
1578       record_call_site_obj(thread, appendix);
1579     }
1580     // process the BSM
1581     int pool_index = indy_info->constant_pool_index();
1582     BootstrapInfo bootstrap_specifier(cp, pool_index, index);
1583     oop bsm = cp->resolve_possibly_cached_constant_at(bootstrap_specifier.bsm_index(), thread);
1584     {
1585       RecordLocation fp(this, "<bsm>");
1586       record_call_site_obj(thread, bsm);
1587     }
1588   }
1589 }
1590 
1591 // Process an invokehandle call site and record any dynamic locations.
1592 void ciEnv::process_invokehandle(const constantPoolHandle &cp, int index, JavaThread* thread) {
1593   const int holder_index = cp->klass_ref_index_at(index, Bytecodes::_invokehandle);
1594   if (!cp->tag_at(holder_index).is_klass()) {
1595     return;  // not resolved
1596   }
1597   Klass* holder = ConstantPool::klass_at_if_loaded(cp, holder_index);
1598   Symbol* name = cp->name_ref_at(index, Bytecodes::_invokehandle);
1599   if (MethodHandles::is_signature_polymorphic_name(holder, name)) {
1600     ResolvedMethodEntry* method_entry = cp->resolved_method_entry_at(index);
1601     if (method_entry->is_resolved(Bytecodes::_invokehandle)) {
1602       // process the adapter
1603       Method* adapter = method_entry->method();
1604       oop appendix = cp->cache()->appendix_if_resolved(method_entry);
1605       record_call_site_method(thread, adapter);
1606       // process the appendix
1607       {
1608         RecordLocation fp(this, "<appendix>");
1609         record_call_site_obj(thread, appendix);
1610       }
1611     }
1612   }
1613 }
1614 
1615 // Search the class hierarchy for dynamic classes reachable through dynamic call sites or
1616 // constant pool entries and record for future lookup.
1617 void ciEnv::find_dynamic_call_sites() {
1618   _dyno_klasses = new (arena()) GrowableArray<const InstanceKlass*>(arena(), 100, 0, nullptr);
1619   _dyno_locs    = new (arena()) GrowableArray<const char *>(arena(), 100, 0, nullptr);
1620 
1621   // Iterate over the class hierarchy
1622   for (ClassHierarchyIterator iter(vmClasses::Object_klass()); !iter.done(); iter.next()) {
1623     Klass* sub = iter.klass();
1624     if (sub->is_instance_klass()) {
1625       InstanceKlass *isub = InstanceKlass::cast(sub);
1626       InstanceKlass* ik = isub;
1627       if (!ik->is_linked()) {
1628         continue;
1629       }
1630       if (ik->is_hidden()) {
1631         continue;
1632       }
1633       JavaThread* thread = JavaThread::current();
1634       const constantPoolHandle pool(thread, ik->constants());
1635 
1636       // Look for invokedynamic/invokehandle call sites
1637       for (int i = 0; i < ik->methods()->length(); ++i) {
1638         Method* m = ik->methods()->at(i);
1639 
1640         BytecodeStream bcs(methodHandle(thread, m));
1641         while (!bcs.is_last_bytecode()) {
1642           Bytecodes::Code opcode = bcs.next();
1643           opcode = bcs.raw_code();
1644           switch (opcode) {
1645           case Bytecodes::_invokedynamic:
1646           case Bytecodes::_invokehandle: {
1647             RecordLocation fp(this, "@bci %s %s %s %d",
1648                          ik->name()->as_quoted_ascii(),
1649                          m->name()->as_quoted_ascii(), m->signature()->as_quoted_ascii(),
1650                          bcs.bci());
1651             if (opcode == Bytecodes::_invokedynamic) {
1652               int index = bcs.get_index_u4();
1653               process_invokedynamic(pool, index, thread);
1654             } else {
1655               assert(opcode == Bytecodes::_invokehandle, "new switch label added?");
1656               int cp_cache_index = bcs.get_index_u2();
1657               process_invokehandle(pool, cp_cache_index, thread);
1658             }
1659             break;
1660           }
1661           default:
1662             break;
1663           }
1664         }
1665       }
1666 
1667       // Look for MethodHandle constant pool entries
1668       RecordLocation fp(this, "@cpi %s", ik->name()->as_quoted_ascii());
1669       int len = pool->length();
1670       for (int i = 0; i < len; ++i) {
1671         if (pool->tag_at(i).is_method_handle()) {
1672           bool found_it;
1673           oop mh = pool->find_cached_constant_at(i, found_it, thread);
1674           if (mh != nullptr) {
1675             RecordLocation fp(this, "%d", i);
1676             record_mh(thread, mh);
1677           }
1678         }
1679       }
1680     }
1681   }
1682 }
1683 
1684 void ciEnv::dump_compile_data(outputStream* out) {
1685   CompileTask* task = this->task();
1686   if (task) {
1687 #ifdef COMPILER2
1688     if (ReplayReduce && compiler_data() != nullptr) {
1689       // Dump C2 "reduced" inlining data.
1690       ((Compile*)compiler_data())->dump_inline_data_reduced(out);
1691     }
1692 #endif
1693     Method* method = task->method();
1694     int entry_bci = task->osr_bci();
1695     int comp_level = task->comp_level();
1696     out->print("compile ");
1697     get_method(method)->dump_name_as_ascii(out);
1698     out->print(" %d %d", entry_bci, comp_level);
1699     if (compiler_data() != nullptr) {
1700       if (is_c2_compile(comp_level)) {
1701 #ifdef COMPILER2
1702         // Dump C2 inlining data.
1703         ((Compile*)compiler_data())->dump_inline_data(out);
1704 #endif
1705       } else if (is_c1_compile(comp_level)) {
1706 #ifdef COMPILER1
1707         // Dump C1 inlining data.
1708         ((Compilation*)compiler_data())->dump_inline_data(out);
1709 #endif
1710       }
1711     }
1712     out->cr();
1713   }
1714 }
1715 
1716 // Called from VM error reporter, so be careful.
1717 // Don't safepoint or acquire any locks.
1718 //
1719 void ciEnv::dump_replay_data_helper(outputStream* out) {
1720   NoSafepointVerifier no_safepoint;
1721   ResourceMark rm;
1722 
1723   dump_replay_data_version(out);
1724 #if INCLUDE_JVMTI
1725   out->print_cr("JvmtiExport can_access_local_variables %d",     _jvmti_can_access_local_variables);
1726   out->print_cr("JvmtiExport can_hotswap_or_post_breakpoint %d", _jvmti_can_hotswap_or_post_breakpoint);
1727   out->print_cr("JvmtiExport can_post_on_exceptions %d",         _jvmti_can_post_on_exceptions);
1728 #endif // INCLUDE_JVMTI
1729 
1730   find_dynamic_call_sites();
1731 
1732   GrowableArray<ciMetadata*>* objects = _factory->get_ci_metadata();
1733   out->print_cr("# %d ciObject found", objects->length());
1734 
1735   // The very first entry is the InstanceKlass of the root method of the current compilation in order to get the right
1736   // protection domain to load subsequent classes during replay compilation.
1737   ciInstanceKlass::dump_replay_instanceKlass(out, task()->method()->method_holder());
1738 
1739   for (int i = 0; i < objects->length(); i++) {
1740     objects->at(i)->dump_replay_data(out);
1741   }
1742   dump_compile_data(out);
1743   out->flush();
1744 }
1745 
1746 // Called from VM error reporter, so be careful.
1747 // Don't safepoint or acquire any locks.
1748 //
1749 void ciEnv::dump_replay_data_unsafe(outputStream* out) {
1750   GUARDED_VM_ENTRY(
1751     dump_replay_data_helper(out);
1752   )
1753 }
1754 
1755 void ciEnv::dump_replay_data(outputStream* out) {
1756   GUARDED_VM_ENTRY(
1757     MutexLocker ml(Compile_lock);
1758     dump_replay_data_helper(out);
1759   )
1760 }
1761 
1762 void ciEnv::dump_replay_data(int compile_id) {
1763   char buffer[64];
1764   int ret = jio_snprintf(buffer, sizeof(buffer), "replay_pid%d_compid%d.log", os::current_process_id(), compile_id);
1765   if (ret > 0) {
1766     int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);
1767     if (fd != -1) {
1768       FILE* replay_data_file = os::fdopen(fd, "w");
1769       if (replay_data_file != nullptr) {
1770         fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1771         dump_replay_data(&replay_data_stream);
1772         tty->print_cr("# Compiler replay data is saved as: %s", buffer);
1773       } else {
1774         tty->print_cr("# Can't open file to dump replay data.");
1775         close(fd);
1776       }
1777     }
1778   }
1779 }
1780 
1781 void ciEnv::dump_inline_data(int compile_id) {
1782   char buffer[64];
1783   int ret = jio_snprintf(buffer, sizeof(buffer), "inline_pid%d_compid%d.log", os::current_process_id(), compile_id);
1784   if (ret > 0) {
1785     int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);
1786     if (fd != -1) {
1787       FILE* inline_data_file = os::fdopen(fd, "w");
1788       if (inline_data_file != nullptr) {
1789         fileStream replay_data_stream(inline_data_file, /*need_close=*/true);
1790         GUARDED_VM_ENTRY(
1791           MutexLocker ml(Compile_lock);
1792           dump_replay_data_version(&replay_data_stream);
1793           dump_compile_data(&replay_data_stream);
1794         )
1795         replay_data_stream.flush();
1796         tty->print("# Compiler inline data is saved as: ");
1797         tty->print_cr("%s", buffer);
1798       } else {
1799         tty->print_cr("# Can't open file to dump inline data.");
1800         close(fd);
1801       }
1802     }
1803   }
1804 }
1805 
1806 void ciEnv::dump_replay_data_version(outputStream* out) {
1807   out->print_cr("version %d", REPLAY_VERSION);
1808 }
1809 
1810 bool ciEnv::is_precompiled() {
1811   return (task() != nullptr) && (task()->compile_reason() == CompileTask::Reason_Precompile          ||
1812                                  task()->compile_reason() == CompileTask::Reason_PrecompileForPreload);
1813 }
1814 
1815 bool ciEnv::is_fully_initialized(InstanceKlass* ik) {
1816   assert(is_precompiled(), "");
1817   if (task()->method()->method_holder() == ik) {
1818     return true; // FIXME: may be too strong; being_initialized, at least
1819   }
1820   switch (task()->compile_reason()) {
1821     case CompileTask::Reason_Precompile: {
1822       // check init dependencies
1823       MethodTrainingData* mtd = TrainingData::lookup_for(task()->method());
1824       if (mtd != nullptr) {
1825         CompileTrainingData* ctd = mtd->last_toplevel_compile(task()->comp_level());
1826         if (ctd != nullptr) {
1827           for (int i = 0; i < ctd->init_dep_count(); i++) {
1828             KlassTrainingData* ktd = ctd->init_dep(i);
1829             if (ktd->has_holder() && (ktd->holder() == ik)) {
1830               log_trace(precompile)("%d: init_dependency: %s: %s", task()->compile_id(), InstanceKlass::state2name(ik->init_state()), ik->external_name());
1831               return true; // init dependency present
1832             }
1833           }
1834         }
1835       }
1836       return false; // no init dependency
1837     }
1838     case CompileTask::Reason_PrecompileForPreload: {
1839       // FIXME: assumes that all shared classes are initialized
1840       if (ik->is_shared()) {
1841         return true; // class init barriers
1842       }
1843       if (CDSConfig::is_dumping_final_static_archive() && ArchiveBuilder::is_active() &&
1844           ArchiveBuilder::current()->has_been_archived((address)ik)) {
1845         return true; // class init barriers
1846       }
1847       return false;
1848     }
1849     default: fatal("%s", CompileTask::reason_name(task()->compile_reason()));
1850   }
1851   return false;
1852 }
1853 
1854 InstanceKlass::ClassState ciEnv::compute_init_state_for_precompiled(InstanceKlass* ik) {
1855   ASSERT_IN_VM;
1856   assert(is_precompiled(), "");
1857   ResourceMark rm;
1858   if (is_fully_initialized(ik)) {
1859     log_trace(precompile)("%d: fully_initialized: %s", task()->compile_id(), ik->external_name());
1860     return InstanceKlass::ClassState::fully_initialized;
1861   } else if (MetaspaceObj::is_shared(ik)) {
1862     guarantee(ik->is_loaded(), ""); // FIXME: assumes pre-loading by CDS; ik->is_linked() requires pre-linking
1863     log_trace(precompile)("%d: %s: %s", task()->compile_id(), InstanceKlass::state2name(ik->init_state()), ik->external_name());
1864     return ik->init_state(); // not yet initialized
1865   } else if (CDSConfig::is_dumping_final_static_archive() && ArchiveBuilder::is_active()) {
1866     if (!ArchiveBuilder::current()->has_been_archived((address)ik)) {
1867       fatal("New workflow: should not compile code for unarchived class: %s", ik->external_name());
1868     }
1869     guarantee(ik->is_loaded(), "");
1870     log_trace(precompile)("%d: %s: %s", task()->compile_id(), InstanceKlass::state2name(ik->init_state()), ik->external_name());
1871     return ik->init_state(); // not yet initialized
1872   } else {
1873     // Not present in the archive.
1874     fatal("unloaded: %s", ik->external_name());
1875 //    guarantee(SystemDictionaryShared::lookup_init_state(ik) == ik->init_state(), "");
1876     log_trace(precompile)("%d: allocated: %s", task()->compile_id(), ik->external_name());
1877     return InstanceKlass::ClassState::allocated; // not yet linked
1878   }
1879 }