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