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