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