1 /*
   2  * Copyright (c) 1999, 2019, 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/ciUtilities.inline.hpp"
  36 #include "classfile/symbolTable.hpp"
  37 #include "classfile/systemDictionary.hpp"
  38 #include "classfile/vmSymbols.hpp"
  39 #include "code/codeCache.hpp"
  40 #include "code/scopeDesc.hpp"
  41 #include "compiler/compileBroker.hpp"
  42 #include "compiler/compileLog.hpp"
  43 #include "compiler/disassembler.hpp"
  44 #include "gc/shared/collectedHeap.inline.hpp"
  45 #include "interpreter/linkResolver.hpp"
  46 #include "jfr/jfrEvents.hpp"
  47 #include "logging/log.hpp"
  48 #include "memory/allocation.inline.hpp"
  49 #include "memory/oopFactory.hpp"
  50 #include "memory/resourceArea.hpp"
  51 #include "memory/universe.hpp"
  52 #include "oops/constantPool.inline.hpp"
  53 #include "oops/cpCache.inline.hpp"
  54 #include "oops/method.inline.hpp"
  55 #include "oops/methodData.hpp"
  56 #include "oops/objArrayKlass.hpp"
  57 #include "oops/objArrayOop.inline.hpp"
  58 #include "oops/oop.inline.hpp"
  59 #include "prims/jvmtiExport.hpp"
  60 #include "runtime/handles.inline.hpp"
  61 #include "runtime/init.hpp"
  62 #include "runtime/reflection.hpp"
  63 #include "runtime/jniHandles.inline.hpp"
  64 #include "runtime/safepointVerifiers.hpp"
  65 #include "runtime/sharedRuntime.hpp"
  66 #include "runtime/thread.inline.hpp"
  67 #include "utilities/dtrace.hpp"
  68 #include "utilities/macros.hpp"
  69 #ifdef COMPILER1
  70 #include "c1/c1_Runtime1.hpp"
  71 #endif
  72 #ifdef COMPILER2
  73 #include "opto/runtime.hpp"
  74 #endif
  75 
  76 // ciEnv
  77 //
  78 // This class is the top level broker for requests from the compiler
  79 // to the VM.
  80 
  81 ciObject*              ciEnv::_null_object_instance;
  82 
  83 #define WK_KLASS_DEFN(name, ignore_s) ciInstanceKlass* ciEnv::_##name = NULL;
  84 WK_KLASSES_DO(WK_KLASS_DEFN)
  85 #undef WK_KLASS_DEFN
  86 
  87 ciSymbol*        ciEnv::_unloaded_cisymbol = NULL;
  88 ciInstanceKlass* ciEnv::_unloaded_ciinstance_klass = NULL;
  89 ciObjArrayKlass* ciEnv::_unloaded_ciobjarrayklass = NULL;
  90 
  91 jobject ciEnv::_ArrayIndexOutOfBoundsException_handle = NULL;
  92 jobject ciEnv::_ArrayStoreException_handle = NULL;
  93 jobject ciEnv::_ClassCastException_handle = NULL;
  94 
  95 #ifndef PRODUCT
  96 static bool firstEnv = true;
  97 #endif /* PRODUCT */
  98 
  99 // ------------------------------------------------------------------
 100 // ciEnv::ciEnv
 101 ciEnv::ciEnv(CompileTask* task, int system_dictionary_modification_counter)
 102   : _ciEnv_arena(mtCompiler) {
 103   VM_ENTRY_MARK;
 104 
 105   // Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc.
 106   thread->set_env(this);
 107   assert(ciEnv::current() == this, "sanity");
 108 
 109   _oop_recorder = NULL;
 110   _debug_info = NULL;
 111   _dependencies = NULL;
 112   _failure_reason = NULL;
 113   _inc_decompile_count_on_failure = true;
 114   _compilable = MethodCompilable;
 115   _break_at_compile = false;
 116   _compiler_data = NULL;
 117 #ifndef PRODUCT
 118   assert(!firstEnv, "not initialized properly");
 119 #endif /* !PRODUCT */
 120 
 121   _system_dictionary_modification_counter = system_dictionary_modification_counter;
 122   _num_inlined_bytecodes = 0;
 123   assert(task == NULL || thread->task() == task, "sanity");
 124   if (task != NULL) {
 125     task->mark_started(os::elapsed_counter());
 126   }
 127   _task = task;
 128   _log = NULL;
 129 
 130   // Temporary buffer for creating symbols and such.
 131   _name_buffer = NULL;
 132   _name_buffer_len = 0;
 133 
 134   _arena   = &_ciEnv_arena;
 135   _factory = new (_arena) ciObjectFactory(_arena, 128);
 136 
 137   // Preload commonly referenced system ciObjects.
 138 
 139   // During VM initialization, these instances have not yet been created.
 140   // Assertions ensure that these instances are not accessed before
 141   // their initialization.
 142 
 143   assert(Universe::is_fully_initialized(), "should be complete");
 144 
 145   oop o = Universe::null_ptr_exception_instance();
 146   assert(o != NULL, "should have been initialized");
 147   _NullPointerException_instance = get_object(o)->as_instance();
 148   o = Universe::arithmetic_exception_instance();
 149   assert(o != NULL, "should have been initialized");
 150   _ArithmeticException_instance = get_object(o)->as_instance();
 151 
 152   _ArrayIndexOutOfBoundsException_instance = NULL;
 153   _ArrayStoreException_instance = NULL;
 154   _ClassCastException_instance = NULL;
 155   _the_null_string = NULL;
 156   _the_min_jint_string = NULL;
 157 
 158   _jvmti_can_hotswap_or_post_breakpoint = false;
 159   _jvmti_can_access_local_variables = false;
 160   _jvmti_can_post_on_exceptions = false;
 161   _jvmti_can_pop_frame = false;
 162 }
 163 
 164 ciEnv::ciEnv(Arena* arena) : _ciEnv_arena(mtCompiler) {
 165   ASSERT_IN_VM;
 166 
 167   // Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc.
 168   CompilerThread* current_thread = CompilerThread::current();
 169   assert(current_thread->env() == NULL, "must be");
 170   current_thread->set_env(this);
 171   assert(ciEnv::current() == this, "sanity");
 172 
 173   _oop_recorder = NULL;
 174   _debug_info = NULL;
 175   _dependencies = NULL;
 176   _failure_reason = NULL;
 177   _inc_decompile_count_on_failure = true;
 178   _compilable = MethodCompilable_never;
 179   _break_at_compile = false;
 180   _compiler_data = NULL;
 181 #ifndef PRODUCT
 182   assert(firstEnv, "must be first");
 183   firstEnv = false;
 184 #endif /* !PRODUCT */
 185 
 186   _system_dictionary_modification_counter = 0;
 187   _num_inlined_bytecodes = 0;
 188   _task = NULL;
 189   _log = NULL;
 190 
 191   // Temporary buffer for creating symbols and such.
 192   _name_buffer = NULL;
 193   _name_buffer_len = 0;
 194 
 195   _arena   = arena;
 196   _factory = new (_arena) ciObjectFactory(_arena, 128);
 197 
 198   // Preload commonly referenced system ciObjects.
 199 
 200   // During VM initialization, these instances have not yet been created.
 201   // Assertions ensure that these instances are not accessed before
 202   // their initialization.
 203 
 204   assert(Universe::is_fully_initialized(), "must be");
 205 
 206   _NullPointerException_instance = NULL;
 207   _ArithmeticException_instance = NULL;
 208   _ArrayIndexOutOfBoundsException_instance = NULL;
 209   _ArrayStoreException_instance = NULL;
 210   _ClassCastException_instance = NULL;
 211   _the_null_string = NULL;
 212   _the_min_jint_string = NULL;
 213 
 214   _jvmti_can_hotswap_or_post_breakpoint = false;
 215   _jvmti_can_access_local_variables = false;
 216   _jvmti_can_post_on_exceptions = false;
 217   _jvmti_can_pop_frame = false;
 218 }
 219 
 220 ciEnv::~ciEnv() {
 221   GUARDED_VM_ENTRY(
 222       CompilerThread* current_thread = CompilerThread::current();
 223       _factory->remove_symbols();
 224       // Need safepoint to clear the env on the thread.  RedefineClasses might
 225       // be reading it.
 226       current_thread->set_env(NULL);
 227   )
 228 }
 229 
 230 // ------------------------------------------------------------------
 231 // Cache Jvmti state
 232 void ciEnv::cache_jvmti_state() {
 233   VM_ENTRY_MARK;
 234   // Get Jvmti capabilities under lock to get consistant values.
 235   MutexLocker mu(JvmtiThreadState_lock);
 236   _jvmti_can_hotswap_or_post_breakpoint = JvmtiExport::can_hotswap_or_post_breakpoint();
 237   _jvmti_can_access_local_variables     = JvmtiExport::can_access_local_variables();
 238   _jvmti_can_post_on_exceptions         = JvmtiExport::can_post_on_exceptions();
 239   _jvmti_can_pop_frame                  = JvmtiExport::can_pop_frame();
 240 }
 241 
 242 bool ciEnv::jvmti_state_changed() const {
 243   if (!_jvmti_can_access_local_variables &&
 244       JvmtiExport::can_access_local_variables()) {
 245     return true;
 246   }
 247   if (!_jvmti_can_hotswap_or_post_breakpoint &&
 248       JvmtiExport::can_hotswap_or_post_breakpoint()) {
 249     return true;
 250   }
 251   if (!_jvmti_can_post_on_exceptions &&
 252       JvmtiExport::can_post_on_exceptions()) {
 253     return true;
 254   }
 255   if (!_jvmti_can_pop_frame &&
 256       JvmtiExport::can_pop_frame()) {
 257     return true;
 258   }
 259   return false;
 260 }
 261 
 262 // ------------------------------------------------------------------
 263 // Cache DTrace flags
 264 void ciEnv::cache_dtrace_flags() {
 265   // Need lock?
 266   _dtrace_extended_probes = ExtendedDTraceProbes;
 267   if (_dtrace_extended_probes) {
 268     _dtrace_monitor_probes  = true;
 269     _dtrace_method_probes   = true;
 270     _dtrace_alloc_probes    = true;
 271   } else {
 272     _dtrace_monitor_probes  = DTraceMonitorProbes;
 273     _dtrace_method_probes   = DTraceMethodProbes;
 274     _dtrace_alloc_probes    = DTraceAllocProbes;
 275   }
 276 }
 277 
 278 // ------------------------------------------------------------------
 279 // helper for lazy exception creation
 280 ciInstance* ciEnv::get_or_create_exception(jobject& handle, Symbol* name) {
 281   VM_ENTRY_MARK;
 282   if (handle == NULL) {
 283     // Cf. universe.cpp, creation of Universe::_null_ptr_exception_instance.
 284     Klass* k = SystemDictionary::find(name, Handle(), Handle(), THREAD);
 285     jobject objh = NULL;
 286     if (!HAS_PENDING_EXCEPTION && k != NULL) {
 287       oop obj = InstanceKlass::cast(k)->allocate_instance(THREAD);
 288       if (!HAS_PENDING_EXCEPTION)
 289         objh = JNIHandles::make_global(Handle(THREAD, obj));
 290     }
 291     if (HAS_PENDING_EXCEPTION) {
 292       CLEAR_PENDING_EXCEPTION;
 293     } else {
 294       handle = objh;
 295     }
 296   }
 297   oop obj = JNIHandles::resolve(handle);
 298   return obj == NULL? NULL: get_object(obj)->as_instance();
 299 }
 300 
 301 ciInstance* ciEnv::ArrayIndexOutOfBoundsException_instance() {
 302   if (_ArrayIndexOutOfBoundsException_instance == NULL) {
 303     _ArrayIndexOutOfBoundsException_instance
 304           = get_or_create_exception(_ArrayIndexOutOfBoundsException_handle,
 305           vmSymbols::java_lang_ArrayIndexOutOfBoundsException());
 306   }
 307   return _ArrayIndexOutOfBoundsException_instance;
 308 }
 309 ciInstance* ciEnv::ArrayStoreException_instance() {
 310   if (_ArrayStoreException_instance == NULL) {
 311     _ArrayStoreException_instance
 312           = get_or_create_exception(_ArrayStoreException_handle,
 313           vmSymbols::java_lang_ArrayStoreException());
 314   }
 315   return _ArrayStoreException_instance;
 316 }
 317 ciInstance* ciEnv::ClassCastException_instance() {
 318   if (_ClassCastException_instance == NULL) {
 319     _ClassCastException_instance
 320           = get_or_create_exception(_ClassCastException_handle,
 321           vmSymbols::java_lang_ClassCastException());
 322   }
 323   return _ClassCastException_instance;
 324 }
 325 
 326 ciInstance* ciEnv::the_null_string() {
 327   if (_the_null_string == NULL) {
 328     VM_ENTRY_MARK;
 329     _the_null_string = get_object(Universe::the_null_string())->as_instance();
 330   }
 331   return _the_null_string;
 332 }
 333 
 334 ciInstance* ciEnv::the_min_jint_string() {
 335   if (_the_min_jint_string == NULL) {
 336     VM_ENTRY_MARK;
 337     _the_min_jint_string = get_object(Universe::the_min_jint_string())->as_instance();
 338   }
 339   return _the_min_jint_string;
 340 }
 341 
 342 // ------------------------------------------------------------------
 343 // ciEnv::get_method_from_handle
 344 ciMethod* ciEnv::get_method_from_handle(Method* method) {
 345   VM_ENTRY_MARK;
 346   return get_metadata(method)->as_method();
 347 }
 348 
 349 // ------------------------------------------------------------------
 350 // ciEnv::array_element_offset_in_bytes
 351 int ciEnv::array_element_offset_in_bytes(ciArray* a_h, ciObject* o_h) {
 352   VM_ENTRY_MARK;
 353   objArrayOop a = (objArrayOop)a_h->get_oop();
 354   assert(a->is_objArray(), "");
 355   int length = a->length();
 356   oop o = o_h->get_oop();
 357   for (int i = 0; i < length; i++) {
 358     if (a->obj_at(i) == o)  return i;
 359   }
 360   return -1;
 361 }
 362 
 363 
 364 // ------------------------------------------------------------------
 365 // ciEnv::check_klass_accessiblity
 366 //
 367 // Note: the logic of this method should mirror the logic of
 368 // ConstantPool::verify_constant_pool_resolve.
 369 bool ciEnv::check_klass_accessibility(ciKlass* accessing_klass,
 370                                       Klass* resolved_klass) {
 371   if (accessing_klass == NULL || !accessing_klass->is_loaded()) {
 372     return true;
 373   }
 374   if (accessing_klass->is_obj_array_klass()) {
 375     accessing_klass = accessing_klass->as_obj_array_klass()->base_element_klass();
 376   }
 377   if (!accessing_klass->is_instance_klass()) {
 378     return true;
 379   }
 380 
 381   if (resolved_klass->is_objArray_klass()) {
 382     // Find the element klass, if this is an array.
 383     resolved_klass = ObjArrayKlass::cast(resolved_klass)->bottom_klass();
 384   }
 385   if (resolved_klass->is_instance_klass()) {
 386     return (Reflection::verify_class_access(accessing_klass->get_Klass(),
 387                                             InstanceKlass::cast(resolved_klass),
 388                                             true) == Reflection::ACCESS_OK);
 389   }
 390   return true;
 391 }
 392 
 393 // ------------------------------------------------------------------
 394 // ciEnv::get_klass_by_name_impl
 395 ciKlass* ciEnv::get_klass_by_name_impl(ciKlass* accessing_klass,
 396                                        const constantPoolHandle& cpool,
 397                                        ciSymbol* name,
 398                                        bool require_local) {
 399   ASSERT_IN_VM;
 400   EXCEPTION_CONTEXT;
 401 
 402   // Now we need to check the SystemDictionary
 403   Symbol* sym = name->get_symbol();
 404   if (sym->char_at(0) == 'L' &&
 405     sym->char_at(sym->utf8_length()-1) == ';') {
 406     // This is a name from a signature.  Strip off the trimmings.
 407     // Call recursive to keep scope of strippedsym.
 408     TempNewSymbol strippedsym = SymbolTable::new_symbol(sym->as_utf8()+1,
 409                                                         sym->utf8_length()-2);
 410     ciSymbol* strippedname = get_symbol(strippedsym);
 411     return get_klass_by_name_impl(accessing_klass, cpool, strippedname, require_local);
 412   }
 413 
 414   // Check for prior unloaded klass.  The SystemDictionary's answers
 415   // can vary over time but the compiler needs consistency.
 416   ciKlass* unloaded_klass = check_get_unloaded_klass(accessing_klass, name);
 417   if (unloaded_klass != NULL) {
 418     if (require_local)  return NULL;
 419     return unloaded_klass;
 420   }
 421 
 422   Handle loader(THREAD, (oop)NULL);
 423   Handle domain(THREAD, (oop)NULL);
 424   if (accessing_klass != NULL) {
 425     loader = Handle(THREAD, accessing_klass->loader());
 426     domain = Handle(THREAD, accessing_klass->protection_domain());
 427   }
 428 
 429   // setup up the proper type to return on OOM
 430   ciKlass* fail_type;
 431   if (sym->char_at(0) == '[') {
 432     fail_type = _unloaded_ciobjarrayklass;
 433   } else {
 434     fail_type = _unloaded_ciinstance_klass;
 435   }
 436   Klass* found_klass;
 437   {
 438     ttyUnlocker ttyul;  // release tty lock to avoid ordering problems
 439     MutexLocker ml(Compile_lock);
 440     Klass* kls;
 441     if (!require_local) {
 442       kls = SystemDictionary::find_constrained_instance_or_array_klass(sym, loader,
 443                                                                        KILL_COMPILE_ON_FATAL_(fail_type));
 444     } else {
 445       kls = SystemDictionary::find_instance_or_array_klass(sym, loader, domain,
 446                                                            KILL_COMPILE_ON_FATAL_(fail_type));
 447     }
 448     found_klass = kls;
 449   }
 450 
 451   // If we fail to find an array klass, look again for its element type.
 452   // The element type may be available either locally or via constraints.
 453   // In either case, if we can find the element type in the system dictionary,
 454   // we must build an array type around it.  The CI requires array klasses
 455   // to be loaded if their element klasses are loaded, except when memory
 456   // is exhausted.
 457   if (sym->char_at(0) == '[' &&
 458       (sym->char_at(1) == '[' || sym->char_at(1) == 'L')) {
 459     // We have an unloaded array.
 460     // Build it on the fly if the element class exists.
 461     TempNewSymbol elem_sym = SymbolTable::new_symbol(sym->as_utf8()+1,
 462                                                      sym->utf8_length()-1);
 463 
 464     // Get element ciKlass recursively.
 465     ciKlass* elem_klass =
 466       get_klass_by_name_impl(accessing_klass,
 467                              cpool,
 468                              get_symbol(elem_sym),
 469                              require_local);
 470     if (elem_klass != NULL && elem_klass->is_loaded()) {
 471       // Now make an array for it
 472       return ciObjArrayKlass::make_impl(elem_klass);
 473     }
 474   }
 475 
 476   if (found_klass == NULL && !cpool.is_null() && cpool->has_preresolution()) {
 477     // Look inside the constant pool for pre-resolved class entries.
 478     for (int i = cpool->length() - 1; i >= 1; i--) {
 479       if (cpool->tag_at(i).is_klass()) {
 480         Klass* kls = cpool->resolved_klass_at(i);
 481         if (kls->name() == sym) {
 482           found_klass = kls;
 483           break;
 484         }
 485       }
 486     }
 487   }
 488 
 489   if (found_klass != NULL) {
 490     // Found it.  Build a CI handle.
 491     return get_klass(found_klass);
 492   }
 493 
 494   if (require_local)  return NULL;
 495 
 496   // Not yet loaded into the VM, or not governed by loader constraints.
 497   // Make a CI representative for it.
 498   return get_unloaded_klass(accessing_klass, name);
 499 }
 500 
 501 // ------------------------------------------------------------------
 502 // ciEnv::get_klass_by_name
 503 ciKlass* ciEnv::get_klass_by_name(ciKlass* accessing_klass,
 504                                   ciSymbol* klass_name,
 505                                   bool require_local) {
 506   GUARDED_VM_ENTRY(return get_klass_by_name_impl(accessing_klass,
 507                                                  constantPoolHandle(),
 508                                                  klass_name,
 509                                                  require_local);)
 510 }
 511 
 512 // ------------------------------------------------------------------
 513 // ciEnv::get_klass_by_index_impl
 514 //
 515 // Implementation of get_klass_by_index.
 516 ciKlass* ciEnv::get_klass_by_index_impl(const constantPoolHandle& cpool,
 517                                         int index,
 518                                         bool& is_accessible,
 519                                         ciInstanceKlass* accessor) {
 520   EXCEPTION_CONTEXT;
 521   Klass* klass = NULL;
 522   Symbol* klass_name = NULL;
 523 
 524   if (cpool->tag_at(index).is_symbol()) {
 525     klass_name = cpool->symbol_at(index);
 526   } else {
 527     // Check if it's resolved if it's not a symbol constant pool entry.
 528     klass =  ConstantPool::klass_at_if_loaded(cpool, index);
 529     // Try to look it up by name.
 530     if (klass == NULL) {
 531       klass_name = cpool->klass_name_at(index);
 532     }
 533   }
 534 
 535   if (klass == NULL) {
 536     // Not found in constant pool.  Use the name to do the lookup.
 537     ciKlass* k = get_klass_by_name_impl(accessor,
 538                                         cpool,
 539                                         get_symbol(klass_name),
 540                                         false);
 541     // Calculate accessibility the hard way.
 542     if (!k->is_loaded()) {
 543       is_accessible = false;
 544     } else if (!oopDesc::equals(k->loader(), accessor->loader()) &&
 545                get_klass_by_name_impl(accessor, cpool, k->name(), true) == NULL) {
 546       // Loaded only remotely.  Not linked yet.
 547       is_accessible = false;
 548     } else {
 549       // Linked locally, and we must also check public/private, etc.
 550       is_accessible = check_klass_accessibility(accessor, k->get_Klass());
 551     }
 552     return k;
 553   }
 554 
 555   // Check for prior unloaded klass.  The SystemDictionary's answers
 556   // can vary over time but the compiler needs consistency.
 557   ciSymbol* name = get_symbol(klass->name());
 558   ciKlass* unloaded_klass = check_get_unloaded_klass(accessor, name);
 559   if (unloaded_klass != NULL) {
 560     is_accessible = false;
 561     return unloaded_klass;
 562   }
 563 
 564   // It is known to be accessible, since it was found in the constant pool.
 565   is_accessible = true;
 566   return get_klass(klass);
 567 }
 568 
 569 // ------------------------------------------------------------------
 570 // ciEnv::get_klass_by_index
 571 //
 572 // Get a klass from the constant pool.
 573 ciKlass* ciEnv::get_klass_by_index(const constantPoolHandle& cpool,
 574                                    int index,
 575                                    bool& is_accessible,
 576                                    ciInstanceKlass* accessor) {
 577   GUARDED_VM_ENTRY(return get_klass_by_index_impl(cpool, index, is_accessible, accessor);)
 578 }
 579 
 580 // ------------------------------------------------------------------
 581 // ciEnv::get_constant_by_index_impl
 582 //
 583 // Implementation of get_constant_by_index().
 584 ciConstant ciEnv::get_constant_by_index_impl(const constantPoolHandle& cpool,
 585                                              int pool_index, int cache_index,
 586                                              ciInstanceKlass* accessor) {
 587   bool ignore_will_link;
 588   EXCEPTION_CONTEXT;
 589   int index = pool_index;
 590   if (cache_index >= 0) {
 591     assert(index < 0, "only one kind of index at a time");
 592     index = cpool->object_to_cp_index(cache_index);
 593     oop obj = cpool->resolved_references()->obj_at(cache_index);
 594     if (obj != NULL) {
 595       if (oopDesc::equals(obj, Universe::the_null_sentinel())) {
 596         return ciConstant(T_OBJECT, get_object(NULL));
 597       }
 598       BasicType bt = T_OBJECT;
 599       if (cpool->tag_at(index).is_dynamic_constant())
 600         bt = FieldType::basic_type(cpool->uncached_signature_ref_at(index));
 601       if (is_reference_type(bt)) {
 602       } else {
 603         // we have to unbox the primitive value
 604         if (!is_java_primitive(bt))  return ciConstant();
 605         jvalue value;
 606         BasicType bt2 = java_lang_boxing_object::get_value(obj, &value);
 607         assert(bt2 == bt, "");
 608         switch (bt2) {
 609         case T_DOUBLE:  return ciConstant(value.d);
 610         case T_FLOAT:   return ciConstant(value.f);
 611         case T_LONG:    return ciConstant(value.j);
 612         case T_INT:     return ciConstant(bt2, value.i);
 613         case T_SHORT:   return ciConstant(bt2, value.s);
 614         case T_BYTE:    return ciConstant(bt2, value.b);
 615         case T_CHAR:    return ciConstant(bt2, value.c);
 616         case T_BOOLEAN: return ciConstant(bt2, value.z);
 617         default:  return ciConstant();
 618         }
 619       }
 620       ciObject* ciobj = get_object(obj);
 621       if (ciobj->is_array()) {
 622         return ciConstant(T_ARRAY, ciobj);
 623       } else {
 624         assert(ciobj->is_instance(), "should be an instance");
 625         return ciConstant(T_OBJECT, ciobj);
 626       }
 627     }
 628   }
 629   constantTag tag = cpool->tag_at(index);
 630   if (tag.is_int()) {
 631     return ciConstant(T_INT, (jint)cpool->int_at(index));
 632   } else if (tag.is_long()) {
 633     return ciConstant((jlong)cpool->long_at(index));
 634   } else if (tag.is_float()) {
 635     return ciConstant((jfloat)cpool->float_at(index));
 636   } else if (tag.is_double()) {
 637     return ciConstant((jdouble)cpool->double_at(index));
 638   } else if (tag.is_string()) {
 639     oop string = NULL;
 640     assert(cache_index >= 0, "should have a cache index");
 641     if (cpool->is_pseudo_string_at(index)) {
 642       string = cpool->pseudo_string_at(index, cache_index);
 643     } else {
 644       string = cpool->string_at(index, cache_index, THREAD);
 645       if (HAS_PENDING_EXCEPTION) {
 646         CLEAR_PENDING_EXCEPTION;
 647         record_out_of_memory_failure();
 648         return ciConstant();
 649       }
 650     }
 651     ciObject* constant = get_object(string);
 652     if (constant->is_array()) {
 653       return ciConstant(T_ARRAY, constant);
 654     } else {
 655       assert (constant->is_instance(), "must be an instance, or not? ");
 656       return ciConstant(T_OBJECT, constant);
 657     }
 658   } else if (tag.is_klass() || tag.is_unresolved_klass()) {
 659     // 4881222: allow ldc to take a class type
 660     ciKlass* klass = get_klass_by_index_impl(cpool, index, ignore_will_link, accessor);
 661     if (HAS_PENDING_EXCEPTION) {
 662       CLEAR_PENDING_EXCEPTION;
 663       record_out_of_memory_failure();
 664       return ciConstant();
 665     }
 666     assert (klass->is_instance_klass() || klass->is_array_klass(),
 667             "must be an instance or array klass ");
 668     return ciConstant(T_OBJECT, klass->java_mirror());
 669   } else if (tag.is_method_type()) {
 670     // must execute Java code to link this CP entry into cache[i].f1
 671     ciSymbol* signature = get_symbol(cpool->method_type_signature_at(index));
 672     ciObject* ciobj = get_unloaded_method_type_constant(signature);
 673     return ciConstant(T_OBJECT, ciobj);
 674   } else if (tag.is_method_handle()) {
 675     // must execute Java code to link this CP entry into cache[i].f1
 676     int ref_kind        = cpool->method_handle_ref_kind_at(index);
 677     int callee_index    = cpool->method_handle_klass_index_at(index);
 678     ciKlass* callee     = get_klass_by_index_impl(cpool, callee_index, ignore_will_link, accessor);
 679     ciSymbol* name      = get_symbol(cpool->method_handle_name_ref_at(index));
 680     ciSymbol* signature = get_symbol(cpool->method_handle_signature_ref_at(index));
 681     ciObject* ciobj     = get_unloaded_method_handle_constant(callee, name, signature, ref_kind);
 682     return ciConstant(T_OBJECT, ciobj);
 683   } else if (tag.is_dynamic_constant()) {
 684     return ciConstant();
 685   } else {
 686     ShouldNotReachHere();
 687     return ciConstant();
 688   }
 689 }
 690 
 691 // ------------------------------------------------------------------
 692 // ciEnv::get_constant_by_index
 693 //
 694 // Pull a constant out of the constant pool.  How appropriate.
 695 //
 696 // Implementation note: this query is currently in no way cached.
 697 ciConstant ciEnv::get_constant_by_index(const constantPoolHandle& cpool,
 698                                         int pool_index, int cache_index,
 699                                         ciInstanceKlass* accessor) {
 700   GUARDED_VM_ENTRY(return get_constant_by_index_impl(cpool, pool_index, cache_index, accessor);)
 701 }
 702 
 703 // ------------------------------------------------------------------
 704 // ciEnv::get_field_by_index_impl
 705 //
 706 // Implementation of get_field_by_index.
 707 //
 708 // Implementation note: the results of field lookups are cached
 709 // in the accessor klass.
 710 ciField* ciEnv::get_field_by_index_impl(ciInstanceKlass* accessor,
 711                                         int index) {
 712   ciConstantPoolCache* cache = accessor->field_cache();
 713   if (cache == NULL) {
 714     ciField* field = new (arena()) ciField(accessor, index);
 715     return field;
 716   } else {
 717     ciField* field = (ciField*)cache->get(index);
 718     if (field == NULL) {
 719       field = new (arena()) ciField(accessor, index);
 720       cache->insert(index, field);
 721     }
 722     return field;
 723   }
 724 }
 725 
 726 // ------------------------------------------------------------------
 727 // ciEnv::get_field_by_index
 728 //
 729 // Get a field by index from a klass's constant pool.
 730 ciField* ciEnv::get_field_by_index(ciInstanceKlass* accessor,
 731                                    int index) {
 732   GUARDED_VM_ENTRY(return get_field_by_index_impl(accessor, index);)
 733 }
 734 
 735 // ------------------------------------------------------------------
 736 // ciEnv::lookup_method
 737 //
 738 // Perform an appropriate method lookup based on accessor, holder,
 739 // name, signature, and bytecode.
 740 Method* ciEnv::lookup_method(ciInstanceKlass* accessor,
 741                              ciKlass*         holder,
 742                              Symbol*          name,
 743                              Symbol*          sig,
 744                              Bytecodes::Code  bc,
 745                              constantTag      tag) {
 746   // Accessibility checks are performed in ciEnv::get_method_by_index_impl.
 747   assert(check_klass_accessibility(accessor, holder->get_Klass()), "holder not accessible");
 748 
 749   InstanceKlass* accessor_klass = accessor->get_instanceKlass();
 750   Klass* holder_klass = holder->get_Klass();
 751   methodHandle dest_method;
 752   LinkInfo link_info(holder_klass, name, sig, accessor_klass, LinkInfo::needs_access_check, tag);
 753   switch (bc) {
 754   case Bytecodes::_invokestatic:
 755     dest_method =
 756       LinkResolver::resolve_static_call_or_null(link_info);
 757     break;
 758   case Bytecodes::_invokespecial:
 759     dest_method =
 760       LinkResolver::resolve_special_call_or_null(link_info);
 761     break;
 762   case Bytecodes::_invokeinterface:
 763     dest_method =
 764       LinkResolver::linktime_resolve_interface_method_or_null(link_info);
 765     break;
 766   case Bytecodes::_invokevirtual:
 767     dest_method =
 768       LinkResolver::linktime_resolve_virtual_method_or_null(link_info);
 769     break;
 770   default: ShouldNotReachHere();
 771   }
 772 
 773   return dest_method();
 774 }
 775 
 776 
 777 // ------------------------------------------------------------------
 778 // ciEnv::get_method_by_index_impl
 779 ciMethod* ciEnv::get_method_by_index_impl(const constantPoolHandle& cpool,
 780                                           int index, Bytecodes::Code bc,
 781                                           ciInstanceKlass* accessor) {
 782   if (bc == Bytecodes::_invokedynamic) {
 783     ConstantPoolCacheEntry* cpce = cpool->invokedynamic_cp_cache_entry_at(index);
 784     bool is_resolved = !cpce->is_f1_null();
 785     // FIXME: code generation could allow for null (unlinked) call site
 786     // The call site could be made patchable as follows:
 787     // Load the appendix argument from the constant pool.
 788     // Test the appendix argument and jump to a known deopt routine if it is null.
 789     // Jump through a patchable call site, which is initially a deopt routine.
 790     // Patch the call site to the nmethod entry point of the static compiled lambda form.
 791     // As with other two-component call sites, both values must be independently verified.
 792 
 793     if (is_resolved) {
 794       // Get the invoker Method* from the constant pool.
 795       // (The appendix argument, if any, will be noted in the method's signature.)
 796       Method* adapter = cpce->f1_as_method();
 797       return get_method(adapter);
 798     }
 799 
 800     // Fake a method that is equivalent to a declared method.
 801     ciInstanceKlass* holder    = get_instance_klass(SystemDictionary::MethodHandle_klass());
 802     ciSymbol*        name      = ciSymbol::invokeBasic_name();
 803     ciSymbol*        signature = get_symbol(cpool->signature_ref_at(index));
 804     return get_unloaded_method(holder, name, signature, accessor);
 805   } else {
 806     const int holder_index = cpool->klass_ref_index_at(index);
 807     bool holder_is_accessible;
 808     ciKlass* holder = get_klass_by_index_impl(cpool, holder_index, holder_is_accessible, accessor);
 809 
 810     // Get the method's name and signature.
 811     Symbol* name_sym = cpool->name_ref_at(index);
 812     Symbol* sig_sym  = cpool->signature_ref_at(index);
 813 
 814     if (cpool->has_preresolution()
 815         || ((holder == ciEnv::MethodHandle_klass() || holder == ciEnv::VarHandle_klass()) &&
 816             MethodHandles::is_signature_polymorphic_name(holder->get_Klass(), name_sym))) {
 817       // Short-circuit lookups for JSR 292-related call sites.
 818       // That is, do not rely only on name-based lookups, because they may fail
 819       // if the names are not resolvable in the boot class loader (7056328).
 820       switch (bc) {
 821       case Bytecodes::_invokevirtual:
 822       case Bytecodes::_invokeinterface:
 823       case Bytecodes::_invokespecial:
 824       case Bytecodes::_invokestatic:
 825         {
 826           Method* m = ConstantPool::method_at_if_loaded(cpool, index);
 827           if (m != NULL) {
 828             return get_method(m);
 829           }
 830         }
 831         break;
 832       default:
 833         break;
 834       }
 835     }
 836 
 837     if (holder_is_accessible) {  // Our declared holder is loaded.
 838       constantTag tag = cpool->tag_ref_at(index);
 839       assert(accessor->get_instanceKlass() == cpool->pool_holder(), "not the pool holder?");
 840       Method* m = lookup_method(accessor, holder, name_sym, sig_sym, bc, tag);
 841       if (m != NULL &&
 842           (bc == Bytecodes::_invokestatic
 843            ?  m->method_holder()->is_not_initialized()
 844            : !m->method_holder()->is_loaded())) {
 845         m = NULL;
 846       }
 847 #ifdef ASSERT
 848       if (m != NULL && ReplayCompiles && !ciReplay::is_loaded(m)) {
 849         m = NULL;
 850       }
 851 #endif
 852       if (m != NULL) {
 853         // We found the method.
 854         return get_method(m);
 855       }
 856     }
 857 
 858     // Either the declared holder was not loaded, or the method could
 859     // not be found.  Create a dummy ciMethod to represent the failed
 860     // lookup.
 861     ciSymbol* name      = get_symbol(name_sym);
 862     ciSymbol* signature = get_symbol(sig_sym);
 863     return get_unloaded_method(holder, name, signature, accessor);
 864   }
 865 }
 866 
 867 
 868 // ------------------------------------------------------------------
 869 // ciEnv::get_instance_klass_for_declared_method_holder
 870 ciInstanceKlass* ciEnv::get_instance_klass_for_declared_method_holder(ciKlass* method_holder) {
 871   // For the case of <array>.clone(), the method holder can be a ciArrayKlass
 872   // instead of a ciInstanceKlass.  For that case simply pretend that the
 873   // declared holder is Object.clone since that's where the call will bottom out.
 874   // A more correct fix would trickle out through many interfaces in CI,
 875   // requiring ciInstanceKlass* to become ciKlass* and many more places would
 876   // require checks to make sure the expected type was found.  Given that this
 877   // only occurs for clone() the more extensive fix seems like overkill so
 878   // instead we simply smear the array type into Object.
 879   guarantee(method_holder != NULL, "no method holder");
 880   if (method_holder->is_instance_klass()) {
 881     return method_holder->as_instance_klass();
 882   } else if (method_holder->is_array_klass()) {
 883     return current()->Object_klass();
 884   } else {
 885     ShouldNotReachHere();
 886   }
 887   return NULL;
 888 }
 889 
 890 
 891 // ------------------------------------------------------------------
 892 // ciEnv::get_method_by_index
 893 ciMethod* ciEnv::get_method_by_index(const constantPoolHandle& cpool,
 894                                      int index, Bytecodes::Code bc,
 895                                      ciInstanceKlass* accessor) {
 896   GUARDED_VM_ENTRY(return get_method_by_index_impl(cpool, index, bc, accessor);)
 897 }
 898 
 899 
 900 // ------------------------------------------------------------------
 901 // ciEnv::name_buffer
 902 char *ciEnv::name_buffer(int req_len) {
 903   if (_name_buffer_len < req_len) {
 904     if (_name_buffer == NULL) {
 905       _name_buffer = (char*)arena()->Amalloc(sizeof(char)*req_len);
 906       _name_buffer_len = req_len;
 907     } else {
 908       _name_buffer =
 909         (char*)arena()->Arealloc(_name_buffer, _name_buffer_len, req_len);
 910       _name_buffer_len = req_len;
 911     }
 912   }
 913   return _name_buffer;
 914 }
 915 
 916 // ------------------------------------------------------------------
 917 // ciEnv::is_in_vm
 918 bool ciEnv::is_in_vm() {
 919   return JavaThread::current()->thread_state() == _thread_in_vm;
 920 }
 921 
 922 bool ciEnv::system_dictionary_modification_counter_changed_locked() {
 923   assert_locked_or_safepoint(Compile_lock);
 924   return _system_dictionary_modification_counter != SystemDictionary::number_of_modifications();
 925 }
 926 
 927 bool ciEnv::system_dictionary_modification_counter_changed() {
 928   VM_ENTRY_MARK;
 929   MutexLocker ml(Compile_lock, THREAD); // lock with safepoint check
 930   return system_dictionary_modification_counter_changed_locked();
 931 }
 932 
 933 // ------------------------------------------------------------------
 934 // ciEnv::validate_compile_task_dependencies
 935 //
 936 // Check for changes during compilation (e.g. class loads, evolution,
 937 // breakpoints, call site invalidation).
 938 void ciEnv::validate_compile_task_dependencies(ciMethod* target) {
 939   if (failing())  return;  // no need for further checks
 940 
 941   bool counter_changed = system_dictionary_modification_counter_changed_locked();
 942   Dependencies::DepType result = dependencies()->validate_dependencies(_task, counter_changed);
 943   if (result != Dependencies::end_marker) {
 944     if (result == Dependencies::call_site_target_value) {
 945       _inc_decompile_count_on_failure = false;
 946       record_failure("call site target change");
 947     } else if (Dependencies::is_klass_type(result)) {
 948       record_failure("concurrent class loading");
 949     } else {
 950       record_failure("invalid non-klass dependency");
 951     }
 952   }
 953 }
 954 
 955 // ------------------------------------------------------------------
 956 // ciEnv::register_method
 957 void ciEnv::register_method(ciMethod* target,
 958                             int entry_bci,
 959                             CodeOffsets* offsets,
 960                             int orig_pc_offset,
 961                             CodeBuffer* code_buffer,
 962                             int frame_words,
 963                             OopMapSet* oop_map_set,
 964                             ExceptionHandlerTable* handler_table,
 965                             ImplicitExceptionTable* inc_table,
 966                             AbstractCompiler* compiler,
 967                             bool has_unsafe_access,
 968                             bool has_wide_vectors,
 969                             RTMState  rtm_state) {
 970   VM_ENTRY_MARK;
 971   nmethod* nm = NULL;
 972   {
 973     // To prevent compile queue updates.
 974     MutexLocker locker(MethodCompileQueue_lock, THREAD);
 975 
 976     // Prevent SystemDictionary::add_to_hierarchy from running
 977     // and invalidating our dependencies until we install this method.
 978     // No safepoints are allowed. Otherwise, class redefinition can occur in between.
 979     MutexLocker ml(Compile_lock);
 980     NoSafepointVerifier nsv;
 981 
 982     // Change in Jvmti state may invalidate compilation.
 983     if (!failing() && jvmti_state_changed()) {
 984       record_failure("Jvmti state change invalidated dependencies");
 985     }
 986 
 987     // Change in DTrace flags may invalidate compilation.
 988     if (!failing() &&
 989         ( (!dtrace_extended_probes() && ExtendedDTraceProbes) ||
 990           (!dtrace_method_probes() && DTraceMethodProbes) ||
 991           (!dtrace_alloc_probes() && DTraceAllocProbes) )) {
 992       record_failure("DTrace flags change invalidated dependencies");
 993     }
 994 
 995     if (!failing() && target->needs_clinit_barrier() &&
 996         target->holder()->is_in_error_state()) {
 997       record_failure("method holder is in error state");
 998     }
 999 
1000     if (!failing()) {
1001       if (log() != NULL) {
1002         // Log the dependencies which this compilation declares.
1003         dependencies()->log_all_dependencies();
1004       }
1005 
1006       // Encode the dependencies now, so we can check them right away.
1007       dependencies()->encode_content_bytes();
1008 
1009       // Check for {class loads, evolution, breakpoints, ...} during compilation
1010       validate_compile_task_dependencies(target);
1011     }
1012 
1013     methodHandle method(THREAD, target->get_Method());
1014 
1015 #if INCLUDE_RTM_OPT
1016     if (!failing() && (rtm_state != NoRTM) &&
1017         (method()->method_data() != NULL) &&
1018         (method()->method_data()->rtm_state() != rtm_state)) {
1019       // Preemptive decompile if rtm state was changed.
1020       record_failure("RTM state change invalidated rtm code");
1021     }
1022 #endif
1023 
1024     if (failing()) {
1025       // While not a true deoptimization, it is a preemptive decompile.
1026       MethodData* mdo = method()->method_data();
1027       if (mdo != NULL && _inc_decompile_count_on_failure) {
1028         mdo->inc_decompile_count();
1029       }
1030 
1031       // All buffers in the CodeBuffer are allocated in the CodeCache.
1032       // If the code buffer is created on each compile attempt
1033       // as in C2, then it must be freed.
1034       code_buffer->free_blob();
1035       return;
1036     }
1037 
1038     assert(offsets->value(CodeOffsets::Deopt) != -1, "must have deopt entry");
1039     assert(offsets->value(CodeOffsets::Exceptions) != -1, "must have exception entry");
1040 
1041     nm =  nmethod::new_nmethod(method,
1042                                compile_id(),
1043                                entry_bci,
1044                                offsets,
1045                                orig_pc_offset,
1046                                debug_info(), dependencies(), code_buffer,
1047                                frame_words, oop_map_set,
1048                                handler_table, inc_table,
1049                                compiler, task()->comp_level());
1050 
1051     // Free codeBlobs
1052     code_buffer->free_blob();
1053 
1054     if (nm != NULL) {
1055       nm->set_has_unsafe_access(has_unsafe_access);
1056       nm->set_has_wide_vectors(has_wide_vectors);
1057 #if INCLUDE_RTM_OPT
1058       nm->set_rtm_state(rtm_state);
1059 #endif
1060 
1061       // Record successful registration.
1062       // (Put nm into the task handle *before* publishing to the Java heap.)
1063       if (task() != NULL) {
1064         task()->set_code(nm);
1065       }
1066 
1067       if (entry_bci == InvocationEntryBci) {
1068         if (TieredCompilation) {
1069           // If there is an old version we're done with it
1070           CompiledMethod* old = method->code();
1071           if (TraceMethodReplacement && old != NULL) {
1072             ResourceMark rm;
1073             char *method_name = method->name_and_sig_as_C_string();
1074             tty->print_cr("Replacing method %s", method_name);
1075           }
1076           if (old != NULL) {
1077             old->make_not_used();
1078           }
1079         }
1080 
1081         LogTarget(Info, nmethod, install) lt;
1082         if (lt.is_enabled()) {
1083           ResourceMark rm;
1084           char *method_name = method->name_and_sig_as_C_string();
1085           lt.print("Installing method (%d) %s ",
1086                     task()->comp_level(), method_name);
1087         }
1088         // Allow the code to be executed
1089         method->set_code(method, nm);
1090       } else {
1091         LogTarget(Info, nmethod, install) lt;
1092         if (lt.is_enabled()) {
1093           ResourceMark rm;
1094           char *method_name = method->name_and_sig_as_C_string();
1095           lt.print("Installing osr method (%d) %s @ %d",
1096                     task()->comp_level(), method_name, entry_bci);
1097         }
1098         method->method_holder()->add_osr_nmethod(nm);
1099       }
1100       nm->make_in_use();
1101     }
1102   }  // safepoints are allowed again
1103 
1104   if (nm != NULL) {
1105     // JVMTI -- compiled method notification (must be done outside lock)
1106     nm->post_compiled_method_load_event();
1107   } else {
1108     // The CodeCache is full.
1109     record_failure("code cache is full");
1110   }
1111 }
1112 
1113 
1114 // ------------------------------------------------------------------
1115 // ciEnv::find_system_klass
1116 ciKlass* ciEnv::find_system_klass(ciSymbol* klass_name) {
1117   VM_ENTRY_MARK;
1118   return get_klass_by_name_impl(NULL, constantPoolHandle(), klass_name, false);
1119 }
1120 
1121 // ------------------------------------------------------------------
1122 // ciEnv::comp_level
1123 int ciEnv::comp_level() {
1124   if (task() == NULL)  return CompLevel_highest_tier;
1125   return task()->comp_level();
1126 }
1127 
1128 // ------------------------------------------------------------------
1129 // ciEnv::compile_id
1130 uint ciEnv::compile_id() {
1131   if (task() == NULL)  return 0;
1132   return task()->compile_id();
1133 }
1134 
1135 // ------------------------------------------------------------------
1136 // ciEnv::notice_inlined_method()
1137 void ciEnv::notice_inlined_method(ciMethod* method) {
1138   _num_inlined_bytecodes += method->code_size_for_inlining();
1139 }
1140 
1141 // ------------------------------------------------------------------
1142 // ciEnv::num_inlined_bytecodes()
1143 int ciEnv::num_inlined_bytecodes() const {
1144   return _num_inlined_bytecodes;
1145 }
1146 
1147 // ------------------------------------------------------------------
1148 // ciEnv::record_failure()
1149 void ciEnv::record_failure(const char* reason) {
1150   if (_failure_reason == NULL) {
1151     // Record the first failure reason.
1152     _failure_reason = reason;
1153   }
1154 }
1155 
1156 void ciEnv::report_failure(const char* reason) {
1157   EventCompilationFailure event;
1158   if (event.should_commit()) {
1159     event.set_compileId(compile_id());
1160     event.set_failureMessage(reason);
1161     event.commit();
1162   }
1163 }
1164 
1165 // ------------------------------------------------------------------
1166 // ciEnv::record_method_not_compilable()
1167 void ciEnv::record_method_not_compilable(const char* reason, bool all_tiers) {
1168   int new_compilable =
1169     all_tiers ? MethodCompilable_never : MethodCompilable_not_at_tier ;
1170 
1171   // Only note transitions to a worse state
1172   if (new_compilable > _compilable) {
1173     if (log() != NULL) {
1174       if (all_tiers) {
1175         log()->elem("method_not_compilable");
1176       } else {
1177         log()->elem("method_not_compilable_at_tier level='%d'",
1178                     current()->task()->comp_level());
1179       }
1180     }
1181     _compilable = new_compilable;
1182 
1183     // Reset failure reason; this one is more important.
1184     _failure_reason = NULL;
1185     record_failure(reason);
1186   }
1187 }
1188 
1189 // ------------------------------------------------------------------
1190 // ciEnv::record_out_of_memory_failure()
1191 void ciEnv::record_out_of_memory_failure() {
1192   // If memory is low, we stop compiling methods.
1193   record_method_not_compilable("out of memory");
1194 }
1195 
1196 ciInstance* ciEnv::unloaded_ciinstance() {
1197   GUARDED_VM_ENTRY(return _factory->get_unloaded_object_constant();)
1198 }
1199 
1200 // ------------------------------------------------------------------
1201 // ciEnv::dump_replay_data*
1202 
1203 // Don't change thread state and acquire any locks.
1204 // Safe to call from VM error reporter.
1205 
1206 void ciEnv::dump_compile_data(outputStream* out) {
1207   CompileTask* task = this->task();
1208   if (task) {
1209     Method* method = task->method();
1210     int entry_bci = task->osr_bci();
1211     int comp_level = task->comp_level();
1212     out->print("compile %s %s %s %d %d",
1213                method->klass_name()->as_quoted_ascii(),
1214                method->name()->as_quoted_ascii(),
1215                method->signature()->as_quoted_ascii(),
1216                entry_bci, comp_level);
1217     if (compiler_data() != NULL) {
1218       if (is_c2_compile(comp_level)) {
1219 #ifdef COMPILER2
1220         // Dump C2 inlining data.
1221         ((Compile*)compiler_data())->dump_inline_data(out);
1222 #endif
1223       } else if (is_c1_compile(comp_level)) {
1224 #ifdef COMPILER1
1225         // Dump C1 inlining data.
1226         ((Compilation*)compiler_data())->dump_inline_data(out);
1227 #endif
1228       }
1229     }
1230     out->cr();
1231   }
1232 }
1233 
1234 void ciEnv::dump_replay_data_unsafe(outputStream* out) {
1235   ResourceMark rm;
1236 #if INCLUDE_JVMTI
1237   out->print_cr("JvmtiExport can_access_local_variables %d",     _jvmti_can_access_local_variables);
1238   out->print_cr("JvmtiExport can_hotswap_or_post_breakpoint %d", _jvmti_can_hotswap_or_post_breakpoint);
1239   out->print_cr("JvmtiExport can_post_on_exceptions %d",         _jvmti_can_post_on_exceptions);
1240 #endif // INCLUDE_JVMTI
1241 
1242   GrowableArray<ciMetadata*>* objects = _factory->get_ci_metadata();
1243   out->print_cr("# %d ciObject found", objects->length());
1244   for (int i = 0; i < objects->length(); i++) {
1245     objects->at(i)->dump_replay_data(out);
1246   }
1247   dump_compile_data(out);
1248   out->flush();
1249 }
1250 
1251 void ciEnv::dump_replay_data(outputStream* out) {
1252   GUARDED_VM_ENTRY(
1253     MutexLocker ml(Compile_lock);
1254     dump_replay_data_unsafe(out);
1255   )
1256 }
1257 
1258 void ciEnv::dump_replay_data(int compile_id) {
1259   static char buffer[O_BUFLEN];
1260   int ret = jio_snprintf(buffer, O_BUFLEN, "replay_pid%p_compid%d.log", os::current_process_id(), compile_id);
1261   if (ret > 0) {
1262     int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);
1263     if (fd != -1) {
1264       FILE* replay_data_file = os::open(fd, "w");
1265       if (replay_data_file != NULL) {
1266         fileStream replay_data_stream(replay_data_file, /*need_close=*/true);
1267         dump_replay_data(&replay_data_stream);
1268         tty->print_cr("# Compiler replay data is saved as: %s", buffer);
1269       } else {
1270         tty->print_cr("# Can't open file to dump replay data.");
1271       }
1272     }
1273   }
1274 }
1275 
1276 void ciEnv::dump_inline_data(int compile_id) {
1277   static char buffer[O_BUFLEN];
1278   int ret = jio_snprintf(buffer, O_BUFLEN, "inline_pid%p_compid%d.log", os::current_process_id(), compile_id);
1279   if (ret > 0) {
1280     int fd = os::open(buffer, O_RDWR | O_CREAT | O_TRUNC, 0666);
1281     if (fd != -1) {
1282       FILE* inline_data_file = os::open(fd, "w");
1283       if (inline_data_file != NULL) {
1284         fileStream replay_data_stream(inline_data_file, /*need_close=*/true);
1285         GUARDED_VM_ENTRY(
1286           MutexLocker ml(Compile_lock);
1287           dump_compile_data(&replay_data_stream);
1288         )
1289         replay_data_stream.flush();
1290         tty->print("# Compiler inline data is saved as: ");
1291         tty->print_cr("%s", buffer);
1292       } else {
1293         tty->print_cr("# Can't open file to dump inline data.");
1294       }
1295     }
1296   }
1297 }