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