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