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