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