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