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   Handle domain;
 466   if (accessing_klass != nullptr) {
 467     loader = Handle(current, accessing_klass->loader());
 468     domain = Handle(current, accessing_klass->protection_domain());
 469   }
 470 
 471   Klass* found_klass = require_local ?
 472                          SystemDictionary::find_instance_or_array_klass(current, sym, loader, domain) :
 473                          SystemDictionary::find_constrained_instance_or_array_klass(current, sym, loader);
 474 
 475   // If we fail to find an array klass, look again for its element type.
 476   // The element type may be available either locally or via constraints.
 477   // In either case, if we can find the element type in the system dictionary,
 478   // we must build an array type around it.  The CI requires array klasses
 479   // to be loaded if their element klasses are loaded, except when memory
 480   // is exhausted.
 481   if (Signature::is_array(sym) &&
 482       (sym->char_at(1) == JVM_SIGNATURE_ARRAY || sym->char_at(1) == JVM_SIGNATURE_CLASS)) {
 483     // We have an unloaded array.
 484     // Build it on the fly if the element class exists.
 485     SignatureStream ss(sym, false);
 486     ss.skip_array_prefix(1);
 487     // Get element ciKlass recursively.
 488     ciKlass* elem_klass =
 489       get_klass_by_name_impl(accessing_klass,
 490                              cpool,
 491                              get_symbol(ss.as_symbol()),
 492                              require_local);
 493     if (elem_klass != nullptr && elem_klass->is_loaded()) {
 494       // Now make an array for it
 495       return ciObjArrayKlass::make_impl(elem_klass);
 496     }
 497   }
 498 
 499   if (found_klass == nullptr && !cpool.is_null() && cpool->has_preresolution()) {
 500     // Look inside the constant pool for pre-resolved class entries.
 501     for (int i = cpool->length() - 1; i >= 1; i--) {
 502       if (cpool->tag_at(i).is_klass()) {
 503         Klass* kls = cpool->resolved_klass_at(i);
 504         if (kls->name() == sym) {
 505           found_klass = kls;
 506           break;
 507         }
 508       }
 509     }
 510   }
 511 
 512   if (found_klass != nullptr) {
 513     // Found it.  Build a CI handle.
 514     return get_klass(found_klass);
 515   }
 516 
 517   if (require_local)  return nullptr;
 518 
 519   // Not yet loaded into the VM, or not governed by loader constraints.
 520   // Make a CI representative for it.
 521   return get_unloaded_klass(accessing_klass, name);
 522 }
 523 
 524 // ------------------------------------------------------------------
 525 // ciEnv::get_klass_by_name
 526 ciKlass* ciEnv::get_klass_by_name(ciKlass* accessing_klass,
 527                                   ciSymbol* klass_name,
 528                                   bool require_local) {
 529   GUARDED_VM_ENTRY(return get_klass_by_name_impl(accessing_klass,
 530                                                  constantPoolHandle(),
 531                                                  klass_name,
 532                                                  require_local);)
 533 }
 534 
 535 // ------------------------------------------------------------------
 536 // ciEnv::get_klass_by_index_impl
 537 //
 538 // Implementation of get_klass_by_index.
 539 ciKlass* ciEnv::get_klass_by_index_impl(const constantPoolHandle& cpool,
 540                                         int index,
 541                                         bool& is_accessible,
 542                                         ciInstanceKlass* accessor) {
 543   Klass* klass = nullptr;
 544   Symbol* klass_name = nullptr;
 545 
 546   if (cpool->tag_at(index).is_symbol()) {
 547     klass_name = cpool->symbol_at(index);
 548   } else {
 549     // Check if it's resolved if it's not a symbol constant pool entry.
 550     klass = ConstantPool::klass_at_if_loaded(cpool, index);
 551     // Try to look it up by name.
 552     if (klass == nullptr) {
 553       klass_name = cpool->klass_name_at(index);
 554     }
 555   }
 556 
 557   if (klass == nullptr) {
 558     // Not found in constant pool.  Use the name to do the lookup.
 559     ciKlass* k = get_klass_by_name_impl(accessor,
 560                                         cpool,
 561                                         get_symbol(klass_name),
 562                                         false);
 563     // Calculate accessibility the hard way.
 564     if (!k->is_loaded()) {
 565       is_accessible = false;
 566     } else if (k->loader() != accessor->loader() &&
 567                get_klass_by_name_impl(accessor, cpool, k->name(), true) == nullptr) {
 568       // Loaded only remotely.  Not linked yet.
 569       is_accessible = false;
 570     } else {
 571       // Linked locally, and we must also check public/private, etc.
 572       is_accessible = check_klass_accessibility(accessor, k->get_Klass());
 573     }
 574     return k;
 575   }
 576 
 577   // Check for prior unloaded klass.  The SystemDictionary's answers
 578   // can vary over time but the compiler needs consistency.
 579   ciSymbol* name = get_symbol(klass->name());
 580   ciKlass* unloaded_klass = check_get_unloaded_klass(accessor, name);
 581   if (unloaded_klass != nullptr) {
 582     is_accessible = false;
 583     return unloaded_klass;
 584   }
 585 
 586   // It is known to be accessible, since it was found in the constant pool.
 587   ciKlass* ciKlass = get_klass(klass);
 588   is_accessible = true;
 589   if (ReplayCompiles && ciKlass == _unloaded_ciinstance_klass) {
 590     // Klass was unresolved at replay dump time and therefore not accessible.
 591     is_accessible = false;
 592   }
 593   return ciKlass;
 594 }
 595 
 596 // ------------------------------------------------------------------
 597 // ciEnv::get_klass_by_index
 598 //
 599 // Get a klass from the constant pool.
 600 ciKlass* ciEnv::get_klass_by_index(const constantPoolHandle& cpool,
 601                                    int index,
 602                                    bool& is_accessible,
 603                                    ciInstanceKlass* accessor) {
 604   GUARDED_VM_ENTRY(return get_klass_by_index_impl(cpool, index, is_accessible, accessor);)
 605 }
 606 
 607 // ------------------------------------------------------------------
 608 // ciEnv::unbox_primitive_value
 609 //
 610 // Unbox a primitive and return it as a ciConstant.
 611 ciConstant ciEnv::unbox_primitive_value(ciObject* cibox, BasicType expected_bt) {
 612   jvalue value;
 613   BasicType bt = java_lang_boxing_object::get_value(cibox->get_oop(), &value);
 614   if (bt != expected_bt && expected_bt != T_ILLEGAL) {
 615     assert(false, "type mismatch: %s vs %s", type2name(expected_bt), cibox->klass()->name()->as_klass_external_name());
 616     return ciConstant();
 617   }
 618   switch (bt) {
 619     case T_BOOLEAN: return ciConstant(bt, value.z);
 620     case T_BYTE:    return ciConstant(bt, value.b);
 621     case T_SHORT:   return ciConstant(bt, value.s);
 622     case T_CHAR:    return ciConstant(bt, value.c);
 623     case T_INT:     return ciConstant(bt, value.i);
 624     case T_LONG:    return ciConstant(value.j);
 625     case T_FLOAT:   return ciConstant(value.f);
 626     case T_DOUBLE:  return ciConstant(value.d);
 627 
 628     default:
 629       assert(false, "not a primitive type: %s", type2name(bt));
 630       return ciConstant();
 631   }
 632 }
 633 
 634 // ------------------------------------------------------------------
 635 // ciEnv::get_resolved_constant
 636 //
 637 ciConstant ciEnv::get_resolved_constant(const constantPoolHandle& cpool, int obj_index) {
 638   assert(obj_index >= 0, "");
 639   oop obj = cpool->resolved_reference_at(obj_index);
 640   if (obj == nullptr) {
 641     // Unresolved constant. It is resolved when the corresponding slot contains a non-null reference.
 642     // Null constant is represented as a sentinel (non-null) value.
 643     return ciConstant();
 644   } else if (obj == Universe::the_null_sentinel()) {
 645     return ciConstant(T_OBJECT, get_object(nullptr));
 646   } else {
 647     ciObject* ciobj = get_object(obj);
 648     if (ciobj->is_array()) {
 649       return ciConstant(T_ARRAY, ciobj);
 650     } else {
 651       int cp_index = cpool->object_to_cp_index(obj_index);
 652       BasicType bt = cpool->basic_type_for_constant_at(cp_index);
 653       if (is_java_primitive(bt)) {
 654         assert(cpool->tag_at(cp_index).is_dynamic_constant(), "sanity");
 655         return unbox_primitive_value(ciobj, bt);
 656       } else {
 657         assert(ciobj->is_instance(), "should be an instance");
 658         return ciConstant(T_OBJECT, ciobj);
 659       }
 660     }
 661   }
 662 }
 663 
 664 // ------------------------------------------------------------------
 665 // ciEnv::get_constant_by_index_impl
 666 //
 667 // Implementation of get_constant_by_index().
 668 ciConstant ciEnv::get_constant_by_index_impl(const constantPoolHandle& cpool,
 669                                              int index, int obj_index,
 670                                              ciInstanceKlass* accessor) {
 671   if (obj_index >= 0) {
 672     ciConstant con = get_resolved_constant(cpool, obj_index);
 673     if (con.is_valid()) {
 674       return con;
 675     }
 676   }
 677   constantTag tag = cpool->tag_at(index);
 678   if (tag.is_int()) {
 679     return ciConstant(T_INT, (jint)cpool->int_at(index));
 680   } else if (tag.is_long()) {
 681     return ciConstant((jlong)cpool->long_at(index));
 682   } else if (tag.is_float()) {
 683     return ciConstant((jfloat)cpool->float_at(index));
 684   } else if (tag.is_double()) {
 685     return ciConstant((jdouble)cpool->double_at(index));
 686   } else if (tag.is_string()) {
 687     EXCEPTION_CONTEXT;
 688     assert(obj_index >= 0, "should have an object index");
 689     oop string = cpool->string_at(index, obj_index, THREAD);
 690     if (HAS_PENDING_EXCEPTION) {
 691       CLEAR_PENDING_EXCEPTION;
 692       record_out_of_memory_failure();
 693       return ciConstant();
 694     }
 695     ciInstance* constant = get_object(string)->as_instance();
 696     return ciConstant(T_OBJECT, constant);
 697   } else if (tag.is_unresolved_klass_in_error()) {
 698     return ciConstant(T_OBJECT, get_unloaded_klass_mirror(nullptr));
 699   } else if (tag.is_klass() || tag.is_unresolved_klass()) {
 700     bool will_link;
 701     ciKlass* klass = get_klass_by_index_impl(cpool, index, will_link, accessor);
 702     ciInstance* mirror = (will_link ? klass->java_mirror() : get_unloaded_klass_mirror(klass));
 703     return ciConstant(T_OBJECT, mirror);
 704   } else if (tag.is_method_type() || tag.is_method_type_in_error()) {
 705     // must execute Java code to link this CP entry into cache[i].f1
 706     assert(obj_index >= 0, "should have an object index");
 707     ciSymbol* signature = get_symbol(cpool->method_type_signature_at(index));
 708     ciObject* ciobj = get_unloaded_method_type_constant(signature);
 709     return ciConstant(T_OBJECT, ciobj);
 710   } else if (tag.is_method_handle() || tag.is_method_handle_in_error()) {
 711     // must execute Java code to link this CP entry into cache[i].f1
 712     assert(obj_index >= 0, "should have an object index");
 713     bool ignore_will_link;
 714     int ref_kind        = cpool->method_handle_ref_kind_at(index);
 715     int callee_index    = cpool->method_handle_klass_index_at(index);
 716     ciKlass* callee     = get_klass_by_index_impl(cpool, callee_index, ignore_will_link, accessor);
 717     ciSymbol* name      = get_symbol(cpool->method_handle_name_ref_at(index));
 718     ciSymbol* signature = get_symbol(cpool->method_handle_signature_ref_at(index));
 719     ciObject* ciobj     = get_unloaded_method_handle_constant(callee, name, signature, ref_kind);
 720     return ciConstant(T_OBJECT, ciobj);
 721   } else if (tag.is_dynamic_constant() || tag.is_dynamic_constant_in_error()) {
 722     assert(obj_index >= 0, "should have an object index");
 723     return ciConstant(T_OBJECT, unloaded_ciinstance()); // unresolved dynamic constant
 724   } else {
 725     assert(false, "unknown tag: %d (%s)", tag.value(), tag.internal_name());
 726     return ciConstant();
 727   }
 728 }
 729 
 730 // ------------------------------------------------------------------
 731 // ciEnv::get_constant_by_index
 732 //
 733 // Pull a constant out of the constant pool.  How appropriate.
 734 //
 735 // Implementation note: this query is currently in no way cached.
 736 ciConstant ciEnv::get_constant_by_index(const constantPoolHandle& cpool,
 737                                         int pool_index, int cache_index,
 738                                         ciInstanceKlass* accessor) {
 739   GUARDED_VM_ENTRY(return get_constant_by_index_impl(cpool, pool_index, cache_index, accessor);)
 740 }
 741 
 742 // ------------------------------------------------------------------
 743 // ciEnv::get_field_by_index_impl
 744 //
 745 // Implementation of get_field_by_index.
 746 //
 747 // Implementation note: the results of field lookups are cached
 748 // in the accessor klass.
 749 ciField* ciEnv::get_field_by_index_impl(ciInstanceKlass* accessor,
 750                                         int index, Bytecodes::Code bc) {
 751   ciConstantPoolCache* cache = accessor->field_cache();
 752   if (cache == nullptr) {
 753     ciField* field = new (arena()) ciField(accessor, index, bc);
 754     return field;
 755   } else {
 756     ciField* field = (ciField*)cache->get(index);
 757     if (field == nullptr) {
 758       field = new (arena()) ciField(accessor, index, bc);
 759       cache->insert(index, field);
 760     }
 761     return field;
 762   }
 763 }
 764 
 765 // ------------------------------------------------------------------
 766 // ciEnv::get_field_by_index
 767 //
 768 // Get a field by index from a klass's constant pool.
 769 ciField* ciEnv::get_field_by_index(ciInstanceKlass* accessor,
 770                                    int index, Bytecodes::Code bc) {
 771   GUARDED_VM_ENTRY(return get_field_by_index_impl(accessor, index, bc);)
 772 }
 773 
 774 // ------------------------------------------------------------------
 775 // ciEnv::lookup_method
 776 //
 777 // Perform an appropriate method lookup based on accessor, holder,
 778 // name, signature, and bytecode.
 779 Method* ciEnv::lookup_method(ciInstanceKlass* accessor,
 780                              ciKlass*         holder,
 781                              Symbol*          name,
 782                              Symbol*          sig,
 783                              Bytecodes::Code  bc,
 784                              constantTag      tag) {
 785   InstanceKlass* accessor_klass = accessor->get_instanceKlass();
 786   Klass* holder_klass = holder->get_Klass();
 787 
 788   // Accessibility checks are performed in ciEnv::get_method_by_index_impl.
 789   assert(check_klass_accessibility(accessor, holder_klass), "holder not accessible");
 790 
 791   LinkInfo link_info(holder_klass, name, sig, accessor_klass,
 792                      LinkInfo::AccessCheck::required,
 793                      LinkInfo::LoaderConstraintCheck::required,
 794                      tag);
 795   switch (bc) {
 796     case Bytecodes::_invokestatic:
 797       return LinkResolver::resolve_static_call_or_null(link_info);
 798     case Bytecodes::_invokespecial:
 799       return LinkResolver::resolve_special_call_or_null(link_info);
 800     case Bytecodes::_invokeinterface:
 801       return LinkResolver::linktime_resolve_interface_method_or_null(link_info);
 802     case Bytecodes::_invokevirtual:
 803       return LinkResolver::linktime_resolve_virtual_method_or_null(link_info);
 804     default:
 805       fatal("Unhandled bytecode: %s", Bytecodes::name(bc));
 806       return nullptr; // silence compiler warnings
 807   }
 808 }
 809 
 810 
 811 // ------------------------------------------------------------------
 812 // ciEnv::get_method_by_index_impl
 813 ciMethod* ciEnv::get_method_by_index_impl(const constantPoolHandle& cpool,
 814                                           int index, Bytecodes::Code bc,
 815                                           ciInstanceKlass* accessor) {
 816   assert(cpool.not_null(), "need constant pool");
 817   assert(accessor != nullptr, "need origin of access");
 818   if (bc == Bytecodes::_invokedynamic) {
 819     // FIXME: code generation could allow for null (unlinked) call site
 820     // The call site could be made patchable as follows:
 821     // Load the appendix argument from the constant pool.
 822     // Test the appendix argument and jump to a known deopt routine if it is null.
 823     // Jump through a patchable call site, which is initially a deopt routine.
 824     // Patch the call site to the nmethod entry point of the static compiled lambda form.
 825     // As with other two-component call sites, both values must be independently verified.
 826     assert(index < cpool->cache()->resolved_indy_entries_length(), "impossible");
 827     Method* adapter = cpool->resolved_indy_entry_at(index)->method();
 828     // Resolved if the adapter is non null.
 829     if (adapter != nullptr) {
 830       return get_method(adapter);
 831     }
 832 
 833     // Fake a method that is equivalent to a declared method.
 834     ciInstanceKlass* holder    = get_instance_klass(vmClasses::MethodHandle_klass());
 835     ciSymbol*        name      = ciSymbols::invokeBasic_name();
 836     ciSymbol*        signature = get_symbol(cpool->signature_ref_at(index, bc));
 837     return get_unloaded_method(holder, name, signature, accessor);
 838   } else {
 839     const int holder_index = cpool->klass_ref_index_at(index, bc);
 840     bool holder_is_accessible;
 841     ciKlass* holder = get_klass_by_index_impl(cpool, holder_index, holder_is_accessible, accessor);
 842 
 843     // Get the method's name and signature.
 844     Symbol* name_sym = cpool->name_ref_at(index, bc);
 845     Symbol* sig_sym  = cpool->signature_ref_at(index, bc);
 846 
 847     if (cpool->has_preresolution()
 848         || ((holder == ciEnv::MethodHandle_klass() || holder == ciEnv::VarHandle_klass()) &&
 849             MethodHandles::is_signature_polymorphic_name(holder->get_Klass(), name_sym))) {
 850       // Short-circuit lookups for JSR 292-related call sites.
 851       // That is, do not rely only on name-based lookups, because they may fail
 852       // if the names are not resolvable in the boot class loader (7056328).
 853       switch (bc) {
 854       case Bytecodes::_invokevirtual:
 855       case Bytecodes::_invokeinterface:
 856       case Bytecodes::_invokespecial:
 857       case Bytecodes::_invokestatic:
 858         {
 859           Method* m = ConstantPool::method_at_if_loaded(cpool, index);
 860           if (m != nullptr) {
 861             return get_method(m);
 862           }
 863         }
 864         break;
 865       default:
 866         break;
 867       }
 868     }
 869 
 870     if (holder_is_accessible) {  // Our declared holder is loaded.
 871       constantTag tag = cpool->tag_ref_at(index, bc);
 872       assert(accessor->get_instanceKlass() == cpool->pool_holder(), "not the pool holder?");
 873       Method* m = lookup_method(accessor, holder, name_sym, sig_sym, bc, tag);
 874       if (m != nullptr &&
 875           (bc == Bytecodes::_invokestatic
 876            ?  m->method_holder()->is_not_initialized()
 877            : !m->method_holder()->is_loaded())) {
 878         m = nullptr;
 879       }
 880       if (m != nullptr && ReplayCompiles && !ciReplay::is_loaded(m)) {
 881         m = nullptr;
 882       }
 883       if (m != nullptr) {
 884         // We found the method.
 885         return get_method(m);
 886       }
 887     }
 888 
 889     // Either the declared holder was not loaded, or the method could
 890     // not be found.  Create a dummy ciMethod to represent the failed
 891     // lookup.
 892     ciSymbol* name      = get_symbol(name_sym);
 893     ciSymbol* signature = get_symbol(sig_sym);
 894     return get_unloaded_method(holder, name, signature, accessor);
 895   }
 896 }
 897 
 898 
 899 // ------------------------------------------------------------------
 900 // ciEnv::get_instance_klass_for_declared_method_holder
 901 ciInstanceKlass* ciEnv::get_instance_klass_for_declared_method_holder(ciKlass* method_holder) {
 902   // For the case of <array>.clone(), the method holder can be a ciArrayKlass
 903   // instead of a ciInstanceKlass.  For that case simply pretend that the
 904   // declared holder is Object.clone since that's where the call will bottom out.
 905   // A more correct fix would trickle out through many interfaces in CI,
 906   // requiring ciInstanceKlass* to become ciKlass* and many more places would
 907   // require checks to make sure the expected type was found.  Given that this
 908   // only occurs for clone() the more extensive fix seems like overkill so
 909   // instead we simply smear the array type into Object.
 910   guarantee(method_holder != nullptr, "no method holder");
 911   if (method_holder->is_instance_klass()) {
 912     return method_holder->as_instance_klass();
 913   } else if (method_holder->is_array_klass()) {
 914     return current()->Object_klass();
 915   } else {
 916     ShouldNotReachHere();
 917   }
 918   return nullptr;
 919 }
 920 
 921 
 922 // ------------------------------------------------------------------
 923 // ciEnv::get_method_by_index
 924 ciMethod* ciEnv::get_method_by_index(const constantPoolHandle& cpool,
 925                                      int index, Bytecodes::Code bc,
 926                                      ciInstanceKlass* accessor) {
 927   GUARDED_VM_ENTRY(return get_method_by_index_impl(cpool, index, bc, accessor);)
 928 }
 929 
 930 
 931 // ------------------------------------------------------------------
 932 // ciEnv::name_buffer
 933 char *ciEnv::name_buffer(int req_len) {
 934   if (_name_buffer_len < req_len) {
 935     if (_name_buffer == nullptr) {
 936       _name_buffer = (char*)arena()->Amalloc(sizeof(char)*req_len);
 937       _name_buffer_len = req_len;
 938     } else {
 939       _name_buffer =
 940         (char*)arena()->Arealloc(_name_buffer, _name_buffer_len, req_len);
 941       _name_buffer_len = req_len;
 942     }
 943   }
 944   return _name_buffer;
 945 }
 946 
 947 // ------------------------------------------------------------------
 948 // ciEnv::is_in_vm
 949 bool ciEnv::is_in_vm() {
 950   return JavaThread::current()->thread_state() == _thread_in_vm;
 951 }
 952 
 953 // ------------------------------------------------------------------
 954 // ciEnv::validate_compile_task_dependencies
 955 //
 956 // Check for changes during compilation (e.g. class loads, evolution,
 957 // breakpoints, call site invalidation).
 958 void ciEnv::validate_compile_task_dependencies(ciMethod* target) {
 959   if (failing())  return;  // no need for further checks
 960 
 961   Dependencies::DepType result = dependencies()->validate_dependencies(_task);
 962   if (result != Dependencies::end_marker) {
 963     if (result == Dependencies::call_site_target_value) {
 964       _inc_decompile_count_on_failure = false;
 965       record_failure("call site target change");
 966     } else if (Dependencies::is_klass_type(result)) {
 967       record_failure("concurrent class loading");
 968     } else {
 969       record_failure("invalid non-klass dependency");
 970     }
 971   }
 972 }
 973 
 974 // ------------------------------------------------------------------
 975 // ciEnv::register_method
 976 void ciEnv::register_method(ciMethod* target,
 977                             int entry_bci,
 978                             CodeOffsets* offsets,
 979                             int orig_pc_offset,
 980                             CodeBuffer* code_buffer,
 981                             int frame_words,
 982                             OopMapSet* oop_map_set,
 983                             ExceptionHandlerTable* handler_table,
 984                             ImplicitExceptionTable* inc_table,
 985                             AbstractCompiler* compiler,
 986                             bool has_unsafe_access,
 987                             bool has_wide_vectors,
 988                             bool has_monitors,
 989                             bool has_scoped_access,
 990                             int immediate_oops_patched) {
 991   VM_ENTRY_MARK;
 992   nmethod* nm = nullptr;
 993   {
 994     methodHandle method(THREAD, target->get_Method());
 995 
 996     // We require method counters to store some method state (max compilation levels) required by the compilation policy.
 997     if (method->get_method_counters(THREAD) == nullptr) {
 998       record_failure("can't create method counters");
 999       // All buffers in the CodeBuffer are allocated in the CodeCache.
1000       // If the code buffer is created on each compile attempt
1001       // as in C2, then it must be freed.
1002       code_buffer->free_blob();
1003       return;
1004     }
1005 
1006     // Check if memory should be freed before allocation
1007     CodeCache::gc_on_allocation();
1008 
1009     // To prevent compile queue updates.
1010     MutexLocker locker(THREAD, MethodCompileQueue_lock);
1011 
1012     // Prevent InstanceKlass::add_to_hierarchy from running
1013     // and invalidating our dependencies until we install this method.
1014     // No safepoints are allowed. Otherwise, class redefinition can occur in between.
1015     MutexLocker ml(Compile_lock);
1016     NoSafepointVerifier nsv;
1017 
1018     // Change in Jvmti state may invalidate compilation.
1019     if (!failing() && jvmti_state_changed()) {
1020       record_failure("Jvmti state change invalidated dependencies");
1021     }
1022 
1023     // Change in DTrace flags may invalidate compilation.
1024     if (!failing() &&
1025         ( (!dtrace_method_probes() && DTraceMethodProbes) ||
1026           (!dtrace_alloc_probes() && DTraceAllocProbes) )) {
1027       record_failure("DTrace flags change invalidated dependencies");
1028     }
1029 
1030     if (!failing() && target->needs_clinit_barrier() &&
1031         target->holder()->is_in_error_state()) {
1032       record_failure("method holder is in error state");
1033     }
1034 
1035     if (!failing()) {
1036       if (log() != nullptr) {
1037         // Log the dependencies which this compilation declares.
1038         dependencies()->log_all_dependencies();
1039       }
1040 
1041       // Encode the dependencies now, so we can check them right away.
1042       dependencies()->encode_content_bytes();
1043 
1044       // Check for {class loads, evolution, breakpoints, ...} during compilation
1045       validate_compile_task_dependencies(target);
1046     }
1047 
1048     if (failing()) {
1049       // While not a true deoptimization, it is a preemptive decompile.
1050       MethodData* mdo = method()->method_data();
1051       if (mdo != nullptr && _inc_decompile_count_on_failure) {
1052         mdo->inc_decompile_count();
1053       }
1054 
1055       // All buffers in the CodeBuffer are allocated in the CodeCache.
1056       // If the code buffer is created on each compile attempt
1057       // as in C2, then it must be freed.
1058       code_buffer->free_blob();
1059       return;
1060     }
1061 
1062     assert(offsets->value(CodeOffsets::Deopt) != -1, "must have deopt entry");
1063     assert(offsets->value(CodeOffsets::Exceptions) != -1, "must have exception entry");
1064 
1065     nm =  nmethod::new_nmethod(method,
1066                                compile_id(),
1067                                entry_bci,
1068                                offsets,
1069                                orig_pc_offset,
1070                                debug_info(), dependencies(), code_buffer,
1071                                frame_words, oop_map_set,
1072                                handler_table, inc_table,
1073                                compiler, CompLevel(task()->comp_level()));
1074 
1075     // Free codeBlobs
1076     code_buffer->free_blob();
1077 
1078     if (nm != nullptr) {
1079       nm->set_has_unsafe_access(has_unsafe_access);
1080       nm->set_has_wide_vectors(has_wide_vectors);
1081       nm->set_has_monitors(has_monitors);
1082       nm->set_has_scoped_access(has_scoped_access);
1083       assert(!method->is_synchronized() || nm->has_monitors(), "");
1084 
1085       if (entry_bci == InvocationEntryBci) {
1086         if (TieredCompilation) {
1087           // If there is an old version we're done with it
1088           nmethod* old = method->code();
1089           if (TraceMethodReplacement && old != nullptr) {
1090             ResourceMark rm;
1091             char *method_name = method->name_and_sig_as_C_string();
1092             tty->print_cr("Replacing method %s", method_name);
1093           }
1094           if (old != nullptr) {
1095             old->make_not_used();
1096           }
1097         }
1098 
1099         LogTarget(Info, nmethod, install) lt;
1100         if (lt.is_enabled()) {
1101           ResourceMark rm;
1102           char *method_name = method->name_and_sig_as_C_string();
1103           lt.print("Installing method (%d) %s ",
1104                     task()->comp_level(), method_name);
1105         }
1106         // Allow the code to be executed
1107         MutexLocker ml(NMethodState_lock, Mutex::_no_safepoint_check_flag);
1108         if (nm->make_in_use()) {
1109           method->set_code(method, nm);
1110         }
1111       } else {
1112         LogTarget(Info, nmethod, install) lt;
1113         if (lt.is_enabled()) {
1114           ResourceMark rm;
1115           char *method_name = method->name_and_sig_as_C_string();
1116           lt.print("Installing osr method (%d) %s @ %d",
1117                     task()->comp_level(), method_name, entry_bci);
1118         }
1119         MutexLocker ml(NMethodState_lock, Mutex::_no_safepoint_check_flag);
1120         if (nm->make_in_use()) {
1121           method->method_holder()->add_osr_nmethod(nm);
1122         }
1123       }
1124     }
1125   }
1126 
1127   NoSafepointVerifier nsv;
1128   if (nm != nullptr) {
1129     // Compilation succeeded, post what we know about it
1130     nm->post_compiled_method(task());
1131     task()->set_num_inlined_bytecodes(num_inlined_bytecodes());
1132   } else {
1133     // The CodeCache is full.
1134     record_failure("code cache is full");
1135   }
1136 
1137   // safepoints are allowed again
1138 }
1139 
1140 // ------------------------------------------------------------------
1141 // ciEnv::find_system_klass
1142 ciKlass* ciEnv::find_system_klass(ciSymbol* klass_name) {
1143   VM_ENTRY_MARK;
1144   return get_klass_by_name_impl(nullptr, constantPoolHandle(), klass_name, false);
1145 }
1146 
1147 // ------------------------------------------------------------------
1148 // ciEnv::comp_level
1149 int ciEnv::comp_level() {
1150   if (task() == nullptr)  return CompilationPolicy::highest_compile_level();
1151   return task()->comp_level();
1152 }
1153 
1154 // ------------------------------------------------------------------
1155 // ciEnv::compile_id
1156 int ciEnv::compile_id() {
1157   if (task() == nullptr)  return 0;
1158   return task()->compile_id();
1159 }
1160 
1161 // ------------------------------------------------------------------
1162 // ciEnv::notice_inlined_method()
1163 void ciEnv::notice_inlined_method(ciMethod* method) {
1164   _num_inlined_bytecodes += method->code_size_for_inlining();
1165 }
1166 
1167 // ------------------------------------------------------------------
1168 // ciEnv::num_inlined_bytecodes()
1169 int ciEnv::num_inlined_bytecodes() const {
1170   return _num_inlined_bytecodes;
1171 }
1172 
1173 // ------------------------------------------------------------------
1174 // ciEnv::record_failure()
1175 void ciEnv::record_failure(const char* reason) {
1176   if (_failure_reason.get() == nullptr) {
1177     // Record the first failure reason.
1178     _failure_reason.set(reason);
1179   }
1180 }
1181 
1182 void ciEnv::report_failure(const char* reason) {
1183   EventCompilationFailure event;
1184   if (event.should_commit()) {
1185     CompilerEvent::CompilationFailureEvent::post(event, compile_id(), reason);
1186   }
1187 }
1188 
1189 // ------------------------------------------------------------------
1190 // ciEnv::record_method_not_compilable()
1191 void ciEnv::record_method_not_compilable(const char* reason, bool all_tiers) {
1192   int new_compilable =
1193     all_tiers ? MethodCompilable_never : MethodCompilable_not_at_tier ;
1194 
1195   // Only note transitions to a worse state
1196   if (new_compilable > _compilable) {
1197     if (log() != nullptr) {
1198       if (all_tiers) {
1199         log()->elem("method_not_compilable");
1200       } else {
1201         log()->elem("method_not_compilable_at_tier level='%d'",
1202                     current()->task()->comp_level());
1203       }
1204     }
1205     _compilable = new_compilable;
1206 
1207     // Reset failure reason; this one is more important.
1208     _failure_reason.clear();
1209     record_failure(reason);
1210   }
1211 }
1212 
1213 // ------------------------------------------------------------------
1214 // ciEnv::record_out_of_memory_failure()
1215 void ciEnv::record_out_of_memory_failure() {
1216   // If memory is low, we stop compiling methods.
1217   record_method_not_compilable("out of memory");
1218 }
1219 
1220 ciInstance* ciEnv::unloaded_ciinstance() {
1221   GUARDED_VM_ENTRY(return _factory->get_unloaded_object_constant();)
1222 }
1223 
1224 // ------------------------------------------------------------------
1225 // Replay support
1226 
1227 
1228 // Lookup location descriptor for the class, if any.
1229 // Returns false if not found.
1230 bool ciEnv::dyno_loc(const InstanceKlass* ik, const char *&loc) const {
1231   bool found = false;
1232   int pos = _dyno_klasses->find_sorted<const InstanceKlass*, klass_compare>(ik, found);
1233   if (!found) {
1234     return false;
1235   }
1236   loc = _dyno_locs->at(pos);
1237   return found;
1238 }
1239 
1240 // Associate the current location descriptor with the given class and record for later lookup.
1241 void ciEnv::set_dyno_loc(const InstanceKlass* ik) {
1242   const char *loc = os::strdup(_dyno_name);
1243   bool found = false;
1244   int pos = _dyno_klasses->find_sorted<const InstanceKlass*, klass_compare>(ik, found);
1245   if (found) {
1246     _dyno_locs->at_put(pos, loc);
1247   } else {
1248     _dyno_klasses->insert_before(pos, ik);
1249     _dyno_locs->insert_before(pos, loc);
1250   }
1251 }
1252 
1253 // Associate the current location descriptor with the given class and record for later lookup.
1254 // If it turns out that there are multiple locations for the given class, that conflict should
1255 // be handled here.  Currently we choose the first location found.
1256 void ciEnv::record_best_dyno_loc(const InstanceKlass* ik) {
1257   if (!ik->is_hidden()) {
1258     return;
1259   }
1260   const char *loc0;
1261   if (!dyno_loc(ik, loc0)) {
1262     set_dyno_loc(ik);
1263   }
1264 }
1265 
1266 // Look up the location descriptor for the given class and print it to the output stream.
1267 bool ciEnv::print_dyno_loc(outputStream* out, const InstanceKlass* ik) const {
1268   const char *loc;
1269   if (dyno_loc(ik, loc)) {
1270     out->print("%s", loc);
1271     return true;
1272   } else {
1273     return false;
1274   }
1275 }
1276 
1277 // Look up the location descriptor for the given class and return it as a string.
1278 // Returns null if no location is found.
1279 const char *ciEnv::dyno_name(const InstanceKlass* ik) const {
1280   if (ik->is_hidden()) {
1281     stringStream ss;
1282     if (print_dyno_loc(&ss, ik)) {
1283       ss.print(" ;"); // add terminator
1284       const char* call_site = ss.as_string();
1285       return call_site;
1286     }
1287   }
1288   return nullptr;
1289 }
1290 
1291 // Look up the location descriptor for the given class and return it as a string.
1292 // Returns the class name as a fallback if no location is found.
1293 const char *ciEnv::replay_name(ciKlass* k) const {
1294   if (k->is_instance_klass()) {
1295     return replay_name(k->as_instance_klass()->get_instanceKlass());
1296   }
1297   return k->name()->as_quoted_ascii();
1298 }
1299 
1300 // Look up the location descriptor for the given class and return it as a string.
1301 // Returns the class name as a fallback if no location is found.
1302 const char *ciEnv::replay_name(const InstanceKlass* ik) const {
1303   const char* name = dyno_name(ik);
1304   if (name != nullptr) {
1305       return name;
1306   }
1307   return ik->name()->as_quoted_ascii();
1308 }
1309 
1310 // Process a java.lang.invoke.MemberName object and record any dynamic locations.
1311 void ciEnv::record_member(Thread* thread, oop member) {
1312   assert(java_lang_invoke_MemberName::is_instance(member), "!");
1313   // Check MemberName.clazz field
1314   oop clazz = java_lang_invoke_MemberName::clazz(member);
1315   if (clazz->klass()->is_instance_klass()) {
1316     RecordLocation fp(this, "clazz");
1317     InstanceKlass* ik = InstanceKlass::cast(clazz->klass());
1318     record_best_dyno_loc(ik);
1319   }
1320   // Check MemberName.method.vmtarget field
1321   Method* vmtarget = java_lang_invoke_MemberName::vmtarget(member);
1322   if (vmtarget != nullptr) {
1323     RecordLocation fp2(this, "<vmtarget>");
1324     InstanceKlass* ik = vmtarget->method_holder();
1325     record_best_dyno_loc(ik);
1326   }
1327 }
1328 
1329 // Read an object field.  Lookup is done by name only.
1330 static inline oop obj_field(oop obj, const char* name) {
1331     return ciReplay::obj_field(obj, name);
1332 }
1333 
1334 // Process a java.lang.invoke.LambdaForm object and record any dynamic locations.
1335 void ciEnv::record_lambdaform(Thread* thread, oop form) {
1336   assert(java_lang_invoke_LambdaForm::is_instance(form), "!");
1337 
1338   {
1339     // Check LambdaForm.vmentry field
1340     oop member = java_lang_invoke_LambdaForm::vmentry(form);
1341     RecordLocation fp0(this, "vmentry");
1342     record_member(thread, member);
1343   }
1344 
1345   // Check LambdaForm.names array
1346   objArrayOop names = (objArrayOop)obj_field(form, "names");
1347   if (names != nullptr) {
1348     RecordLocation lp0(this, "names");
1349     int len = names->length();
1350     for (int i = 0; i < len; ++i) {
1351       oop name = names->obj_at(i);
1352       RecordLocation lp1(this, "%d", i);
1353      // Check LambdaForm.names[i].function field
1354       RecordLocation lp2(this, "function");
1355       oop function = obj_field(name, "function");
1356       if (function != nullptr) {
1357         // Check LambdaForm.names[i].function.member field
1358         oop member = obj_field(function, "member");
1359         if (member != nullptr) {
1360           RecordLocation lp3(this, "member");
1361           record_member(thread, member);
1362         }
1363         // Check LambdaForm.names[i].function.resolvedHandle field
1364         oop mh = obj_field(function, "resolvedHandle");
1365         if (mh != nullptr) {
1366           RecordLocation lp3(this, "resolvedHandle");
1367           record_mh(thread, mh);
1368         }
1369         // Check LambdaForm.names[i].function.invoker field
1370         oop invoker = obj_field(function, "invoker");
1371         if (invoker != nullptr) {
1372           RecordLocation lp3(this, "invoker");
1373           record_mh(thread, invoker);
1374         }
1375       }
1376     }
1377   }
1378 }
1379 
1380 // Process a java.lang.invoke.MethodHandle object and record any dynamic locations.
1381 void ciEnv::record_mh(Thread* thread, oop mh) {
1382   {
1383     // Check MethodHandle.form field
1384     oop form = java_lang_invoke_MethodHandle::form(mh);
1385     RecordLocation fp(this, "form");
1386     record_lambdaform(thread, form);
1387   }
1388   // Check DirectMethodHandle.member field
1389   if (java_lang_invoke_DirectMethodHandle::is_instance(mh)) {
1390     oop member = java_lang_invoke_DirectMethodHandle::member(mh);
1391     RecordLocation fp(this, "member");
1392     record_member(thread, member);
1393   } else {
1394     // Check <MethodHandle subclass>.argL<n> fields
1395     // Probably BoundMethodHandle.Species_L*, but we only care if the field exists
1396     char arg_name[] = "argLXX";
1397     int max_arg = 99;
1398     for (int index = 0; index <= max_arg; ++index) {
1399       jio_snprintf(arg_name, sizeof (arg_name), "argL%d", index);
1400       oop arg = obj_field(mh, arg_name);
1401       if (arg != nullptr) {
1402         RecordLocation fp(this, "%s", arg_name);
1403         if (arg->klass()->is_instance_klass()) {
1404           InstanceKlass* ik2 = InstanceKlass::cast(arg->klass());
1405           record_best_dyno_loc(ik2);
1406           record_call_site_obj(thread, arg);
1407         }
1408       } else {
1409         break;
1410       }
1411     }
1412   }
1413 }
1414 
1415 // Process an object found at an invokedynamic/invokehandle call site and record any dynamic locations.
1416 // Types currently supported are MethodHandle and CallSite.
1417 // The object is typically the "appendix" object, or Bootstrap Method (BSM) object.
1418 void ciEnv::record_call_site_obj(Thread* thread, oop obj)
1419 {
1420   if (obj != nullptr) {
1421     if (java_lang_invoke_MethodHandle::is_instance(obj)) {
1422         record_mh(thread, obj);
1423     } else if (java_lang_invoke_ConstantCallSite::is_instance(obj)) {
1424       oop target = java_lang_invoke_CallSite::target(obj);
1425       if (target->klass()->is_instance_klass()) {
1426         RecordLocation fp(this, "target");
1427         InstanceKlass* ik = InstanceKlass::cast(target->klass());
1428         record_best_dyno_loc(ik);
1429       }
1430     }
1431   }
1432 }
1433 
1434 // Process an adapter Method* found at an invokedynamic/invokehandle call site and record any dynamic locations.
1435 void ciEnv::record_call_site_method(Thread* thread, Method* adapter) {
1436   InstanceKlass* holder = adapter->method_holder();
1437   if (!holder->is_hidden()) {
1438     return;
1439   }
1440   RecordLocation fp(this, "<adapter>");
1441   record_best_dyno_loc(holder);
1442 }
1443 
1444 // Process an invokedynamic call site and record any dynamic locations.
1445 void ciEnv::process_invokedynamic(const constantPoolHandle &cp, int indy_index, JavaThread* thread) {
1446   ResolvedIndyEntry* indy_info = cp->resolved_indy_entry_at(indy_index);
1447   if (indy_info->method() != nullptr) {
1448     // process the adapter
1449     Method* adapter = indy_info->method();
1450     record_call_site_method(thread, adapter);
1451     // process the appendix
1452     oop appendix = cp->resolved_reference_from_indy(indy_index);
1453     {
1454       RecordLocation fp(this, "<appendix>");
1455       record_call_site_obj(thread, appendix);
1456     }
1457     // process the BSM
1458     int pool_index = indy_info->constant_pool_index();
1459     BootstrapInfo bootstrap_specifier(cp, pool_index, indy_index);
1460     oop bsm = cp->resolve_possibly_cached_constant_at(bootstrap_specifier.bsm_index(), thread);
1461     {
1462       RecordLocation fp(this, "<bsm>");
1463       record_call_site_obj(thread, bsm);
1464     }
1465   }
1466 }
1467 
1468 // Process an invokehandle call site and record any dynamic locations.
1469 void ciEnv::process_invokehandle(const constantPoolHandle &cp, int index, JavaThread* thread) {
1470   const int holder_index = cp->klass_ref_index_at(index, Bytecodes::_invokehandle);
1471   if (!cp->tag_at(holder_index).is_klass()) {
1472     return;  // not resolved
1473   }
1474   Klass* holder = ConstantPool::klass_at_if_loaded(cp, holder_index);
1475   Symbol* name = cp->name_ref_at(index, Bytecodes::_invokehandle);
1476   if (MethodHandles::is_signature_polymorphic_name(holder, name)) {
1477     ResolvedMethodEntry* method_entry = cp->resolved_method_entry_at(index);
1478     if (method_entry->is_resolved(Bytecodes::_invokehandle)) {
1479       // process the adapter
1480       Method* adapter = method_entry->method();
1481       oop appendix = cp->cache()->appendix_if_resolved(method_entry);
1482       record_call_site_method(thread, adapter);
1483       // process the appendix
1484       {
1485         RecordLocation fp(this, "<appendix>");
1486         record_call_site_obj(thread, appendix);
1487       }
1488     }
1489   }
1490 }
1491 
1492 // Search the class hierarchy for dynamic classes reachable through dynamic call sites or
1493 // constant pool entries and record for future lookup.
1494 void ciEnv::find_dynamic_call_sites() {
1495   _dyno_klasses = new (arena()) GrowableArray<const InstanceKlass*>(arena(), 100, 0, nullptr);
1496   _dyno_locs    = new (arena()) GrowableArray<const char *>(arena(), 100, 0, nullptr);
1497 
1498   // Iterate over the class hierarchy
1499   for (ClassHierarchyIterator iter(vmClasses::Object_klass()); !iter.done(); iter.next()) {
1500     Klass* sub = iter.klass();
1501     if (sub->is_instance_klass()) {
1502       InstanceKlass *isub = InstanceKlass::cast(sub);
1503       InstanceKlass* ik = isub;
1504       if (!ik->is_linked()) {
1505         continue;
1506       }
1507       if (ik->is_hidden()) {
1508         continue;
1509       }
1510       JavaThread* thread = JavaThread::current();
1511       const constantPoolHandle pool(thread, ik->constants());
1512 
1513       // Look for invokedynamic/invokehandle call sites
1514       for (int i = 0; i < ik->methods()->length(); ++i) {
1515         Method* m = ik->methods()->at(i);
1516 
1517         BytecodeStream bcs(methodHandle(thread, m));
1518         while (!bcs.is_last_bytecode()) {
1519           Bytecodes::Code opcode = bcs.next();
1520           opcode = bcs.raw_code();
1521           switch (opcode) {
1522           case Bytecodes::_invokedynamic:
1523           case Bytecodes::_invokehandle: {
1524             RecordLocation fp(this, "@bci %s %s %s %d",
1525                          ik->name()->as_quoted_ascii(),
1526                          m->name()->as_quoted_ascii(), m->signature()->as_quoted_ascii(),
1527                          bcs.bci());
1528             if (opcode == Bytecodes::_invokedynamic) {
1529               int index = bcs.get_index_u4();
1530               process_invokedynamic(pool, index, thread);
1531             } else {
1532               assert(opcode == Bytecodes::_invokehandle, "new switch label added?");
1533               int cp_cache_index = bcs.get_index_u2();
1534               process_invokehandle(pool, cp_cache_index, thread);
1535             }
1536             break;
1537           }
1538           default:
1539             break;
1540           }
1541         }
1542       }
1543 
1544       // Look for MethodHandle constant pool entries
1545       RecordLocation fp(this, "@cpi %s", ik->name()->as_quoted_ascii());
1546       int len = pool->length();
1547       for (int i = 0; i < len; ++i) {
1548         if (pool->tag_at(i).is_method_handle()) {
1549           bool found_it;
1550           oop mh = pool->find_cached_constant_at(i, found_it, thread);
1551           if (mh != nullptr) {
1552             RecordLocation fp(this, "%d", i);
1553             record_mh(thread, mh);
1554           }
1555         }
1556       }
1557     }
1558   }
1559 }
1560 
1561 void ciEnv::dump_compile_data(outputStream* out) {
1562   CompileTask* task = this->task();
1563   if (task) {
1564 #ifdef COMPILER2
1565     if (ReplayReduce && compiler_data() != nullptr) {
1566       // Dump C2 "reduced" inlining data.
1567       ((Compile*)compiler_data())->dump_inline_data_reduced(out);
1568     }
1569 #endif
1570     Method* method = task->method();
1571     int entry_bci = task->osr_bci();
1572     int comp_level = task->comp_level();
1573     out->print("compile ");
1574     get_method(method)->dump_name_as_ascii(out);
1575     out->print(" %d %d", entry_bci, comp_level);
1576     if (compiler_data() != nullptr) {
1577       if (is_c2_compile(comp_level)) {
1578 #ifdef COMPILER2
1579         // Dump C2 inlining data.
1580         ((Compile*)compiler_data())->dump_inline_data(out);
1581 #endif
1582       } else if (is_c1_compile(comp_level)) {
1583 #ifdef COMPILER1
1584         // Dump C1 inlining data.
1585         ((Compilation*)compiler_data())->dump_inline_data(out);
1586 #endif
1587       }
1588     }
1589     out->cr();
1590   }
1591 }
1592 
1593 // Called from VM error reporter, so be careful.
1594 // Don't safepoint or acquire any locks.
1595 //
1596 void ciEnv::dump_replay_data_helper(outputStream* out) {
1597   NoSafepointVerifier no_safepoint;
1598   ResourceMark rm;
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 in order to get the right
1613   // protection domain to load subsequent classes during replay compilation.
1614   ciInstanceKlass::dump_replay_instanceKlass(out, task()->method()->method_holder());
1615 
1616   for (int i = 0; i < objects->length(); i++) {
1617     objects->at(i)->dump_replay_data(out);
1618   }
1619 
1620   if (this->task() != nullptr) {
1621     dump_compile_data(out);
1622   }
1623   out->flush();
1624 }
1625 
1626 // Called from VM error reporter, so be careful.
1627 // Don't safepoint or acquire any locks.
1628 //
1629 void ciEnv::dump_replay_data_unsafe(outputStream* out) {
1630   GUARDED_VM_ENTRY(
1631     dump_replay_data_helper(out);
1632   )
1633 }
1634 
1635 void ciEnv::dump_replay_data(outputStream* out) {
1636   GUARDED_VM_ENTRY(
1637     MutexLocker ml(Compile_lock);
1638     dump_replay_data_helper(out);
1639   )
1640 }
1641 
1642 void ciEnv::dump_replay_data(int compile_id) {
1643   char buffer[64];
1644   int ret = jio_snprintf(buffer, sizeof(buffer), "replay_pid%d_compid%d.log", os::current_process_id(), compile_id);
1645   if (ret > 0) {
1646     int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);
1647     if (fd != -1) {
1648       FILE* replay_data_file = os::fdopen(fd, "w");
1649       if (replay_data_file != nullptr) {
1650         fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1651         dump_replay_data(&replay_data_stream);
1652         tty->print_cr("# Compiler replay data is saved as: %s", buffer);
1653       } else {
1654         tty->print_cr("# Can't open file to dump replay data.");
1655         close(fd);
1656       }
1657     }
1658   }
1659 }
1660 
1661 void ciEnv::dump_inline_data(int compile_id) {
1662   char buffer[64];
1663   int ret = jio_snprintf(buffer, sizeof(buffer), "inline_pid%d_compid%d.log", os::current_process_id(), compile_id);
1664   if (ret > 0) {
1665     int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);
1666     if (fd != -1) {
1667       FILE* inline_data_file = os::fdopen(fd, "w");
1668       if (inline_data_file != nullptr) {
1669         fileStream replay_data_stream(inline_data_file, /*need_close=*/true);
1670         GUARDED_VM_ENTRY(
1671           MutexLocker ml(Compile_lock);
1672           dump_replay_data_version(&replay_data_stream);
1673           dump_compile_data(&replay_data_stream);
1674         )
1675         replay_data_stream.flush();
1676         tty->print("# Compiler inline data is saved as: ");
1677         tty->print_cr("%s", buffer);
1678       } else {
1679         tty->print_cr("# Can't open file to dump inline data.");
1680         close(fd);
1681       }
1682     }
1683   }
1684 }
1685 
1686 void ciEnv::dump_replay_data_version(outputStream* out) {
1687   out->print_cr("version %d", REPLAY_VERSION);
1688 }