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