1 /*
   2  * Copyright 1999-2009 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20  * CA 95054 USA or visit www.sun.com if you need additional information or
  21  * have any questions.
  22  *
  23  */
  24 
  25 #include "incls/_precompiled.incl"
  26 #include "incls/_ciEnv.cpp.incl"
  27 
  28 // ciEnv
  29 //
  30 // This class is the top level broker for requests from the compiler
  31 // to the VM.
  32 
  33 ciObject*              ciEnv::_null_object_instance;
  34 ciMethodKlass*         ciEnv::_method_klass_instance;
  35 ciSymbolKlass*         ciEnv::_symbol_klass_instance;
  36 ciKlassKlass*          ciEnv::_klass_klass_instance;
  37 ciInstanceKlassKlass*  ciEnv::_instance_klass_klass_instance;
  38 ciTypeArrayKlassKlass* ciEnv::_type_array_klass_klass_instance;
  39 ciObjArrayKlassKlass*  ciEnv::_obj_array_klass_klass_instance;
  40 
  41 ciInstanceKlass* ciEnv::_ArrayStoreException;
  42 ciInstanceKlass* ciEnv::_Class;
  43 ciInstanceKlass* ciEnv::_ClassCastException;
  44 ciInstanceKlass* ciEnv::_Object;
  45 ciInstanceKlass* ciEnv::_Throwable;
  46 ciInstanceKlass* ciEnv::_Thread;
  47 ciInstanceKlass* ciEnv::_OutOfMemoryError;
  48 ciInstanceKlass* ciEnv::_String;
  49 
  50 ciSymbol*        ciEnv::_unloaded_cisymbol = NULL;
  51 ciInstanceKlass* ciEnv::_unloaded_ciinstance_klass = NULL;
  52 ciObjArrayKlass* ciEnv::_unloaded_ciobjarrayklass = NULL;
  53 
  54 jobject ciEnv::_ArrayIndexOutOfBoundsException_handle = NULL;
  55 jobject ciEnv::_ArrayStoreException_handle = NULL;
  56 jobject ciEnv::_ClassCastException_handle = NULL;
  57 
  58 #ifndef PRODUCT
  59 static bool firstEnv = true;
  60 #endif /* PRODUCT */
  61 
  62 // ------------------------------------------------------------------
  63 // ciEnv::ciEnv
  64 ciEnv::ciEnv(CompileTask* task, int system_dictionary_modification_counter) {
  65   VM_ENTRY_MARK;
  66 
  67   // Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc.
  68   thread->set_env(this);
  69   assert(ciEnv::current() == this, "sanity");
  70 
  71   _oop_recorder = NULL;
  72   _debug_info = NULL;
  73   _dependencies = NULL;
  74   _failure_reason = NULL;
  75   _compilable = MethodCompilable;
  76   _break_at_compile = false;
  77   _compiler_data = NULL;
  78 #ifndef PRODUCT
  79   assert(!firstEnv, "not initialized properly");
  80 #endif /* !PRODUCT */
  81 
  82   _system_dictionary_modification_counter = system_dictionary_modification_counter;
  83   _num_inlined_bytecodes = 0;
  84   assert(task == NULL || thread->task() == task, "sanity");
  85   _task = task;
  86   _log = NULL;
  87 
  88   // Temporary buffer for creating symbols and such.
  89   _name_buffer = NULL;
  90   _name_buffer_len = 0;
  91 
  92   _arena   = &_ciEnv_arena;
  93   _factory = new (_arena) ciObjectFactory(_arena, 128);
  94 
  95   // Preload commonly referenced system ciObjects.
  96 
  97   // During VM initialization, these instances have not yet been created.
  98   // Assertions ensure that these instances are not accessed before
  99   // their initialization.
 100 
 101   assert(Universe::is_fully_initialized(), "should be complete");
 102 
 103   oop o = Universe::null_ptr_exception_instance();
 104   assert(o != NULL, "should have been initialized");
 105   _NullPointerException_instance = get_object(o)->as_instance();
 106   o = Universe::arithmetic_exception_instance();
 107   assert(o != NULL, "should have been initialized");
 108   _ArithmeticException_instance = get_object(o)->as_instance();
 109 
 110   _ArrayIndexOutOfBoundsException_instance = NULL;
 111   _ArrayStoreException_instance = NULL;
 112   _ClassCastException_instance = NULL;
 113 }
 114 
 115 ciEnv::ciEnv(Arena* arena) {
 116   ASSERT_IN_VM;
 117 
 118   // Set up ciEnv::current immediately, for the sake of ciObjectFactory, etc.
 119   CompilerThread* current_thread = CompilerThread::current();
 120   assert(current_thread->env() == NULL, "must be");
 121   current_thread->set_env(this);
 122   assert(ciEnv::current() == this, "sanity");
 123 
 124   _oop_recorder = NULL;
 125   _debug_info = NULL;
 126   _dependencies = NULL;
 127   _failure_reason = NULL;
 128   _compilable = MethodCompilable_never;
 129   _break_at_compile = false;
 130   _compiler_data = NULL;
 131 #ifndef PRODUCT
 132   assert(firstEnv, "must be first");
 133   firstEnv = false;
 134 #endif /* !PRODUCT */
 135 
 136   _system_dictionary_modification_counter = 0;
 137   _num_inlined_bytecodes = 0;
 138   _task = NULL;
 139   _log = NULL;
 140 
 141   // Temporary buffer for creating symbols and such.
 142   _name_buffer = NULL;
 143   _name_buffer_len = 0;
 144 
 145   _arena   = arena;
 146   _factory = new (_arena) ciObjectFactory(_arena, 128);
 147 
 148   // Preload commonly referenced system ciObjects.
 149 
 150   // During VM initialization, these instances have not yet been created.
 151   // Assertions ensure that these instances are not accessed before
 152   // their initialization.
 153 
 154   assert(Universe::is_fully_initialized(), "must be");
 155 
 156   oop o = Universe::null_ptr_exception_instance();
 157   assert(o != NULL, "should have been initialized");
 158   _NullPointerException_instance = get_object(o)->as_instance();
 159   o = Universe::arithmetic_exception_instance();
 160   assert(o != NULL, "should have been initialized");
 161   _ArithmeticException_instance = get_object(o)->as_instance();
 162 
 163   _ArrayIndexOutOfBoundsException_instance = NULL;
 164   _ArrayStoreException_instance = NULL;
 165   _ClassCastException_instance = NULL;
 166 }
 167 
 168 ciEnv::~ciEnv() {
 169   CompilerThread* current_thread = CompilerThread::current();
 170   current_thread->set_env(NULL);
 171 }
 172 
 173 // ------------------------------------------------------------------
 174 // Cache Jvmti state
 175 void ciEnv::cache_jvmti_state() {
 176   VM_ENTRY_MARK;
 177   // Get Jvmti capabilities under lock to get consistant values.
 178   MutexLocker mu(JvmtiThreadState_lock);
 179   _jvmti_can_hotswap_or_post_breakpoint = JvmtiExport::can_hotswap_or_post_breakpoint();
 180   _jvmti_can_examine_or_deopt_anywhere  = JvmtiExport::can_examine_or_deopt_anywhere();
 181   _jvmti_can_access_local_variables     = JvmtiExport::can_access_local_variables();
 182   _jvmti_can_post_exceptions            = JvmtiExport::can_post_exceptions();
 183 }
 184 
 185 // ------------------------------------------------------------------
 186 // Cache DTrace flags
 187 void ciEnv::cache_dtrace_flags() {
 188   // Need lock?
 189   _dtrace_extended_probes = ExtendedDTraceProbes;
 190   if (_dtrace_extended_probes) {
 191     _dtrace_monitor_probes  = true;
 192     _dtrace_method_probes   = true;
 193     _dtrace_alloc_probes    = true;
 194   } else {
 195     _dtrace_monitor_probes  = DTraceMonitorProbes;
 196     _dtrace_method_probes   = DTraceMethodProbes;
 197     _dtrace_alloc_probes    = DTraceAllocProbes;
 198   }
 199 }
 200 
 201 // ------------------------------------------------------------------
 202 // helper for lazy exception creation
 203 ciInstance* ciEnv::get_or_create_exception(jobject& handle, symbolHandle name) {
 204   VM_ENTRY_MARK;
 205   if (handle == NULL) {
 206     // Cf. universe.cpp, creation of Universe::_null_ptr_exception_instance.
 207     klassOop k = SystemDictionary::find(name, Handle(), Handle(), THREAD);
 208     jobject objh = NULL;
 209     if (!HAS_PENDING_EXCEPTION && k != NULL) {
 210       oop obj = instanceKlass::cast(k)->allocate_permanent_instance(THREAD);
 211       if (!HAS_PENDING_EXCEPTION)
 212         objh = JNIHandles::make_global(obj);
 213     }
 214     if (HAS_PENDING_EXCEPTION) {
 215       CLEAR_PENDING_EXCEPTION;
 216     } else {
 217       handle = objh;
 218     }
 219   }
 220   oop obj = JNIHandles::resolve(handle);
 221   return obj == NULL? NULL: get_object(obj)->as_instance();
 222 }
 223 
 224 // ------------------------------------------------------------------
 225 // ciEnv::ArrayIndexOutOfBoundsException_instance, etc.
 226 ciInstance* ciEnv::ArrayIndexOutOfBoundsException_instance() {
 227   if (_ArrayIndexOutOfBoundsException_instance == NULL) {
 228     _ArrayIndexOutOfBoundsException_instance
 229           = get_or_create_exception(_ArrayIndexOutOfBoundsException_handle,
 230           vmSymbolHandles::java_lang_ArrayIndexOutOfBoundsException());
 231   }
 232   return _ArrayIndexOutOfBoundsException_instance;
 233 }
 234 ciInstance* ciEnv::ArrayStoreException_instance() {
 235   if (_ArrayStoreException_instance == NULL) {
 236     _ArrayStoreException_instance
 237           = get_or_create_exception(_ArrayStoreException_handle,
 238           vmSymbolHandles::java_lang_ArrayStoreException());
 239   }
 240   return _ArrayStoreException_instance;
 241 }
 242 ciInstance* ciEnv::ClassCastException_instance() {
 243   if (_ClassCastException_instance == NULL) {
 244     _ClassCastException_instance
 245           = get_or_create_exception(_ClassCastException_handle,
 246           vmSymbolHandles::java_lang_ClassCastException());
 247   }
 248   return _ClassCastException_instance;
 249 }
 250 
 251 // ------------------------------------------------------------------
 252 // ciEnv::get_method_from_handle
 253 ciMethod* ciEnv::get_method_from_handle(jobject method) {
 254   VM_ENTRY_MARK;
 255   return get_object(JNIHandles::resolve(method))->as_method();
 256 }
 257 
 258 // ------------------------------------------------------------------
 259 // ciEnv::make_array
 260 ciArray* ciEnv::make_system_array(GrowableArray<ciObject*>* objects) {
 261   VM_ENTRY_MARK;
 262   int length = objects->length();
 263   objArrayOop a = oopFactory::new_system_objArray(length, THREAD);
 264   if (HAS_PENDING_EXCEPTION) {
 265     CLEAR_PENDING_EXCEPTION;
 266     record_out_of_memory_failure();
 267     return NULL;
 268   }
 269   for (int i = 0; i < length; i++) {
 270     a->obj_at_put(i, objects->at(i)->get_oop());
 271   }
 272   assert(a->is_perm(), "");
 273   return get_object(a)->as_array();
 274 }
 275 
 276 
 277 // ------------------------------------------------------------------
 278 // ciEnv::array_element_offset_in_bytes
 279 int ciEnv::array_element_offset_in_bytes(ciArray* a_h, ciObject* o_h) {
 280   VM_ENTRY_MARK;
 281   objArrayOop a = (objArrayOop)a_h->get_oop();
 282   assert(a->is_objArray(), "");
 283   int length = a->length();
 284   oop o = o_h->get_oop();
 285   for (int i = 0; i < length; i++) {
 286     if (a->obj_at(i) == o)  return i;
 287   }
 288   return -1;
 289 }
 290 
 291 
 292 // ------------------------------------------------------------------
 293 // ciEnv::check_klass_accessiblity
 294 //
 295 // Note: the logic of this method should mirror the logic of
 296 // constantPoolOopDesc::verify_constant_pool_resolve.
 297 bool ciEnv::check_klass_accessibility(ciKlass* accessing_klass,
 298                                       klassOop resolved_klass) {
 299   if (accessing_klass == NULL || !accessing_klass->is_loaded()) {
 300     return true;
 301   }
 302   if (accessing_klass->is_obj_array()) {
 303     accessing_klass = accessing_klass->as_obj_array_klass()->base_element_klass();
 304   }
 305   if (!accessing_klass->is_instance_klass()) {
 306     return true;
 307   }
 308 
 309   if (resolved_klass->klass_part()->oop_is_objArray()) {
 310     // Find the element klass, if this is an array.
 311     resolved_klass = objArrayKlass::cast(resolved_klass)->bottom_klass();
 312   }
 313   if (resolved_klass->klass_part()->oop_is_instance()) {
 314     return Reflection::verify_class_access(accessing_klass->get_klassOop(),
 315                                            resolved_klass,
 316                                            true);
 317   }
 318   return true;
 319 }
 320 
 321 // ------------------------------------------------------------------
 322 // ciEnv::get_klass_by_name_impl
 323 ciKlass* ciEnv::get_klass_by_name_impl(ciKlass* accessing_klass,
 324                                        ciSymbol* name,
 325                                        bool require_local) {
 326   ASSERT_IN_VM;
 327   EXCEPTION_CONTEXT;
 328 
 329   // Now we need to check the SystemDictionary
 330   symbolHandle sym(THREAD, name->get_symbolOop());
 331   if (sym->byte_at(0) == 'L' &&
 332     sym->byte_at(sym->utf8_length()-1) == ';') {
 333     // This is a name from a signature.  Strip off the trimmings.
 334     sym = oopFactory::new_symbol_handle(sym->as_utf8()+1,
 335                                         sym->utf8_length()-2,
 336                                         KILL_COMPILE_ON_FATAL_(_unloaded_ciinstance_klass));
 337     name = get_object(sym())->as_symbol();
 338   }
 339 
 340   // Check for prior unloaded klass.  The SystemDictionary's answers
 341   // can vary over time but the compiler needs consistency.
 342   ciKlass* unloaded_klass = check_get_unloaded_klass(accessing_klass, name);
 343   if (unloaded_klass != NULL) {
 344     if (require_local)  return NULL;
 345     return unloaded_klass;
 346   }
 347 
 348   Handle loader(THREAD, (oop)NULL);
 349   Handle domain(THREAD, (oop)NULL);
 350   if (accessing_klass != NULL) {
 351     loader = Handle(THREAD, accessing_klass->loader());
 352     domain = Handle(THREAD, accessing_klass->protection_domain());
 353   }
 354 
 355   // setup up the proper type to return on OOM
 356   ciKlass* fail_type;
 357   if (sym->byte_at(0) == '[') {
 358     fail_type = _unloaded_ciobjarrayklass;
 359   } else {
 360     fail_type = _unloaded_ciinstance_klass;
 361   }
 362   klassOop found_klass;
 363   if (!require_local) {
 364     found_klass =
 365       SystemDictionary::find_constrained_instance_or_array_klass(sym, loader,
 366                                                                  KILL_COMPILE_ON_FATAL_(fail_type));
 367   } else {
 368     found_klass =
 369       SystemDictionary::find_instance_or_array_klass(sym, loader, domain,
 370                                                      KILL_COMPILE_ON_FATAL_(fail_type));
 371   }
 372 
 373   if (found_klass != NULL) {
 374     // Found it.  Build a CI handle.
 375     return get_object(found_klass)->as_klass();
 376   }
 377 
 378   // If we fail to find an array klass, look again for its element type.
 379   // The element type may be available either locally or via constraints.
 380   // In either case, if we can find the element type in the system dictionary,
 381   // we must build an array type around it.  The CI requires array klasses
 382   // to be loaded if their element klasses are loaded, except when memory
 383   // is exhausted.
 384   if (sym->byte_at(0) == '[' &&
 385       (sym->byte_at(1) == '[' || sym->byte_at(1) == 'L')) {
 386     // We have an unloaded array.
 387     // Build it on the fly if the element class exists.
 388     symbolOop elem_sym = oopFactory::new_symbol(sym->as_utf8()+1,
 389                                                 sym->utf8_length()-1,
 390                                                 KILL_COMPILE_ON_FATAL_(fail_type));
 391     // Get element ciKlass recursively.
 392     ciKlass* elem_klass =
 393       get_klass_by_name_impl(accessing_klass,
 394                              get_object(elem_sym)->as_symbol(),
 395                              require_local);
 396     if (elem_klass != NULL && elem_klass->is_loaded()) {
 397       // Now make an array for it
 398       return ciObjArrayKlass::make_impl(elem_klass);
 399     }
 400   }
 401 
 402   if (require_local)  return NULL;
 403   // Not yet loaded into the VM, or not governed by loader constraints.
 404   // Make a CI representative for it.
 405   return get_unloaded_klass(accessing_klass, name);
 406 }
 407 
 408 // ------------------------------------------------------------------
 409 // ciEnv::get_klass_by_name
 410 ciKlass* ciEnv::get_klass_by_name(ciKlass* accessing_klass,
 411                                   ciSymbol* klass_name,
 412                                   bool require_local) {
 413   GUARDED_VM_ENTRY(return get_klass_by_name_impl(accessing_klass,
 414                                                  klass_name,
 415                                                  require_local);)
 416 }
 417 
 418 // ------------------------------------------------------------------
 419 // ciEnv::get_klass_by_index_impl
 420 //
 421 // Implementation of get_klass_by_index.
 422 ciKlass* ciEnv::get_klass_by_index_impl(ciInstanceKlass* accessor,
 423                                         int index,
 424                                         bool& is_accessible) {
 425   assert(accessor->get_instanceKlass()->is_linked(), "must be linked before accessing constant pool");
 426   EXCEPTION_CONTEXT;
 427   constantPoolHandle cpool(THREAD, accessor->get_instanceKlass()->constants());
 428   KlassHandle klass (THREAD, constantPoolOopDesc::klass_at_if_loaded(cpool, index));
 429   symbolHandle klass_name;
 430   if (klass.is_null()) {
 431     // The klass has not been inserted into the constant pool.
 432     // Try to look it up by name.
 433     {
 434       // We have to lock the cpool to keep the oop from being resolved
 435       // while we are accessing it.
 436       ObjectLocker ol(cpool, THREAD);
 437 
 438       constantTag tag = cpool->tag_at(index);
 439       if (tag.is_klass()) {
 440         // The klass has been inserted into the constant pool
 441         // very recently.
 442         klass = KlassHandle(THREAD, cpool->resolved_klass_at(index));
 443       } else if (tag.is_symbol()) {
 444         klass_name = symbolHandle(THREAD, cpool->symbol_at(index));
 445       } else {
 446         assert(cpool->tag_at(index).is_unresolved_klass(), "wrong tag");
 447         klass_name = symbolHandle(THREAD, cpool->unresolved_klass_at(index));
 448       }
 449     }
 450   }
 451 
 452   if (klass.is_null()) {
 453     // Not found in constant pool.  Use the name to do the lookup.
 454     ciKlass* k = get_klass_by_name_impl(accessor,
 455                                         get_object(klass_name())->as_symbol(),
 456                                         false);
 457     // Calculate accessibility the hard way.
 458     if (!k->is_loaded()) {
 459       is_accessible = false;
 460     } else if (k->loader() != accessor->loader() &&
 461                get_klass_by_name_impl(accessor, k->name(), true) == NULL) {
 462       // Loaded only remotely.  Not linked yet.
 463       is_accessible = false;
 464     } else {
 465       // Linked locally, and we must also check public/private, etc.
 466       is_accessible = check_klass_accessibility(accessor, k->get_klassOop());
 467     }
 468     return k;
 469   }
 470 
 471   // Check for prior unloaded klass.  The SystemDictionary's answers
 472   // can vary over time but the compiler needs consistency.
 473   ciSymbol* name = get_object(klass()->klass_part()->name())->as_symbol();
 474   ciKlass* unloaded_klass = check_get_unloaded_klass(accessor, name);
 475   if (unloaded_klass != NULL) {
 476     is_accessible = false;
 477     return unloaded_klass;
 478   }
 479 
 480   // It is known to be accessible, since it was found in the constant pool.
 481   is_accessible = true;
 482   return get_object(klass())->as_klass();
 483 }
 484 
 485 // ------------------------------------------------------------------
 486 // ciEnv::get_klass_by_index
 487 //
 488 // Get a klass from the constant pool.
 489 ciKlass* ciEnv::get_klass_by_index(ciInstanceKlass* accessor,
 490                                    int index,
 491                                    bool& is_accessible) {
 492   GUARDED_VM_ENTRY(return get_klass_by_index_impl(accessor, index, is_accessible);)
 493 }
 494 
 495 // ------------------------------------------------------------------
 496 // ciEnv::get_constant_by_index_impl
 497 //
 498 // Implementation of get_constant_by_index().
 499 ciConstant ciEnv::get_constant_by_index_impl(ciInstanceKlass* accessor,
 500                                              int index) {
 501   EXCEPTION_CONTEXT;
 502   instanceKlass* ik_accessor = accessor->get_instanceKlass();
 503   assert(ik_accessor->is_linked(), "must be linked before accessing constant pool");
 504   constantPoolOop cpool = ik_accessor->constants();
 505   constantTag tag = cpool->tag_at(index);
 506   if (tag.is_int()) {
 507     return ciConstant(T_INT, (jint)cpool->int_at(index));
 508   } else if (tag.is_long()) {
 509     return ciConstant((jlong)cpool->long_at(index));
 510   } else if (tag.is_float()) {
 511     return ciConstant((jfloat)cpool->float_at(index));
 512   } else if (tag.is_double()) {
 513     return ciConstant((jdouble)cpool->double_at(index));
 514   } else if (tag.is_string() || tag.is_unresolved_string()) {
 515     oop string = NULL;
 516     if (cpool->is_pseudo_string_at(index)) {
 517       string = cpool->pseudo_string_at(index);
 518     } else {
 519       string = cpool->string_at(index, THREAD);
 520       if (HAS_PENDING_EXCEPTION) {
 521         CLEAR_PENDING_EXCEPTION;
 522         record_out_of_memory_failure();
 523         return ciConstant();
 524       }
 525     }
 526     ciObject* constant = get_object(string);
 527     assert (constant->is_instance(), "must be an instance, or not? ");
 528     return ciConstant(T_OBJECT, constant);
 529   } else if (tag.is_klass() || tag.is_unresolved_klass()) {
 530     // 4881222: allow ldc to take a class type
 531     bool ignore;
 532     ciKlass* klass = get_klass_by_index_impl(accessor, index, ignore);
 533     if (HAS_PENDING_EXCEPTION) {
 534       CLEAR_PENDING_EXCEPTION;
 535       record_out_of_memory_failure();
 536       return ciConstant();
 537     }
 538     assert (klass->is_instance_klass() || klass->is_array_klass(),
 539             "must be an instance or array klass ");
 540     return ciConstant(T_OBJECT, klass);
 541   } else {
 542     ShouldNotReachHere();
 543     return ciConstant();
 544   }
 545 }
 546 
 547 // ------------------------------------------------------------------
 548 // ciEnv::is_unresolved_string_impl
 549 //
 550 // Implementation of is_unresolved_string().
 551 bool ciEnv::is_unresolved_string_impl(instanceKlass* accessor, int index) const {
 552   EXCEPTION_CONTEXT;
 553   assert(accessor->is_linked(), "must be linked before accessing constant pool");
 554   constantPoolOop cpool = accessor->constants();
 555   constantTag tag = cpool->tag_at(index);
 556   return tag.is_unresolved_string();
 557 }
 558 
 559 // ------------------------------------------------------------------
 560 // ciEnv::is_unresolved_klass_impl
 561 //
 562 // Implementation of is_unresolved_klass().
 563 bool ciEnv::is_unresolved_klass_impl(instanceKlass* accessor, int index) const {
 564   EXCEPTION_CONTEXT;
 565   assert(accessor->is_linked(), "must be linked before accessing constant pool");
 566   constantPoolOop cpool = accessor->constants();
 567   constantTag tag = cpool->tag_at(index);
 568   return tag.is_unresolved_klass();
 569 }
 570 
 571 // ------------------------------------------------------------------
 572 // ciEnv::get_constant_by_index
 573 //
 574 // Pull a constant out of the constant pool.  How appropriate.
 575 //
 576 // Implementation note: this query is currently in no way cached.
 577 ciConstant ciEnv::get_constant_by_index(ciInstanceKlass* accessor,
 578                                         int index) {
 579   GUARDED_VM_ENTRY(return get_constant_by_index_impl(accessor, index); )
 580 }
 581 
 582 // ------------------------------------------------------------------
 583 // ciEnv::is_unresolved_string
 584 //
 585 // Check constant pool
 586 //
 587 // Implementation note: this query is currently in no way cached.
 588 bool ciEnv::is_unresolved_string(ciInstanceKlass* accessor,
 589                                         int index) const {
 590   GUARDED_VM_ENTRY(return is_unresolved_string_impl(accessor->get_instanceKlass(), index); )
 591 }
 592 
 593 // ------------------------------------------------------------------
 594 // ciEnv::is_unresolved_klass
 595 //
 596 // Check constant pool
 597 //
 598 // Implementation note: this query is currently in no way cached.
 599 bool ciEnv::is_unresolved_klass(ciInstanceKlass* accessor,
 600                                         int index) const {
 601   GUARDED_VM_ENTRY(return is_unresolved_klass_impl(accessor->get_instanceKlass(), index); )
 602 }
 603 
 604 // ------------------------------------------------------------------
 605 // ciEnv::get_field_by_index_impl
 606 //
 607 // Implementation of get_field_by_index.
 608 //
 609 // Implementation note: the results of field lookups are cached
 610 // in the accessor klass.
 611 ciField* ciEnv::get_field_by_index_impl(ciInstanceKlass* accessor,
 612                                         int index) {
 613   ciConstantPoolCache* cache = accessor->field_cache();
 614   if (cache == NULL) {
 615     ciField* field = new (arena()) ciField(accessor, index);
 616     return field;
 617   } else {
 618     ciField* field = (ciField*)cache->get(index);
 619     if (field == NULL) {
 620       field = new (arena()) ciField(accessor, index);
 621       cache->insert(index, field);
 622     }
 623     return field;
 624   }
 625 }
 626 
 627 // ------------------------------------------------------------------
 628 // ciEnv::get_field_by_index
 629 //
 630 // Get a field by index from a klass's constant pool.
 631 ciField* ciEnv::get_field_by_index(ciInstanceKlass* accessor,
 632                                    int index) {
 633   GUARDED_VM_ENTRY(return get_field_by_index_impl(accessor, index);)
 634 }
 635 
 636 // ------------------------------------------------------------------
 637 // ciEnv::lookup_method
 638 //
 639 // Perform an appropriate method lookup based on accessor, holder,
 640 // name, signature, and bytecode.
 641 methodOop ciEnv::lookup_method(instanceKlass*  accessor,
 642                                instanceKlass*  holder,
 643                                symbolOop       name,
 644                                symbolOop       sig,
 645                                Bytecodes::Code bc) {
 646   EXCEPTION_CONTEXT;
 647   KlassHandle h_accessor(THREAD, accessor);
 648   KlassHandle h_holder(THREAD, holder);
 649   symbolHandle h_name(THREAD, name);
 650   symbolHandle h_sig(THREAD, sig);
 651   LinkResolver::check_klass_accessability(h_accessor, h_holder, KILL_COMPILE_ON_FATAL_(NULL));
 652   methodHandle dest_method;
 653   switch (bc) {
 654   case Bytecodes::_invokestatic:
 655     dest_method =
 656       LinkResolver::resolve_static_call_or_null(h_holder, h_name, h_sig, h_accessor);
 657     break;
 658   case Bytecodes::_invokespecial:
 659     dest_method =
 660       LinkResolver::resolve_special_call_or_null(h_holder, h_name, h_sig, h_accessor);
 661     break;
 662   case Bytecodes::_invokeinterface:
 663     dest_method =
 664       LinkResolver::linktime_resolve_interface_method_or_null(h_holder, h_name, h_sig,
 665                                                               h_accessor, true);
 666     break;
 667   case Bytecodes::_invokevirtual:
 668     dest_method =
 669       LinkResolver::linktime_resolve_virtual_method_or_null(h_holder, h_name, h_sig,
 670                                                             h_accessor, true);
 671     break;
 672   default: ShouldNotReachHere();
 673   }
 674 
 675   return dest_method();
 676 }
 677 
 678 
 679 // ------------------------------------------------------------------
 680 // ciEnv::get_method_by_index_impl
 681 ciMethod* ciEnv::get_method_by_index_impl(ciInstanceKlass* accessor,
 682                                      int index, Bytecodes::Code bc) {
 683   // Get the method's declared holder.
 684 
 685   assert(accessor->get_instanceKlass()->is_linked(), "must be linked before accessing constant pool");
 686   constantPoolHandle cpool = accessor->get_instanceKlass()->constants();
 687   int holder_index = cpool->klass_ref_index_at(index);
 688   bool holder_is_accessible;
 689   ciKlass* holder = get_klass_by_index_impl(accessor, holder_index, holder_is_accessible);
 690   ciInstanceKlass* declared_holder = get_instance_klass_for_declared_method_holder(holder);
 691 
 692   // Get the method's name and signature.
 693   symbolOop name_sym = cpool->name_ref_at(index);
 694   symbolOop sig_sym  = cpool->signature_ref_at(index);
 695 
 696   if (holder_is_accessible) { // Our declared holder is loaded.
 697     instanceKlass* lookup = declared_holder->get_instanceKlass();
 698     methodOop m = lookup_method(accessor->get_instanceKlass(), lookup, name_sym, sig_sym, bc);
 699     if (m != NULL) {
 700       // We found the method.
 701       return get_object(m)->as_method();
 702     }
 703   }
 704 
 705   // Either the declared holder was not loaded, or the method could
 706   // not be found.  Create a dummy ciMethod to represent the failed
 707   // lookup.
 708 
 709   return get_unloaded_method(declared_holder,
 710                              get_object(name_sym)->as_symbol(),
 711                              get_object(sig_sym)->as_symbol());
 712 }
 713 
 714 
 715 // ------------------------------------------------------------------
 716 // ciEnv::get_instance_klass_for_declared_method_holder
 717 ciInstanceKlass* ciEnv::get_instance_klass_for_declared_method_holder(ciKlass* method_holder) {
 718   // For the case of <array>.clone(), the method holder can be a ciArrayKlass
 719   // instead of a ciInstanceKlass.  For that case simply pretend that the
 720   // declared holder is Object.clone since that's where the call will bottom out.
 721   // A more correct fix would trickle out through many interfaces in CI,
 722   // requiring ciInstanceKlass* to become ciKlass* and many more places would
 723   // require checks to make sure the expected type was found.  Given that this
 724   // only occurs for clone() the more extensive fix seems like overkill so
 725   // instead we simply smear the array type into Object.
 726   if (method_holder->is_instance_klass()) {
 727     return method_holder->as_instance_klass();
 728   } else if (method_holder->is_array_klass()) {
 729     return current()->Object_klass();
 730   } else {
 731     ShouldNotReachHere();
 732   }
 733   return NULL;
 734 }
 735 
 736 
 737 
 738 
 739 // ------------------------------------------------------------------
 740 // ciEnv::get_method_by_index
 741 ciMethod* ciEnv::get_method_by_index(ciInstanceKlass* accessor,
 742                                      int index, Bytecodes::Code bc) {
 743   GUARDED_VM_ENTRY(return get_method_by_index_impl(accessor, index, bc);)
 744 }
 745 
 746 // ------------------------------------------------------------------
 747 // ciEnv::name_buffer
 748 char *ciEnv::name_buffer(int req_len) {
 749   if (_name_buffer_len < req_len) {
 750     if (_name_buffer == NULL) {
 751       _name_buffer = (char*)arena()->Amalloc(sizeof(char)*req_len);
 752       _name_buffer_len = req_len;
 753     } else {
 754       _name_buffer =
 755         (char*)arena()->Arealloc(_name_buffer, _name_buffer_len, req_len);
 756       _name_buffer_len = req_len;
 757     }
 758   }
 759   return _name_buffer;
 760 }
 761 
 762 // ------------------------------------------------------------------
 763 // ciEnv::is_in_vm
 764 bool ciEnv::is_in_vm() {
 765   return JavaThread::current()->thread_state() == _thread_in_vm;
 766 }
 767 
 768 bool ciEnv::system_dictionary_modification_counter_changed() {
 769   return _system_dictionary_modification_counter != SystemDictionary::number_of_modifications();
 770 }
 771 
 772 // ------------------------------------------------------------------
 773 // ciEnv::check_for_system_dictionary_modification
 774 // Check for changes to the system dictionary during compilation
 775 // class loads, evolution, breakpoints
 776 void ciEnv::check_for_system_dictionary_modification(ciMethod* target) {
 777   if (failing())  return;  // no need for further checks
 778 
 779   // Dependencies must be checked when the system dictionary changes.
 780   // If logging is enabled all violated dependences will be recorded in
 781   // the log.  In debug mode check dependencies even if the system
 782   // dictionary hasn't changed to verify that no invalid dependencies
 783   // were inserted.  Any violated dependences in this case are dumped to
 784   // the tty.
 785 
 786   bool counter_changed = system_dictionary_modification_counter_changed();
 787   bool test_deps = counter_changed;
 788   DEBUG_ONLY(test_deps = true);
 789   if (!test_deps)  return;
 790 
 791   bool print_failures = false;
 792   DEBUG_ONLY(print_failures = !counter_changed);
 793 
 794   bool keep_going = (print_failures || xtty != NULL);
 795 
 796   int violated = 0;
 797 
 798   for (Dependencies::DepStream deps(dependencies()); deps.next(); ) {
 799     klassOop witness = deps.check_dependency();
 800     if (witness != NULL) {
 801       ++violated;
 802       if (print_failures)  deps.print_dependency(witness, /*verbose=*/ true);
 803       // If there's no log and we're not sanity-checking, we're done.
 804       if (!keep_going)     break;
 805     }
 806   }
 807 
 808   if (violated != 0) {
 809     assert(counter_changed, "failed dependencies, but counter didn't change");
 810     record_failure("concurrent class loading");
 811   }
 812 }
 813 
 814 // ------------------------------------------------------------------
 815 // ciEnv::register_method
 816 void ciEnv::register_method(ciMethod* target,
 817                             int entry_bci,
 818                             CodeOffsets* offsets,
 819                             int orig_pc_offset,
 820                             CodeBuffer* code_buffer,
 821                             int frame_words,
 822                             OopMapSet* oop_map_set,
 823                             ExceptionHandlerTable* handler_table,
 824                             ImplicitExceptionTable* inc_table,
 825                             AbstractCompiler* compiler,
 826                             int comp_level,
 827                             bool has_debug_info,
 828                             bool has_unsafe_access) {
 829   VM_ENTRY_MARK;
 830   nmethod* nm = NULL;
 831   {
 832     // To prevent compile queue updates.
 833     MutexLocker locker(MethodCompileQueue_lock, THREAD);
 834 
 835     // Prevent SystemDictionary::add_to_hierarchy from running
 836     // and invalidating our dependencies until we install this method.
 837     MutexLocker ml(Compile_lock);
 838 
 839     // Change in Jvmti state may invalidate compilation.
 840     if (!failing() &&
 841         ( (!jvmti_can_hotswap_or_post_breakpoint() &&
 842            JvmtiExport::can_hotswap_or_post_breakpoint()) ||
 843           (!jvmti_can_examine_or_deopt_anywhere() &&
 844            JvmtiExport::can_examine_or_deopt_anywhere()) ||
 845           (!jvmti_can_access_local_variables() &&
 846            JvmtiExport::can_access_local_variables()) ||
 847           (!jvmti_can_post_exceptions() &&
 848            JvmtiExport::can_post_exceptions()) )) {
 849       record_failure("Jvmti state change invalidated dependencies");
 850     }
 851 
 852     // Change in DTrace flags may invalidate compilation.
 853     if (!failing() &&
 854         ( (!dtrace_extended_probes() && ExtendedDTraceProbes) ||
 855           (!dtrace_method_probes() && DTraceMethodProbes) ||
 856           (!dtrace_alloc_probes() && DTraceAllocProbes) )) {
 857       record_failure("DTrace flags change invalidated dependencies");
 858     }
 859 
 860     if (!failing()) {
 861       if (log() != NULL) {
 862         // Log the dependencies which this compilation declares.
 863         dependencies()->log_all_dependencies();
 864       }
 865 
 866       // Encode the dependencies now, so we can check them right away.
 867       dependencies()->encode_content_bytes();
 868 
 869       // Check for {class loads, evolution, breakpoints} during compilation
 870       check_for_system_dictionary_modification(target);
 871     }
 872 
 873     methodHandle method(THREAD, target->get_methodOop());
 874 
 875     if (failing()) {
 876       // While not a true deoptimization, it is a preemptive decompile.
 877       methodDataOop mdo = method()->method_data();
 878       if (mdo != NULL) {
 879         mdo->inc_decompile_count();
 880       }
 881 
 882       // All buffers in the CodeBuffer are allocated in the CodeCache.
 883       // If the code buffer is created on each compile attempt
 884       // as in C2, then it must be freed.
 885       code_buffer->free_blob();
 886       return;
 887     }
 888 
 889     assert(offsets->value(CodeOffsets::Deopt) != -1, "must have deopt entry");
 890     assert(offsets->value(CodeOffsets::Exceptions) != -1, "must have exception entry");
 891 
 892     nm =  nmethod::new_nmethod(method,
 893                                compile_id(),
 894                                entry_bci,
 895                                offsets,
 896                                orig_pc_offset,
 897                                debug_info(), dependencies(), code_buffer,
 898                                frame_words, oop_map_set,
 899                                handler_table, inc_table,
 900                                compiler, comp_level);
 901 
 902     // Free codeBlobs
 903     code_buffer->free_blob();
 904 
 905     // stress test 6243940 by immediately making the method
 906     // non-entrant behind the system's back. This has serious
 907     // side effects on the code cache and is not meant for
 908     // general stress testing
 909     if (nm != NULL && StressNonEntrant) {
 910       MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
 911       NativeJump::patch_verified_entry(nm->entry_point(), nm->verified_entry_point(),
 912                   SharedRuntime::get_handle_wrong_method_stub());
 913     }
 914 
 915     if (nm == NULL) {
 916       // The CodeCache is full.  Print out warning and disable compilation.
 917       record_failure("code cache is full");
 918       UseInterpreter = true;
 919       if (UseCompiler || AlwaysCompileLoopMethods ) {
 920 #ifndef PRODUCT
 921         warning("CodeCache is full. Compiler has been disabled");
 922         if (CompileTheWorld || ExitOnFullCodeCache) {
 923           before_exit(JavaThread::current());
 924           exit_globals(); // will delete tty
 925           vm_direct_exit(CompileTheWorld ? 0 : 1);
 926         }
 927 #endif
 928         UseCompiler               = false;
 929         AlwaysCompileLoopMethods  = false;
 930       }
 931     } else {
 932       NOT_PRODUCT(nm->set_has_debug_info(has_debug_info); )
 933       nm->set_has_unsafe_access(has_unsafe_access);
 934 
 935       // Record successful registration.
 936       // (Put nm into the task handle *before* publishing to the Java heap.)
 937       if (task() != NULL)  task()->set_code(nm);
 938 
 939       if (entry_bci == InvocationEntryBci) {
 940 #ifdef TIERED
 941         // If there is an old version we're done with it
 942         nmethod* old = method->code();
 943         if (TraceMethodReplacement && old != NULL) {
 944           ResourceMark rm;
 945           char *method_name = method->name_and_sig_as_C_string();
 946           tty->print_cr("Replacing method %s", method_name);
 947         }
 948         if (old != NULL ) {
 949           old->make_not_entrant();
 950         }
 951 #endif // TIERED
 952         if (TraceNMethodInstalls ) {
 953           ResourceMark rm;
 954           char *method_name = method->name_and_sig_as_C_string();
 955           ttyLocker ttyl;
 956           tty->print_cr("Installing method (%d) %s ",
 957                         comp_level,
 958                         method_name);
 959         }
 960         // Allow the code to be executed
 961         method->set_code(method, nm);
 962       } else {
 963         if (TraceNMethodInstalls ) {
 964           ResourceMark rm;
 965           char *method_name = method->name_and_sig_as_C_string();
 966           ttyLocker ttyl;
 967           tty->print_cr("Installing osr method (%d) %s @ %d",
 968                         comp_level,
 969                         method_name,
 970                         entry_bci);
 971         }
 972         instanceKlass::cast(method->method_holder())->add_osr_nmethod(nm);
 973 
 974       }
 975     }
 976   }
 977   // JVMTI -- compiled method notification (must be done outside lock)
 978   if (nm != NULL) {
 979     nm->post_compiled_method_load_event();
 980   }
 981 
 982 }
 983 
 984 
 985 // ------------------------------------------------------------------
 986 // ciEnv::find_system_klass
 987 ciKlass* ciEnv::find_system_klass(ciSymbol* klass_name) {
 988   VM_ENTRY_MARK;
 989   return get_klass_by_name_impl(NULL, klass_name, false);
 990 }
 991 
 992 // ------------------------------------------------------------------
 993 // ciEnv::comp_level
 994 int ciEnv::comp_level() {
 995   if (task() == NULL)  return CompLevel_full_optimization;
 996   return task()->comp_level();
 997 }
 998 
 999 // ------------------------------------------------------------------
1000 // ciEnv::compile_id
1001 uint ciEnv::compile_id() {
1002   if (task() == NULL)  return 0;
1003   return task()->compile_id();
1004 }
1005 
1006 // ------------------------------------------------------------------
1007 // ciEnv::notice_inlined_method()
1008 void ciEnv::notice_inlined_method(ciMethod* method) {
1009   _num_inlined_bytecodes += method->code_size();
1010 }
1011 
1012 // ------------------------------------------------------------------
1013 // ciEnv::num_inlined_bytecodes()
1014 int ciEnv::num_inlined_bytecodes() const {
1015   return _num_inlined_bytecodes;
1016 }
1017 
1018 // ------------------------------------------------------------------
1019 // ciEnv::record_failure()
1020 void ciEnv::record_failure(const char* reason) {
1021   if (log() != NULL) {
1022     log()->elem("failure reason='%s'", reason);
1023   }
1024   if (_failure_reason == NULL) {
1025     // Record the first failure reason.
1026     _failure_reason = reason;
1027   }
1028 }
1029 
1030 // ------------------------------------------------------------------
1031 // ciEnv::record_method_not_compilable()
1032 void ciEnv::record_method_not_compilable(const char* reason, bool all_tiers) {
1033   int new_compilable =
1034     all_tiers ? MethodCompilable_never : MethodCompilable_not_at_tier ;
1035 
1036   // Only note transitions to a worse state
1037   if (new_compilable > _compilable) {
1038     if (log() != NULL) {
1039       if (all_tiers) {
1040         log()->elem("method_not_compilable");
1041       } else {
1042         log()->elem("method_not_compilable_at_tier");
1043       }
1044     }
1045     _compilable = new_compilable;
1046 
1047     // Reset failure reason; this one is more important.
1048     _failure_reason = NULL;
1049     record_failure(reason);
1050   }
1051 }
1052 
1053 // ------------------------------------------------------------------
1054 // ciEnv::record_out_of_memory_failure()
1055 void ciEnv::record_out_of_memory_failure() {
1056   // If memory is low, we stop compiling methods.
1057   record_method_not_compilable("out of memory");
1058 }