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