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