1 /*
   2  * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/systemDictionary.hpp"
  27 #include "classfile/vmSymbols.hpp"
  28 #include "code/compiledIC.hpp"
  29 #include "code/icBuffer.hpp"
  30 #include "code/nmethod.hpp"
  31 #include "code/pcDesc.hpp"
  32 #include "code/scopeDesc.hpp"
  33 #include "code/vtableStubs.hpp"
  34 #include "compiler/compileBroker.hpp"
  35 #include "compiler/compilerOracle.hpp"
  36 #include "compiler/oopMap.hpp"
  37 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
  38 #include "gc_implementation/g1/heapRegion.hpp"
  39 #include "gc_interface/collectedHeap.hpp"
  40 #include "interpreter/bytecode.hpp"
  41 #include "interpreter/interpreter.hpp"
  42 #include "interpreter/linkResolver.hpp"
  43 #include "memory/barrierSet.hpp"
  44 #include "memory/gcLocker.inline.hpp"
  45 #include "memory/oopFactory.hpp"
  46 #include "oops/objArrayKlass.hpp"
  47 #include "oops/oop.inline.hpp"
  48 #include "opto/addnode.hpp"
  49 #include "opto/callnode.hpp"
  50 #include "opto/cfgnode.hpp"
  51 #include "opto/connode.hpp"
  52 #include "opto/graphKit.hpp"
  53 #include "opto/machnode.hpp"
  54 #include "opto/matcher.hpp"
  55 #include "opto/memnode.hpp"
  56 #include "opto/mulnode.hpp"
  57 #include "opto/runtime.hpp"
  58 #include "opto/subnode.hpp"
  59 #include "runtime/fprofiler.hpp"
  60 #include "runtime/handles.inline.hpp"
  61 #include "runtime/interfaceSupport.hpp"
  62 #include "runtime/javaCalls.hpp"
  63 #include "runtime/sharedRuntime.hpp"
  64 #include "runtime/signature.hpp"
  65 #include "runtime/threadCritical.hpp"
  66 #include "runtime/vframe.hpp"
  67 #include "runtime/vframeArray.hpp"
  68 #include "runtime/vframe_hp.hpp"
  69 #include "utilities/copy.hpp"
  70 #include "utilities/preserveException.hpp"
  71 #ifdef TARGET_ARCH_MODEL_x86_32
  72 # include "adfiles/ad_x86_32.hpp"
  73 #endif
  74 #ifdef TARGET_ARCH_MODEL_x86_64
  75 # include "adfiles/ad_x86_64.hpp"
  76 #endif
  77 #ifdef TARGET_ARCH_MODEL_sparc
  78 # include "adfiles/ad_sparc.hpp"
  79 #endif
  80 #ifdef TARGET_ARCH_MODEL_zero
  81 # include "adfiles/ad_zero.hpp"
  82 #endif
  83 #ifdef TARGET_ARCH_MODEL_arm
  84 # include "adfiles/ad_arm.hpp"
  85 #endif
  86 #ifdef TARGET_ARCH_MODEL_ppc
  87 # include "adfiles/ad_ppc.hpp"
  88 #endif
  89 
  90 
  91 // For debugging purposes:
  92 //  To force FullGCALot inside a runtime function, add the following two lines
  93 //
  94 //  Universe::release_fullgc_alot_dummy();
  95 //  MarkSweep::invoke(0, "Debugging");
  96 //
  97 // At command line specify the parameters: -XX:+FullGCALot -XX:FullGCALotStart=100000000
  98 
  99 
 100 
 101 
 102 // Compiled code entry points
 103 address OptoRuntime::_new_instance_Java                           = NULL;
 104 address OptoRuntime::_new_array_Java                              = NULL;
 105 address OptoRuntime::_new_array_nozero_Java                       = NULL;
 106 address OptoRuntime::_multianewarray2_Java                        = NULL;
 107 address OptoRuntime::_multianewarray3_Java                        = NULL;
 108 address OptoRuntime::_multianewarray4_Java                        = NULL;
 109 address OptoRuntime::_multianewarray5_Java                        = NULL;
 110 address OptoRuntime::_multianewarrayN_Java                        = NULL;
 111 address OptoRuntime::_g1_wb_pre_Java                              = NULL;
 112 address OptoRuntime::_g1_wb_post_Java                             = NULL;
 113 address OptoRuntime::_vtable_must_compile_Java                    = NULL;
 114 address OptoRuntime::_complete_monitor_locking_Java               = NULL;
 115 address OptoRuntime::_rethrow_Java                                = NULL;
 116 
 117 address OptoRuntime::_slow_arraycopy_Java                         = NULL;
 118 address OptoRuntime::_register_finalizer_Java                     = NULL;
 119 
 120 # ifdef ENABLE_ZAP_DEAD_LOCALS
 121 address OptoRuntime::_zap_dead_Java_locals_Java                   = NULL;
 122 address OptoRuntime::_zap_dead_native_locals_Java                 = NULL;
 123 # endif
 124 
 125 ExceptionBlob* OptoRuntime::_exception_blob;
 126 
 127 // This should be called in an assertion at the start of OptoRuntime routines
 128 // which are entered from compiled code (all of them)
 129 #ifndef PRODUCT
 130 static bool check_compiled_frame(JavaThread* thread) {
 131   assert(thread->last_frame().is_runtime_frame(), "cannot call runtime directly from compiled code");
 132 #ifdef ASSERT
 133   RegisterMap map(thread, false);
 134   frame caller = thread->last_frame().sender(&map);
 135   assert(caller.is_compiled_frame(), "not being called from compiled like code");
 136 #endif  /* ASSERT */
 137   return true;
 138 }
 139 #endif
 140 
 141 
 142 #define gen(env, var, type_func_gen, c_func, fancy_jump, pass_tls, save_arg_regs, return_pc) \
 143   var = generate_stub(env, type_func_gen, CAST_FROM_FN_PTR(address, c_func), #var, fancy_jump, pass_tls, save_arg_regs, return_pc)
 144 
 145 void OptoRuntime::generate(ciEnv* env) {
 146 
 147   generate_exception_blob();
 148 
 149   // Note: tls: Means fetching the return oop out of the thread-local storage
 150   //
 151   //   variable/name                       type-function-gen              , runtime method                  ,fncy_jp, tls,save_args,retpc
 152   // -------------------------------------------------------------------------------------------------------------------------------
 153   gen(env, _new_instance_Java              , new_instance_Type            , new_instance_C                  ,    0 , true , false, false);
 154   gen(env, _new_array_Java                 , new_array_Type               , new_array_C                     ,    0 , true , false, false);
 155   gen(env, _new_array_nozero_Java          , new_array_Type               , new_array_nozero_C              ,    0 , true , false, false);
 156   gen(env, _multianewarray2_Java           , multianewarray2_Type         , multianewarray2_C               ,    0 , true , false, false);
 157   gen(env, _multianewarray3_Java           , multianewarray3_Type         , multianewarray3_C               ,    0 , true , false, false);
 158   gen(env, _multianewarray4_Java           , multianewarray4_Type         , multianewarray4_C               ,    0 , true , false, false);
 159   gen(env, _multianewarray5_Java           , multianewarray5_Type         , multianewarray5_C               ,    0 , true , false, false);
 160   gen(env, _multianewarrayN_Java           , multianewarrayN_Type         , multianewarrayN_C               ,    0 , true , false, false);
 161   gen(env, _g1_wb_pre_Java                 , g1_wb_pre_Type               , SharedRuntime::g1_wb_pre        ,    0 , false, false, false);
 162   gen(env, _g1_wb_post_Java                , g1_wb_post_Type              , SharedRuntime::g1_wb_post       ,    0 , false, false, false);
 163   gen(env, _complete_monitor_locking_Java  , complete_monitor_enter_Type  , SharedRuntime::complete_monitor_locking_C      ,    0 , false, false, false);
 164   gen(env, _rethrow_Java                   , rethrow_Type                 , rethrow_C                       ,    2 , true , false, true );
 165 
 166   gen(env, _slow_arraycopy_Java            , slow_arraycopy_Type          , SharedRuntime::slow_arraycopy_C ,    0 , false, false, false);
 167   gen(env, _register_finalizer_Java        , register_finalizer_Type      , register_finalizer              ,    0 , false, false, false);
 168 
 169 # ifdef ENABLE_ZAP_DEAD_LOCALS
 170   gen(env, _zap_dead_Java_locals_Java      , zap_dead_locals_Type         , zap_dead_Java_locals_C          ,    0 , false, true , false );
 171   gen(env, _zap_dead_native_locals_Java    , zap_dead_locals_Type         , zap_dead_native_locals_C        ,    0 , false, true , false );
 172 # endif
 173 
 174 }
 175 
 176 #undef gen
 177 
 178 
 179 // Helper method to do generation of RunTimeStub's
 180 address OptoRuntime::generate_stub( ciEnv* env,
 181                                     TypeFunc_generator gen, address C_function,
 182                                     const char *name, int is_fancy_jump,
 183                                     bool pass_tls,
 184                                     bool save_argument_registers,
 185                                     bool return_pc ) {
 186   ResourceMark rm;
 187   Compile C( env, gen, C_function, name, is_fancy_jump, pass_tls, save_argument_registers, return_pc );
 188   return  C.stub_entry_point();
 189 }
 190 
 191 const char* OptoRuntime::stub_name(address entry) {
 192 #ifndef PRODUCT
 193   CodeBlob* cb = CodeCache::find_blob(entry);
 194   RuntimeStub* rs =(RuntimeStub *)cb;
 195   assert(rs != NULL && rs->is_runtime_stub(), "not a runtime stub");
 196   return rs->name();
 197 #else
 198   // Fast implementation for product mode (maybe it should be inlined too)
 199   return "runtime stub";
 200 #endif
 201 }
 202 
 203 
 204 //=============================================================================
 205 // Opto compiler runtime routines
 206 //=============================================================================
 207 
 208 
 209 //=============================allocation======================================
 210 // We failed the fast-path allocation.  Now we need to do a scavenge or GC
 211 // and try allocation again.
 212 
 213 void OptoRuntime::new_store_pre_barrier(JavaThread* thread) {
 214   // After any safepoint, just before going back to compiled code,
 215   // we inform the GC that we will be doing initializing writes to
 216   // this object in the future without emitting card-marks, so
 217   // GC may take any compensating steps.
 218   // NOTE: Keep this code consistent with GraphKit::store_barrier.
 219 
 220   oop new_obj = thread->vm_result();
 221   if (new_obj == NULL)  return;
 222 
 223   assert(Universe::heap()->can_elide_tlab_store_barriers(),
 224          "compiler must check this first");
 225   // GC may decide to give back a safer copy of new_obj.
 226   new_obj = Universe::heap()->new_store_pre_barrier(thread, new_obj);
 227   thread->set_vm_result(new_obj);
 228 }
 229 
 230 // object allocation
 231 JRT_BLOCK_ENTRY(void, OptoRuntime::new_instance_C(klassOopDesc* klass, JavaThread* thread))
 232   JRT_BLOCK;
 233 #ifndef PRODUCT
 234   SharedRuntime::_new_instance_ctr++;         // new instance requires GC
 235 #endif
 236   assert(check_compiled_frame(thread), "incorrect caller");
 237 
 238   // These checks are cheap to make and support reflective allocation.
 239   int lh = Klass::cast(klass)->layout_helper();
 240   if (Klass::layout_helper_needs_slow_path(lh)
 241       || !instanceKlass::cast(klass)->is_initialized()) {
 242     KlassHandle kh(THREAD, klass);
 243     kh->check_valid_for_instantiation(false, THREAD);
 244     if (!HAS_PENDING_EXCEPTION) {
 245       instanceKlass::cast(kh())->initialize(THREAD);
 246     }
 247     if (!HAS_PENDING_EXCEPTION) {
 248       klass = kh();
 249     } else {
 250       klass = NULL;
 251     }
 252   }
 253 
 254   if (klass != NULL) {
 255     // Scavenge and allocate an instance.
 256     oop result = instanceKlass::cast(klass)->allocate_instance(THREAD);
 257     thread->set_vm_result(result);
 258 
 259     // Pass oops back through thread local storage.  Our apparent type to Java
 260     // is that we return an oop, but we can block on exit from this routine and
 261     // a GC can trash the oop in C's return register.  The generated stub will
 262     // fetch the oop from TLS after any possible GC.
 263   }
 264 
 265   deoptimize_caller_frame(thread, HAS_PENDING_EXCEPTION);
 266   JRT_BLOCK_END;
 267 
 268   if (GraphKit::use_ReduceInitialCardMarks()) {
 269     // inform GC that we won't do card marks for initializing writes.
 270     new_store_pre_barrier(thread);
 271   }
 272 JRT_END
 273 
 274 
 275 // array allocation
 276 JRT_BLOCK_ENTRY(void, OptoRuntime::new_array_C(klassOopDesc* array_type, int len, JavaThread *thread))
 277   JRT_BLOCK;
 278 #ifndef PRODUCT
 279   SharedRuntime::_new_array_ctr++;            // new array requires GC
 280 #endif
 281   assert(check_compiled_frame(thread), "incorrect caller");
 282 
 283   // Scavenge and allocate an instance.
 284   oop result;
 285 
 286   if (Klass::cast(array_type)->oop_is_typeArray()) {
 287     // The oopFactory likes to work with the element type.
 288     // (We could bypass the oopFactory, since it doesn't add much value.)
 289     BasicType elem_type = typeArrayKlass::cast(array_type)->element_type();
 290     result = oopFactory::new_typeArray(elem_type, len, THREAD);
 291   } else {
 292     // Although the oopFactory likes to work with the elem_type,
 293     // the compiler prefers the array_type, since it must already have
 294     // that latter value in hand for the fast path.
 295     klassOopDesc* elem_type = objArrayKlass::cast(array_type)->element_klass();
 296     result = oopFactory::new_objArray(elem_type, len, THREAD);
 297   }
 298 
 299   // Pass oops back through thread local storage.  Our apparent type to Java
 300   // is that we return an oop, but we can block on exit from this routine and
 301   // a GC can trash the oop in C's return register.  The generated stub will
 302   // fetch the oop from TLS after any possible GC.
 303   deoptimize_caller_frame(thread, HAS_PENDING_EXCEPTION);
 304   thread->set_vm_result(result);
 305   JRT_BLOCK_END;
 306 
 307   if (GraphKit::use_ReduceInitialCardMarks()) {
 308     // inform GC that we won't do card marks for initializing writes.
 309     new_store_pre_barrier(thread);
 310   }
 311 JRT_END
 312 
 313 // array allocation without zeroing
 314 JRT_BLOCK_ENTRY(void, OptoRuntime::new_array_nozero_C(klassOopDesc* array_type, int len, JavaThread *thread))
 315   JRT_BLOCK;
 316 #ifndef PRODUCT
 317   SharedRuntime::_new_array_ctr++;            // new array requires GC
 318 #endif
 319   assert(check_compiled_frame(thread), "incorrect caller");
 320 
 321   // Scavenge and allocate an instance.
 322   oop result;
 323 
 324   assert(Klass::cast(array_type)->oop_is_typeArray(), "should be called only for type array");
 325   // The oopFactory likes to work with the element type.
 326   BasicType elem_type = typeArrayKlass::cast(array_type)->element_type();
 327   result = oopFactory::new_typeArray_nozero(elem_type, len, THREAD);
 328 
 329   // Pass oops back through thread local storage.  Our apparent type to Java
 330   // is that we return an oop, but we can block on exit from this routine and
 331   // a GC can trash the oop in C's return register.  The generated stub will
 332   // fetch the oop from TLS after any possible GC.
 333   deoptimize_caller_frame(thread, HAS_PENDING_EXCEPTION);
 334   thread->set_vm_result(result);
 335   JRT_BLOCK_END;
 336 
 337   if (GraphKit::use_ReduceInitialCardMarks()) {
 338     // inform GC that we won't do card marks for initializing writes.
 339     new_store_pre_barrier(thread);
 340   }
 341 JRT_END
 342 
 343 // Note: multianewarray for one dimension is handled inline by GraphKit::new_array.
 344 
 345 // multianewarray for 2 dimensions
 346 JRT_ENTRY(void, OptoRuntime::multianewarray2_C(klassOopDesc* elem_type, int len1, int len2, JavaThread *thread))
 347 #ifndef PRODUCT
 348   SharedRuntime::_multi2_ctr++;                // multianewarray for 1 dimension
 349 #endif
 350   assert(check_compiled_frame(thread), "incorrect caller");
 351   assert(oop(elem_type)->is_klass(), "not a class");
 352   jint dims[2];
 353   dims[0] = len1;
 354   dims[1] = len2;
 355   oop obj = arrayKlass::cast(elem_type)->multi_allocate(2, dims, THREAD);
 356   deoptimize_caller_frame(thread, HAS_PENDING_EXCEPTION);
 357   thread->set_vm_result(obj);
 358 JRT_END
 359 
 360 // multianewarray for 3 dimensions
 361 JRT_ENTRY(void, OptoRuntime::multianewarray3_C(klassOopDesc* elem_type, int len1, int len2, int len3, JavaThread *thread))
 362 #ifndef PRODUCT
 363   SharedRuntime::_multi3_ctr++;                // multianewarray for 1 dimension
 364 #endif
 365   assert(check_compiled_frame(thread), "incorrect caller");
 366   assert(oop(elem_type)->is_klass(), "not a class");
 367   jint dims[3];
 368   dims[0] = len1;
 369   dims[1] = len2;
 370   dims[2] = len3;
 371   oop obj = arrayKlass::cast(elem_type)->multi_allocate(3, dims, THREAD);
 372   deoptimize_caller_frame(thread, HAS_PENDING_EXCEPTION);
 373   thread->set_vm_result(obj);
 374 JRT_END
 375 
 376 // multianewarray for 4 dimensions
 377 JRT_ENTRY(void, OptoRuntime::multianewarray4_C(klassOopDesc* elem_type, int len1, int len2, int len3, int len4, JavaThread *thread))
 378 #ifndef PRODUCT
 379   SharedRuntime::_multi4_ctr++;                // multianewarray for 1 dimension
 380 #endif
 381   assert(check_compiled_frame(thread), "incorrect caller");
 382   assert(oop(elem_type)->is_klass(), "not a class");
 383   jint dims[4];
 384   dims[0] = len1;
 385   dims[1] = len2;
 386   dims[2] = len3;
 387   dims[3] = len4;
 388   oop obj = arrayKlass::cast(elem_type)->multi_allocate(4, dims, THREAD);
 389   deoptimize_caller_frame(thread, HAS_PENDING_EXCEPTION);
 390   thread->set_vm_result(obj);
 391 JRT_END
 392 
 393 // multianewarray for 5 dimensions
 394 JRT_ENTRY(void, OptoRuntime::multianewarray5_C(klassOopDesc* elem_type, int len1, int len2, int len3, int len4, int len5, JavaThread *thread))
 395 #ifndef PRODUCT
 396   SharedRuntime::_multi5_ctr++;                // multianewarray for 1 dimension
 397 #endif
 398   assert(check_compiled_frame(thread), "incorrect caller");
 399   assert(oop(elem_type)->is_klass(), "not a class");
 400   jint dims[5];
 401   dims[0] = len1;
 402   dims[1] = len2;
 403   dims[2] = len3;
 404   dims[3] = len4;
 405   dims[4] = len5;
 406   oop obj = arrayKlass::cast(elem_type)->multi_allocate(5, dims, THREAD);
 407   deoptimize_caller_frame(thread, HAS_PENDING_EXCEPTION);
 408   thread->set_vm_result(obj);
 409 JRT_END
 410 
 411 JRT_ENTRY(void, OptoRuntime::multianewarrayN_C(klassOopDesc* elem_type, arrayOopDesc* dims, JavaThread *thread))
 412   assert(check_compiled_frame(thread), "incorrect caller");
 413   assert(oop(elem_type)->is_klass(), "not a class");
 414   assert(oop(dims)->is_typeArray(), "not an array");
 415 
 416   ResourceMark rm;
 417   jint len = dims->length();
 418   assert(len > 0, "Dimensions array should contain data");
 419   jint *j_dims = typeArrayOop(dims)->int_at_addr(0);
 420   jint *c_dims = NEW_RESOURCE_ARRAY(jint, len);
 421   Copy::conjoint_jints_atomic(j_dims, c_dims, len);
 422 
 423   oop obj = arrayKlass::cast(elem_type)->multi_allocate(len, c_dims, THREAD);
 424   deoptimize_caller_frame(thread, HAS_PENDING_EXCEPTION);
 425   thread->set_vm_result(obj);
 426 JRT_END
 427 
 428 
 429 const TypeFunc *OptoRuntime::new_instance_Type() {
 430   // create input type (domain)
 431   const Type **fields = TypeTuple::fields(1);
 432   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL; // Klass to be allocated
 433   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+1, fields);
 434 
 435   // create result type (range)
 436   fields = TypeTuple::fields(1);
 437   fields[TypeFunc::Parms+0] = TypeRawPtr::NOTNULL; // Returned oop
 438 
 439   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+1, fields);
 440 
 441   return TypeFunc::make(domain, range);
 442 }
 443 
 444 
 445 const TypeFunc *OptoRuntime::athrow_Type() {
 446   // create input type (domain)
 447   const Type **fields = TypeTuple::fields(1);
 448   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL; // Klass to be allocated
 449   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+1, fields);
 450 
 451   // create result type (range)
 452   fields = TypeTuple::fields(0);
 453 
 454   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0, fields);
 455 
 456   return TypeFunc::make(domain, range);
 457 }
 458 
 459 
 460 const TypeFunc *OptoRuntime::new_array_Type() {
 461   // create input type (domain)
 462   const Type **fields = TypeTuple::fields(2);
 463   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL;   // element klass
 464   fields[TypeFunc::Parms+1] = TypeInt::INT;       // array size
 465   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
 466 
 467   // create result type (range)
 468   fields = TypeTuple::fields(1);
 469   fields[TypeFunc::Parms+0] = TypeRawPtr::NOTNULL; // Returned oop
 470 
 471   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+1, fields);
 472 
 473   return TypeFunc::make(domain, range);
 474 }
 475 
 476 const TypeFunc *OptoRuntime::multianewarray_Type(int ndim) {
 477   // create input type (domain)
 478   const int nargs = ndim + 1;
 479   const Type **fields = TypeTuple::fields(nargs);
 480   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL;   // element klass
 481   for( int i = 1; i < nargs; i++ )
 482     fields[TypeFunc::Parms + i] = TypeInt::INT;       // array size
 483   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+nargs, fields);
 484 
 485   // create result type (range)
 486   fields = TypeTuple::fields(1);
 487   fields[TypeFunc::Parms+0] = TypeRawPtr::NOTNULL; // Returned oop
 488   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+1, fields);
 489 
 490   return TypeFunc::make(domain, range);
 491 }
 492 
 493 const TypeFunc *OptoRuntime::multianewarray2_Type() {
 494   return multianewarray_Type(2);
 495 }
 496 
 497 const TypeFunc *OptoRuntime::multianewarray3_Type() {
 498   return multianewarray_Type(3);
 499 }
 500 
 501 const TypeFunc *OptoRuntime::multianewarray4_Type() {
 502   return multianewarray_Type(4);
 503 }
 504 
 505 const TypeFunc *OptoRuntime::multianewarray5_Type() {
 506   return multianewarray_Type(5);
 507 }
 508 
 509 const TypeFunc *OptoRuntime::multianewarrayN_Type() {
 510   // create input type (domain)
 511   const Type **fields = TypeTuple::fields(2);
 512   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL;   // element klass
 513   fields[TypeFunc::Parms+1] = TypeInstPtr::NOTNULL;   // array of dim sizes
 514   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
 515 
 516   // create result type (range)
 517   fields = TypeTuple::fields(1);
 518   fields[TypeFunc::Parms+0] = TypeRawPtr::NOTNULL; // Returned oop
 519   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+1, fields);
 520 
 521   return TypeFunc::make(domain, range);
 522 }
 523 
 524 const TypeFunc *OptoRuntime::g1_wb_pre_Type() {
 525   const Type **fields = TypeTuple::fields(2);
 526   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL; // original field value
 527   fields[TypeFunc::Parms+1] = TypeRawPtr::NOTNULL; // thread
 528   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
 529 
 530   // create result type (range)
 531   fields = TypeTuple::fields(0);
 532   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0, fields);
 533 
 534   return TypeFunc::make(domain, range);
 535 }
 536 
 537 const TypeFunc *OptoRuntime::g1_wb_post_Type() {
 538 
 539   const Type **fields = TypeTuple::fields(2);
 540   fields[TypeFunc::Parms+0] = TypeRawPtr::NOTNULL;  // Card addr
 541   fields[TypeFunc::Parms+1] = TypeRawPtr::NOTNULL;  // thread
 542   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
 543 
 544   // create result type (range)
 545   fields = TypeTuple::fields(0);
 546   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms, fields);
 547 
 548   return TypeFunc::make(domain, range);
 549 }
 550 
 551 const TypeFunc *OptoRuntime::uncommon_trap_Type() {
 552   // create input type (domain)
 553   const Type **fields = TypeTuple::fields(1);
 554   // Symbol* name of class to be loaded
 555   fields[TypeFunc::Parms+0] = TypeInt::INT;
 556   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+1, fields);
 557 
 558   // create result type (range)
 559   fields = TypeTuple::fields(0);
 560   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0, fields);
 561 
 562   return TypeFunc::make(domain, range);
 563 }
 564 
 565 # ifdef ENABLE_ZAP_DEAD_LOCALS
 566 // Type used for stub generation for zap_dead_locals.
 567 // No inputs or outputs
 568 const TypeFunc *OptoRuntime::zap_dead_locals_Type() {
 569   // create input type (domain)
 570   const Type **fields = TypeTuple::fields(0);
 571   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms,fields);
 572 
 573   // create result type (range)
 574   fields = TypeTuple::fields(0);
 575   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms,fields);
 576 
 577   return TypeFunc::make(domain,range);
 578 }
 579 # endif
 580 
 581 
 582 //-----------------------------------------------------------------------------
 583 // Monitor Handling
 584 const TypeFunc *OptoRuntime::complete_monitor_enter_Type() {
 585   // create input type (domain)
 586   const Type **fields = TypeTuple::fields(2);
 587   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL;  // Object to be Locked
 588   fields[TypeFunc::Parms+1] = TypeRawPtr::BOTTOM;   // Address of stack location for lock
 589   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2,fields);
 590 
 591   // create result type (range)
 592   fields = TypeTuple::fields(0);
 593 
 594   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0,fields);
 595 
 596   return TypeFunc::make(domain,range);
 597 }
 598 
 599 
 600 //-----------------------------------------------------------------------------
 601 const TypeFunc *OptoRuntime::complete_monitor_exit_Type() {
 602   // create input type (domain)
 603   const Type **fields = TypeTuple::fields(2);
 604   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL;  // Object to be Locked
 605   fields[TypeFunc::Parms+1] = TypeRawPtr::BOTTOM;   // Address of stack location for lock
 606   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2,fields);
 607 
 608   // create result type (range)
 609   fields = TypeTuple::fields(0);
 610 
 611   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0,fields);
 612 
 613   return TypeFunc::make(domain,range);
 614 }
 615 
 616 const TypeFunc* OptoRuntime::flush_windows_Type() {
 617   // create input type (domain)
 618   const Type** fields = TypeTuple::fields(1);
 619   fields[TypeFunc::Parms+0] = NULL; // void
 620   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms, fields);
 621 
 622   // create result type
 623   fields = TypeTuple::fields(1);
 624   fields[TypeFunc::Parms+0] = NULL; // void
 625   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms, fields);
 626 
 627   return TypeFunc::make(domain, range);
 628 }
 629 
 630 const TypeFunc* OptoRuntime::l2f_Type() {
 631   // create input type (domain)
 632   const Type **fields = TypeTuple::fields(2);
 633   fields[TypeFunc::Parms+0] = TypeLong::LONG;
 634   fields[TypeFunc::Parms+1] = Type::HALF;
 635   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
 636 
 637   // create result type (range)
 638   fields = TypeTuple::fields(1);
 639   fields[TypeFunc::Parms+0] = Type::FLOAT;
 640   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+1, fields);
 641 
 642   return TypeFunc::make(domain, range);
 643 }
 644 
 645 const TypeFunc* OptoRuntime::modf_Type() {
 646   const Type **fields = TypeTuple::fields(2);
 647   fields[TypeFunc::Parms+0] = Type::FLOAT;
 648   fields[TypeFunc::Parms+1] = Type::FLOAT;
 649   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
 650 
 651   // create result type (range)
 652   fields = TypeTuple::fields(1);
 653   fields[TypeFunc::Parms+0] = Type::FLOAT;
 654 
 655   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+1, fields);
 656 
 657   return TypeFunc::make(domain, range);
 658 }
 659 
 660 const TypeFunc *OptoRuntime::Math_D_D_Type() {
 661   // create input type (domain)
 662   const Type **fields = TypeTuple::fields(2);
 663   // Symbol* name of class to be loaded
 664   fields[TypeFunc::Parms+0] = Type::DOUBLE;
 665   fields[TypeFunc::Parms+1] = Type::HALF;
 666   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
 667 
 668   // create result type (range)
 669   fields = TypeTuple::fields(2);
 670   fields[TypeFunc::Parms+0] = Type::DOUBLE;
 671   fields[TypeFunc::Parms+1] = Type::HALF;
 672   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+2, fields);
 673 
 674   return TypeFunc::make(domain, range);
 675 }
 676 
 677 const TypeFunc* OptoRuntime::Math_DD_D_Type() {
 678   const Type **fields = TypeTuple::fields(4);
 679   fields[TypeFunc::Parms+0] = Type::DOUBLE;
 680   fields[TypeFunc::Parms+1] = Type::HALF;
 681   fields[TypeFunc::Parms+2] = Type::DOUBLE;
 682   fields[TypeFunc::Parms+3] = Type::HALF;
 683   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+4, fields);
 684 
 685   // create result type (range)
 686   fields = TypeTuple::fields(2);
 687   fields[TypeFunc::Parms+0] = Type::DOUBLE;
 688   fields[TypeFunc::Parms+1] = Type::HALF;
 689   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+2, fields);
 690 
 691   return TypeFunc::make(domain, range);
 692 }
 693 
 694 //-------------- currentTimeMillis
 695 
 696 const TypeFunc* OptoRuntime::current_time_millis_Type() {
 697   // create input type (domain)
 698   const Type **fields = TypeTuple::fields(0);
 699   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+0, fields);
 700 
 701   // create result type (range)
 702   fields = TypeTuple::fields(2);
 703   fields[TypeFunc::Parms+0] = TypeLong::LONG;
 704   fields[TypeFunc::Parms+1] = Type::HALF;
 705   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+2, fields);
 706 
 707   return TypeFunc::make(domain, range);
 708 }
 709 
 710 // arraycopy stub variations:
 711 enum ArrayCopyType {
 712   ac_fast,                      // void(ptr, ptr, size_t)
 713   ac_checkcast,                 //  int(ptr, ptr, size_t, size_t, ptr)
 714   ac_slow,                      // void(ptr, int, ptr, int, int)
 715   ac_generic                    //  int(ptr, int, ptr, int, int)
 716 };
 717 
 718 static const TypeFunc* make_arraycopy_Type(ArrayCopyType act) {
 719   // create input type (domain)
 720   int num_args      = (act == ac_fast ? 3 : 5);
 721   int num_size_args = (act == ac_fast ? 1 : act == ac_checkcast ? 2 : 0);
 722   int argcnt = num_args;
 723   LP64_ONLY(argcnt += num_size_args); // halfwords for lengths
 724   const Type** fields = TypeTuple::fields(argcnt);
 725   int argp = TypeFunc::Parms;
 726   fields[argp++] = TypePtr::NOTNULL;    // src
 727   if (num_size_args == 0) {
 728     fields[argp++] = TypeInt::INT;      // src_pos
 729   }
 730   fields[argp++] = TypePtr::NOTNULL;    // dest
 731   if (num_size_args == 0) {
 732     fields[argp++] = TypeInt::INT;      // dest_pos
 733     fields[argp++] = TypeInt::INT;      // length
 734   }
 735   while (num_size_args-- > 0) {
 736     fields[argp++] = TypeX_X;               // size in whatevers (size_t)
 737     LP64_ONLY(fields[argp++] = Type::HALF); // other half of long length
 738   }
 739   if (act == ac_checkcast) {
 740     fields[argp++] = TypePtr::NOTNULL;  // super_klass
 741   }
 742   assert(argp == TypeFunc::Parms+argcnt, "correct decoding of act");
 743   const TypeTuple* domain = TypeTuple::make(TypeFunc::Parms+argcnt, fields);
 744 
 745   // create result type if needed
 746   int retcnt = (act == ac_checkcast || act == ac_generic ? 1 : 0);
 747   fields = TypeTuple::fields(1);
 748   if (retcnt == 0)
 749     fields[TypeFunc::Parms+0] = NULL; // void
 750   else
 751     fields[TypeFunc::Parms+0] = TypeInt::INT; // status result, if needed
 752   const TypeTuple* range = TypeTuple::make(TypeFunc::Parms+retcnt, fields);
 753   return TypeFunc::make(domain, range);
 754 }
 755 
 756 const TypeFunc* OptoRuntime::fast_arraycopy_Type() {
 757   // This signature is simple:  Two base pointers and a size_t.
 758   return make_arraycopy_Type(ac_fast);
 759 }
 760 
 761 const TypeFunc* OptoRuntime::checkcast_arraycopy_Type() {
 762   // An extension of fast_arraycopy_Type which adds type checking.
 763   return make_arraycopy_Type(ac_checkcast);
 764 }
 765 
 766 const TypeFunc* OptoRuntime::slow_arraycopy_Type() {
 767   // This signature is exactly the same as System.arraycopy.
 768   // There are no intptr_t (int/long) arguments.
 769   return make_arraycopy_Type(ac_slow);
 770 }
 771 
 772 const TypeFunc* OptoRuntime::generic_arraycopy_Type() {
 773   // This signature is like System.arraycopy, except that it returns status.
 774   return make_arraycopy_Type(ac_generic);
 775 }
 776 
 777 
 778 const TypeFunc* OptoRuntime::array_fill_Type() {
 779   // create input type (domain): pointer, int, size_t
 780   const Type** fields = TypeTuple::fields(3 LP64_ONLY( + 1));
 781   int argp = TypeFunc::Parms;
 782   fields[argp++] = TypePtr::NOTNULL;
 783   fields[argp++] = TypeInt::INT;
 784   fields[argp++] = TypeX_X;               // size in whatevers (size_t)
 785   LP64_ONLY(fields[argp++] = Type::HALF); // other half of long length
 786   const TypeTuple *domain = TypeTuple::make(argp, fields);
 787 
 788   // create result type
 789   fields = TypeTuple::fields(1);
 790   fields[TypeFunc::Parms+0] = NULL; // void
 791   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms, fields);
 792 
 793   return TypeFunc::make(domain, range);
 794 }
 795 
 796 //------------- Interpreter state access for on stack replacement
 797 const TypeFunc* OptoRuntime::osr_end_Type() {
 798   // create input type (domain)
 799   const Type **fields = TypeTuple::fields(1);
 800   fields[TypeFunc::Parms+0] = TypeRawPtr::BOTTOM; // OSR temp buf
 801   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+1, fields);
 802 
 803   // create result type
 804   fields = TypeTuple::fields(1);
 805   // fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL; // locked oop
 806   fields[TypeFunc::Parms+0] = NULL; // void
 807   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms, fields);
 808   return TypeFunc::make(domain, range);
 809 }
 810 
 811 //-------------- methodData update helpers
 812 
 813 const TypeFunc* OptoRuntime::profile_receiver_type_Type() {
 814   // create input type (domain)
 815   const Type **fields = TypeTuple::fields(2);
 816   fields[TypeFunc::Parms+0] = TypeAryPtr::NOTNULL;    // methodData pointer
 817   fields[TypeFunc::Parms+1] = TypeInstPtr::BOTTOM;    // receiver oop
 818   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2, fields);
 819 
 820   // create result type
 821   fields = TypeTuple::fields(1);
 822   fields[TypeFunc::Parms+0] = NULL; // void
 823   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms, fields);
 824   return TypeFunc::make(domain,range);
 825 }
 826 
 827 JRT_LEAF(void, OptoRuntime::profile_receiver_type_C(DataLayout* data, oopDesc* receiver))
 828   if (receiver == NULL) return;
 829   klassOop receiver_klass = receiver->klass();
 830 
 831   intptr_t* mdp = ((intptr_t*)(data)) + DataLayout::header_size_in_cells();
 832   int empty_row = -1;           // free row, if any is encountered
 833 
 834   // ReceiverTypeData* vc = new ReceiverTypeData(mdp);
 835   for (uint row = 0; row < ReceiverTypeData::row_limit(); row++) {
 836     // if (vc->receiver(row) == receiver_klass)
 837     int receiver_off = ReceiverTypeData::receiver_cell_index(row);
 838     intptr_t row_recv = *(mdp + receiver_off);
 839     if (row_recv == (intptr_t) receiver_klass) {
 840       // vc->set_receiver_count(row, vc->receiver_count(row) + DataLayout::counter_increment);
 841       int count_off = ReceiverTypeData::receiver_count_cell_index(row);
 842       *(mdp + count_off) += DataLayout::counter_increment;
 843       return;
 844     } else if (row_recv == 0) {
 845       // else if (vc->receiver(row) == NULL)
 846       empty_row = (int) row;
 847     }
 848   }
 849 
 850   if (empty_row != -1) {
 851     int receiver_off = ReceiverTypeData::receiver_cell_index(empty_row);
 852     // vc->set_receiver(empty_row, receiver_klass);
 853     *(mdp + receiver_off) = (intptr_t) receiver_klass;
 854     // vc->set_receiver_count(empty_row, DataLayout::counter_increment);
 855     int count_off = ReceiverTypeData::receiver_count_cell_index(empty_row);
 856     *(mdp + count_off) = DataLayout::counter_increment;
 857   } else {
 858     // Receiver did not match any saved receiver and there is no empty row for it.
 859     // Increment total counter to indicate polymorphic case.
 860     intptr_t* count_p = (intptr_t*)(((byte*)(data)) + in_bytes(CounterData::count_offset()));
 861     *count_p += DataLayout::counter_increment;
 862   }
 863 JRT_END
 864 
 865 //-----------------------------------------------------------------------------
 866 // implicit exception support.
 867 
 868 static void report_null_exception_in_code_cache(address exception_pc) {
 869   ResourceMark rm;
 870   CodeBlob* n = CodeCache::find_blob(exception_pc);
 871   if (n != NULL) {
 872     tty->print_cr("#");
 873     tty->print_cr("# HotSpot Runtime Error, null exception in generated code");
 874     tty->print_cr("#");
 875     tty->print_cr("# pc where exception happened = " INTPTR_FORMAT, exception_pc);
 876 
 877     if (n->is_nmethod()) {
 878       methodOop method = ((nmethod*)n)->method();
 879       tty->print_cr("# Method where it happened %s.%s ", Klass::cast(method->method_holder())->name()->as_C_string(), method->name()->as_C_string());
 880       tty->print_cr("#");
 881       if (ShowMessageBoxOnError && UpdateHotSpotCompilerFileOnError) {
 882         const char* title    = "HotSpot Runtime Error";
 883         const char* question = "Do you want to exclude compilation of this method in future runs?";
 884         if (os::message_box(title, question)) {
 885           CompilerOracle::append_comment_to_file("");
 886           CompilerOracle::append_comment_to_file("Null exception in compiled code resulted in the following exclude");
 887           CompilerOracle::append_comment_to_file("");
 888           CompilerOracle::append_exclude_to_file(method);
 889           tty->print_cr("#");
 890           tty->print_cr("# %s has been updated to exclude the specified method", CompileCommandFile);
 891           tty->print_cr("#");
 892         }
 893       }
 894       fatal("Implicit null exception happened in compiled method");
 895     } else {
 896       n->print();
 897       fatal("Implicit null exception happened in generated stub");
 898     }
 899   }
 900   fatal("Implicit null exception at wrong place");
 901 }
 902 
 903 
 904 //-------------------------------------------------------------------------------------
 905 // register policy
 906 
 907 bool OptoRuntime::is_callee_saved_register(MachRegisterNumbers reg) {
 908   assert(reg >= 0 && reg < _last_Mach_Reg, "must be a machine register");
 909   switch (register_save_policy[reg]) {
 910     case 'C': return false; //SOC
 911     case 'E': return true ; //SOE
 912     case 'N': return false; //NS
 913     case 'A': return false; //AS
 914   }
 915   ShouldNotReachHere();
 916   return false;
 917 }
 918 
 919 //-----------------------------------------------------------------------
 920 // Exceptions
 921 //
 922 
 923 static void trace_exception(oop exception_oop, address exception_pc, const char* msg) PRODUCT_RETURN;
 924 
 925 // The method is an entry that is always called by a C++ method not
 926 // directly from compiled code. Compiled code will call the C++ method following.
 927 // We can't allow async exception to be installed during  exception processing.
 928 JRT_ENTRY_NO_ASYNC(address, OptoRuntime::handle_exception_C_helper(JavaThread* thread, nmethod* &nm))
 929 
 930   // Do not confuse exception_oop with pending_exception. The exception_oop
 931   // is only used to pass arguments into the method. Not for general
 932   // exception handling.  DO NOT CHANGE IT to use pending_exception, since
 933   // the runtime stubs checks this on exit.
 934   assert(thread->exception_oop() != NULL, "exception oop is found");
 935   address handler_address = NULL;
 936 
 937   Handle exception(thread, thread->exception_oop());
 938 
 939   if (TraceExceptions) {
 940     trace_exception(exception(), thread->exception_pc(), "");
 941   }
 942   // for AbortVMOnException flag
 943   NOT_PRODUCT(Exceptions::debug_check_abort(exception));
 944 
 945   #ifdef ASSERT
 946     if (!(exception->is_a(SystemDictionary::Throwable_klass()))) {
 947       // should throw an exception here
 948       ShouldNotReachHere();
 949     }
 950   #endif
 951 
 952 
 953   // new exception handling: this method is entered only from adapters
 954   // exceptions from compiled java methods are handled in compiled code
 955   // using rethrow node
 956 
 957   address pc = thread->exception_pc();
 958   nm = CodeCache::find_nmethod(pc);
 959   assert(nm != NULL, "No NMethod found");
 960   if (nm->is_native_method()) {
 961     fatal("Native mathod should not have path to exception handling");
 962   } else {
 963     // we are switching to old paradigm: search for exception handler in caller_frame
 964     // instead in exception handler of caller_frame.sender()
 965 
 966     if (JvmtiExport::can_post_on_exceptions()) {
 967       // "Full-speed catching" is not necessary here,
 968       // since we're notifying the VM on every catch.
 969       // Force deoptimization and the rest of the lookup
 970       // will be fine.
 971       deoptimize_caller_frame(thread, true);
 972     }
 973 
 974     // Check the stack guard pages.  If enabled, look for handler in this frame;
 975     // otherwise, forcibly unwind the frame.
 976     //
 977     // 4826555: use default current sp for reguard_stack instead of &nm: it's more accurate.
 978     bool force_unwind = !thread->reguard_stack();
 979     bool deopting = false;
 980     if (nm->is_deopt_pc(pc)) {
 981       deopting = true;
 982       RegisterMap map(thread, false);
 983       frame deoptee = thread->last_frame().sender(&map);
 984       assert(deoptee.is_deoptimized_frame(), "must be deopted");
 985       // Adjust the pc back to the original throwing pc
 986       pc = deoptee.pc();
 987     }
 988 
 989     // If we are forcing an unwind because of stack overflow then deopt is
 990     // irrelevant sice we are throwing the frame away anyway.
 991 
 992     if (deopting && !force_unwind) {
 993       handler_address = SharedRuntime::deopt_blob()->unpack_with_exception();
 994     } else {
 995 
 996       handler_address =
 997         force_unwind ? NULL : nm->handler_for_exception_and_pc(exception, pc);
 998 
 999       if (handler_address == NULL) {
1000         handler_address = SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, force_unwind, true);
1001         assert (handler_address != NULL, "must have compiled handler");
1002         // Update the exception cache only when the unwind was not forced.
1003         if (!force_unwind) {
1004           nm->add_handler_for_exception_and_pc(exception,pc,handler_address);
1005         }
1006       } else {
1007         assert(handler_address == SharedRuntime::compute_compiled_exc_handler(nm, pc, exception, force_unwind, true), "Must be the same");
1008       }
1009     }
1010 
1011     thread->set_exception_pc(pc);
1012     thread->set_exception_handler_pc(handler_address);
1013 
1014     // Check if the exception PC is a MethodHandle call site.
1015     thread->set_is_method_handle_return(nm->is_method_handle_return(pc));
1016   }
1017 
1018   // Restore correct return pc.  Was saved above.
1019   thread->set_exception_oop(exception());
1020   return handler_address;
1021 
1022 JRT_END
1023 
1024 // We are entering here from exception_blob
1025 // If there is a compiled exception handler in this method, we will continue there;
1026 // otherwise we will unwind the stack and continue at the caller of top frame method
1027 // Note we enter without the usual JRT wrapper. We will call a helper routine that
1028 // will do the normal VM entry. We do it this way so that we can see if the nmethod
1029 // we looked up the handler for has been deoptimized in the meantime. If it has been
1030 // we must not use the handler and instread return the deopt blob.
1031 address OptoRuntime::handle_exception_C(JavaThread* thread) {
1032 //
1033 // We are in Java not VM and in debug mode we have a NoHandleMark
1034 //
1035 #ifndef PRODUCT
1036   SharedRuntime::_find_handler_ctr++;          // find exception handler
1037 #endif
1038   debug_only(NoHandleMark __hm;)
1039   nmethod* nm = NULL;
1040   address handler_address = NULL;
1041   {
1042     // Enter the VM
1043 
1044     ResetNoHandleMark rnhm;
1045     handler_address = handle_exception_C_helper(thread, nm);
1046   }
1047 
1048   // Back in java: Use no oops, DON'T safepoint
1049 
1050   // Now check to see if the handler we are returning is in a now
1051   // deoptimized frame
1052 
1053   if (nm != NULL) {
1054     RegisterMap map(thread, false);
1055     frame caller = thread->last_frame().sender(&map);
1056 #ifdef ASSERT
1057     assert(caller.is_compiled_frame(), "must be");
1058 #endif // ASSERT
1059     if (caller.is_deoptimized_frame()) {
1060       handler_address = SharedRuntime::deopt_blob()->unpack_with_exception();
1061     }
1062   }
1063   return handler_address;
1064 }
1065 
1066 //------------------------------rethrow----------------------------------------
1067 // We get here after compiled code has executed a 'RethrowNode'.  The callee
1068 // is either throwing or rethrowing an exception.  The callee-save registers
1069 // have been restored, synchronized objects have been unlocked and the callee
1070 // stack frame has been removed.  The return address was passed in.
1071 // Exception oop is passed as the 1st argument.  This routine is then called
1072 // from the stub.  On exit, we know where to jump in the caller's code.
1073 // After this C code exits, the stub will pop his frame and end in a jump
1074 // (instead of a return).  We enter the caller's default handler.
1075 //
1076 // This must be JRT_LEAF:
1077 //     - caller will not change its state as we cannot block on exit,
1078 //       therefore raw_exception_handler_for_return_address is all it takes
1079 //       to handle deoptimized blobs
1080 //
1081 // However, there needs to be a safepoint check in the middle!  So compiled
1082 // safepoints are completely watertight.
1083 //
1084 // Thus, it cannot be a leaf since it contains the No_GC_Verifier.
1085 //
1086 // *THIS IS NOT RECOMMENDED PROGRAMMING STYLE*
1087 //
1088 address OptoRuntime::rethrow_C(oopDesc* exception, JavaThread* thread, address ret_pc) {
1089 #ifndef PRODUCT
1090   SharedRuntime::_rethrow_ctr++;               // count rethrows
1091 #endif
1092   assert (exception != NULL, "should have thrown a NULLPointerException");
1093 #ifdef ASSERT
1094   if (!(exception->is_a(SystemDictionary::Throwable_klass()))) {
1095     // should throw an exception here
1096     ShouldNotReachHere();
1097   }
1098 #endif
1099 
1100   thread->set_vm_result(exception);
1101   // Frame not compiled (handles deoptimization blob)
1102   return SharedRuntime::raw_exception_handler_for_return_address(thread, ret_pc);
1103 }
1104 
1105 
1106 const TypeFunc *OptoRuntime::rethrow_Type() {
1107   // create input type (domain)
1108   const Type **fields = TypeTuple::fields(1);
1109   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL; // Exception oop
1110   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+1,fields);
1111 
1112   // create result type (range)
1113   fields = TypeTuple::fields(1);
1114   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL; // Exception oop
1115   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+1, fields);
1116 
1117   return TypeFunc::make(domain, range);
1118 }
1119 
1120 
1121 void OptoRuntime::deoptimize_caller_frame(JavaThread *thread, bool doit) {
1122   // Deoptimize frame
1123   if (doit) {
1124     // Called from within the owner thread, so no need for safepoint
1125     RegisterMap reg_map(thread);
1126     frame stub_frame = thread->last_frame();
1127     assert(stub_frame.is_runtime_frame() || exception_blob()->contains(stub_frame.pc()), "sanity check");
1128     frame caller_frame = stub_frame.sender(&reg_map);
1129 
1130     // bypass VM_DeoptimizeFrame and deoptimize the frame directly
1131     Deoptimization::deoptimize_frame(thread, caller_frame.id());
1132   }
1133 }
1134 
1135 
1136 const TypeFunc *OptoRuntime::register_finalizer_Type() {
1137   // create input type (domain)
1138   const Type **fields = TypeTuple::fields(1);
1139   fields[TypeFunc::Parms+0] = TypeInstPtr::NOTNULL;  // oop;          Receiver
1140   // // The JavaThread* is passed to each routine as the last argument
1141   // fields[TypeFunc::Parms+1] = TypeRawPtr::NOTNULL;  // JavaThread *; Executing thread
1142   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+1,fields);
1143 
1144   // create result type (range)
1145   fields = TypeTuple::fields(0);
1146 
1147   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0,fields);
1148 
1149   return TypeFunc::make(domain,range);
1150 }
1151 
1152 
1153 //-----------------------------------------------------------------------------
1154 // Dtrace support.  entry and exit probes have the same signature
1155 const TypeFunc *OptoRuntime::dtrace_method_entry_exit_Type() {
1156   // create input type (domain)
1157   const Type **fields = TypeTuple::fields(2);
1158   fields[TypeFunc::Parms+0] = TypeRawPtr::BOTTOM; // Thread-local storage
1159   fields[TypeFunc::Parms+1] = TypeInstPtr::NOTNULL;  // methodOop;    Method we are entering
1160   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2,fields);
1161 
1162   // create result type (range)
1163   fields = TypeTuple::fields(0);
1164 
1165   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0,fields);
1166 
1167   return TypeFunc::make(domain,range);
1168 }
1169 
1170 const TypeFunc *OptoRuntime::dtrace_object_alloc_Type() {
1171   // create input type (domain)
1172   const Type **fields = TypeTuple::fields(2);
1173   fields[TypeFunc::Parms+0] = TypeRawPtr::BOTTOM; // Thread-local storage
1174   fields[TypeFunc::Parms+1] = TypeInstPtr::NOTNULL;  // oop;    newly allocated object
1175 
1176   const TypeTuple *domain = TypeTuple::make(TypeFunc::Parms+2,fields);
1177 
1178   // create result type (range)
1179   fields = TypeTuple::fields(0);
1180 
1181   const TypeTuple *range = TypeTuple::make(TypeFunc::Parms+0,fields);
1182 
1183   return TypeFunc::make(domain,range);
1184 }
1185 
1186 
1187 JRT_ENTRY_NO_ASYNC(void, OptoRuntime::register_finalizer(oopDesc* obj, JavaThread* thread))
1188   assert(obj->is_oop(), "must be a valid oop");
1189   assert(obj->klass()->klass_part()->has_finalizer(), "shouldn't be here otherwise");
1190   instanceKlass::register_finalizer(instanceOop(obj), CHECK);
1191 JRT_END
1192 
1193 //-----------------------------------------------------------------------------
1194 
1195 NamedCounter * volatile OptoRuntime::_named_counters = NULL;
1196 
1197 //
1198 // dump the collected NamedCounters.
1199 //
1200 void OptoRuntime::print_named_counters() {
1201   int total_lock_count = 0;
1202   int eliminated_lock_count = 0;
1203 
1204   NamedCounter* c = _named_counters;
1205   while (c) {
1206     if (c->tag() == NamedCounter::LockCounter || c->tag() == NamedCounter::EliminatedLockCounter) {
1207       int count = c->count();
1208       if (count > 0) {
1209         bool eliminated = c->tag() == NamedCounter::EliminatedLockCounter;
1210         if (Verbose) {
1211           tty->print_cr("%d %s%s", count, c->name(), eliminated ? " (eliminated)" : "");
1212         }
1213         total_lock_count += count;
1214         if (eliminated) {
1215           eliminated_lock_count += count;
1216         }
1217       }
1218     } else if (c->tag() == NamedCounter::BiasedLockingCounter) {
1219       BiasedLockingCounters* blc = ((BiasedLockingNamedCounter*)c)->counters();
1220       if (blc->nonzero()) {
1221         tty->print_cr("%s", c->name());
1222         blc->print_on(tty);
1223       }
1224     }
1225     c = c->next();
1226   }
1227   if (total_lock_count > 0) {
1228     tty->print_cr("dynamic locks: %d", total_lock_count);
1229     if (eliminated_lock_count) {
1230       tty->print_cr("eliminated locks: %d (%d%%)", eliminated_lock_count,
1231                     (int)(eliminated_lock_count * 100.0 / total_lock_count));
1232     }
1233   }
1234 }
1235 
1236 //
1237 //  Allocate a new NamedCounter.  The JVMState is used to generate the
1238 //  name which consists of method@line for the inlining tree.
1239 //
1240 
1241 NamedCounter* OptoRuntime::new_named_counter(JVMState* youngest_jvms, NamedCounter::CounterTag tag) {
1242   int max_depth = youngest_jvms->depth();
1243 
1244   // Visit scopes from youngest to oldest.
1245   bool first = true;
1246   stringStream st;
1247   for (int depth = max_depth; depth >= 1; depth--) {
1248     JVMState* jvms = youngest_jvms->of_depth(depth);
1249     ciMethod* m = jvms->has_method() ? jvms->method() : NULL;
1250     if (!first) {
1251       st.print(" ");
1252     } else {
1253       first = false;
1254     }
1255     int bci = jvms->bci();
1256     if (bci < 0) bci = 0;
1257     st.print("%s.%s@%d", m->holder()->name()->as_utf8(), m->name()->as_utf8(), bci);
1258     // To print linenumbers instead of bci use: m->line_number_from_bci(bci)
1259   }
1260   NamedCounter* c;
1261   if (tag == NamedCounter::BiasedLockingCounter) {
1262     c = new BiasedLockingNamedCounter(strdup(st.as_string()));
1263   } else {
1264     c = new NamedCounter(strdup(st.as_string()), tag);
1265   }
1266 
1267   // atomically add the new counter to the head of the list.  We only
1268   // add counters so this is safe.
1269   NamedCounter* head;
1270   do {
1271     head = _named_counters;
1272     c->set_next(head);
1273   } while (Atomic::cmpxchg_ptr(c, &_named_counters, head) != head);
1274   return c;
1275 }
1276 
1277 //-----------------------------------------------------------------------------
1278 // Non-product code
1279 #ifndef PRODUCT
1280 
1281 int trace_exception_counter = 0;
1282 static void trace_exception(oop exception_oop, address exception_pc, const char* msg) {
1283   ttyLocker ttyl;
1284   trace_exception_counter++;
1285   tty->print("%d [Exception (%s): ", trace_exception_counter, msg);
1286   exception_oop->print_value();
1287   tty->print(" in ");
1288   CodeBlob* blob = CodeCache::find_blob(exception_pc);
1289   if (blob->is_nmethod()) {
1290     ((nmethod*)blob)->method()->print_value();
1291   } else if (blob->is_runtime_stub()) {
1292     tty->print("<runtime-stub>");
1293   } else {
1294     tty->print("<unknown>");
1295   }
1296   tty->print(" at " INTPTR_FORMAT,  exception_pc);
1297   tty->print_cr("]");
1298 }
1299 
1300 #endif  // PRODUCT
1301 
1302 
1303 # ifdef ENABLE_ZAP_DEAD_LOCALS
1304 // Called from call sites in compiled code with oop maps (actually safepoints)
1305 // Zaps dead locals in first java frame.
1306 // Is entry because may need to lock to generate oop maps
1307 // Currently, only used for compiler frames, but someday may be used
1308 // for interpreter frames, too.
1309 
1310 int OptoRuntime::ZapDeadCompiledLocals_count = 0;
1311 
1312 // avoid pointers to member funcs with these helpers
1313 static bool is_java_frame(  frame* f) { return f->is_java_frame();   }
1314 static bool is_native_frame(frame* f) { return f->is_native_frame(); }
1315 
1316 
1317 void OptoRuntime::zap_dead_java_or_native_locals(JavaThread* thread,
1318                                                 bool (*is_this_the_right_frame_to_zap)(frame*)) {
1319   assert(JavaThread::current() == thread, "is this needed?");
1320 
1321   if ( !ZapDeadCompiledLocals )  return;
1322 
1323   bool skip = false;
1324 
1325        if ( ZapDeadCompiledLocalsFirst  ==  0  ) ; // nothing special
1326   else if ( ZapDeadCompiledLocalsFirst  >  ZapDeadCompiledLocals_count )  skip = true;
1327   else if ( ZapDeadCompiledLocalsFirst  == ZapDeadCompiledLocals_count )
1328     warning("starting zapping after skipping");
1329 
1330        if ( ZapDeadCompiledLocalsLast  ==  -1  ) ; // nothing special
1331   else if ( ZapDeadCompiledLocalsLast  <   ZapDeadCompiledLocals_count )  skip = true;
1332   else if ( ZapDeadCompiledLocalsLast  ==  ZapDeadCompiledLocals_count )
1333     warning("about to zap last zap");
1334 
1335   ++ZapDeadCompiledLocals_count; // counts skipped zaps, too
1336 
1337   if ( skip )  return;
1338 
1339   // find java frame and zap it
1340 
1341   for (StackFrameStream sfs(thread);  !sfs.is_done();  sfs.next()) {
1342     if (is_this_the_right_frame_to_zap(sfs.current()) ) {
1343       sfs.current()->zap_dead_locals(thread, sfs.register_map());
1344       return;
1345     }
1346   }
1347   warning("no frame found to zap in zap_dead_Java_locals_C");
1348 }
1349 
1350 JRT_LEAF(void, OptoRuntime::zap_dead_Java_locals_C(JavaThread* thread))
1351   zap_dead_java_or_native_locals(thread, is_java_frame);
1352 JRT_END
1353 
1354 // The following does not work because for one thing, the
1355 // thread state is wrong; it expects java, but it is native.
1356 // Also, the invariants in a native stub are different and
1357 // I'm not sure it is safe to have a MachCalRuntimeDirectNode
1358 // in there.
1359 // So for now, we do not zap in native stubs.
1360 
1361 JRT_LEAF(void, OptoRuntime::zap_dead_native_locals_C(JavaThread* thread))
1362   zap_dead_java_or_native_locals(thread, is_native_frame);
1363 JRT_END
1364 
1365 # endif