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