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