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                             RTMState  rtm_state,
1027                             const GrowableArrayView<RuntimeStub*>& native_invokers) {
1028   VM_ENTRY_MARK;
1029   nmethod* nm = NULL;
1030   {
1031     methodHandle method(THREAD, target->get_Method());
1032 
1033     // We require method counters to store some method state (max compilation levels) required by the compilation policy.
1034     if (method->get_method_counters(THREAD) == NULL) {
1035       record_failure("can't create method counters");
1036       // All buffers in the CodeBuffer are allocated in the CodeCache.
1037       // If the code buffer is created on each compile attempt
1038       // as in C2, then it must be freed.
1039       code_buffer->free_blob();
1040       return;
1041     }
1042 
1043     // To prevent compile queue updates.
1044     MutexLocker locker(THREAD, MethodCompileQueue_lock);
1045 
1046     // Prevent SystemDictionary::add_to_hierarchy from running
1047     // and invalidating our dependencies until we install this method.
1048     // No safepoints are allowed. Otherwise, class redefinition can occur in between.
1049     MutexLocker ml(Compile_lock);
1050     NoSafepointVerifier nsv;
1051 
1052     // Change in Jvmti state may invalidate compilation.
1053     if (!failing() && jvmti_state_changed()) {
1054       record_failure("Jvmti state change invalidated dependencies");
1055     }
1056 
1057     // Change in DTrace flags may invalidate compilation.
1058     if (!failing() &&
1059         ( (!dtrace_extended_probes() && ExtendedDTraceProbes) ||
1060           (!dtrace_method_probes() && DTraceMethodProbes) ||
1061           (!dtrace_alloc_probes() && DTraceAllocProbes) )) {
1062       record_failure("DTrace flags change invalidated dependencies");
1063     }
1064 
1065     if (!failing() && target->needs_clinit_barrier() &&
1066         target->holder()->is_in_error_state()) {
1067       record_failure("method holder is in error state");
1068     }
1069 
1070     if (!failing()) {
1071       if (log() != NULL) {
1072         // Log the dependencies which this compilation declares.
1073         dependencies()->log_all_dependencies();
1074       }
1075 
1076       // Encode the dependencies now, so we can check them right away.
1077       dependencies()->encode_content_bytes();
1078 
1079       // Check for {class loads, evolution, breakpoints, ...} during compilation
1080       validate_compile_task_dependencies(target);
1081     }
1082 #if INCLUDE_RTM_OPT
1083     if (!failing() && (rtm_state != NoRTM) &&
1084         (method()->method_data() != NULL) &&
1085         (method()->method_data()->rtm_state() != rtm_state)) {
1086       // Preemptive decompile if rtm state was changed.
1087       record_failure("RTM state change invalidated rtm code");
1088     }
1089 #endif
1090 
1091     if (failing()) {
1092       // While not a true deoptimization, it is a preemptive decompile.
1093       MethodData* mdo = method()->method_data();
1094       if (mdo != NULL && _inc_decompile_count_on_failure) {
1095         mdo->inc_decompile_count();
1096       }
1097 
1098       // All buffers in the CodeBuffer are allocated in the CodeCache.
1099       // If the code buffer is created on each compile attempt
1100       // as in C2, then it must be freed.
1101       code_buffer->free_blob();
1102       return;
1103     }
1104 
1105     assert(offsets->value(CodeOffsets::Deopt) != -1, "must have deopt entry");
1106     assert(offsets->value(CodeOffsets::Exceptions) != -1, "must have exception entry");
1107 
1108     nm =  nmethod::new_nmethod(method,
1109                                compile_id(),
1110                                entry_bci,
1111                                offsets,
1112                                orig_pc_offset,
1113                                debug_info(), dependencies(), code_buffer,
1114                                frame_words, oop_map_set,
1115                                handler_table, inc_table,
1116                                compiler, task()->comp_level(),
1117                                native_invokers);
1118 
1119     // Free codeBlobs
1120     code_buffer->free_blob();
1121 
1122     if (nm != NULL) {
1123       nm->set_has_unsafe_access(has_unsafe_access);
1124       nm->set_has_wide_vectors(has_wide_vectors);
1125 #if INCLUDE_RTM_OPT
1126       nm->set_rtm_state(rtm_state);
1127 #endif
1128 
1129       // Record successful registration.
1130       // (Put nm into the task handle *before* publishing to the Java heap.)
1131       if (task() != NULL) {
1132         task()->set_code(nm);
1133       }
1134 
1135       if (entry_bci == InvocationEntryBci) {
1136         if (TieredCompilation) {
1137           // If there is an old version we're done with it
1138           CompiledMethod* old = method->code();
1139           if (TraceMethodReplacement && old != NULL) {
1140             ResourceMark rm;
1141             char *method_name = method->name_and_sig_as_C_string();
1142             tty->print_cr("Replacing method %s", method_name);
1143           }
1144           if (old != NULL) {
1145             old->make_not_used();
1146           }
1147         }
1148 
1149         LogTarget(Info, nmethod, install) lt;
1150         if (lt.is_enabled()) {
1151           ResourceMark rm;
1152           char *method_name = method->name_and_sig_as_C_string();
1153           lt.print("Installing method (%d) %s ",
1154                     task()->comp_level(), method_name);
1155         }
1156         // Allow the code to be executed
1157         MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
1158         if (nm->make_in_use()) {
1159           method->set_code(method, nm);
1160         }
1161       } else {
1162         LogTarget(Info, nmethod, install) lt;
1163         if (lt.is_enabled()) {
1164           ResourceMark rm;
1165           char *method_name = method->name_and_sig_as_C_string();
1166           lt.print("Installing osr method (%d) %s @ %d",
1167                     task()->comp_level(), method_name, entry_bci);
1168         }
1169         MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
1170         if (nm->make_in_use()) {
1171           method->method_holder()->add_osr_nmethod(nm);
1172         }
1173       }
1174     }
1175   }  // safepoints are allowed again
1176 
1177   if (nm != NULL) {
1178     // JVMTI -- compiled method notification (must be done outside lock)
1179     nm->post_compiled_method_load_event();
1180   } else {
1181     // The CodeCache is full.
1182     record_failure("code cache is full");
1183   }
1184 }
1185 
1186 // ------------------------------------------------------------------
1187 // ciEnv::comp_level
1188 int ciEnv::comp_level() {
1189   if (task() == NULL)  return CompilationPolicy::highest_compile_level();
1190   return task()->comp_level();
1191 }
1192 
1193 // ------------------------------------------------------------------
1194 // ciEnv::compile_id
1195 uint ciEnv::compile_id() {
1196   if (task() == NULL)  return 0;
1197   return task()->compile_id();
1198 }
1199 
1200 // ------------------------------------------------------------------
1201 // ciEnv::notice_inlined_method()
1202 void ciEnv::notice_inlined_method(ciMethod* method) {
1203   _num_inlined_bytecodes += method->code_size_for_inlining();
1204 }
1205 
1206 // ------------------------------------------------------------------
1207 // ciEnv::num_inlined_bytecodes()
1208 int ciEnv::num_inlined_bytecodes() const {
1209   return _num_inlined_bytecodes;
1210 }
1211 
1212 // ------------------------------------------------------------------
1213 // ciEnv::record_failure()
1214 void ciEnv::record_failure(const char* reason) {
1215   if (_failure_reason == NULL) {
1216     // Record the first failure reason.
1217     _failure_reason = reason;
1218   }
1219 }
1220 
1221 void ciEnv::report_failure(const char* reason) {
1222   EventCompilationFailure event;
1223   if (event.should_commit()) {
1224     CompilerEvent::CompilationFailureEvent::post(event, compile_id(), reason);
1225   }
1226 }
1227 
1228 // ------------------------------------------------------------------
1229 // ciEnv::record_method_not_compilable()
1230 void ciEnv::record_method_not_compilable(const char* reason, bool all_tiers) {
1231   int new_compilable =
1232     all_tiers ? MethodCompilable_never : MethodCompilable_not_at_tier ;
1233 
1234   // Only note transitions to a worse state
1235   if (new_compilable > _compilable) {
1236     if (log() != NULL) {
1237       if (all_tiers) {
1238         log()->elem("method_not_compilable");
1239       } else {
1240         log()->elem("method_not_compilable_at_tier level='%d'",
1241                     current()->task()->comp_level());
1242       }
1243     }
1244     _compilable = new_compilable;
1245 
1246     // Reset failure reason; this one is more important.
1247     _failure_reason = NULL;
1248     record_failure(reason);
1249   }
1250 }
1251 
1252 // ------------------------------------------------------------------
1253 // ciEnv::record_out_of_memory_failure()
1254 void ciEnv::record_out_of_memory_failure() {
1255   // If memory is low, we stop compiling methods.
1256   record_method_not_compilable("out of memory");
1257 }
1258 
1259 ciInstance* ciEnv::unloaded_ciinstance() {
1260   GUARDED_VM_ENTRY(return _factory->get_unloaded_object_constant();)
1261 }
1262 
1263 // ------------------------------------------------------------------
1264 // Replay support
1265 
1266 
1267 // Lookup location descriptor for the class, if any.
1268 // Returns false if not found.
1269 bool ciEnv::dyno_loc(const InstanceKlass* ik, const char *&loc) const {
1270   bool found = false;
1271   int pos = _dyno_klasses->find_sorted<const InstanceKlass*, klass_compare>(ik, found);
1272   if (!found) {
1273     return false;
1274   }
1275   loc = _dyno_locs->at(pos);
1276   return found;
1277 }
1278 
1279 // Associate the current location descriptor with the given class and record for later lookup.
1280 void ciEnv::set_dyno_loc(const InstanceKlass* ik) {
1281   const char *loc = os::strdup(_dyno_name);
1282   bool found = false;
1283   int pos = _dyno_klasses->find_sorted<const InstanceKlass*, klass_compare>(ik, found);
1284   if (found) {
1285     _dyno_locs->at_put(pos, loc);
1286   } else {
1287     _dyno_klasses->insert_before(pos, ik);
1288     _dyno_locs->insert_before(pos, loc);
1289   }
1290 }
1291 
1292 // Associate the current location descriptor with the given class and record for later lookup.
1293 // If it turns out that there are multiple locations for the given class, that conflict should
1294 // be handled here.  Currently we choose the first location found.
1295 void ciEnv::record_best_dyno_loc(const InstanceKlass* ik) {
1296   if (!ik->is_hidden()) {
1297     return;
1298   }
1299   const char *loc0;
1300   if (dyno_loc(ik, loc0)) {
1301     // TODO: found multiple references, see if we can improve
1302     if (Verbose) {
1303       tty->print_cr("existing call site @ %s for %s",
1304                      loc0, ik->external_name());
1305     }
1306   } else {
1307     set_dyno_loc(ik);
1308   }
1309 }
1310 
1311 // Look up the location descriptor for the given class and print it to the output stream.
1312 bool ciEnv::print_dyno_loc(outputStream* out, const InstanceKlass* ik) const {
1313   const char *loc;
1314   if (dyno_loc(ik, loc)) {
1315     out->print("%s", loc);
1316     return true;
1317   } else {
1318     return false;
1319   }
1320 }
1321 
1322 // Look up the location descriptor for the given class and return it as a string.
1323 // Returns NULL if no location is found.
1324 const char *ciEnv::dyno_name(const InstanceKlass* ik) const {
1325   if (ik->is_hidden()) {
1326     stringStream ss;
1327     if (print_dyno_loc(&ss, ik)) {
1328       ss.print(" ;"); // add terminator
1329       const char* call_site = ss.as_string();
1330       return call_site;
1331     }
1332   }
1333   return NULL;
1334 }
1335 
1336 // Look up the location descriptor for the given class and return it as a string.
1337 // Returns the class name as a fallback if no location is found.
1338 const char *ciEnv::replay_name(ciKlass* k) const {
1339   if (k->is_instance_klass()) {
1340     return replay_name(k->as_instance_klass()->get_instanceKlass());
1341   }
1342   return k->name()->as_quoted_ascii();
1343 }
1344 
1345 // Look up the location descriptor for the given class and return it as a string.
1346 // Returns the class name as a fallback if no location is found.
1347 const char *ciEnv::replay_name(const InstanceKlass* ik) const {
1348   const char* name = dyno_name(ik);
1349   if (name != NULL) {
1350       return name;
1351   }
1352   return ik->name()->as_quoted_ascii();
1353 }
1354 
1355 // Process a java.lang.invoke.MemberName object and record any dynamic locations.
1356 void ciEnv::record_member(Thread* thread, oop member) {
1357   assert(java_lang_invoke_MemberName::is_instance(member), "!");
1358   // Check MemberName.clazz field
1359   oop clazz = java_lang_invoke_MemberName::clazz(member);
1360   if (clazz->klass()->is_instance_klass()) {
1361     RecordLocation fp(this, "clazz");
1362     InstanceKlass* ik = InstanceKlass::cast(clazz->klass());
1363     record_best_dyno_loc(ik);
1364   }
1365   // Check MemberName.method.vmtarget field
1366   Method* vmtarget = java_lang_invoke_MemberName::vmtarget(member);
1367   if (vmtarget != NULL) {
1368     RecordLocation fp2(this, "<vmtarget>");
1369     InstanceKlass* ik = vmtarget->method_holder();
1370     record_best_dyno_loc(ik);
1371   }
1372 }
1373 
1374 // Read an object field.  Lookup is done by name only.
1375 static inline oop obj_field(oop obj, const char* name) {
1376     return ciReplay::obj_field(obj, name);
1377 }
1378 
1379 // Process a java.lang.invoke.LambdaForm object and record any dynamic locations.
1380 void ciEnv::record_lambdaform(Thread* thread, oop form) {
1381   assert(java_lang_invoke_LambdaForm::is_instance(form), "!");
1382 
1383   {
1384     // Check LambdaForm.vmentry field
1385     oop member = java_lang_invoke_LambdaForm::vmentry(form);
1386     RecordLocation fp0(this, "vmentry");
1387     record_member(thread, member);
1388   }
1389 
1390   // Check LambdaForm.names array
1391   objArrayOop names = (objArrayOop)obj_field(form, "names");
1392   if (names != NULL) {
1393     RecordLocation lp0(this, "names");
1394     int len = names->length();
1395     for (int i = 0; i < len; ++i) {
1396       oop name = names->obj_at(i);
1397       RecordLocation lp1(this, "%d", i);
1398      // Check LambdaForm.names[i].function field
1399       RecordLocation lp2(this, "function");
1400       oop function = obj_field(name, "function");
1401       if (function != NULL) {
1402         // Check LambdaForm.names[i].function.member field
1403         oop member = obj_field(function, "member");
1404         if (member != NULL) {
1405           RecordLocation lp3(this, "member");
1406           record_member(thread, member);
1407         }
1408         // Check LambdaForm.names[i].function.resolvedHandle field
1409         oop mh = obj_field(function, "resolvedHandle");
1410         if (mh != NULL) {
1411           RecordLocation lp3(this, "resolvedHandle");
1412           record_mh(thread, mh);
1413         }
1414         // Check LambdaForm.names[i].function.invoker field
1415         oop invoker = obj_field(function, "invoker");
1416         if (invoker != NULL) {
1417           RecordLocation lp3(this, "invoker");
1418           record_mh(thread, invoker);
1419         }
1420       }
1421     }
1422   }
1423 }
1424 
1425 // Process a java.lang.invoke.MethodHandle object and record any dynamic locations.
1426 void ciEnv::record_mh(Thread* thread, oop mh) {
1427   {
1428     // Check MethodHandle.form field
1429     oop form = java_lang_invoke_MethodHandle::form(mh);
1430     RecordLocation fp(this, "form");
1431     record_lambdaform(thread, form);
1432   }
1433   // Check DirectMethodHandle.member field
1434   if (java_lang_invoke_DirectMethodHandle::is_instance(mh)) {
1435     oop member = java_lang_invoke_DirectMethodHandle::member(mh);
1436     RecordLocation fp(this, "member");
1437     record_member(thread, member);
1438   } else {
1439     // Check <MethodHandle subclass>.argL0 field
1440     // Probably BoundMethodHandle.Species_L, but we only care if the field exists
1441     oop arg = obj_field(mh, "argL0");
1442     if (arg != NULL) {
1443       RecordLocation fp(this, "argL0");
1444       if (arg->klass()->is_instance_klass()) {
1445         InstanceKlass* ik2 = InstanceKlass::cast(arg->klass());
1446         record_best_dyno_loc(ik2);
1447       }
1448     }
1449   }
1450 }
1451 
1452 // Process an object found at an invokedynamic/invokehandle call site and record any dynamic locations.
1453 // Types currently supported are MethodHandle and CallSite.
1454 // The object is typically the "appendix" object, or Bootstrap Method (BSM) object.
1455 void ciEnv::record_call_site_obj(Thread* thread, const constantPoolHandle& pool, const Handle obj)
1456 {
1457   if (obj.not_null()) {
1458     if (java_lang_invoke_MethodHandle::is_instance(obj())) {
1459         record_mh(thread, obj());
1460     } else if (java_lang_invoke_ConstantCallSite::is_instance(obj())) {
1461       oop target = java_lang_invoke_CallSite::target(obj());
1462       if (target->klass()->is_instance_klass()) {
1463         RecordLocation fp(this, "target");
1464         InstanceKlass* ik = InstanceKlass::cast(target->klass());
1465         record_best_dyno_loc(ik);
1466       }
1467     }
1468   }
1469 }
1470 
1471 // Process an adapter Method* found at an invokedynamic/invokehandle call site and record any dynamic locations.
1472 void ciEnv::record_call_site_method(Thread* thread, const constantPoolHandle& pool, Method* adapter) {
1473   InstanceKlass* holder = adapter->method_holder();
1474   if (!holder->is_hidden()) {
1475     return;
1476   }
1477   RecordLocation fp(this, "<adapter>");
1478   record_best_dyno_loc(holder);
1479 }
1480 
1481 // Process an invokedynamic call site and record any dynamic locations.
1482 void ciEnv::process_invokedynamic(const constantPoolHandle &cp, int indy_index, JavaThread* thread) {
1483   ConstantPoolCacheEntry* cp_cache_entry = cp->invokedynamic_cp_cache_entry_at(indy_index);
1484   if (cp_cache_entry->is_resolved(Bytecodes::_invokedynamic)) {
1485     // process the adapter
1486     Method* adapter = cp_cache_entry->f1_as_method();
1487     record_call_site_method(thread, cp, adapter);
1488     // process the appendix
1489     Handle appendix(thread, cp_cache_entry->appendix_if_resolved(cp));
1490     {
1491       RecordLocation fp(this, "<appendix>");
1492       record_call_site_obj(thread, cp, appendix);
1493     }
1494     // process the BSM
1495     int pool_index = cp_cache_entry->constant_pool_index();
1496     BootstrapInfo bootstrap_specifier(cp, pool_index, indy_index);
1497     oop bsm_oop = cp->resolve_possibly_cached_constant_at(bootstrap_specifier.bsm_index(), thread);
1498     Handle bsm(thread, bsm_oop);
1499     {
1500       RecordLocation fp(this, "<bsm>");
1501       record_call_site_obj(thread, cp, bsm);
1502     }
1503   }
1504 }
1505 
1506 // Process an invokehandle call site and record any dynamic locations.
1507 void ciEnv::process_invokehandle(const constantPoolHandle &cp, int index, JavaThread* thread) {
1508   const int holder_index = cp->klass_ref_index_at(index);
1509   if (!cp->tag_at(holder_index).is_klass()) {
1510     return;  // not resolved
1511   }
1512   Klass* holder = ConstantPool::klass_at_if_loaded(cp, holder_index);
1513   Symbol* name = cp->name_ref_at(index);
1514   if (MethodHandles::is_signature_polymorphic_name(holder, name)) {
1515     ConstantPoolCacheEntry* cp_cache_entry = cp->cache()->entry_at(cp->decode_cpcache_index(index));
1516     if (cp_cache_entry->is_resolved(Bytecodes::_invokehandle)) {
1517       // process the adapter
1518       Method* adapter = cp_cache_entry->f1_as_method();
1519       Handle appendix(thread, cp_cache_entry->appendix_if_resolved(cp));
1520       record_call_site_method(thread, cp, adapter);
1521       // process the appendix
1522       {
1523         RecordLocation fp(this, "<appendix>");
1524         record_call_site_obj(thread, cp, appendix);
1525       }
1526     }
1527   }
1528 }
1529 
1530 // Search the class hierarchy for dynamic classes reachable through dynamic call sites or
1531 // constant pool entries and record for future lookup.
1532 void ciEnv::find_dynamic_call_sites() {
1533   _dyno_klasses = new (arena()) GrowableArray<const InstanceKlass*>(arena(), 100, 0, NULL);
1534   _dyno_locs    = new (arena()) GrowableArray<const char *>(arena(), 100, 0, NULL);
1535 
1536   // Iterate over the class hierarchy
1537   for (ClassHierarchyIterator iter(vmClasses::Object_klass()); !iter.done(); iter.next()) {
1538     Klass* sub = iter.klass();
1539     if (sub->is_instance_klass()) {
1540       InstanceKlass *isub = InstanceKlass::cast(sub);
1541       InstanceKlass* ik = isub;
1542       if (!ik->is_linked()) {
1543         continue;
1544       }
1545       if (ik->is_hidden()) {
1546         continue;
1547       }
1548       JavaThread* thread = JavaThread::current();
1549       const constantPoolHandle pool(thread, ik->constants());
1550 
1551       // Look for invokedynamic/invokehandle call sites
1552       for (int i = 0; i < ik->methods()->length(); ++i) {
1553         Method* m = ik->methods()->at(i);
1554 
1555         BytecodeStream bcs(methodHandle(thread, m));
1556         while (!bcs.is_last_bytecode()) {
1557           Bytecodes::Code opcode = bcs.next();
1558           opcode = bcs.raw_code();
1559           switch (opcode) {
1560           case Bytecodes::_invokedynamic:
1561           case Bytecodes::_invokehandle: {
1562             RecordLocation fp(this, "@bci %s %s %s %d",
1563                          ik->name()->as_quoted_ascii(),
1564                          m->name()->as_quoted_ascii(), m->signature()->as_quoted_ascii(),
1565                          bcs.bci());
1566             if (opcode == Bytecodes::_invokedynamic) {
1567               int index = bcs.get_index_u4();
1568               process_invokedynamic(pool, index, thread);
1569             } else {
1570               assert(opcode == Bytecodes::_invokehandle, "new switch label added?");
1571               int cp_cache_index = bcs.get_index_u2_cpcache();
1572               process_invokehandle(pool, cp_cache_index, thread);
1573             }
1574             break;
1575           }
1576           default:
1577             break;
1578           }
1579         }
1580       }
1581 
1582       // Look for MethodHandle contant pool entries
1583       RecordLocation fp(this, "@cpi %s", ik->name()->as_quoted_ascii());
1584       int len = pool->length();
1585       for (int i = 0; i < len; ++i) {
1586         if (pool->tag_at(i).is_method_handle()) {
1587           bool found_it;
1588           oop mh = pool->find_cached_constant_at(i, found_it, thread);
1589           if (mh != NULL) {
1590             RecordLocation fp(this, "%d", i);
1591             record_mh(thread, mh);
1592           }
1593         }
1594       }
1595     }
1596   }
1597 }
1598 
1599 void ciEnv::dump_compile_data(outputStream* out) {
1600   CompileTask* task = this->task();
1601   if (task) {
1602     Method* method = task->method();
1603     int entry_bci = task->osr_bci();
1604     int comp_level = task->comp_level();
1605     out->print("compile ");
1606     get_method(method)->dump_name_as_ascii(out);
1607     out->print(" %d %d", entry_bci, comp_level);
1608     if (compiler_data() != NULL) {
1609       if (is_c2_compile(comp_level)) {
1610 #ifdef COMPILER2
1611         // Dump C2 inlining data.
1612         ((Compile*)compiler_data())->dump_inline_data(out);
1613 #endif
1614       } else if (is_c1_compile(comp_level)) {
1615 #ifdef COMPILER1
1616         // Dump C1 inlining data.
1617         ((Compilation*)compiler_data())->dump_inline_data(out);
1618 #endif
1619       }
1620     }
1621     out->cr();
1622   }
1623 }
1624 
1625 // Called from VM error reporter, so be careful.
1626 // Don't safepoint or acquire any locks.
1627 //
1628 void ciEnv::dump_replay_data_helper(outputStream* out) {
1629   NoSafepointVerifier no_safepoint;
1630   ResourceMark rm;
1631 
1632 #if INCLUDE_JVMTI
1633   out->print_cr("JvmtiExport can_access_local_variables %d",     _jvmti_can_access_local_variables);
1634   out->print_cr("JvmtiExport can_hotswap_or_post_breakpoint %d", _jvmti_can_hotswap_or_post_breakpoint);
1635   out->print_cr("JvmtiExport can_post_on_exceptions %d",         _jvmti_can_post_on_exceptions);
1636 #endif // INCLUDE_JVMTI
1637 
1638   find_dynamic_call_sites();
1639 
1640   GrowableArray<ciMetadata*>* objects = _factory->get_ci_metadata();
1641   out->print_cr("# %d ciObject found", objects->length());
1642   for (int i = 0; i < objects->length(); i++) {
1643     objects->at(i)->dump_replay_data(out);
1644   }
1645   dump_compile_data(out);
1646   out->flush();
1647 }
1648 
1649 // Called from VM error reporter, so be careful.
1650 // Don't safepoint or acquire any locks.
1651 //
1652 void ciEnv::dump_replay_data_unsafe(outputStream* out) {
1653   GUARDED_VM_ENTRY(
1654     dump_replay_data_helper(out);
1655   )
1656 }
1657 
1658 void ciEnv::dump_replay_data(outputStream* out) {
1659   GUARDED_VM_ENTRY(
1660     MutexLocker ml(Compile_lock);
1661     dump_replay_data_helper(out);
1662   )
1663 }
1664 
1665 void ciEnv::dump_replay_data(int compile_id) {
1666   static char buffer[O_BUFLEN];
1667   int ret = jio_snprintf(buffer, O_BUFLEN, "replay_pid%p_compid%d.log", os::current_process_id(), compile_id);
1668   if (ret > 0) {
1669     int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);
1670     if (fd != -1) {
1671       FILE* replay_data_file = os::open(fd, "w");
1672       if (replay_data_file != NULL) {
1673         fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1674         dump_replay_data(&replay_data_stream);
1675         tty->print_cr("# Compiler replay data is saved as: %s", buffer);
1676       } else {
1677         tty->print_cr("# Can't open file to dump replay data.");
1678       }
1679     }
1680   }
1681 }
1682 
1683 void ciEnv::dump_inline_data(int compile_id) {
1684   static char buffer[O_BUFLEN];
1685   int ret = jio_snprintf(buffer, O_BUFLEN, "inline_pid%p_compid%d.log", os::current_process_id(), compile_id);
1686   if (ret > 0) {
1687     int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);
1688     if (fd != -1) {
1689       FILE* inline_data_file = os::open(fd, "w");
1690       if (inline_data_file != NULL) {
1691         fileStream replay_data_stream(inline_data_file, /*need_close=*/true);
1692         GUARDED_VM_ENTRY(
1693           MutexLocker ml(Compile_lock);
1694           dump_compile_data(&replay_data_stream);
1695         )
1696         replay_data_stream.flush();
1697         tty->print("# Compiler inline data is saved as: ");
1698         tty->print_cr("%s", buffer);
1699       } else {
1700         tty->print_cr("# Can't open file to dump inline data.");
1701       }
1702     }
1703   }
1704 }