< prev index next >

src/hotspot/share/runtime/sharedRuntime.cpp

Print this page

  27 #include "jvm.h"
  28 #include "classfile/stringTable.hpp"
  29 #include "classfile/vmClasses.hpp"
  30 #include "classfile/vmSymbols.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "code/compiledIC.hpp"
  33 #include "code/icBuffer.hpp"
  34 #include "code/compiledMethod.inline.hpp"
  35 #include "code/scopeDesc.hpp"
  36 #include "code/vtableStubs.hpp"
  37 #include "compiler/abstractCompiler.hpp"
  38 #include "compiler/compileBroker.hpp"
  39 #include "compiler/disassembler.hpp"
  40 #include "gc/shared/barrierSet.hpp"
  41 #include "gc/shared/collectedHeap.hpp"
  42 #include "gc/shared/gcLocker.inline.hpp"
  43 #include "interpreter/interpreter.hpp"
  44 #include "interpreter/interpreterRuntime.hpp"
  45 #include "jfr/jfrEvents.hpp"
  46 #include "logging/log.hpp"

  47 #include "memory/resourceArea.hpp"
  48 #include "memory/universe.hpp"


  49 #include "oops/compiledICHolder.inline.hpp"
  50 #include "oops/klass.hpp"
  51 #include "oops/method.inline.hpp"
  52 #include "oops/objArrayKlass.hpp"

  53 #include "oops/oop.inline.hpp"

  54 #include "prims/forte.hpp"
  55 #include "prims/jvmtiExport.hpp"
  56 #include "prims/methodHandles.hpp"
  57 #include "prims/nativeLookup.hpp"
  58 #include "runtime/atomic.hpp"
  59 #include "runtime/frame.inline.hpp"
  60 #include "runtime/handles.inline.hpp"
  61 #include "runtime/init.hpp"
  62 #include "runtime/interfaceSupport.inline.hpp"
  63 #include "runtime/java.hpp"
  64 #include "runtime/javaCalls.hpp"
  65 #include "runtime/sharedRuntime.hpp"
  66 #include "runtime/stackWatermarkSet.hpp"
  67 #include "runtime/stubRoutines.hpp"
  68 #include "runtime/synchronizer.hpp"
  69 #include "runtime/vframe.inline.hpp"
  70 #include "runtime/vframeArray.hpp"
  71 #include "runtime/vm_version.hpp"
  72 #include "utilities/copy.hpp"
  73 #include "utilities/dtrace.hpp"
  74 #include "utilities/events.hpp"
  75 #include "utilities/hashtable.inline.hpp"
  76 #include "utilities/macros.hpp"
  77 #include "utilities/xmlstream.hpp"
  78 #ifdef COMPILER1
  79 #include "c1/c1_Runtime1.hpp"
  80 #endif
  81 
  82 // Shared stub locations
  83 RuntimeStub*        SharedRuntime::_wrong_method_blob;
  84 RuntimeStub*        SharedRuntime::_wrong_method_abstract_blob;
  85 RuntimeStub*        SharedRuntime::_ic_miss_blob;
  86 RuntimeStub*        SharedRuntime::_resolve_opt_virtual_call_blob;
  87 RuntimeStub*        SharedRuntime::_resolve_virtual_call_blob;
  88 RuntimeStub*        SharedRuntime::_resolve_static_call_blob;
  89 address             SharedRuntime::_resolve_static_call_entry;
  90 
  91 DeoptimizationBlob* SharedRuntime::_deopt_blob;
  92 SafepointBlob*      SharedRuntime::_polling_page_vectors_safepoint_handler_blob;
  93 SafepointBlob*      SharedRuntime::_polling_page_safepoint_handler_blob;
  94 SafepointBlob*      SharedRuntime::_polling_page_return_handler_blob;
  95 
  96 #ifdef COMPILER2
  97 UncommonTrapBlob*   SharedRuntime::_uncommon_trap_blob;
  98 #endif // COMPILER2
  99 
 100 
 101 //----------------------------generate_stubs-----------------------------------
 102 void SharedRuntime::generate_stubs() {
 103   _wrong_method_blob                   = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method),          "wrong_method_stub");
 104   _wrong_method_abstract_blob          = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_abstract), "wrong_method_abstract_stub");
 105   _ic_miss_blob                        = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_ic_miss),  "ic_miss_stub");
 106   _resolve_opt_virtual_call_blob       = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_opt_virtual_call_C),   "resolve_opt_virtual_call");
 107   _resolve_virtual_call_blob           = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_virtual_call_C),       "resolve_virtual_call");
 108   _resolve_static_call_blob            = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_static_call_C),        "resolve_static_call");
 109   _resolve_static_call_entry           = _resolve_static_call_blob->entry_point();
 110 
 111   AdapterHandlerLibrary::initialize();
 112 
 113 #if COMPILER2_OR_JVMCI
 114   // Vectors are generated only by C2 and JVMCI.
 115   bool support_wide = is_wide_vector(MaxVectorSize);
 116   if (support_wide) {
 117     _polling_page_vectors_safepoint_handler_blob = generate_handler_blob(CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception), POLL_AT_VECTOR_LOOP);
 118   }
 119 #endif // COMPILER2_OR_JVMCI
 120   _polling_page_safepoint_handler_blob = generate_handler_blob(CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception), POLL_AT_LOOP);
 121   _polling_page_return_handler_blob    = generate_handler_blob(CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception), POLL_AT_RETURN);
 122 
 123   generate_deopt_blob();
 124 
 125 #ifdef COMPILER2
 126   generate_uncommon_trap_blob();
 127 #endif // COMPILER2
 128 }
 129 

 969   // forwarded before we look at the return value.
 970   THROW_(vmSymbols::java_lang_UnsatisfiedLinkError(), (void*)badAddress);
 971 }
 972 JNI_END
 973 
 974 address SharedRuntime::native_method_throw_unsatisfied_link_error_entry() {
 975   return CAST_FROM_FN_PTR(address, &throw_unsatisfied_link_error);
 976 }
 977 
 978 JRT_ENTRY_NO_ASYNC(void, SharedRuntime::register_finalizer(JavaThread* current, oopDesc* obj))
 979 #if INCLUDE_JVMCI
 980   if (!obj->klass()->has_finalizer()) {
 981     return;
 982   }
 983 #endif // INCLUDE_JVMCI
 984   assert(oopDesc::is_oop(obj), "must be a valid oop");
 985   assert(obj->klass()->has_finalizer(), "shouldn't be here otherwise");
 986   InstanceKlass::register_finalizer(instanceOop(obj), CHECK);
 987 JRT_END
 988 

 989 jlong SharedRuntime::get_java_tid(Thread* thread) {
 990   if (thread != NULL) {
 991     if (thread->is_Java_thread()) {
 992       oop obj = JavaThread::cast(thread)->threadObj();
 993       return (obj == NULL) ? 0 : java_lang_Thread::thread_id(obj);
 994     }
 995   }
 996   return 0;
 997 }
 998 
 999 /**
1000  * This function ought to be a void function, but cannot be because
1001  * it gets turned into a tail-call on sparc, which runs into dtrace bug
1002  * 6254741.  Once that is fixed we can remove the dummy return value.
1003  */
1004 int SharedRuntime::dtrace_object_alloc(oopDesc* o) {
1005   return dtrace_object_alloc(Thread::current(), o, o->size());
1006 }
1007 
1008 int SharedRuntime::dtrace_object_alloc(Thread* thread, oopDesc* o) {

1073     return caller->attached_method_before_pc(pc);
1074   }
1075   return NULL;
1076 }
1077 
1078 // Finds receiver, CallInfo (i.e. receiver method), and calling bytecode
1079 // for a call current in progress, i.e., arguments has been pushed on stack
1080 // but callee has not been invoked yet.  Caller frame must be compiled.
1081 Handle SharedRuntime::find_callee_info_helper(vframeStream& vfst, Bytecodes::Code& bc,
1082                                               CallInfo& callinfo, TRAPS) {
1083   Handle receiver;
1084   Handle nullHandle;  // create a handy null handle for exception returns
1085   JavaThread* current = THREAD;
1086 
1087   assert(!vfst.at_end(), "Java frame must exist");
1088 
1089   // Find caller and bci from vframe
1090   methodHandle caller(current, vfst.method());
1091   int          bci   = vfst.bci();
1092 















1093   Bytecode_invoke bytecode(caller, bci);
1094   int bytecode_index = bytecode.index();
1095   bc = bytecode.invoke_code();
1096 
1097   methodHandle attached_method(current, extract_attached_method(vfst));
1098   if (attached_method.not_null()) {
1099     Method* callee = bytecode.static_target(CHECK_NH);
1100     vmIntrinsics::ID id = callee->intrinsic_id();
1101     // When VM replaces MH.invokeBasic/linkTo* call with a direct/virtual call,
1102     // it attaches statically resolved method to the call site.
1103     if (MethodHandles::is_signature_polymorphic(id) &&
1104         MethodHandles::is_signature_polymorphic_intrinsic(id)) {
1105       bc = MethodHandles::signature_polymorphic_intrinsic_bytecode(id);
1106 
1107       // Adjust invocation mode according to the attached method.
1108       switch (bc) {
1109         case Bytecodes::_invokevirtual:
1110           if (attached_method->method_holder()->is_interface()) {
1111             bc = Bytecodes::_invokeinterface;
1112           }
1113           break;
1114         case Bytecodes::_invokeinterface:
1115           if (!attached_method->method_holder()->is_interface()) {
1116             bc = Bytecodes::_invokevirtual;
1117           }
1118           break;
1119         case Bytecodes::_invokehandle:
1120           if (!MethodHandles::is_signature_polymorphic_method(attached_method())) {
1121             bc = attached_method->is_static() ? Bytecodes::_invokestatic
1122                                               : Bytecodes::_invokevirtual;
1123           }
1124           break;
1125         default:
1126           break;
1127       }






1128     }
1129   }
1130 
1131   assert(bc != Bytecodes::_illegal, "not initialized");
1132 
1133   bool has_receiver = bc != Bytecodes::_invokestatic &&
1134                       bc != Bytecodes::_invokedynamic &&
1135                       bc != Bytecodes::_invokehandle;

1136 
1137   // Find receiver for non-static call
1138   if (has_receiver) {
1139     // This register map must be update since we need to find the receiver for
1140     // compiled frames. The receiver might be in a register.
1141     RegisterMap reg_map2(current);
1142     frame stubFrame   = current->last_frame();
1143     // Caller-frame is a compiled frame
1144     frame callerFrame = stubFrame.sender(&reg_map2);

1145 
1146     if (attached_method.is_null()) {
1147       Method* callee = bytecode.static_target(CHECK_NH);





1148       if (callee == NULL) {
1149         THROW_(vmSymbols::java_lang_NoSuchMethodException(), nullHandle);
1150       }
1151     }
1152 
1153     // Retrieve from a compiled argument list
1154     receiver = Handle(current, callerFrame.retrieve_receiver(&reg_map2));
1155 
1156     if (receiver.is_null()) {
1157       THROW_(vmSymbols::java_lang_NullPointerException(), nullHandle);








1158     }
1159   }
1160 
1161   // Resolve method
1162   if (attached_method.not_null()) {
1163     // Parameterized by attached method.
1164     LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, CHECK_NH);
1165   } else {
1166     // Parameterized by bytecode.
1167     constantPoolHandle constants(current, caller->constants());
1168     LinkResolver::resolve_invoke(callinfo, receiver, constants, bytecode_index, bc, CHECK_NH);
1169   }
1170 
1171 #ifdef ASSERT
1172   // Check that the receiver klass is of the right subtype and that it is initialized for virtual calls
1173   if (has_receiver) {
1174     assert(receiver.not_null(), "should have thrown exception");
1175     Klass* receiver_klass = receiver->klass();
1176     Klass* rk = NULL;
1177     if (attached_method.not_null()) {
1178       // In case there's resolved method attached, use its holder during the check.
1179       rk = attached_method->method_holder();
1180     } else {
1181       // Klass is already loaded.
1182       constantPoolHandle constants(current, caller->constants());
1183       rk = constants->klass_ref_at(bytecode_index, CHECK_NH);
1184     }
1185     Klass* static_receiver_klass = rk;
1186     assert(receiver_klass->is_subtype_of(static_receiver_klass),
1187            "actual receiver must be subclass of static receiver klass");
1188     if (receiver_klass->is_instance_klass()) {
1189       if (InstanceKlass::cast(receiver_klass)->is_not_initialized()) {
1190         tty->print_cr("ERROR: Klass not yet initialized!!");
1191         receiver_klass->print();
1192       }
1193       assert(!InstanceKlass::cast(receiver_klass)->is_not_initialized(), "receiver_klass must be initialized");

1211     // Hence the stack can only contain an entry_frame.  We need to
1212     // find the target method from the stub frame.
1213     RegisterMap reg_map(current, false);
1214     frame fr = current->last_frame();
1215     assert(fr.is_runtime_frame(), "must be a runtimeStub");
1216     fr = fr.sender(&reg_map);
1217     assert(fr.is_entry_frame(), "must be");
1218     // fr is now pointing to the entry frame.
1219     callee_method = methodHandle(current, fr.entry_frame_call_wrapper()->callee_method());
1220   } else {
1221     Bytecodes::Code bc;
1222     CallInfo callinfo;
1223     find_callee_info_helper(vfst, bc, callinfo, CHECK_(methodHandle()));
1224     callee_method = methodHandle(current, callinfo.selected_method());
1225   }
1226   assert(callee_method()->is_method(), "must be");
1227   return callee_method;
1228 }
1229 
1230 // Resolves a call.
1231 methodHandle SharedRuntime::resolve_helper(bool is_virtual, bool is_optimized, TRAPS) {
1232   methodHandle callee_method;
1233   callee_method = resolve_sub_helper(is_virtual, is_optimized, THREAD);
1234   if (JvmtiExport::can_hotswap_or_post_breakpoint()) {
1235     int retry_count = 0;
1236     while (!HAS_PENDING_EXCEPTION && callee_method->is_old() &&
1237            callee_method->method_holder() != vmClasses::Object_klass()) {
1238       // If has a pending exception then there is no need to re-try to
1239       // resolve this method.
1240       // If the method has been redefined, we need to try again.
1241       // Hack: we have no way to update the vtables of arrays, so don't
1242       // require that java.lang.Object has been updated.
1243 
1244       // It is very unlikely that method is redefined more than 100 times
1245       // in the middle of resolve. If it is looping here more than 100 times
1246       // means then there could be a bug here.
1247       guarantee((retry_count++ < 100),
1248                 "Could not resolve to latest version of redefined method");
1249       // method is redefined in the middle of resolve so re-try.
1250       callee_method = resolve_sub_helper(is_virtual, is_optimized, THREAD);
1251     }
1252   }
1253   return callee_method;
1254 }
1255 
1256 // This fails if resolution required refilling of IC stubs
1257 bool SharedRuntime::resolve_sub_helper_internal(methodHandle callee_method, const frame& caller_frame,
1258                                                 CompiledMethod* caller_nm, bool is_virtual, bool is_optimized,
1259                                                 Handle receiver, CallInfo& call_info, Bytecodes::Code invoke_code, TRAPS) {
1260   StaticCallInfo static_call_info;
1261   CompiledICInfo virtual_call_info;
1262 
1263   // Make sure the callee nmethod does not get deoptimized and removed before
1264   // we are done patching the code.
1265   CompiledMethod* callee = callee_method->code();
1266 
1267   if (callee != NULL) {
1268     assert(callee->is_compiled(), "must be nmethod for patching");
1269   }
1270 
1271   if (callee != NULL && !callee->is_in_use()) {
1272     // Patch call site to C2I adapter if callee nmethod is deoptimized or unloaded.
1273     callee = NULL;
1274   }
1275   nmethodLocker nl_callee(callee);
1276 #ifdef ASSERT
1277   address dest_entry_point = callee == NULL ? 0 : callee->entry_point(); // used below
1278 #endif
1279 
1280   bool is_nmethod = caller_nm->is_nmethod();

1281 
1282   if (is_virtual) {
1283     assert(receiver.not_null() || invoke_code == Bytecodes::_invokehandle, "sanity check");







1284     bool static_bound = call_info.resolved_method()->can_be_statically_bound();
1285     Klass* klass = invoke_code == Bytecodes::_invokehandle ? NULL : receiver->klass();
1286     CompiledIC::compute_monomorphic_entry(callee_method, klass,
1287                      is_optimized, static_bound, is_nmethod, virtual_call_info,
1288                      CHECK_false);
1289   } else {
1290     // static call
1291     CompiledStaticCall::compute_entry(callee_method, is_nmethod, static_call_info);
1292   }
1293 
1294   // grab lock, check for deoptimization and potentially patch caller
1295   {
1296     CompiledICLocker ml(caller_nm);
1297 
1298     // Lock blocks for safepoint during which both nmethods can change state.
1299 
1300     // Now that we are ready to patch if the Method* was redefined then
1301     // don't update call site and let the caller retry.
1302     // Don't update call site if callee nmethod was unloaded or deoptimized.
1303     // Don't update call site if callee nmethod was replaced by an other nmethod
1304     // which may happen when multiply alive nmethod (tiered compilation)
1305     // will be supported.
1306     if (!callee_method->is_old() &&
1307         (callee == NULL || (callee->is_in_use() && callee_method->code() == callee))) {
1308       NoSafepointVerifier nsv;
1309 #ifdef ASSERT
1310       // We must not try to patch to jump to an already unloaded method.
1311       if (dest_entry_point != 0) {

1321             return false;
1322           }
1323         }
1324       } else {
1325         if (VM_Version::supports_fast_class_init_checks() &&
1326             invoke_code == Bytecodes::_invokestatic &&
1327             callee_method->needs_clinit_barrier() &&
1328             callee != NULL && callee->is_compiled_by_jvmci()) {
1329           return true; // skip patching for JVMCI
1330         }
1331         CompiledStaticCall* ssc = caller_nm->compiledStaticCall_before(caller_frame.pc());
1332         if (ssc->is_clean()) ssc->set(static_call_info);
1333       }
1334     }
1335   } // unlock CompiledICLocker
1336   return true;
1337 }
1338 
1339 // Resolves a call.  The compilers generate code for calls that go here
1340 // and are patched with the real destination of the call.
1341 methodHandle SharedRuntime::resolve_sub_helper(bool is_virtual, bool is_optimized, TRAPS) {
1342   JavaThread* current = THREAD;
1343   ResourceMark rm(current);
1344   RegisterMap cbl_map(current, false);
1345   frame caller_frame = current->last_frame().sender(&cbl_map);
1346 
1347   CodeBlob* caller_cb = caller_frame.cb();
1348   guarantee(caller_cb != NULL && caller_cb->is_compiled(), "must be called from compiled method");
1349   CompiledMethod* caller_nm = caller_cb->as_compiled_method_or_null();

1350 
1351   // make sure caller is not getting deoptimized
1352   // and removed before we are done with it.
1353   // CLEANUP - with lazy deopt shouldn't need this lock
1354   nmethodLocker caller_lock(caller_nm);
1355 
1356   // determine call info & receiver
1357   // note: a) receiver is NULL for static calls
1358   //       b) an exception is thrown if receiver is NULL for non-static calls
1359   CallInfo call_info;
1360   Bytecodes::Code invoke_code = Bytecodes::_illegal;
1361   Handle receiver = find_callee_info(invoke_code, call_info, CHECK_(methodHandle()));
1362   methodHandle callee_method(current, call_info.selected_method());
1363 
1364   assert((!is_virtual && invoke_code == Bytecodes::_invokestatic ) ||
1365          (!is_virtual && invoke_code == Bytecodes::_invokespecial) ||
1366          (!is_virtual && invoke_code == Bytecodes::_invokehandle ) ||
1367          (!is_virtual && invoke_code == Bytecodes::_invokedynamic) ||
1368          ( is_virtual && invoke_code != Bytecodes::_invokestatic ), "inconsistent bytecode");
1369 

1426     bool successful = resolve_sub_helper_internal(callee_method, caller_frame, caller_nm,
1427                                                   is_virtual, is_optimized, receiver,
1428                                                   call_info, invoke_code, CHECK_(methodHandle()));
1429     if (successful) {
1430       return callee_method;
1431     } else {
1432       InlineCacheBuffer::refill_ic_stubs();
1433     }
1434   }
1435 
1436 }
1437 
1438 
1439 // Inline caches exist only in compiled code
1440 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_ic_miss(JavaThread* current))
1441 #ifdef ASSERT
1442   RegisterMap reg_map(current, false);
1443   frame stub_frame = current->last_frame();
1444   assert(stub_frame.is_runtime_frame(), "sanity check");
1445   frame caller_frame = stub_frame.sender(&reg_map);
1446   assert(!caller_frame.is_interpreted_frame() && !caller_frame.is_entry_frame() && !caller_frame.is_optimized_entry_frame(), "unexpected frame");
1447 #endif /* ASSERT */
1448 
1449   methodHandle callee_method;


1450   JRT_BLOCK
1451     callee_method = SharedRuntime::handle_ic_miss_helper(CHECK_NULL);
1452     // Return Method* through TLS
1453     current->set_vm_result_2(callee_method());
1454   JRT_BLOCK_END
1455   // return compiled code entry point after potential safepoints
1456   assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
1457   return callee_method->verified_code_entry();
1458 JRT_END
1459 
1460 
1461 // Handle call site that has been made non-entrant
1462 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method(JavaThread* current))
1463   // 6243940 We might end up in here if the callee is deoptimized
1464   // as we race to call it.  We don't want to take a safepoint if
1465   // the caller was interpreted because the caller frame will look
1466   // interpreted to the stack walkers and arguments are now
1467   // "compiled" so it is much better to make this transition
1468   // invisible to the stack walking code. The i2c path will
1469   // place the callee method in the callee_target. It is stashed
1470   // there because if we try and find the callee by normal means a
1471   // safepoint is possible and have trouble gc'ing the compiled args.
1472   RegisterMap reg_map(current, false);
1473   frame stub_frame = current->last_frame();
1474   assert(stub_frame.is_runtime_frame(), "sanity check");
1475   frame caller_frame = stub_frame.sender(&reg_map);
1476 
1477   if (caller_frame.is_interpreted_frame() ||

1481     guarantee(callee != NULL && callee->is_method(), "bad handshake");
1482     current->set_vm_result_2(callee);
1483     current->set_callee_target(NULL);
1484     if (caller_frame.is_entry_frame() && VM_Version::supports_fast_class_init_checks()) {
1485       // Bypass class initialization checks in c2i when caller is in native.
1486       // JNI calls to static methods don't have class initialization checks.
1487       // Fast class initialization checks are present in c2i adapters and call into
1488       // SharedRuntime::handle_wrong_method() on the slow path.
1489       //
1490       // JVM upcalls may land here as well, but there's a proper check present in
1491       // LinkResolver::resolve_static_call (called from JavaCalls::call_static),
1492       // so bypassing it in c2i adapter is benign.
1493       return callee->get_c2i_no_clinit_check_entry();
1494     } else {
1495       return callee->get_c2i_entry();
1496     }
1497   }
1498 
1499   // Must be compiled to compiled path which is safe to stackwalk
1500   methodHandle callee_method;



1501   JRT_BLOCK
1502     // Force resolving of caller (if we called from compiled frame)
1503     callee_method = SharedRuntime::reresolve_call_site(CHECK_NULL);
1504     current->set_vm_result_2(callee_method());
1505   JRT_BLOCK_END
1506   // return compiled code entry point after potential safepoints
1507   assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
1508   return callee_method->verified_code_entry();
1509 JRT_END
1510 
1511 // Handle abstract method call
1512 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_abstract(JavaThread* current))
1513   // Verbose error message for AbstractMethodError.
1514   // Get the called method from the invoke bytecode.
1515   vframeStream vfst(current, true);
1516   assert(!vfst.at_end(), "Java frame must exist");
1517   methodHandle caller(current, vfst.method());
1518   Bytecode_invoke invoke(caller, vfst.bci());
1519   DEBUG_ONLY( invoke.verify(); )
1520 
1521   // Find the compiled caller frame.
1522   RegisterMap reg_map(current);
1523   frame stubFrame = current->last_frame();
1524   assert(stubFrame.is_runtime_frame(), "must be");
1525   frame callerFrame = stubFrame.sender(&reg_map);
1526   assert(callerFrame.is_compiled_frame(), "must be");
1527 
1528   // Install exception and return forward entry.
1529   address res = StubRoutines::throw_AbstractMethodError_entry();
1530   JRT_BLOCK
1531     methodHandle callee(current, invoke.static_target(current));
1532     if (!callee.is_null()) {
1533       oop recv = callerFrame.retrieve_receiver(&reg_map);
1534       Klass *recv_klass = (recv != NULL) ? recv->klass() : NULL;
1535       res = StubRoutines::forward_exception_entry();
1536       LinkResolver::throw_abstract_method_error(callee, recv_klass, CHECK_(res));
1537     }
1538   JRT_BLOCK_END
1539   return res;
1540 JRT_END
1541 
1542 
1543 // resolve a static call and patch code
1544 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_call_C(JavaThread* current ))
1545   methodHandle callee_method;

1546   JRT_BLOCK
1547     callee_method = SharedRuntime::resolve_helper(false, false, CHECK_NULL);
1548     current->set_vm_result_2(callee_method());
1549   JRT_BLOCK_END
1550   // return compiled code entry point after potential safepoints
1551   assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
1552   return callee_method->verified_code_entry();


1553 JRT_END
1554 
1555 
1556 // resolve virtual call and update inline cache to monomorphic
1557 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_virtual_call_C(JavaThread* current))
1558   methodHandle callee_method;

1559   JRT_BLOCK
1560     callee_method = SharedRuntime::resolve_helper(true, false, CHECK_NULL);
1561     current->set_vm_result_2(callee_method());
1562   JRT_BLOCK_END
1563   // return compiled code entry point after potential safepoints
1564   assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
1565   return callee_method->verified_code_entry();


1566 JRT_END
1567 
1568 
1569 // Resolve a virtual call that can be statically bound (e.g., always
1570 // monomorphic, so it has no inline cache).  Patch code to resolved target.
1571 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_opt_virtual_call_C(JavaThread* current))
1572   methodHandle callee_method;

1573   JRT_BLOCK
1574     callee_method = SharedRuntime::resolve_helper(true, true, CHECK_NULL);
1575     current->set_vm_result_2(callee_method());
1576   JRT_BLOCK_END
1577   // return compiled code entry point after potential safepoints
1578   assert(callee_method->verified_code_entry() != NULL, " Jump to zero!");
1579   return callee_method->verified_code_entry();


1580 JRT_END
1581 
1582 // The handle_ic_miss_helper_internal function returns false if it failed due
1583 // to either running out of vtable stubs or ic stubs due to IC transitions
1584 // to transitional states. The needs_ic_stub_refill value will be set if
1585 // the failure was due to running out of IC stubs, in which case handle_ic_miss_helper
1586 // refills the IC stubs and tries again.
1587 bool SharedRuntime::handle_ic_miss_helper_internal(Handle receiver, CompiledMethod* caller_nm,
1588                                                    const frame& caller_frame, methodHandle callee_method,
1589                                                    Bytecodes::Code bc, CallInfo& call_info,
1590                                                    bool& needs_ic_stub_refill, TRAPS) {
1591   CompiledICLocker ml(caller_nm);
1592   CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1593   bool should_be_mono = false;
1594   if (inline_cache->is_optimized()) {
1595     if (TraceCallFixup) {
1596       ResourceMark rm(THREAD);
1597       tty->print("OPTIMIZED IC miss (%s) call to", Bytecodes::name(bc));
1598       callee_method->print_short_name(tty);
1599       tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1600     }

1601     should_be_mono = true;
1602   } else if (inline_cache->is_icholder_call()) {
1603     CompiledICHolder* ic_oop = inline_cache->cached_icholder();
1604     if (ic_oop != NULL) {
1605       if (!ic_oop->is_loader_alive()) {
1606         // Deferred IC cleaning due to concurrent class unloading
1607         if (!inline_cache->set_to_clean()) {
1608           needs_ic_stub_refill = true;
1609           return false;
1610         }
1611       } else if (receiver()->klass() == ic_oop->holder_klass()) {
1612         // This isn't a real miss. We must have seen that compiled code
1613         // is now available and we want the call site converted to a
1614         // monomorphic compiled call site.
1615         // We can't assert for callee_method->code() != NULL because it
1616         // could have been deoptimized in the meantime
1617         if (TraceCallFixup) {
1618           ResourceMark rm(THREAD);
1619           tty->print("FALSE IC miss (%s) converting to compiled call to", Bytecodes::name(bc));
1620           callee_method->print_short_name(tty);
1621           tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1622         }
1623         should_be_mono = true;
1624       }
1625     }
1626   }
1627 
1628   if (should_be_mono) {
1629     // We have a path that was monomorphic but was going interpreted
1630     // and now we have (or had) a compiled entry. We correct the IC
1631     // by using a new icBuffer.
1632     CompiledICInfo info;
1633     Klass* receiver_klass = receiver()->klass();
1634     inline_cache->compute_monomorphic_entry(callee_method,
1635                                             receiver_klass,
1636                                             inline_cache->is_optimized(),
1637                                             false, caller_nm->is_nmethod(),

1638                                             info, CHECK_false);
1639     if (!inline_cache->set_to_monomorphic(info)) {
1640       needs_ic_stub_refill = true;
1641       return false;
1642     }
1643   } else if (!inline_cache->is_megamorphic() && !inline_cache->is_clean()) {
1644     // Potential change to megamorphic
1645 
1646     bool successful = inline_cache->set_to_megamorphic(&call_info, bc, needs_ic_stub_refill, CHECK_false);
1647     if (needs_ic_stub_refill) {
1648       return false;
1649     }
1650     if (!successful) {
1651       if (!inline_cache->set_to_clean()) {
1652         needs_ic_stub_refill = true;
1653         return false;
1654       }
1655     }
1656   } else {
1657     // Either clean or megamorphic
1658   }
1659   return true;
1660 }
1661 
1662 methodHandle SharedRuntime::handle_ic_miss_helper(TRAPS) {
1663   JavaThread* current = THREAD;
1664   ResourceMark rm(current);
1665   CallInfo call_info;
1666   Bytecodes::Code bc;
1667 
1668   // receiver is NULL for static calls. An exception is thrown for NULL
1669   // receivers for non-static calls
1670   Handle receiver = find_callee_info(bc, call_info, CHECK_(methodHandle()));
1671   // Compiler1 can produce virtual call sites that can actually be statically bound
1672   // If we fell thru to below we would think that the site was going megamorphic
1673   // when in fact the site can never miss. Worse because we'd think it was megamorphic
1674   // we'd try and do a vtable dispatch however methods that can be statically bound
1675   // don't have vtable entries (vtable_index < 0) and we'd blow up. So we force a
1676   // reresolution of the  call site (as if we did a handle_wrong_method and not an
1677   // plain ic_miss) and the site will be converted to an optimized virtual call site
1678   // never to miss again. I don't believe C2 will produce code like this but if it
1679   // did this would still be the correct thing to do for it too, hence no ifdef.
1680   //
1681   if (call_info.resolved_method()->can_be_statically_bound()) {
1682     methodHandle callee_method = SharedRuntime::reresolve_call_site(CHECK_(methodHandle()));


1683     if (TraceCallFixup) {
1684       RegisterMap reg_map(current, false);
1685       frame caller_frame = current->last_frame().sender(&reg_map);
1686       ResourceMark rm(current);
1687       tty->print("converting IC miss to reresolve (%s) call to", Bytecodes::name(bc));
1688       callee_method->print_short_name(tty);
1689       tty->print_cr(" from pc: " INTPTR_FORMAT, p2i(caller_frame.pc()));
1690       tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1691     }
1692     return callee_method;
1693   }
1694 
1695   methodHandle callee_method(current, call_info.selected_method());
1696 
1697 #ifndef PRODUCT
1698   Atomic::inc(&_ic_miss_ctr);
1699 
1700   // Statistics & Tracing
1701   if (TraceCallFixup) {
1702     ResourceMark rm(current);

1712     // produce statistics under the lock
1713     trace_ic_miss(f.pc());
1714   }
1715 #endif
1716 
1717   // install an event collector so that when a vtable stub is created the
1718   // profiler can be notified via a DYNAMIC_CODE_GENERATED event. The
1719   // event can't be posted when the stub is created as locks are held
1720   // - instead the event will be deferred until the event collector goes
1721   // out of scope.
1722   JvmtiDynamicCodeEventCollector event_collector;
1723 
1724   // Update inline cache to megamorphic. Skip update if we are called from interpreted.
1725   // Transitioning IC caches may require transition stubs. If we run out
1726   // of transition stubs, we have to drop locks and perform a safepoint
1727   // that refills them.
1728   RegisterMap reg_map(current, false);
1729   frame caller_frame = current->last_frame().sender(&reg_map);
1730   CodeBlob* cb = caller_frame.cb();
1731   CompiledMethod* caller_nm = cb->as_compiled_method();

1732 
1733   for (;;) {
1734     ICRefillVerifier ic_refill_verifier;
1735     bool needs_ic_stub_refill = false;
1736     bool successful = handle_ic_miss_helper_internal(receiver, caller_nm, caller_frame, callee_method,
1737                                                      bc, call_info, needs_ic_stub_refill, CHECK_(methodHandle()));
1738     if (successful || !needs_ic_stub_refill) {
1739       return callee_method;
1740     } else {
1741       InlineCacheBuffer::refill_ic_stubs();
1742     }
1743   }
1744 }
1745 
1746 static bool clear_ic_at_addr(CompiledMethod* caller_nm, address call_addr, bool is_static_call) {
1747   CompiledICLocker ml(caller_nm);
1748   if (is_static_call) {
1749     CompiledStaticCall* ssc = caller_nm->compiledStaticCall_at(call_addr);
1750     if (!ssc->is_clean()) {
1751       return ssc->set_to_clean();
1752     }
1753   } else {
1754     // compiled, dispatched call (which used to call an interpreted method)
1755     CompiledIC* inline_cache = CompiledIC_at(caller_nm, call_addr);
1756     if (!inline_cache->is_clean()) {
1757       return inline_cache->set_to_clean();
1758     }
1759   }
1760   return true;
1761 }
1762 
1763 //
1764 // Resets a call-site in compiled code so it will get resolved again.
1765 // This routines handles both virtual call sites, optimized virtual call
1766 // sites, and static call sites. Typically used to change a call sites
1767 // destination from compiled to interpreted.
1768 //
1769 methodHandle SharedRuntime::reresolve_call_site(TRAPS) {
1770   JavaThread* current = THREAD;
1771   ResourceMark rm(current);
1772   RegisterMap reg_map(current, false);
1773   frame stub_frame = current->last_frame();
1774   assert(stub_frame.is_runtime_frame(), "must be a runtimeStub");
1775   frame caller = stub_frame.sender(&reg_map);
1776 
1777   // Do nothing if the frame isn't a live compiled frame.
1778   // nmethod could be deoptimized by the time we get here
1779   // so no update to the caller is needed.
1780 
1781   if (caller.is_compiled_frame() && !caller.is_deoptimized_frame()) {
1782 
1783     address pc = caller.pc();
1784 
1785     // Check for static or virtual call
1786     bool is_static_call = false;
1787     CompiledMethod* caller_nm = CodeCache::find_compiled(pc);

1788 
1789     // Default call_addr is the location of the "basic" call.
1790     // Determine the address of the call we a reresolving. With
1791     // Inline Caches we will always find a recognizable call.
1792     // With Inline Caches disabled we may or may not find a
1793     // recognizable call. We will always find a call for static
1794     // calls and for optimized virtual calls. For vanilla virtual
1795     // calls it depends on the state of the UseInlineCaches switch.
1796     //
1797     // With Inline Caches disabled we can get here for a virtual call
1798     // for two reasons:
1799     //   1 - calling an abstract method. The vtable for abstract methods
1800     //       will run us thru handle_wrong_method and we will eventually
1801     //       end up in the interpreter to throw the ame.
1802     //   2 - a racing deoptimization. We could be doing a vanilla vtable
1803     //       call and between the time we fetch the entry address and
1804     //       we jump to it the target gets deoptimized. Similar to 1
1805     //       we will wind up in the interprter (thru a c2i with c2).
1806     //
1807     address call_addr = NULL;

1811       CompiledICLocker ml(caller_nm);
1812       // Location of call instruction
1813       call_addr = caller_nm->call_instruction_address(pc);
1814     }
1815     // Make sure nmethod doesn't get deoptimized and removed until
1816     // this is done with it.
1817     // CLEANUP - with lazy deopt shouldn't need this lock
1818     nmethodLocker nmlock(caller_nm);
1819 
1820     if (call_addr != NULL) {
1821       RelocIterator iter(caller_nm, call_addr, call_addr+1);
1822       int ret = iter.next(); // Get item
1823       if (ret) {
1824         assert(iter.addr() == call_addr, "must find call");
1825         if (iter.type() == relocInfo::static_call_type) {
1826           is_static_call = true;
1827         } else {
1828           assert(iter.type() == relocInfo::virtual_call_type ||
1829                  iter.type() == relocInfo::opt_virtual_call_type
1830                 , "unexpected relocInfo. type");

1831         }
1832       } else {
1833         assert(!UseInlineCaches, "relocation info. must exist for this address");
1834       }
1835 
1836       // Cleaning the inline cache will force a new resolve. This is more robust
1837       // than directly setting it to the new destination, since resolving of calls
1838       // is always done through the same code path. (experience shows that it
1839       // leads to very hard to track down bugs, if an inline cache gets updated
1840       // to a wrong method). It should not be performance critical, since the
1841       // resolve is only done once.
1842 
1843       for (;;) {
1844         ICRefillVerifier ic_refill_verifier;
1845         if (!clear_ic_at_addr(caller_nm, call_addr, is_static_call)) {
1846           InlineCacheBuffer::refill_ic_stubs();
1847         } else {
1848           break;
1849         }
1850       }
1851     }
1852   }
1853 
1854   methodHandle callee_method = find_callee_method(CHECK_(methodHandle()));
1855 
1856 
1857 #ifndef PRODUCT
1858   Atomic::inc(&_wrong_method_ctr);
1859 
1860   if (TraceCallFixup) {
1861     ResourceMark rm(current);
1862     tty->print("handle_wrong_method reresolving call to");
1863     callee_method->print_short_name(tty);
1864     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1865   }
1866 #endif
1867 
1868   return callee_method;
1869 }
1870 
1871 address SharedRuntime::handle_unsafe_access(JavaThread* thread, address next_pc) {
1872   // The faulting unsafe accesses should be changed to throw the error
1873   // synchronously instead. Meanwhile the faulting instruction will be
1874   // skipped over (effectively turning it into a no-op) and an
1875   // asynchronous exception will be raised which the thread will
1876   // handle at a later point. If the instruction is a load it will

1932     if (TraceCallFixup) {
1933       tty->print("already patched callsite at " INTPTR_FORMAT " to compiled code for", p2i(caller_pc));
1934       moop->print_short_name(tty);
1935       tty->print_cr(" to " INTPTR_FORMAT, p2i(entry_point));
1936     }
1937   }
1938   return false;
1939 }
1940 
1941 // ---------------------------------------------------------------------------
1942 // We are calling the interpreter via a c2i. Normally this would mean that
1943 // we were called by a compiled method. However we could have lost a race
1944 // where we went int -> i2c -> c2i and so the caller could in fact be
1945 // interpreted. If the caller is compiled we attempt to patch the caller
1946 // so he no longer calls into the interpreter.
1947 JRT_LEAF(void, SharedRuntime::fixup_callers_callsite(Method* method, address caller_pc))
1948   Method* moop(method);
1949 
1950   AARCH64_PORT_ONLY(assert(pauth_ptr_is_raw(caller_pc), "should be raw"));
1951 
1952   address entry_point = moop->from_compiled_entry_no_trampoline();
1953 
1954   // It's possible that deoptimization can occur at a call site which hasn't
1955   // been resolved yet, in which case this function will be called from
1956   // an nmethod that has been patched for deopt and we can ignore the
1957   // request for a fixup.
1958   // Also it is possible that we lost a race in that from_compiled_entry
1959   // is now back to the i2c in that case we don't need to patch and if
1960   // we did we'd leap into space because the callsite needs to use
1961   // "to interpreter" stub in order to load up the Method*. Don't
1962   // ask me how I know this...
1963 
1964   CodeBlob* cb = CodeCache::find_blob(caller_pc);
1965   if (cb == NULL || !cb->is_compiled() || entry_point == moop->get_c2i_entry()) {




1966     return;
1967   }
1968 
1969   // The check above makes sure this is a nmethod.
1970   CompiledMethod* nm = cb->as_compiled_method_or_null();
1971   assert(nm, "must be");
1972 
1973   // Get the return PC for the passed caller PC.
1974   address return_pc = caller_pc + frame::pc_return_offset;
1975 
1976   // There is a benign race here. We could be attempting to patch to a compiled
1977   // entry point at the same time the callee is being deoptimized. If that is
1978   // the case then entry_point may in fact point to a c2i and we'd patch the
1979   // call site with the same old data. clear_code will set code() to NULL
1980   // at the end of it. If we happen to see that NULL then we can skip trying
1981   // to patch. If we hit the window where the callee has a c2i in the
1982   // from_compiled_entry and the NULL isn't present yet then we lose the race
1983   // and patch the code with the same old data. Asi es la vida.
1984 
1985   if (moop->code() == NULL) return;

2320  private:
2321   enum {
2322     _basic_type_bits = 4,
2323     _basic_type_mask = right_n_bits(_basic_type_bits),
2324     _basic_types_per_int = BitsPerInt / _basic_type_bits,
2325     _compact_int_count = 3
2326   };
2327   // TO DO:  Consider integrating this with a more global scheme for compressing signatures.
2328   // For now, 4 bits per components (plus T_VOID gaps after double/long) is not excessive.
2329 
2330   union {
2331     int  _compact[_compact_int_count];
2332     int* _fingerprint;
2333   } _value;
2334   int _length; // A negative length indicates the fingerprint is in the compact form,
2335                // Otherwise _value._fingerprint is the array.
2336 
2337   // Remap BasicTypes that are handled equivalently by the adapters.
2338   // These are correct for the current system but someday it might be
2339   // necessary to make this mapping platform dependent.
2340   static int adapter_encoding(BasicType in) {
2341     switch (in) {
2342       case T_BOOLEAN:
2343       case T_BYTE:
2344       case T_SHORT:
2345       case T_CHAR:
2346         // There are all promoted to T_INT in the calling convention
2347         return T_INT;
2348 
2349       case T_OBJECT:
2350       case T_ARRAY:
2351         // In other words, we assume that any register good enough for
2352         // an int or long is good enough for a managed pointer.
2353 #ifdef _LP64
2354         return T_LONG;
2355 #else
2356         return T_INT;
2357 #endif
2358 
2359       case T_INT:
2360       case T_LONG:
2361       case T_FLOAT:
2362       case T_DOUBLE:
2363       case T_VOID:
2364         return in;
2365 
2366       default:
2367         ShouldNotReachHere();
2368         return T_CONFLICT;
2369     }
2370   }
2371 
2372  public:
2373   AdapterFingerPrint(int total_args_passed, BasicType* sig_bt) {
2374     // The fingerprint is based on the BasicType signature encoded
2375     // into an array of ints with eight entries per int.

2376     int* ptr;
2377     int len = (total_args_passed + (_basic_types_per_int-1)) / _basic_types_per_int;
2378     if (len <= _compact_int_count) {
2379       assert(_compact_int_count == 3, "else change next line");
2380       _value._compact[0] = _value._compact[1] = _value._compact[2] = 0;
2381       // Storing the signature encoded as signed chars hits about 98%
2382       // of the time.
2383       _length = -len;
2384       ptr = _value._compact;
2385     } else {
2386       _length = len;
2387       _value._fingerprint = NEW_C_HEAP_ARRAY(int, _length, mtCode);
2388       ptr = _value._fingerprint;
2389     }
2390 
2391     // Now pack the BasicTypes with 8 per int
2392     int sig_index = 0;


2393     for (int index = 0; index < len; index++) {
2394       int value = 0;
2395       for (int byte = 0; sig_index < total_args_passed && byte < _basic_types_per_int; byte++) {
2396         int bt = adapter_encoding(sig_bt[sig_index++]);
2397         assert((bt & _basic_type_mask) == bt, "must fit in 4 bits");
2398         value = (value << _basic_type_bits) | bt;























2399       }
2400       ptr[index] = value;
2401     }

2402   }
2403 
2404   ~AdapterFingerPrint() {
2405     if (_length > 0) {
2406       FREE_C_HEAP_ARRAY(int, _value._fingerprint);
2407     }
2408   }
2409 
2410   int value(int index) {
2411     if (_length < 0) {
2412       return _value._compact[index];
2413     }
2414     return _value._fingerprint[index];
2415   }
2416   int length() {
2417     if (_length < 0) return -_length;
2418     return _length;
2419   }
2420 
2421   bool is_compact() {

2446   const char* as_basic_args_string() {
2447     stringStream st;
2448     bool long_prev = false;
2449     for (int i = 0; i < length(); i++) {
2450       unsigned val = (unsigned)value(i);
2451       // args are packed so that first/lower arguments are in the highest
2452       // bits of each int value, so iterate from highest to the lowest
2453       for (int j = 32 - _basic_type_bits; j >= 0; j -= _basic_type_bits) {
2454         unsigned v = (val >> j) & _basic_type_mask;
2455         if (v == 0) {
2456           assert(i == length() - 1, "Only expect zeroes in the last word");
2457           continue;
2458         }
2459         if (long_prev) {
2460           long_prev = false;
2461           if (v == T_VOID) {
2462             st.print("J");
2463           } else {
2464             st.print("L");
2465           }
2466         }
2467         switch (v) {
2468           case T_INT:    st.print("I");    break;
2469           case T_LONG:   long_prev = true; break;
2470           case T_FLOAT:  st.print("F");    break;
2471           case T_DOUBLE: st.print("D");    break;
2472           case T_VOID:   break;
2473           default: ShouldNotReachHere();
2474         }
2475       }
2476     }
2477     if (long_prev) {
2478       st.print("L");
2479     }
2480     return st.as_string();
2481   }
2482 #endif // !product
2483 
2484   bool equals(AdapterFingerPrint* other) {
2485     if (other->_length != _length) {
2486       return false;
2487     }
2488     if (_length < 0) {
2489       assert(_compact_int_count == 3, "else change next line");
2490       return _value._compact[0] == other->_value._compact[0] &&
2491              _value._compact[1] == other->_value._compact[1] &&
2492              _value._compact[2] == other->_value._compact[2];
2493     } else {

2508 
2509  private:
2510 
2511 #ifndef PRODUCT
2512   static int _lookups; // number of calls to lookup
2513   static int _buckets; // number of buckets checked
2514   static int _equals;  // number of buckets checked with matching hash
2515   static int _hits;    // number of successful lookups
2516   static int _compact; // number of equals calls with compact signature
2517 #endif
2518 
2519   AdapterHandlerEntry* bucket(int i) {
2520     return (AdapterHandlerEntry*)BasicHashtable<mtCode>::bucket(i);
2521   }
2522 
2523  public:
2524   AdapterHandlerTable()
2525     : BasicHashtable<mtCode>(293, (sizeof(AdapterHandlerEntry))) { }
2526 
2527   // Create a new entry suitable for insertion in the table
2528   AdapterHandlerEntry* new_entry(AdapterFingerPrint* fingerprint, address i2c_entry, address c2i_entry, address c2i_unverified_entry, address c2i_no_clinit_check_entry) {


2529     AdapterHandlerEntry* entry = (AdapterHandlerEntry*)BasicHashtable<mtCode>::new_entry(fingerprint->compute_hash());
2530     entry->init(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry, c2i_no_clinit_check_entry);

2531     return entry;
2532   }
2533 
2534   // Insert an entry into the table
2535   void add(AdapterHandlerEntry* entry) {
2536     int index = hash_to_index(entry->hash());
2537     add_entry(index, entry);
2538   }
2539 
2540   void free_entry(AdapterHandlerEntry* entry) {
2541     entry->deallocate();
2542     BasicHashtable<mtCode>::free_entry(entry);
2543   }
2544 
2545   // Find a entry with the same fingerprint if it exists
2546   AdapterHandlerEntry* lookup(int total_args_passed, BasicType* sig_bt) {
2547     NOT_PRODUCT(_lookups++);
2548     AdapterFingerPrint fp(total_args_passed, sig_bt);
2549     unsigned int hash = fp.compute_hash();
2550     int index = hash_to_index(hash);
2551     for (AdapterHandlerEntry* e = bucket(index); e != NULL; e = e->next()) {
2552       NOT_PRODUCT(_buckets++);
2553       if (e->hash() == hash) {
2554         NOT_PRODUCT(_equals++);
2555         if (fp.equals(e->fingerprint())) {
2556 #ifndef PRODUCT
2557           if (fp.is_compact()) _compact++;
2558           _hits++;
2559 #endif
2560           return e;
2561         }
2562       }
2563     }
2564     return NULL;
2565   }
2566 
2567 #ifndef PRODUCT
2568   void print_statistics() {

2629       AdapterHandlerEntry* result = _current;
2630       _current = _current->next();
2631       if (_current == NULL) scan();
2632       return result;
2633     } else {
2634       return NULL;
2635     }
2636   }
2637 };
2638 
2639 
2640 // ---------------------------------------------------------------------------
2641 // Implementation of AdapterHandlerLibrary
2642 AdapterHandlerTable* AdapterHandlerLibrary::_adapters = NULL;
2643 AdapterHandlerEntry* AdapterHandlerLibrary::_abstract_method_handler = NULL;
2644 AdapterHandlerEntry* AdapterHandlerLibrary::_no_arg_handler = NULL;
2645 AdapterHandlerEntry* AdapterHandlerLibrary::_int_arg_handler = NULL;
2646 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_arg_handler = NULL;
2647 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_int_arg_handler = NULL;
2648 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_obj_arg_handler = NULL;
2649 const int AdapterHandlerLibrary_size = 16*K;
2650 BufferBlob* AdapterHandlerLibrary::_buffer = NULL;
2651 
2652 BufferBlob* AdapterHandlerLibrary::buffer_blob() {
2653   return _buffer;
2654 }
2655 
2656 extern "C" void unexpected_adapter_call() {
2657   ShouldNotCallThis();
2658 }
2659 
2660 static void post_adapter_creation(const AdapterBlob* new_adapter, const AdapterHandlerEntry* entry) {
2661   char blob_id[256];
2662   jio_snprintf(blob_id,
2663                 sizeof(blob_id),
2664                 "%s(%s)",
2665                 new_adapter->name(),
2666                 entry->fingerprint()->as_string());
2667   Forte::register_stub(blob_id, new_adapter->content_begin(), new_adapter->content_end());
2668 
2669   if (JvmtiExport::should_post_dynamic_code_generated()) {

2673 
2674 void AdapterHandlerLibrary::initialize() {
2675   ResourceMark rm;
2676   AdapterBlob* no_arg_blob = NULL;
2677   AdapterBlob* int_arg_blob = NULL;
2678   AdapterBlob* obj_arg_blob = NULL;
2679   AdapterBlob* obj_int_arg_blob = NULL;
2680   AdapterBlob* obj_obj_arg_blob = NULL;
2681   {
2682     MutexLocker mu(AdapterHandlerLibrary_lock);
2683     assert(_adapters == NULL, "Initializing more than once");
2684 
2685     _adapters = new AdapterHandlerTable();
2686 
2687     // Create a special handler for abstract methods.  Abstract methods
2688     // are never compiled so an i2c entry is somewhat meaningless, but
2689     // throw AbstractMethodError just in case.
2690     // Pass wrong_method_abstract for the c2i transitions to return
2691     // AbstractMethodError for invalid invocations.
2692     address wrong_method_abstract = SharedRuntime::get_handle_wrong_method_abstract_stub();
2693     _abstract_method_handler = AdapterHandlerLibrary::new_entry(new AdapterFingerPrint(0, NULL),
2694                                                                 StubRoutines::throw_AbstractMethodError_entry(),

2695                                                                 wrong_method_abstract, wrong_method_abstract);
2696 
2697     _buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size);
2698 
2699     _no_arg_handler = create_adapter(no_arg_blob, 0, NULL, true);


2700 
2701     BasicType obj_args[] = { T_OBJECT };
2702     _obj_arg_handler = create_adapter(obj_arg_blob, 1, obj_args, true);


2703 
2704     BasicType int_args[] = { T_INT };
2705     _int_arg_handler = create_adapter(int_arg_blob, 1, int_args, true);


2706 
2707     BasicType obj_int_args[] = { T_OBJECT, T_INT };
2708     _obj_int_arg_handler = create_adapter(obj_int_arg_blob, 2, obj_int_args, true);



2709 
2710     BasicType obj_obj_args[] = { T_OBJECT, T_OBJECT };
2711     _obj_obj_arg_handler = create_adapter(obj_obj_arg_blob, 2, obj_obj_args, true);



2712 
2713     assert(no_arg_blob != NULL &&
2714           obj_arg_blob != NULL &&
2715           int_arg_blob != NULL &&
2716           obj_int_arg_blob != NULL &&
2717           obj_obj_arg_blob != NULL, "Initial adapters must be properly created");
2718   }

2719 
2720   // Outside of the lock
2721   post_adapter_creation(no_arg_blob, _no_arg_handler);
2722   post_adapter_creation(obj_arg_blob, _obj_arg_handler);
2723   post_adapter_creation(int_arg_blob, _int_arg_handler);
2724   post_adapter_creation(obj_int_arg_blob, _obj_int_arg_handler);
2725   post_adapter_creation(obj_obj_arg_blob, _obj_obj_arg_handler);
2726 }
2727 
2728 AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint,
2729                                                       address i2c_entry,
2730                                                       address c2i_entry,


2731                                                       address c2i_unverified_entry,

2732                                                       address c2i_no_clinit_check_entry) {
2733   return _adapters->new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry, c2i_no_clinit_check_entry);

2734 }
2735 
2736 AdapterHandlerEntry* AdapterHandlerLibrary::get_simple_adapter(const methodHandle& method) {
2737   if (method->is_abstract()) {
2738     return _abstract_method_handler;
2739   }
2740   int total_args_passed = method->size_of_parameters(); // All args on stack
2741   if (total_args_passed == 0) {
2742     return _no_arg_handler;
2743   } else if (total_args_passed == 1) {
2744     if (!method->is_static()) {
2745       return _obj_arg_handler;
2746     }
2747     switch (method->signature()->char_at(1)) {
2748       case JVM_SIGNATURE_CLASS:








2749       case JVM_SIGNATURE_ARRAY:
2750         return _obj_arg_handler;
2751       case JVM_SIGNATURE_INT:
2752       case JVM_SIGNATURE_BOOLEAN:
2753       case JVM_SIGNATURE_CHAR:
2754       case JVM_SIGNATURE_BYTE:
2755       case JVM_SIGNATURE_SHORT:
2756         return _int_arg_handler;
2757     }
2758   } else if (total_args_passed == 2 &&
2759              !method->is_static()) {
2760     switch (method->signature()->char_at(1)) {
2761       case JVM_SIGNATURE_CLASS:








2762       case JVM_SIGNATURE_ARRAY:
2763         return _obj_obj_arg_handler;
2764       case JVM_SIGNATURE_INT:
2765       case JVM_SIGNATURE_BOOLEAN:
2766       case JVM_SIGNATURE_CHAR:
2767       case JVM_SIGNATURE_BYTE:
2768       case JVM_SIGNATURE_SHORT:
2769         return _obj_int_arg_handler;
2770     }
2771   }
2772   return NULL;
2773 }
2774 
2775 class AdapterSignatureIterator : public SignatureIterator {
2776  private:
2777   BasicType stack_sig_bt[16];
2778   BasicType* sig_bt;
2779   int index;




2780 
2781  public:
2782   AdapterSignatureIterator(Symbol* signature,
2783                            fingerprint_t fingerprint,
2784                            bool is_static,
2785                            int total_args_passed) :
2786     SignatureIterator(signature, fingerprint),
2787     index(0)
2788   {
2789     sig_bt = (total_args_passed <= 16) ? stack_sig_bt : NEW_RESOURCE_ARRAY(BasicType, total_args_passed);
2790     if (!is_static) { // Pass in receiver first
2791       sig_bt[index++] = T_OBJECT;
2792     }
2793     do_parameters_on(this);
2794   }
2795 
2796   BasicType* basic_types() {
2797     return sig_bt;











2798   }
2799 
2800 #ifdef ASSERT
2801   int slots() {
2802     return index;





























































2803   }
2804 #endif
2805 
2806  private:













2807 
2808   friend class SignatureIterator;  // so do_parameters_on can call do_type
2809   void do_type(BasicType type) {
2810     sig_bt[index++] = type;
2811     if (type == T_LONG || type == T_DOUBLE) {
2812       sig_bt[index++] = T_VOID; // Longs & doubles take 2 Java slots
2813     }
2814   }
2815 };









2816 
2817 AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(const methodHandle& method) {
2818   // Use customized signature handler.  Need to lock around updates to
2819   // the AdapterHandlerTable (it is not safe for concurrent readers
2820   // and a single writer: this could be fixed if it becomes a
2821   // problem).
2822   assert(_adapters != NULL, "Uninitialized");
2823 
2824   // Fast-path for trivial adapters
2825   AdapterHandlerEntry* entry = get_simple_adapter(method);
2826   if (entry != NULL) {
2827     return entry;
2828   }
2829 
2830   ResourceMark rm;
2831   AdapterBlob* new_adapter = NULL;
2832 
2833   // Fill in the signature array, for the calling-convention call.
2834   int total_args_passed = method->size_of_parameters(); // All args on stack







2835 
2836   AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(),
2837                               method->is_static(), total_args_passed);
2838   assert(si.slots() == total_args_passed, "");
2839   BasicType* sig_bt = si.basic_types();
2840   {
2841     MutexLocker mu(AdapterHandlerLibrary_lock);
2842 













2843     // Lookup method signature's fingerprint
2844     entry = _adapters->lookup(total_args_passed, sig_bt);
2845 
2846     if (entry != NULL) {
2847 #ifdef ASSERT
2848       if (VerifyAdapterSharing) {
2849         AdapterBlob* comparison_blob = NULL;
2850         AdapterHandlerEntry* comparison_entry = create_adapter(comparison_blob, total_args_passed, sig_bt, false);
2851         assert(comparison_blob == NULL, "no blob should be created when creating an adapter for comparison");
2852         assert(comparison_entry->compare_code(entry), "code must match");
2853         // Release the one just created and return the original
2854         _adapters->free_entry(comparison_entry);
2855       }
2856 #endif
2857       return entry;
2858     }
2859 
2860     entry = create_adapter(new_adapter, total_args_passed, sig_bt, /* allocate_code_blob */ true);
2861   }
2862 
2863   // Outside of the lock
2864   if (new_adapter != NULL) {
2865     post_adapter_creation(new_adapter, entry);
2866   }
2867   return entry;
2868 }
2869 
2870 AdapterHandlerEntry* AdapterHandlerLibrary::create_adapter(AdapterBlob*& new_adapter,
2871                                                            int total_args_passed,
2872                                                            BasicType* sig_bt,
2873                                                            bool allocate_code_blob) {
2874 
2875   // StubRoutines::code2() is initialized after this function can be called. As a result,
2876   // VerifyAdapterCalls and VerifyAdapterSharing can fail if we re-use code that generated
2877   // prior to StubRoutines::code2() being set. Checks refer to checks generated in an I2C
2878   // stub that ensure that an I2C stub is called from an interpreter frame.
2879   bool contains_all_checks = StubRoutines::code2() != NULL;
2880 
2881   VMRegPair stack_regs[16];
2882   VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
2883 
2884   // Get a description of the compiled java calling convention and the largest used (VMReg) stack slot usage
2885   int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
2886   BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
2887   CodeBuffer buffer(buf);
2888   short buffer_locs[20];
2889   buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs,
2890                                           sizeof(buffer_locs)/sizeof(relocInfo));
2891 
2892   // Make a C heap allocated version of the fingerprint to store in the adapter
2893   AdapterFingerPrint* fingerprint = new AdapterFingerPrint(total_args_passed, sig_bt);
2894   MacroAssembler _masm(&buffer);
2895   AdapterHandlerEntry* entry = SharedRuntime::generate_i2c2i_adapters(&_masm,
2896                                                 total_args_passed,
2897                                                 comp_args_on_stack,
2898                                                 sig_bt,
2899                                                 regs,
2900                                                 fingerprint);












2901 
2902 #ifdef ASSERT
2903   if (VerifyAdapterSharing) {
2904     entry->save_code(buf->code_begin(), buffer.insts_size());
2905     if (!allocate_code_blob) {
2906       return entry;
2907     }
2908   }
2909 #endif
2910 
2911   new_adapter = AdapterBlob::create(&buffer);
2912   NOT_PRODUCT(int insts_size = buffer.insts_size());
2913   if (new_adapter == NULL) {
2914     // CodeCache is full, disable compilation
2915     // Ought to log this but compile log is only per compile thread
2916     // and we're some non descript Java thread.
2917     return NULL;
2918   }
2919   entry->relocate(new_adapter->content_begin());
2920 #ifndef PRODUCT
2921   // debugging suppport
2922   if (PrintAdapterHandlers || PrintStubCode) {
2923     ttyLocker ttyl;
2924     entry->print_adapter_on(tty);
2925     tty->print_cr("i2c argument handler #%d for: %s %s (%d bytes generated)",
2926                   _adapters->number_of_entries(), fingerprint->as_basic_args_string(),
2927                   fingerprint->as_string(), insts_size);
2928     tty->print_cr("c2i argument handler starts at %p", entry->get_c2i_entry());
2929     if (Verbose || PrintStubCode) {
2930       address first_pc = entry->base_address();
2931       if (first_pc != NULL) {
2932         Disassembler::decode(first_pc, first_pc + insts_size, tty
2933                              NOT_PRODUCT(COMMA &new_adapter->asm_remarks()));
2934         tty->cr();
2935       }
2936     }
2937   }
2938 #endif
2939 
2940   // Add the entry only if the entry contains all required checks (see sharedRuntime_xxx.cpp)
2941   // The checks are inserted only if -XX:+VerifyAdapterCalls is specified.
2942   if (contains_all_checks || !VerifyAdapterCalls) {
2943     _adapters->add(entry);
2944   }
2945   return entry;
2946 }
2947 
2948 address AdapterHandlerEntry::base_address() {
2949   address base = _i2c_entry;
2950   if (base == NULL)  base = _c2i_entry;
2951   assert(base <= _c2i_entry || _c2i_entry == NULL, "");


2952   assert(base <= _c2i_unverified_entry || _c2i_unverified_entry == NULL, "");

2953   assert(base <= _c2i_no_clinit_check_entry || _c2i_no_clinit_check_entry == NULL, "");
2954   return base;
2955 }
2956 
2957 void AdapterHandlerEntry::relocate(address new_base) {
2958   address old_base = base_address();
2959   assert(old_base != NULL, "");
2960   ptrdiff_t delta = new_base - old_base;
2961   if (_i2c_entry != NULL)
2962     _i2c_entry += delta;
2963   if (_c2i_entry != NULL)
2964     _c2i_entry += delta;




2965   if (_c2i_unverified_entry != NULL)
2966     _c2i_unverified_entry += delta;


2967   if (_c2i_no_clinit_check_entry != NULL)
2968     _c2i_no_clinit_check_entry += delta;
2969   assert(base_address() == new_base, "");
2970 }
2971 
2972 
2973 void AdapterHandlerEntry::deallocate() {
2974   delete _fingerprint;



2975 #ifdef ASSERT
2976   FREE_C_HEAP_ARRAY(unsigned char, _saved_code);
2977 #endif
2978 }
2979 
2980 
2981 #ifdef ASSERT
2982 // Capture the code before relocation so that it can be compared
2983 // against other versions.  If the code is captured after relocation
2984 // then relative instructions won't be equivalent.
2985 void AdapterHandlerEntry::save_code(unsigned char* buffer, int length) {
2986   _saved_code = NEW_C_HEAP_ARRAY(unsigned char, length, mtCode);
2987   _saved_code_length = length;
2988   memcpy(_saved_code, buffer, length);
2989 }
2990 
2991 
2992 bool AdapterHandlerEntry::compare_code(AdapterHandlerEntry* other) {
2993   assert(_saved_code != NULL && other->_saved_code != NULL, "code not saved");
2994 

3027     assert(compile_id > 0, "Must generate native wrapper");
3028 
3029 
3030     ResourceMark rm;
3031     BufferBlob*  buf = buffer_blob(); // the temporary code buffer in CodeCache
3032     if (buf != NULL) {
3033       CodeBuffer buffer(buf);
3034       struct { double data[20]; } locs_buf;
3035       buffer.insts()->initialize_shared_locs((relocInfo*)&locs_buf, sizeof(locs_buf) / sizeof(relocInfo));
3036 #if defined(AARCH64)
3037       // On AArch64 with ZGC and nmethod entry barriers, we need all oops to be
3038       // in the constant pool to ensure ordering between the barrier and oops
3039       // accesses. For native_wrappers we need a constant.
3040       buffer.initialize_consts_size(8);
3041 #endif
3042       MacroAssembler _masm(&buffer);
3043 
3044       // Fill in the signature array, for the calling-convention call.
3045       const int total_args_passed = method->size_of_parameters();
3046 

3047       VMRegPair stack_regs[16];

3048       VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
3049 
3050       AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(),
3051                               method->is_static(), total_args_passed);
3052       BasicType* sig_bt = si.basic_types();
3053       assert(si.slots() == total_args_passed, "");
3054       BasicType ret_type = si.return_type();








3055 
3056       // Now get the compiled-Java arguments layout.
3057       int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
3058 
3059       // Generate the compiled-to-native wrapper code
3060       nm = SharedRuntime::generate_native_wrapper(&_masm, method, compile_id, sig_bt, regs, ret_type);
3061 
3062       if (nm != NULL) {
3063         {
3064           MutexLocker pl(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
3065           if (nm->make_in_use()) {
3066             method->set_code(method, nm);
3067           }
3068         }
3069 
3070         DirectiveSet* directive = DirectivesStack::getDefaultDirective(CompileBroker::compiler(CompLevel_simple));
3071         if (directive->PrintAssemblyOption) {
3072           nm->print_code();
3073         }
3074         DirectivesStack::release(directive);

3255   AdapterHandlerTableIterator iter(_adapters);
3256   while (iter.has_next()) {
3257     AdapterHandlerEntry* a = iter.next();
3258     if (b == CodeCache::find_blob(a->get_i2c_entry())) {
3259       st->print("Adapter for signature: ");
3260       a->print_adapter_on(tty);
3261       return;
3262     }
3263   }
3264   assert(false, "Should have found handler");
3265 }
3266 
3267 void AdapterHandlerEntry::print_adapter_on(outputStream* st) const {
3268   st->print("AHE@" INTPTR_FORMAT ": %s", p2i(this), fingerprint()->as_string());
3269   if (get_i2c_entry() != NULL) {
3270     st->print(" i2c: " INTPTR_FORMAT, p2i(get_i2c_entry()));
3271   }
3272   if (get_c2i_entry() != NULL) {
3273     st->print(" c2i: " INTPTR_FORMAT, p2i(get_c2i_entry()));
3274   }









3275   if (get_c2i_unverified_entry() != NULL) {
3276     st->print(" c2iUV: " INTPTR_FORMAT, p2i(get_c2i_unverified_entry()));
3277   }
3278   if (get_c2i_no_clinit_check_entry() != NULL) {
3279     st->print(" c2iNCI: " INTPTR_FORMAT, p2i(get_c2i_no_clinit_check_entry()));
3280   }
3281   st->cr();
3282 }
3283 
3284 #ifndef PRODUCT
3285 
3286 void AdapterHandlerLibrary::print_statistics() {
3287   _adapters->print_statistics();
3288 }
3289 
3290 #endif /* PRODUCT */
3291 
3292 JRT_LEAF(void, SharedRuntime::enable_stack_reserved_zone(JavaThread* current))
3293   StackOverflow* overflow_state = current->stack_overflow_state();
3294   overflow_state->enable_stack_reserved_zone(/*check_if_disabled*/true);
3295   overflow_state->set_reserved_stack_activation(current->stack_base());
3296 JRT_END

3341       break;
3342     } else {
3343       fr = fr.java_sender();
3344     }
3345   }
3346   return activation;
3347 }
3348 
3349 void SharedRuntime::on_slowpath_allocation_exit(JavaThread* current) {
3350   // After any safepoint, just before going back to compiled code,
3351   // we inform the GC that we will be doing initializing writes to
3352   // this object in the future without emitting card-marks, so
3353   // GC may take any compensating steps.
3354 
3355   oop new_obj = current->vm_result();
3356   if (new_obj == NULL) return;
3357 
3358   BarrierSet *bs = BarrierSet::barrier_set();
3359   bs->on_slowpath_allocation_exit(current, new_obj);
3360 }































































































































































































  27 #include "jvm.h"
  28 #include "classfile/stringTable.hpp"
  29 #include "classfile/vmClasses.hpp"
  30 #include "classfile/vmSymbols.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "code/compiledIC.hpp"
  33 #include "code/icBuffer.hpp"
  34 #include "code/compiledMethod.inline.hpp"
  35 #include "code/scopeDesc.hpp"
  36 #include "code/vtableStubs.hpp"
  37 #include "compiler/abstractCompiler.hpp"
  38 #include "compiler/compileBroker.hpp"
  39 #include "compiler/disassembler.hpp"
  40 #include "gc/shared/barrierSet.hpp"
  41 #include "gc/shared/collectedHeap.hpp"
  42 #include "gc/shared/gcLocker.inline.hpp"
  43 #include "interpreter/interpreter.hpp"
  44 #include "interpreter/interpreterRuntime.hpp"
  45 #include "jfr/jfrEvents.hpp"
  46 #include "logging/log.hpp"
  47 #include "memory/oopFactory.hpp"
  48 #include "memory/resourceArea.hpp"
  49 #include "memory/universe.hpp"
  50 #include "oops/access.hpp"
  51 #include "oops/fieldStreams.inline.hpp"
  52 #include "oops/compiledICHolder.inline.hpp"
  53 #include "oops/klass.hpp"
  54 #include "oops/method.inline.hpp"
  55 #include "oops/objArrayKlass.hpp"
  56 #include "oops/objArrayOop.inline.hpp"
  57 #include "oops/oop.inline.hpp"
  58 #include "oops/inlineKlass.inline.hpp"
  59 #include "prims/forte.hpp"
  60 #include "prims/jvmtiExport.hpp"
  61 #include "prims/methodHandles.hpp"
  62 #include "prims/nativeLookup.hpp"
  63 #include "runtime/atomic.hpp"
  64 #include "runtime/frame.inline.hpp"
  65 #include "runtime/handles.inline.hpp"
  66 #include "runtime/init.hpp"
  67 #include "runtime/interfaceSupport.inline.hpp"
  68 #include "runtime/java.hpp"
  69 #include "runtime/javaCalls.hpp"
  70 #include "runtime/sharedRuntime.hpp"
  71 #include "runtime/stackWatermarkSet.hpp"
  72 #include "runtime/stubRoutines.hpp"
  73 #include "runtime/synchronizer.hpp"
  74 #include "runtime/vframe.inline.hpp"
  75 #include "runtime/vframeArray.hpp"
  76 #include "runtime/vm_version.hpp"
  77 #include "utilities/copy.hpp"
  78 #include "utilities/dtrace.hpp"
  79 #include "utilities/events.hpp"
  80 #include "utilities/hashtable.inline.hpp"
  81 #include "utilities/macros.hpp"
  82 #include "utilities/xmlstream.hpp"
  83 #ifdef COMPILER1
  84 #include "c1/c1_Runtime1.hpp"
  85 #endif
  86 
  87 // Shared stub locations
  88 RuntimeStub*        SharedRuntime::_wrong_method_blob;
  89 RuntimeStub*        SharedRuntime::_wrong_method_abstract_blob;
  90 RuntimeStub*        SharedRuntime::_ic_miss_blob;
  91 RuntimeStub*        SharedRuntime::_resolve_opt_virtual_call_blob;
  92 RuntimeStub*        SharedRuntime::_resolve_virtual_call_blob;
  93 RuntimeStub*        SharedRuntime::_resolve_static_call_blob;

  94 
  95 DeoptimizationBlob* SharedRuntime::_deopt_blob;
  96 SafepointBlob*      SharedRuntime::_polling_page_vectors_safepoint_handler_blob;
  97 SafepointBlob*      SharedRuntime::_polling_page_safepoint_handler_blob;
  98 SafepointBlob*      SharedRuntime::_polling_page_return_handler_blob;
  99 
 100 #ifdef COMPILER2
 101 UncommonTrapBlob*   SharedRuntime::_uncommon_trap_blob;
 102 #endif // COMPILER2
 103 
 104 
 105 //----------------------------generate_stubs-----------------------------------
 106 void SharedRuntime::generate_stubs() {
 107   _wrong_method_blob                   = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method),          "wrong_method_stub");
 108   _wrong_method_abstract_blob          = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_abstract), "wrong_method_abstract_stub");
 109   _ic_miss_blob                        = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_ic_miss),  "ic_miss_stub");
 110   _resolve_opt_virtual_call_blob       = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_opt_virtual_call_C),   "resolve_opt_virtual_call");
 111   _resolve_virtual_call_blob           = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_virtual_call_C),       "resolve_virtual_call");
 112   _resolve_static_call_blob            = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_static_call_C),        "resolve_static_call");

 113 
 114   AdapterHandlerLibrary::initialize();
 115 
 116 #if COMPILER2_OR_JVMCI
 117   // Vectors are generated only by C2 and JVMCI.
 118   bool support_wide = is_wide_vector(MaxVectorSize);
 119   if (support_wide) {
 120     _polling_page_vectors_safepoint_handler_blob = generate_handler_blob(CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception), POLL_AT_VECTOR_LOOP);
 121   }
 122 #endif // COMPILER2_OR_JVMCI
 123   _polling_page_safepoint_handler_blob = generate_handler_blob(CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception), POLL_AT_LOOP);
 124   _polling_page_return_handler_blob    = generate_handler_blob(CAST_FROM_FN_PTR(address, SafepointSynchronize::handle_polling_page_exception), POLL_AT_RETURN);
 125 
 126   generate_deopt_blob();
 127 
 128 #ifdef COMPILER2
 129   generate_uncommon_trap_blob();
 130 #endif // COMPILER2
 131 }
 132 

 972   // forwarded before we look at the return value.
 973   THROW_(vmSymbols::java_lang_UnsatisfiedLinkError(), (void*)badAddress);
 974 }
 975 JNI_END
 976 
 977 address SharedRuntime::native_method_throw_unsatisfied_link_error_entry() {
 978   return CAST_FROM_FN_PTR(address, &throw_unsatisfied_link_error);
 979 }
 980 
 981 JRT_ENTRY_NO_ASYNC(void, SharedRuntime::register_finalizer(JavaThread* current, oopDesc* obj))
 982 #if INCLUDE_JVMCI
 983   if (!obj->klass()->has_finalizer()) {
 984     return;
 985   }
 986 #endif // INCLUDE_JVMCI
 987   assert(oopDesc::is_oop(obj), "must be a valid oop");
 988   assert(obj->klass()->has_finalizer(), "shouldn't be here otherwise");
 989   InstanceKlass::register_finalizer(instanceOop(obj), CHECK);
 990 JRT_END
 991 
 992 
 993 jlong SharedRuntime::get_java_tid(Thread* thread) {
 994   if (thread != NULL) {
 995     if (thread->is_Java_thread()) {
 996       oop obj = JavaThread::cast(thread)->threadObj();
 997       return (obj == NULL) ? 0 : java_lang_Thread::thread_id(obj);
 998     }
 999   }
1000   return 0;
1001 }
1002 
1003 /**
1004  * This function ought to be a void function, but cannot be because
1005  * it gets turned into a tail-call on sparc, which runs into dtrace bug
1006  * 6254741.  Once that is fixed we can remove the dummy return value.
1007  */
1008 int SharedRuntime::dtrace_object_alloc(oopDesc* o) {
1009   return dtrace_object_alloc(Thread::current(), o, o->size());
1010 }
1011 
1012 int SharedRuntime::dtrace_object_alloc(Thread* thread, oopDesc* o) {

1077     return caller->attached_method_before_pc(pc);
1078   }
1079   return NULL;
1080 }
1081 
1082 // Finds receiver, CallInfo (i.e. receiver method), and calling bytecode
1083 // for a call current in progress, i.e., arguments has been pushed on stack
1084 // but callee has not been invoked yet.  Caller frame must be compiled.
1085 Handle SharedRuntime::find_callee_info_helper(vframeStream& vfst, Bytecodes::Code& bc,
1086                                               CallInfo& callinfo, TRAPS) {
1087   Handle receiver;
1088   Handle nullHandle;  // create a handy null handle for exception returns
1089   JavaThread* current = THREAD;
1090 
1091   assert(!vfst.at_end(), "Java frame must exist");
1092 
1093   // Find caller and bci from vframe
1094   methodHandle caller(current, vfst.method());
1095   int          bci   = vfst.bci();
1096 
1097   // Substitutability test implementation piggy backs on static call resolution
1098   Bytecodes::Code code = caller->java_code_at(bci);
1099   if (code == Bytecodes::_if_acmpeq || code == Bytecodes::_if_acmpne) {
1100     bc = Bytecodes::_invokestatic;
1101     methodHandle attached_method(THREAD, extract_attached_method(vfst));
1102     assert(attached_method.not_null(), "must have attached method");
1103     vmClasses::PrimitiveObjectMethods_klass()->initialize(CHECK_NH);
1104     LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, false, CHECK_NH);
1105 #ifdef ASSERT
1106     Method* is_subst = vmClasses::PrimitiveObjectMethods_klass()->find_method(vmSymbols::isSubstitutable_name(), vmSymbols::object_object_boolean_signature());
1107     assert(callinfo.selected_method() == is_subst, "must be isSubstitutable method");
1108 #endif
1109     return receiver;
1110   }
1111 
1112   Bytecode_invoke bytecode(caller, bci);
1113   int bytecode_index = bytecode.index();
1114   bc = bytecode.invoke_code();
1115 
1116   methodHandle attached_method(current, extract_attached_method(vfst));
1117   if (attached_method.not_null()) {
1118     Method* callee = bytecode.static_target(CHECK_NH);
1119     vmIntrinsics::ID id = callee->intrinsic_id();
1120     // When VM replaces MH.invokeBasic/linkTo* call with a direct/virtual call,
1121     // it attaches statically resolved method to the call site.
1122     if (MethodHandles::is_signature_polymorphic(id) &&
1123         MethodHandles::is_signature_polymorphic_intrinsic(id)) {
1124       bc = MethodHandles::signature_polymorphic_intrinsic_bytecode(id);
1125 
1126       // Adjust invocation mode according to the attached method.
1127       switch (bc) {
1128         case Bytecodes::_invokevirtual:
1129           if (attached_method->method_holder()->is_interface()) {
1130             bc = Bytecodes::_invokeinterface;
1131           }
1132           break;
1133         case Bytecodes::_invokeinterface:
1134           if (!attached_method->method_holder()->is_interface()) {
1135             bc = Bytecodes::_invokevirtual;
1136           }
1137           break;
1138         case Bytecodes::_invokehandle:
1139           if (!MethodHandles::is_signature_polymorphic_method(attached_method())) {
1140             bc = attached_method->is_static() ? Bytecodes::_invokestatic
1141                                               : Bytecodes::_invokevirtual;
1142           }
1143           break;
1144         default:
1145           break;
1146       }
1147     } else {
1148       assert(attached_method->has_scalarized_args(), "invalid use of attached method");
1149       if (!attached_method->method_holder()->is_inline_klass()) {
1150         // Ignore the attached method in this case to not confuse below code
1151         attached_method = methodHandle(current, NULL);
1152       }
1153     }
1154   }
1155 
1156   assert(bc != Bytecodes::_illegal, "not initialized");
1157 
1158   bool has_receiver = bc != Bytecodes::_invokestatic &&
1159                       bc != Bytecodes::_invokedynamic &&
1160                       bc != Bytecodes::_invokehandle;
1161   bool check_null_and_abstract = true;
1162 
1163   // Find receiver for non-static call
1164   if (has_receiver) {
1165     // This register map must be update since we need to find the receiver for
1166     // compiled frames. The receiver might be in a register.
1167     RegisterMap reg_map2(current);
1168     frame stubFrame   = current->last_frame();
1169     // Caller-frame is a compiled frame
1170     frame callerFrame = stubFrame.sender(&reg_map2);
1171     bool caller_is_c1 = false;
1172 
1173     if (callerFrame.is_compiled_frame() && !callerFrame.is_deoptimized_frame()) {
1174       caller_is_c1 = callerFrame.cb()->is_compiled_by_c1();
1175     }
1176 
1177     Method* callee = attached_method();
1178     if (callee == NULL) {
1179       callee = bytecode.static_target(CHECK_NH);
1180       if (callee == NULL) {
1181         THROW_(vmSymbols::java_lang_NoSuchMethodException(), nullHandle);
1182       }
1183     }
1184     if (!caller_is_c1 && callee->is_scalarized_arg(0)) {
1185       // If the receiver is an inline type that is passed as fields, no oop is available
1186       // Resolve the call without receiver null checking.
1187       assert(attached_method.not_null() && !attached_method->is_abstract(), "must have non-abstract attached method");
1188       if (bc == Bytecodes::_invokeinterface) {
1189         bc = Bytecodes::_invokevirtual; // C2 optimistically replaces interface calls by virtual calls
1190       }
1191       check_null_and_abstract = false;
1192     } else {
1193       // Retrieve from a compiled argument list
1194       receiver = Handle(current, callerFrame.retrieve_receiver(&reg_map2));
1195       if (receiver.is_null()) {
1196         THROW_(vmSymbols::java_lang_NullPointerException(), nullHandle);
1197       }
1198     }
1199   }
1200 
1201   // Resolve method
1202   if (attached_method.not_null()) {
1203     // Parameterized by attached method.
1204     LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, check_null_and_abstract, CHECK_NH);
1205   } else {
1206     // Parameterized by bytecode.
1207     constantPoolHandle constants(current, caller->constants());
1208     LinkResolver::resolve_invoke(callinfo, receiver, constants, bytecode_index, bc, CHECK_NH);
1209   }
1210 
1211 #ifdef ASSERT
1212   // Check that the receiver klass is of the right subtype and that it is initialized for virtual calls
1213   if (has_receiver && check_null_and_abstract) {
1214     assert(receiver.not_null(), "should have thrown exception");
1215     Klass* receiver_klass = receiver->klass();
1216     Klass* rk = NULL;
1217     if (attached_method.not_null()) {
1218       // In case there's resolved method attached, use its holder during the check.
1219       rk = attached_method->method_holder();
1220     } else {
1221       // Klass is already loaded.
1222       constantPoolHandle constants(current, caller->constants());
1223       rk = constants->klass_ref_at(bytecode_index, CHECK_NH);
1224     }
1225     Klass* static_receiver_klass = rk;
1226     assert(receiver_klass->is_subtype_of(static_receiver_klass),
1227            "actual receiver must be subclass of static receiver klass");
1228     if (receiver_klass->is_instance_klass()) {
1229       if (InstanceKlass::cast(receiver_klass)->is_not_initialized()) {
1230         tty->print_cr("ERROR: Klass not yet initialized!!");
1231         receiver_klass->print();
1232       }
1233       assert(!InstanceKlass::cast(receiver_klass)->is_not_initialized(), "receiver_klass must be initialized");

1251     // Hence the stack can only contain an entry_frame.  We need to
1252     // find the target method from the stub frame.
1253     RegisterMap reg_map(current, false);
1254     frame fr = current->last_frame();
1255     assert(fr.is_runtime_frame(), "must be a runtimeStub");
1256     fr = fr.sender(&reg_map);
1257     assert(fr.is_entry_frame(), "must be");
1258     // fr is now pointing to the entry frame.
1259     callee_method = methodHandle(current, fr.entry_frame_call_wrapper()->callee_method());
1260   } else {
1261     Bytecodes::Code bc;
1262     CallInfo callinfo;
1263     find_callee_info_helper(vfst, bc, callinfo, CHECK_(methodHandle()));
1264     callee_method = methodHandle(current, callinfo.selected_method());
1265   }
1266   assert(callee_method()->is_method(), "must be");
1267   return callee_method;
1268 }
1269 
1270 // Resolves a call.
1271 methodHandle SharedRuntime::resolve_helper(bool is_virtual, bool is_optimized, bool* caller_is_c1, TRAPS) {
1272   methodHandle callee_method;
1273   callee_method = resolve_sub_helper(is_virtual, is_optimized, caller_is_c1, THREAD);
1274   if (JvmtiExport::can_hotswap_or_post_breakpoint()) {
1275     int retry_count = 0;
1276     while (!HAS_PENDING_EXCEPTION && callee_method->is_old() &&
1277            callee_method->method_holder() != vmClasses::Object_klass()) {
1278       // If has a pending exception then there is no need to re-try to
1279       // resolve this method.
1280       // If the method has been redefined, we need to try again.
1281       // Hack: we have no way to update the vtables of arrays, so don't
1282       // require that java.lang.Object has been updated.
1283 
1284       // It is very unlikely that method is redefined more than 100 times
1285       // in the middle of resolve. If it is looping here more than 100 times
1286       // means then there could be a bug here.
1287       guarantee((retry_count++ < 100),
1288                 "Could not resolve to latest version of redefined method");
1289       // method is redefined in the middle of resolve so re-try.
1290       callee_method = resolve_sub_helper(is_virtual, is_optimized, caller_is_c1, THREAD);
1291     }
1292   }
1293   return callee_method;
1294 }
1295 
1296 // This fails if resolution required refilling of IC stubs
1297 bool SharedRuntime::resolve_sub_helper_internal(methodHandle callee_method, const frame& caller_frame,
1298                                                 CompiledMethod* caller_nm, bool is_virtual, bool is_optimized,
1299                                                 Handle receiver, CallInfo& call_info, Bytecodes::Code invoke_code, TRAPS) {
1300   StaticCallInfo static_call_info;
1301   CompiledICInfo virtual_call_info;
1302 
1303   // Make sure the callee nmethod does not get deoptimized and removed before
1304   // we are done patching the code.
1305   CompiledMethod* callee = callee_method->code();
1306 
1307   if (callee != NULL) {
1308     assert(callee->is_compiled(), "must be nmethod for patching");
1309   }
1310 
1311   if (callee != NULL && !callee->is_in_use()) {
1312     // Patch call site to C2I adapter if callee nmethod is deoptimized or unloaded.
1313     callee = NULL;
1314   }
1315   nmethodLocker nl_callee(callee);
1316 #ifdef ASSERT
1317   address dest_entry_point = callee == NULL ? 0 : callee->entry_point(); // used below
1318 #endif
1319 
1320   bool is_nmethod = caller_nm->is_nmethod();
1321   bool caller_is_c1 = caller_nm->is_compiled_by_c1();
1322 
1323   if (is_virtual) {
1324     Klass* receiver_klass = NULL;
1325     if (!caller_is_c1 && callee_method->is_scalarized_arg(0)) {
1326       // If the receiver is an inline type that is passed as fields, no oop is available
1327       receiver_klass = callee_method->method_holder();
1328     } else {
1329       assert(receiver.not_null() || invoke_code == Bytecodes::_invokehandle, "sanity check");
1330       receiver_klass = invoke_code == Bytecodes::_invokehandle ? NULL : receiver->klass();
1331     }
1332     bool static_bound = call_info.resolved_method()->can_be_statically_bound();
1333     CompiledIC::compute_monomorphic_entry(callee_method, receiver_klass,
1334                      is_optimized, static_bound, is_nmethod, caller_is_c1, virtual_call_info,

1335                      CHECK_false);
1336   } else {
1337     // static call
1338     CompiledStaticCall::compute_entry(callee_method, caller_nm, static_call_info);
1339   }
1340 
1341   // grab lock, check for deoptimization and potentially patch caller
1342   {
1343     CompiledICLocker ml(caller_nm);
1344 
1345     // Lock blocks for safepoint during which both nmethods can change state.
1346 
1347     // Now that we are ready to patch if the Method* was redefined then
1348     // don't update call site and let the caller retry.
1349     // Don't update call site if callee nmethod was unloaded or deoptimized.
1350     // Don't update call site if callee nmethod was replaced by an other nmethod
1351     // which may happen when multiply alive nmethod (tiered compilation)
1352     // will be supported.
1353     if (!callee_method->is_old() &&
1354         (callee == NULL || (callee->is_in_use() && callee_method->code() == callee))) {
1355       NoSafepointVerifier nsv;
1356 #ifdef ASSERT
1357       // We must not try to patch to jump to an already unloaded method.
1358       if (dest_entry_point != 0) {

1368             return false;
1369           }
1370         }
1371       } else {
1372         if (VM_Version::supports_fast_class_init_checks() &&
1373             invoke_code == Bytecodes::_invokestatic &&
1374             callee_method->needs_clinit_barrier() &&
1375             callee != NULL && callee->is_compiled_by_jvmci()) {
1376           return true; // skip patching for JVMCI
1377         }
1378         CompiledStaticCall* ssc = caller_nm->compiledStaticCall_before(caller_frame.pc());
1379         if (ssc->is_clean()) ssc->set(static_call_info);
1380       }
1381     }
1382   } // unlock CompiledICLocker
1383   return true;
1384 }
1385 
1386 // Resolves a call.  The compilers generate code for calls that go here
1387 // and are patched with the real destination of the call.
1388 methodHandle SharedRuntime::resolve_sub_helper(bool is_virtual, bool is_optimized, bool* caller_is_c1, TRAPS) {
1389   JavaThread* current = THREAD;
1390   ResourceMark rm(current);
1391   RegisterMap cbl_map(current, false);
1392   frame caller_frame = current->last_frame().sender(&cbl_map);
1393 
1394   CodeBlob* caller_cb = caller_frame.cb();
1395   guarantee(caller_cb != NULL && caller_cb->is_compiled(), "must be called from compiled method");
1396   CompiledMethod* caller_nm = caller_cb->as_compiled_method_or_null();
1397   *caller_is_c1 = caller_nm->is_compiled_by_c1();
1398 
1399   // make sure caller is not getting deoptimized
1400   // and removed before we are done with it.
1401   // CLEANUP - with lazy deopt shouldn't need this lock
1402   nmethodLocker caller_lock(caller_nm);
1403 
1404   // determine call info & receiver
1405   // note: a) receiver is NULL for static calls
1406   //       b) an exception is thrown if receiver is NULL for non-static calls
1407   CallInfo call_info;
1408   Bytecodes::Code invoke_code = Bytecodes::_illegal;
1409   Handle receiver = find_callee_info(invoke_code, call_info, CHECK_(methodHandle()));
1410   methodHandle callee_method(current, call_info.selected_method());
1411 
1412   assert((!is_virtual && invoke_code == Bytecodes::_invokestatic ) ||
1413          (!is_virtual && invoke_code == Bytecodes::_invokespecial) ||
1414          (!is_virtual && invoke_code == Bytecodes::_invokehandle ) ||
1415          (!is_virtual && invoke_code == Bytecodes::_invokedynamic) ||
1416          ( is_virtual && invoke_code != Bytecodes::_invokestatic ), "inconsistent bytecode");
1417 

1474     bool successful = resolve_sub_helper_internal(callee_method, caller_frame, caller_nm,
1475                                                   is_virtual, is_optimized, receiver,
1476                                                   call_info, invoke_code, CHECK_(methodHandle()));
1477     if (successful) {
1478       return callee_method;
1479     } else {
1480       InlineCacheBuffer::refill_ic_stubs();
1481     }
1482   }
1483 
1484 }
1485 
1486 
1487 // Inline caches exist only in compiled code
1488 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_ic_miss(JavaThread* current))
1489 #ifdef ASSERT
1490   RegisterMap reg_map(current, false);
1491   frame stub_frame = current->last_frame();
1492   assert(stub_frame.is_runtime_frame(), "sanity check");
1493   frame caller_frame = stub_frame.sender(&reg_map);
1494   assert(!caller_frame.is_interpreted_frame() && !caller_frame.is_entry_frame()  && !caller_frame.is_optimized_entry_frame(), "unexpected frame");
1495 #endif /* ASSERT */
1496 
1497   methodHandle callee_method;
1498   bool is_optimized = false;
1499   bool caller_is_c1 = false;
1500   JRT_BLOCK
1501     callee_method = SharedRuntime::handle_ic_miss_helper(is_optimized, caller_is_c1, CHECK_NULL);
1502     // Return Method* through TLS
1503     current->set_vm_result_2(callee_method());
1504   JRT_BLOCK_END
1505   // return compiled code entry point after potential safepoints
1506   return entry_for_handle_wrong_method(callee_method, false, is_optimized, caller_is_c1);

1507 JRT_END
1508 
1509 
1510 // Handle call site that has been made non-entrant
1511 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method(JavaThread* current))
1512   // 6243940 We might end up in here if the callee is deoptimized
1513   // as we race to call it.  We don't want to take a safepoint if
1514   // the caller was interpreted because the caller frame will look
1515   // interpreted to the stack walkers and arguments are now
1516   // "compiled" so it is much better to make this transition
1517   // invisible to the stack walking code. The i2c path will
1518   // place the callee method in the callee_target. It is stashed
1519   // there because if we try and find the callee by normal means a
1520   // safepoint is possible and have trouble gc'ing the compiled args.
1521   RegisterMap reg_map(current, false);
1522   frame stub_frame = current->last_frame();
1523   assert(stub_frame.is_runtime_frame(), "sanity check");
1524   frame caller_frame = stub_frame.sender(&reg_map);
1525 
1526   if (caller_frame.is_interpreted_frame() ||

1530     guarantee(callee != NULL && callee->is_method(), "bad handshake");
1531     current->set_vm_result_2(callee);
1532     current->set_callee_target(NULL);
1533     if (caller_frame.is_entry_frame() && VM_Version::supports_fast_class_init_checks()) {
1534       // Bypass class initialization checks in c2i when caller is in native.
1535       // JNI calls to static methods don't have class initialization checks.
1536       // Fast class initialization checks are present in c2i adapters and call into
1537       // SharedRuntime::handle_wrong_method() on the slow path.
1538       //
1539       // JVM upcalls may land here as well, but there's a proper check present in
1540       // LinkResolver::resolve_static_call (called from JavaCalls::call_static),
1541       // so bypassing it in c2i adapter is benign.
1542       return callee->get_c2i_no_clinit_check_entry();
1543     } else {
1544       return callee->get_c2i_entry();
1545     }
1546   }
1547 
1548   // Must be compiled to compiled path which is safe to stackwalk
1549   methodHandle callee_method;
1550   bool is_static_call = false;
1551   bool is_optimized = false;
1552   bool caller_is_c1 = false;
1553   JRT_BLOCK
1554     // Force resolving of caller (if we called from compiled frame)
1555     callee_method = SharedRuntime::reresolve_call_site(is_static_call, is_optimized, caller_is_c1, CHECK_NULL);
1556     current->set_vm_result_2(callee_method());
1557   JRT_BLOCK_END
1558   // return compiled code entry point after potential safepoints
1559   return entry_for_handle_wrong_method(callee_method, is_static_call, is_optimized, caller_is_c1);

1560 JRT_END
1561 
1562 // Handle abstract method call
1563 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_abstract(JavaThread* current))
1564   // Verbose error message for AbstractMethodError.
1565   // Get the called method from the invoke bytecode.
1566   vframeStream vfst(current, true);
1567   assert(!vfst.at_end(), "Java frame must exist");
1568   methodHandle caller(current, vfst.method());
1569   Bytecode_invoke invoke(caller, vfst.bci());
1570   DEBUG_ONLY( invoke.verify(); )
1571 
1572   // Find the compiled caller frame.
1573   RegisterMap reg_map(current);
1574   frame stubFrame = current->last_frame();
1575   assert(stubFrame.is_runtime_frame(), "must be");
1576   frame callerFrame = stubFrame.sender(&reg_map);
1577   assert(callerFrame.is_compiled_frame(), "must be");
1578 
1579   // Install exception and return forward entry.
1580   address res = StubRoutines::throw_AbstractMethodError_entry();
1581   JRT_BLOCK
1582     methodHandle callee(current, invoke.static_target(current));
1583     if (!callee.is_null()) {
1584       oop recv = callerFrame.retrieve_receiver(&reg_map);
1585       Klass *recv_klass = (recv != NULL) ? recv->klass() : NULL;
1586       res = StubRoutines::forward_exception_entry();
1587       LinkResolver::throw_abstract_method_error(callee, recv_klass, CHECK_(res));
1588     }
1589   JRT_BLOCK_END
1590   return res;
1591 JRT_END
1592 
1593 
1594 // resolve a static call and patch code
1595 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_call_C(JavaThread* current ))
1596   methodHandle callee_method;
1597   bool caller_is_c1;
1598   JRT_BLOCK
1599     callee_method = SharedRuntime::resolve_helper(false, false, &caller_is_c1, CHECK_NULL);
1600     current->set_vm_result_2(callee_method());
1601   JRT_BLOCK_END
1602   // return compiled code entry point after potential safepoints
1603   address entry = caller_is_c1 ?
1604     callee_method->verified_inline_code_entry() : callee_method->verified_code_entry();
1605   assert(entry != NULL, "Jump to zero!");
1606   return entry;
1607 JRT_END
1608 
1609 
1610 // resolve virtual call and update inline cache to monomorphic
1611 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_virtual_call_C(JavaThread* current))
1612   methodHandle callee_method;
1613   bool caller_is_c1;
1614   JRT_BLOCK
1615     callee_method = SharedRuntime::resolve_helper(true, false, &caller_is_c1, CHECK_NULL);
1616     current->set_vm_result_2(callee_method());
1617   JRT_BLOCK_END
1618   // return compiled code entry point after potential safepoints
1619   address entry = caller_is_c1 ?
1620     callee_method->verified_inline_code_entry() : callee_method->verified_inline_ro_code_entry();
1621   assert(entry != NULL, "Jump to zero!");
1622   return entry;
1623 JRT_END
1624 
1625 
1626 // Resolve a virtual call that can be statically bound (e.g., always
1627 // monomorphic, so it has no inline cache).  Patch code to resolved target.
1628 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_opt_virtual_call_C(JavaThread* current))
1629   methodHandle callee_method;
1630   bool caller_is_c1;
1631   JRT_BLOCK
1632     callee_method = SharedRuntime::resolve_helper(true, true, &caller_is_c1, CHECK_NULL);
1633     current->set_vm_result_2(callee_method());
1634   JRT_BLOCK_END
1635   // return compiled code entry point after potential safepoints
1636   address entry = caller_is_c1 ?
1637     callee_method->verified_inline_code_entry() : callee_method->verified_code_entry();
1638   assert(entry != NULL, "Jump to zero!");
1639   return entry;
1640 JRT_END
1641 
1642 // The handle_ic_miss_helper_internal function returns false if it failed due
1643 // to either running out of vtable stubs or ic stubs due to IC transitions
1644 // to transitional states. The needs_ic_stub_refill value will be set if
1645 // the failure was due to running out of IC stubs, in which case handle_ic_miss_helper
1646 // refills the IC stubs and tries again.
1647 bool SharedRuntime::handle_ic_miss_helper_internal(Handle receiver, CompiledMethod* caller_nm,
1648                                                    const frame& caller_frame, methodHandle callee_method,
1649                                                    Bytecodes::Code bc, CallInfo& call_info,
1650                                                    bool& needs_ic_stub_refill, bool& is_optimized, bool caller_is_c1, TRAPS) {
1651   CompiledICLocker ml(caller_nm);
1652   CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1653   bool should_be_mono = false;
1654   if (inline_cache->is_optimized()) {
1655     if (TraceCallFixup) {
1656       ResourceMark rm(THREAD);
1657       tty->print("OPTIMIZED IC miss (%s) call to", Bytecodes::name(bc));
1658       callee_method->print_short_name(tty);
1659       tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1660     }
1661     is_optimized = true;
1662     should_be_mono = true;
1663   } else if (inline_cache->is_icholder_call()) {
1664     CompiledICHolder* ic_oop = inline_cache->cached_icholder();
1665     if (ic_oop != NULL) {
1666       if (!ic_oop->is_loader_alive()) {
1667         // Deferred IC cleaning due to concurrent class unloading
1668         if (!inline_cache->set_to_clean()) {
1669           needs_ic_stub_refill = true;
1670           return false;
1671         }
1672       } else if (receiver()->klass() == ic_oop->holder_klass()) {
1673         // This isn't a real miss. We must have seen that compiled code
1674         // is now available and we want the call site converted to a
1675         // monomorphic compiled call site.
1676         // We can't assert for callee_method->code() != NULL because it
1677         // could have been deoptimized in the meantime
1678         if (TraceCallFixup) {
1679           ResourceMark rm(THREAD);
1680           tty->print("FALSE IC miss (%s) converting to compiled call to", Bytecodes::name(bc));
1681           callee_method->print_short_name(tty);
1682           tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1683         }
1684         should_be_mono = true;
1685       }
1686     }
1687   }
1688 
1689   if (should_be_mono) {
1690     // We have a path that was monomorphic but was going interpreted
1691     // and now we have (or had) a compiled entry. We correct the IC
1692     // by using a new icBuffer.
1693     CompiledICInfo info;
1694     Klass* receiver_klass = receiver()->klass();
1695     inline_cache->compute_monomorphic_entry(callee_method,
1696                                             receiver_klass,
1697                                             inline_cache->is_optimized(),
1698                                             false, caller_nm->is_nmethod(),
1699                                             caller_nm->is_compiled_by_c1(),
1700                                             info, CHECK_false);
1701     if (!inline_cache->set_to_monomorphic(info)) {
1702       needs_ic_stub_refill = true;
1703       return false;
1704     }
1705   } else if (!inline_cache->is_megamorphic() && !inline_cache->is_clean()) {
1706     // Potential change to megamorphic
1707 
1708     bool successful = inline_cache->set_to_megamorphic(&call_info, bc, needs_ic_stub_refill, caller_is_c1, CHECK_false);
1709     if (needs_ic_stub_refill) {
1710       return false;
1711     }
1712     if (!successful) {
1713       if (!inline_cache->set_to_clean()) {
1714         needs_ic_stub_refill = true;
1715         return false;
1716       }
1717     }
1718   } else {
1719     // Either clean or megamorphic
1720   }
1721   return true;
1722 }
1723 
1724 methodHandle SharedRuntime::handle_ic_miss_helper(bool& is_optimized, bool& caller_is_c1, TRAPS) {
1725   JavaThread* current = THREAD;
1726   ResourceMark rm(current);
1727   CallInfo call_info;
1728   Bytecodes::Code bc;
1729 
1730   // receiver is NULL for static calls. An exception is thrown for NULL
1731   // receivers for non-static calls
1732   Handle receiver = find_callee_info(bc, call_info, CHECK_(methodHandle()));
1733   // Compiler1 can produce virtual call sites that can actually be statically bound
1734   // If we fell thru to below we would think that the site was going megamorphic
1735   // when in fact the site can never miss. Worse because we'd think it was megamorphic
1736   // we'd try and do a vtable dispatch however methods that can be statically bound
1737   // don't have vtable entries (vtable_index < 0) and we'd blow up. So we force a
1738   // reresolution of the  call site (as if we did a handle_wrong_method and not an
1739   // plain ic_miss) and the site will be converted to an optimized virtual call site
1740   // never to miss again. I don't believe C2 will produce code like this but if it
1741   // did this would still be the correct thing to do for it too, hence no ifdef.
1742   //
1743   if (call_info.resolved_method()->can_be_statically_bound()) {
1744     bool is_static_call = false;
1745     methodHandle callee_method = SharedRuntime::reresolve_call_site(is_static_call, is_optimized, caller_is_c1, CHECK_(methodHandle()));
1746     assert(!is_static_call, "IC miss at static call?");
1747     if (TraceCallFixup) {
1748       RegisterMap reg_map(current, false);
1749       frame caller_frame = current->last_frame().sender(&reg_map);
1750       ResourceMark rm(current);
1751       tty->print("converting IC miss to reresolve (%s) call to", Bytecodes::name(bc));
1752       callee_method->print_short_name(tty);
1753       tty->print_cr(" from pc: " INTPTR_FORMAT, p2i(caller_frame.pc()));
1754       tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1755     }
1756     return callee_method;
1757   }
1758 
1759   methodHandle callee_method(current, call_info.selected_method());
1760 
1761 #ifndef PRODUCT
1762   Atomic::inc(&_ic_miss_ctr);
1763 
1764   // Statistics & Tracing
1765   if (TraceCallFixup) {
1766     ResourceMark rm(current);

1776     // produce statistics under the lock
1777     trace_ic_miss(f.pc());
1778   }
1779 #endif
1780 
1781   // install an event collector so that when a vtable stub is created the
1782   // profiler can be notified via a DYNAMIC_CODE_GENERATED event. The
1783   // event can't be posted when the stub is created as locks are held
1784   // - instead the event will be deferred until the event collector goes
1785   // out of scope.
1786   JvmtiDynamicCodeEventCollector event_collector;
1787 
1788   // Update inline cache to megamorphic. Skip update if we are called from interpreted.
1789   // Transitioning IC caches may require transition stubs. If we run out
1790   // of transition stubs, we have to drop locks and perform a safepoint
1791   // that refills them.
1792   RegisterMap reg_map(current, false);
1793   frame caller_frame = current->last_frame().sender(&reg_map);
1794   CodeBlob* cb = caller_frame.cb();
1795   CompiledMethod* caller_nm = cb->as_compiled_method();
1796   caller_is_c1 = caller_nm->is_compiled_by_c1();
1797 
1798   for (;;) {
1799     ICRefillVerifier ic_refill_verifier;
1800     bool needs_ic_stub_refill = false;
1801     bool successful = handle_ic_miss_helper_internal(receiver, caller_nm, caller_frame, callee_method,
1802                                                      bc, call_info, needs_ic_stub_refill, is_optimized, caller_is_c1, CHECK_(methodHandle()));
1803     if (successful || !needs_ic_stub_refill) {
1804       return callee_method;
1805     } else {
1806       InlineCacheBuffer::refill_ic_stubs();
1807     }
1808   }
1809 }
1810 
1811 static bool clear_ic_at_addr(CompiledMethod* caller_nm, address call_addr, bool is_static_call) {
1812   CompiledICLocker ml(caller_nm);
1813   if (is_static_call) {
1814     CompiledStaticCall* ssc = caller_nm->compiledStaticCall_at(call_addr);
1815     if (!ssc->is_clean()) {
1816       return ssc->set_to_clean();
1817     }
1818   } else {
1819     // compiled, dispatched call (which used to call an interpreted method)
1820     CompiledIC* inline_cache = CompiledIC_at(caller_nm, call_addr);
1821     if (!inline_cache->is_clean()) {
1822       return inline_cache->set_to_clean();
1823     }
1824   }
1825   return true;
1826 }
1827 
1828 //
1829 // Resets a call-site in compiled code so it will get resolved again.
1830 // This routines handles both virtual call sites, optimized virtual call
1831 // sites, and static call sites. Typically used to change a call sites
1832 // destination from compiled to interpreted.
1833 //
1834 methodHandle SharedRuntime::reresolve_call_site(bool& is_static_call, bool& is_optimized, bool& caller_is_c1, TRAPS) {
1835   JavaThread* current = THREAD;
1836   ResourceMark rm(current);
1837   RegisterMap reg_map(current, false);
1838   frame stub_frame = current->last_frame();
1839   assert(stub_frame.is_runtime_frame(), "must be a runtimeStub");
1840   frame caller = stub_frame.sender(&reg_map);
1841 
1842   // Do nothing if the frame isn't a live compiled frame.
1843   // nmethod could be deoptimized by the time we get here
1844   // so no update to the caller is needed.
1845 
1846   if (caller.is_compiled_frame() && !caller.is_deoptimized_frame()) {
1847 
1848     address pc = caller.pc();
1849 
1850     // Check for static or virtual call

1851     CompiledMethod* caller_nm = CodeCache::find_compiled(pc);
1852     caller_is_c1 = caller_nm->is_compiled_by_c1();
1853 
1854     // Default call_addr is the location of the "basic" call.
1855     // Determine the address of the call we a reresolving. With
1856     // Inline Caches we will always find a recognizable call.
1857     // With Inline Caches disabled we may or may not find a
1858     // recognizable call. We will always find a call for static
1859     // calls and for optimized virtual calls. For vanilla virtual
1860     // calls it depends on the state of the UseInlineCaches switch.
1861     //
1862     // With Inline Caches disabled we can get here for a virtual call
1863     // for two reasons:
1864     //   1 - calling an abstract method. The vtable for abstract methods
1865     //       will run us thru handle_wrong_method and we will eventually
1866     //       end up in the interpreter to throw the ame.
1867     //   2 - a racing deoptimization. We could be doing a vanilla vtable
1868     //       call and between the time we fetch the entry address and
1869     //       we jump to it the target gets deoptimized. Similar to 1
1870     //       we will wind up in the interprter (thru a c2i with c2).
1871     //
1872     address call_addr = NULL;

1876       CompiledICLocker ml(caller_nm);
1877       // Location of call instruction
1878       call_addr = caller_nm->call_instruction_address(pc);
1879     }
1880     // Make sure nmethod doesn't get deoptimized and removed until
1881     // this is done with it.
1882     // CLEANUP - with lazy deopt shouldn't need this lock
1883     nmethodLocker nmlock(caller_nm);
1884 
1885     if (call_addr != NULL) {
1886       RelocIterator iter(caller_nm, call_addr, call_addr+1);
1887       int ret = iter.next(); // Get item
1888       if (ret) {
1889         assert(iter.addr() == call_addr, "must find call");
1890         if (iter.type() == relocInfo::static_call_type) {
1891           is_static_call = true;
1892         } else {
1893           assert(iter.type() == relocInfo::virtual_call_type ||
1894                  iter.type() == relocInfo::opt_virtual_call_type
1895                 , "unexpected relocInfo. type");
1896           is_optimized = (iter.type() == relocInfo::opt_virtual_call_type);
1897         }
1898       } else {
1899         assert(!UseInlineCaches, "relocation info. must exist for this address");
1900       }
1901 
1902       // Cleaning the inline cache will force a new resolve. This is more robust
1903       // than directly setting it to the new destination, since resolving of calls
1904       // is always done through the same code path. (experience shows that it
1905       // leads to very hard to track down bugs, if an inline cache gets updated
1906       // to a wrong method). It should not be performance critical, since the
1907       // resolve is only done once.
1908 
1909       for (;;) {
1910         ICRefillVerifier ic_refill_verifier;
1911         if (!clear_ic_at_addr(caller_nm, call_addr, is_static_call)) {
1912           InlineCacheBuffer::refill_ic_stubs();
1913         } else {
1914           break;
1915         }
1916       }
1917     }
1918   }
1919 
1920   methodHandle callee_method = find_callee_method(CHECK_(methodHandle()));
1921 

1922 #ifndef PRODUCT
1923   Atomic::inc(&_wrong_method_ctr);
1924 
1925   if (TraceCallFixup) {
1926     ResourceMark rm(current);
1927     tty->print("handle_wrong_method reresolving call to");
1928     callee_method->print_short_name(tty);
1929     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1930   }
1931 #endif
1932 
1933   return callee_method;
1934 }
1935 
1936 address SharedRuntime::handle_unsafe_access(JavaThread* thread, address next_pc) {
1937   // The faulting unsafe accesses should be changed to throw the error
1938   // synchronously instead. Meanwhile the faulting instruction will be
1939   // skipped over (effectively turning it into a no-op) and an
1940   // asynchronous exception will be raised which the thread will
1941   // handle at a later point. If the instruction is a load it will

1997     if (TraceCallFixup) {
1998       tty->print("already patched callsite at " INTPTR_FORMAT " to compiled code for", p2i(caller_pc));
1999       moop->print_short_name(tty);
2000       tty->print_cr(" to " INTPTR_FORMAT, p2i(entry_point));
2001     }
2002   }
2003   return false;
2004 }
2005 
2006 // ---------------------------------------------------------------------------
2007 // We are calling the interpreter via a c2i. Normally this would mean that
2008 // we were called by a compiled method. However we could have lost a race
2009 // where we went int -> i2c -> c2i and so the caller could in fact be
2010 // interpreted. If the caller is compiled we attempt to patch the caller
2011 // so he no longer calls into the interpreter.
2012 JRT_LEAF(void, SharedRuntime::fixup_callers_callsite(Method* method, address caller_pc))
2013   Method* moop(method);
2014 
2015   AARCH64_PORT_ONLY(assert(pauth_ptr_is_raw(caller_pc), "should be raw"));
2016 


2017   // It's possible that deoptimization can occur at a call site which hasn't
2018   // been resolved yet, in which case this function will be called from
2019   // an nmethod that has been patched for deopt and we can ignore the
2020   // request for a fixup.
2021   // Also it is possible that we lost a race in that from_compiled_entry
2022   // is now back to the i2c in that case we don't need to patch and if
2023   // we did we'd leap into space because the callsite needs to use
2024   // "to interpreter" stub in order to load up the Method*. Don't
2025   // ask me how I know this...
2026 
2027   CodeBlob* cb = CodeCache::find_blob(caller_pc);
2028   if (cb == NULL || !cb->is_compiled()) {
2029     return;
2030   }
2031   address entry_point = moop->from_compiled_entry_no_trampoline(cb->is_compiled_by_c1());
2032   if (entry_point == moop->get_c2i_entry()) {
2033     return;
2034   }
2035 
2036   // The check above makes sure this is a nmethod.
2037   CompiledMethod* nm = cb->as_compiled_method_or_null();
2038   assert(nm, "must be");
2039 
2040   // Get the return PC for the passed caller PC.
2041   address return_pc = caller_pc + frame::pc_return_offset;
2042 
2043   // There is a benign race here. We could be attempting to patch to a compiled
2044   // entry point at the same time the callee is being deoptimized. If that is
2045   // the case then entry_point may in fact point to a c2i and we'd patch the
2046   // call site with the same old data. clear_code will set code() to NULL
2047   // at the end of it. If we happen to see that NULL then we can skip trying
2048   // to patch. If we hit the window where the callee has a c2i in the
2049   // from_compiled_entry and the NULL isn't present yet then we lose the race
2050   // and patch the code with the same old data. Asi es la vida.
2051 
2052   if (moop->code() == NULL) return;

2387  private:
2388   enum {
2389     _basic_type_bits = 4,
2390     _basic_type_mask = right_n_bits(_basic_type_bits),
2391     _basic_types_per_int = BitsPerInt / _basic_type_bits,
2392     _compact_int_count = 3
2393   };
2394   // TO DO:  Consider integrating this with a more global scheme for compressing signatures.
2395   // For now, 4 bits per components (plus T_VOID gaps after double/long) is not excessive.
2396 
2397   union {
2398     int  _compact[_compact_int_count];
2399     int* _fingerprint;
2400   } _value;
2401   int _length; // A negative length indicates the fingerprint is in the compact form,
2402                // Otherwise _value._fingerprint is the array.
2403 
2404   // Remap BasicTypes that are handled equivalently by the adapters.
2405   // These are correct for the current system but someday it might be
2406   // necessary to make this mapping platform dependent.
2407   static BasicType adapter_encoding(BasicType in) {
2408     switch (in) {
2409       case T_BOOLEAN:
2410       case T_BYTE:
2411       case T_SHORT:
2412       case T_CHAR:
2413         // They are all promoted to T_INT in the calling convention
2414         return T_INT;
2415 
2416       case T_OBJECT:
2417       case T_ARRAY:
2418         // In other words, we assume that any register good enough for
2419         // an int or long is good enough for a managed pointer.
2420 #ifdef _LP64
2421         return T_LONG;
2422 #else
2423         return T_INT;
2424 #endif
2425 
2426       case T_INT:
2427       case T_LONG:
2428       case T_FLOAT:
2429       case T_DOUBLE:
2430       case T_VOID:
2431         return in;
2432 
2433       default:
2434         ShouldNotReachHere();
2435         return T_CONFLICT;
2436     }
2437   }
2438 
2439  public:
2440   AdapterFingerPrint(const GrowableArray<SigEntry>* sig, bool has_ro_adapter = false) {
2441     // The fingerprint is based on the BasicType signature encoded
2442     // into an array of ints with eight entries per int.
2443     int total_args_passed = (sig != NULL) ? sig->length() : 0;
2444     int* ptr;
2445     int len = (total_args_passed + (_basic_types_per_int-1)) / _basic_types_per_int;
2446     if (len <= _compact_int_count) {
2447       assert(_compact_int_count == 3, "else change next line");
2448       _value._compact[0] = _value._compact[1] = _value._compact[2] = 0;
2449       // Storing the signature encoded as signed chars hits about 98%
2450       // of the time.
2451       _length = -len;
2452       ptr = _value._compact;
2453     } else {
2454       _length = len;
2455       _value._fingerprint = NEW_C_HEAP_ARRAY(int, _length, mtCode);
2456       ptr = _value._fingerprint;
2457     }
2458 
2459     // Now pack the BasicTypes with 8 per int
2460     int sig_index = 0;
2461     BasicType prev_bt = T_ILLEGAL;
2462     int vt_count = 0;
2463     for (int index = 0; index < len; index++) {
2464       int value = 0;
2465       for (int byte = 0; byte < _basic_types_per_int; byte++) {
2466         BasicType bt = T_ILLEGAL;
2467         if (sig_index < total_args_passed) {
2468           bt = sig->at(sig_index++)._bt;
2469           if (bt == T_PRIMITIVE_OBJECT) {
2470             // Found start of inline type in signature
2471             assert(InlineTypePassFieldsAsArgs, "unexpected start of inline type");
2472             if (sig_index == 1 && has_ro_adapter) {
2473               // With a ro_adapter, replace receiver inline type delimiter by T_VOID to prevent matching
2474               // with other adapters that have the same inline type as first argument and no receiver.
2475               bt = T_VOID;
2476             }
2477             vt_count++;
2478           } else if (bt == T_VOID && prev_bt != T_LONG && prev_bt != T_DOUBLE) {
2479             // Found end of inline type in signature
2480             assert(InlineTypePassFieldsAsArgs, "unexpected end of inline type");
2481             vt_count--;
2482             assert(vt_count >= 0, "invalid vt_count");
2483           } else if (vt_count == 0) {
2484             // Widen fields that are not part of a scalarized inline type argument
2485             bt = adapter_encoding(bt);
2486           }
2487           prev_bt = bt;
2488         }
2489         int bt_val = (bt == T_ILLEGAL) ? 0 : bt;
2490         assert((bt_val & _basic_type_mask) == bt_val, "must fit in 4 bits");
2491         value = (value << _basic_type_bits) | bt_val;
2492       }
2493       ptr[index] = value;
2494     }
2495     assert(vt_count == 0, "invalid vt_count");
2496   }
2497 
2498   ~AdapterFingerPrint() {
2499     if (_length > 0) {
2500       FREE_C_HEAP_ARRAY(int, _value._fingerprint);
2501     }
2502   }
2503 
2504   int value(int index) {
2505     if (_length < 0) {
2506       return _value._compact[index];
2507     }
2508     return _value._fingerprint[index];
2509   }
2510   int length() {
2511     if (_length < 0) return -_length;
2512     return _length;
2513   }
2514 
2515   bool is_compact() {

2540   const char* as_basic_args_string() {
2541     stringStream st;
2542     bool long_prev = false;
2543     for (int i = 0; i < length(); i++) {
2544       unsigned val = (unsigned)value(i);
2545       // args are packed so that first/lower arguments are in the highest
2546       // bits of each int value, so iterate from highest to the lowest
2547       for (int j = 32 - _basic_type_bits; j >= 0; j -= _basic_type_bits) {
2548         unsigned v = (val >> j) & _basic_type_mask;
2549         if (v == 0) {
2550           assert(i == length() - 1, "Only expect zeroes in the last word");
2551           continue;
2552         }
2553         if (long_prev) {
2554           long_prev = false;
2555           if (v == T_VOID) {
2556             st.print("J");
2557           } else {
2558             st.print("L");
2559           }
2560         } else if (v == T_LONG) {
2561           long_prev = true;
2562         } else if (v != T_VOID){
2563           st.print("%c", type2char((BasicType)v));




2564         }
2565       }
2566     }
2567     if (long_prev) {
2568       st.print("L");
2569     }
2570     return st.as_string();
2571   }
2572 #endif // !product
2573 
2574   bool equals(AdapterFingerPrint* other) {
2575     if (other->_length != _length) {
2576       return false;
2577     }
2578     if (_length < 0) {
2579       assert(_compact_int_count == 3, "else change next line");
2580       return _value._compact[0] == other->_value._compact[0] &&
2581              _value._compact[1] == other->_value._compact[1] &&
2582              _value._compact[2] == other->_value._compact[2];
2583     } else {

2598 
2599  private:
2600 
2601 #ifndef PRODUCT
2602   static int _lookups; // number of calls to lookup
2603   static int _buckets; // number of buckets checked
2604   static int _equals;  // number of buckets checked with matching hash
2605   static int _hits;    // number of successful lookups
2606   static int _compact; // number of equals calls with compact signature
2607 #endif
2608 
2609   AdapterHandlerEntry* bucket(int i) {
2610     return (AdapterHandlerEntry*)BasicHashtable<mtCode>::bucket(i);
2611   }
2612 
2613  public:
2614   AdapterHandlerTable()
2615     : BasicHashtable<mtCode>(293, (sizeof(AdapterHandlerEntry))) { }
2616 
2617   // Create a new entry suitable for insertion in the table
2618   AdapterHandlerEntry* new_entry(AdapterFingerPrint* fingerprint, address i2c_entry, address c2i_entry,
2619                                  address c2i_inline_entry, address c2i_inline_ro_entry,
2620                                  address c2i_unverified_entry, address c2i_unverified_inline_entry, address c2i_no_clinit_check_entry) {
2621     AdapterHandlerEntry* entry = (AdapterHandlerEntry*)BasicHashtable<mtCode>::new_entry(fingerprint->compute_hash());
2622     entry->init(fingerprint, i2c_entry, c2i_entry, c2i_inline_entry, c2i_inline_ro_entry,
2623                 c2i_unverified_entry, c2i_unverified_inline_entry, c2i_no_clinit_check_entry);
2624     return entry;
2625   }
2626 
2627   // Insert an entry into the table
2628   void add(AdapterHandlerEntry* entry) {
2629     int index = hash_to_index(entry->hash());
2630     add_entry(index, entry);
2631   }
2632 
2633   void free_entry(AdapterHandlerEntry* entry) {
2634     entry->deallocate();
2635     BasicHashtable<mtCode>::free_entry(entry);
2636   }
2637 
2638   // Find a entry with the same fingerprint if it exists
2639   AdapterHandlerEntry* lookup(const GrowableArray<SigEntry>* sig, bool has_ro_adapter = false) {
2640     NOT_PRODUCT(_lookups++);
2641     AdapterFingerPrint fp(sig, has_ro_adapter);
2642     unsigned int hash = fp.compute_hash();
2643     int index = hash_to_index(hash);
2644     for (AdapterHandlerEntry* e = bucket(index); e != NULL; e = e->next()) {
2645       NOT_PRODUCT(_buckets++);
2646       if (e->hash() == hash) {
2647         NOT_PRODUCT(_equals++);
2648         if (fp.equals(e->fingerprint())) {
2649 #ifndef PRODUCT
2650           if (fp.is_compact()) _compact++;
2651           _hits++;
2652 #endif
2653           return e;
2654         }
2655       }
2656     }
2657     return NULL;
2658   }
2659 
2660 #ifndef PRODUCT
2661   void print_statistics() {

2722       AdapterHandlerEntry* result = _current;
2723       _current = _current->next();
2724       if (_current == NULL) scan();
2725       return result;
2726     } else {
2727       return NULL;
2728     }
2729   }
2730 };
2731 
2732 
2733 // ---------------------------------------------------------------------------
2734 // Implementation of AdapterHandlerLibrary
2735 AdapterHandlerTable* AdapterHandlerLibrary::_adapters = NULL;
2736 AdapterHandlerEntry* AdapterHandlerLibrary::_abstract_method_handler = NULL;
2737 AdapterHandlerEntry* AdapterHandlerLibrary::_no_arg_handler = NULL;
2738 AdapterHandlerEntry* AdapterHandlerLibrary::_int_arg_handler = NULL;
2739 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_arg_handler = NULL;
2740 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_int_arg_handler = NULL;
2741 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_obj_arg_handler = NULL;
2742 const int AdapterHandlerLibrary_size = 32*K;
2743 BufferBlob* AdapterHandlerLibrary::_buffer = NULL;
2744 
2745 BufferBlob* AdapterHandlerLibrary::buffer_blob() {
2746   return _buffer;
2747 }
2748 
2749 extern "C" void unexpected_adapter_call() {
2750   ShouldNotCallThis();
2751 }
2752 
2753 static void post_adapter_creation(const AdapterBlob* new_adapter, const AdapterHandlerEntry* entry) {
2754   char blob_id[256];
2755   jio_snprintf(blob_id,
2756                 sizeof(blob_id),
2757                 "%s(%s)",
2758                 new_adapter->name(),
2759                 entry->fingerprint()->as_string());
2760   Forte::register_stub(blob_id, new_adapter->content_begin(), new_adapter->content_end());
2761 
2762   if (JvmtiExport::should_post_dynamic_code_generated()) {

2766 
2767 void AdapterHandlerLibrary::initialize() {
2768   ResourceMark rm;
2769   AdapterBlob* no_arg_blob = NULL;
2770   AdapterBlob* int_arg_blob = NULL;
2771   AdapterBlob* obj_arg_blob = NULL;
2772   AdapterBlob* obj_int_arg_blob = NULL;
2773   AdapterBlob* obj_obj_arg_blob = NULL;
2774   {
2775     MutexLocker mu(AdapterHandlerLibrary_lock);
2776     assert(_adapters == NULL, "Initializing more than once");
2777 
2778     _adapters = new AdapterHandlerTable();
2779 
2780     // Create a special handler for abstract methods.  Abstract methods
2781     // are never compiled so an i2c entry is somewhat meaningless, but
2782     // throw AbstractMethodError just in case.
2783     // Pass wrong_method_abstract for the c2i transitions to return
2784     // AbstractMethodError for invalid invocations.
2785     address wrong_method_abstract = SharedRuntime::get_handle_wrong_method_abstract_stub();
2786     _abstract_method_handler = AdapterHandlerLibrary::new_entry(new AdapterFingerPrint(NULL),
2787                                                                 StubRoutines::throw_AbstractMethodError_entry(),
2788                                                                 wrong_method_abstract, wrong_method_abstract, wrong_method_abstract,
2789                                                                 wrong_method_abstract, wrong_method_abstract);

2790     _buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size);
2791 
2792     CompiledEntrySignature no_args;
2793     no_args.compute_calling_conventions();
2794     _no_arg_handler = create_adapter(no_arg_blob, no_args, true);
2795 
2796     CompiledEntrySignature obj_args;
2797     SigEntry::add_entry(&obj_args.sig(), T_OBJECT, NULL);
2798     obj_args.compute_calling_conventions();
2799     _obj_arg_handler = create_adapter(obj_arg_blob, obj_args, true);
2800 
2801     CompiledEntrySignature int_args;
2802     SigEntry::add_entry(&int_args.sig(), T_INT, NULL);
2803     int_args.compute_calling_conventions();
2804     _int_arg_handler = create_adapter(int_arg_blob, int_args, true);
2805 
2806     CompiledEntrySignature obj_int_args;
2807     SigEntry::add_entry(&obj_int_args.sig(), T_OBJECT, NULL);
2808     SigEntry::add_entry(&obj_int_args.sig(), T_INT, NULL);
2809     obj_int_args.compute_calling_conventions();
2810     _obj_int_arg_handler = create_adapter(obj_int_arg_blob, obj_int_args, true);
2811 
2812     CompiledEntrySignature obj_obj_args;
2813     SigEntry::add_entry(&obj_obj_args.sig(), T_OBJECT, NULL);
2814     SigEntry::add_entry(&obj_obj_args.sig(), T_OBJECT, NULL);
2815     obj_obj_args.compute_calling_conventions();
2816     _obj_obj_arg_handler = create_adapter(obj_obj_arg_blob, obj_obj_args, true);
2817 
2818     assert(no_arg_blob != NULL &&
2819           obj_arg_blob != NULL &&
2820           int_arg_blob != NULL &&
2821           obj_int_arg_blob != NULL &&
2822           obj_obj_arg_blob != NULL, "Initial adapters must be properly created");
2823   }
2824   return;
2825 
2826   // Outside of the lock
2827   post_adapter_creation(no_arg_blob, _no_arg_handler);
2828   post_adapter_creation(obj_arg_blob, _obj_arg_handler);
2829   post_adapter_creation(int_arg_blob, _int_arg_handler);
2830   post_adapter_creation(obj_int_arg_blob, _obj_int_arg_handler);
2831   post_adapter_creation(obj_obj_arg_blob, _obj_obj_arg_handler);
2832 }
2833 
2834 AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint,
2835                                                       address i2c_entry,
2836                                                       address c2i_entry,
2837                                                       address c2i_inline_entry,
2838                                                       address c2i_inline_ro_entry,
2839                                                       address c2i_unverified_entry,
2840                                                       address c2i_unverified_inline_entry,
2841                                                       address c2i_no_clinit_check_entry) {
2842   return _adapters->new_entry(fingerprint, i2c_entry, c2i_entry, c2i_inline_entry, c2i_inline_ro_entry, c2i_unverified_entry,
2843                               c2i_unverified_inline_entry, c2i_no_clinit_check_entry);
2844 }
2845 
2846 AdapterHandlerEntry* AdapterHandlerLibrary::get_simple_adapter(const methodHandle& method) {
2847   if (method->is_abstract()) {
2848     return NULL;
2849   }
2850   int total_args_passed = method->size_of_parameters(); // All args on stack
2851   if (total_args_passed == 0) {
2852     return _no_arg_handler;
2853   } else if (total_args_passed == 1) {
2854     if (!method->is_static() && (!InlineTypePassFieldsAsArgs || !method->method_holder()->is_inline_klass())) {
2855       return _obj_arg_handler;
2856     }
2857     switch (method->signature()->char_at(1)) {
2858       case JVM_SIGNATURE_CLASS: {
2859         if (InlineTypePassFieldsAsArgs) {
2860           SignatureStream ss(method->signature());
2861           if (method->method_holder()->is_preload_class(ss.as_symbol())) {
2862             return NULL;
2863           }
2864         }
2865         return _obj_arg_handler;
2866       }
2867       case JVM_SIGNATURE_ARRAY:
2868         return _obj_arg_handler;
2869       case JVM_SIGNATURE_INT:
2870       case JVM_SIGNATURE_BOOLEAN:
2871       case JVM_SIGNATURE_CHAR:
2872       case JVM_SIGNATURE_BYTE:
2873       case JVM_SIGNATURE_SHORT:
2874         return _int_arg_handler;
2875     }
2876   } else if (total_args_passed == 2 &&
2877              !method->is_static() && (!InlineTypePassFieldsAsArgs || !method->method_holder()->is_inline_klass())) {
2878     switch (method->signature()->char_at(1)) {
2879       case JVM_SIGNATURE_CLASS: {
2880         if (InlineTypePassFieldsAsArgs) {
2881           SignatureStream ss(method->signature());
2882           if (method->method_holder()->is_preload_class(ss.as_symbol())) {
2883             return NULL;
2884           }
2885         }
2886         return _obj_obj_arg_handler;
2887       }
2888       case JVM_SIGNATURE_ARRAY:
2889         return _obj_obj_arg_handler;
2890       case JVM_SIGNATURE_INT:
2891       case JVM_SIGNATURE_BOOLEAN:
2892       case JVM_SIGNATURE_CHAR:
2893       case JVM_SIGNATURE_BYTE:
2894       case JVM_SIGNATURE_SHORT:
2895         return _obj_int_arg_handler;
2896     }
2897   }
2898   return NULL;
2899 }
2900 
2901 CompiledEntrySignature::CompiledEntrySignature(Method* method) :
2902   _method(method), _num_inline_args(0), _has_inline_recv(false),
2903   _regs(NULL), _regs_cc(NULL), _regs_cc_ro(NULL),
2904   _args_on_stack(0), _args_on_stack_cc(0), _args_on_stack_cc_ro(0),
2905   _c1_needs_stack_repair(false), _c2_needs_stack_repair(false) {
2906   _sig = new GrowableArray<SigEntry>((method != NULL) ? method->size_of_parameters() : 1);
2907   _sig_cc = new GrowableArray<SigEntry>((method != NULL) ? method->size_of_parameters() : 1);
2908   _sig_cc_ro = new GrowableArray<SigEntry>((method != NULL) ? method->size_of_parameters() : 1);
2909 }
2910 
2911 // See if we can save space by sharing the same entry for VIEP and VIEP(RO),
2912 // or the same entry for VEP and VIEP(RO).
2913 CodeOffsets::Entries CompiledEntrySignature::c1_inline_ro_entry_type() const {
2914   if (!has_scalarized_args()) {
2915     // VEP/VIEP/VIEP(RO) all share the same entry. There's no packing.
2916     return CodeOffsets::Verified_Entry;
2917   }
2918   if (_method->is_static()) {
2919     // Static methods don't need VIEP(RO)
2920     return CodeOffsets::Verified_Entry;



2921   }
2922 
2923   if (has_inline_recv()) {
2924     if (num_inline_args() == 1) {
2925       // Share same entry for VIEP and VIEP(RO).
2926       // This is quite common: we have an instance method in an InlineKlass that has
2927       // no inline type args other than <this>.
2928       return CodeOffsets::Verified_Inline_Entry;
2929     } else {
2930       assert(num_inline_args() > 1, "must be");
2931       // No sharing:
2932       //   VIEP(RO) -- <this> is passed as object
2933       //   VEP      -- <this> is passed as fields
2934       return CodeOffsets::Verified_Inline_Entry_RO;
2935     }
2936   }
2937 
2938   // Either a static method, or <this> is not an inline type
2939   if (args_on_stack_cc() != args_on_stack_cc_ro()) {
2940     // No sharing:
2941     // Some arguments are passed on the stack, and we have inserted reserved entries
2942     // into the VEP, but we never insert reserved entries into the VIEP(RO).
2943     return CodeOffsets::Verified_Inline_Entry_RO;
2944   } else {
2945     // Share same entry for VEP and VIEP(RO).
2946     return CodeOffsets::Verified_Entry;
2947   }
2948 }
2949 
2950 void CompiledEntrySignature::compute_calling_conventions(bool init) {
2951   // Iterate over arguments and compute scalarized and non-scalarized signatures
2952   bool has_scalarized = false;
2953   if (_method != NULL) {
2954     InstanceKlass* holder = _method->method_holder();
2955     int arg_num = 0;
2956     if (!_method->is_static()) {
2957       if (holder->is_inline_klass() && InlineKlass::cast(holder)->can_be_passed_as_fields() &&
2958           (init || _method->is_scalarized_arg(arg_num))) {
2959         _sig_cc->appendAll(InlineKlass::cast(holder)->extended_sig());
2960         has_scalarized = true;
2961         _has_inline_recv = true;
2962         _num_inline_args++;
2963       } else {
2964         SigEntry::add_entry(_sig_cc, T_OBJECT, holder->name());
2965       }
2966       SigEntry::add_entry(_sig, T_OBJECT, holder->name());
2967       SigEntry::add_entry(_sig_cc_ro, T_OBJECT, holder->name());
2968       arg_num++;
2969     }
2970     for (SignatureStream ss(_method->signature()); !ss.at_return_type(); ss.next()) {
2971       BasicType bt = ss.type();
2972       if (bt == T_OBJECT || bt == T_PRIMITIVE_OBJECT) {
2973         InlineKlass* vk = ss.as_inline_klass(holder);
2974         // TODO 8284443 Mismatch handling, we need to check parent method args (look at klassVtable::needs_new_vtable_entry)
2975         if (vk != NULL && (bt == T_PRIMITIVE_OBJECT || holder->is_preload_class(vk->name())) &&
2976             vk->can_be_passed_as_fields() && (init || _method->is_scalarized_arg(arg_num))) {
2977           _num_inline_args++;
2978           has_scalarized = true;
2979           int last = _sig_cc->length();
2980           int last_ro = _sig_cc_ro->length();
2981           _sig_cc->appendAll(vk->extended_sig());
2982           _sig_cc_ro->appendAll(vk->extended_sig());
2983           if (bt == T_OBJECT) {
2984             // Nullable inline type argument, insert InlineTypeBaseNode::IsInit field right after T_PRIMITIVE_OBJECT
2985             _sig_cc->insert_before(last+1, SigEntry(T_BOOLEAN, -1, NULL));
2986             _sig_cc_ro->insert_before(last_ro+1, SigEntry(T_BOOLEAN, -1, NULL));
2987           }
2988         } else {
2989           SigEntry::add_entry(_sig_cc, T_OBJECT, ss.as_symbol());
2990           SigEntry::add_entry(_sig_cc_ro, T_OBJECT, ss.as_symbol());
2991         }
2992         bt = T_OBJECT;
2993       } else {
2994         SigEntry::add_entry(_sig_cc, ss.type(), ss.as_symbol());
2995         SigEntry::add_entry(_sig_cc_ro, ss.type(), ss.as_symbol());
2996       }
2997       SigEntry::add_entry(_sig, bt, ss.as_symbol());
2998       if (bt != T_VOID) {
2999         arg_num++;
3000       }
3001     }
3002   }

3003 
3004   // Compute the non-scalarized calling convention
3005   _regs = NEW_RESOURCE_ARRAY(VMRegPair, _sig->length());
3006   _args_on_stack = SharedRuntime::java_calling_convention(_sig, _regs);
3007 
3008   // Compute the scalarized calling conventions if there are scalarized inline types in the signature
3009   if (has_scalarized && !_method->is_native()) {
3010     _regs_cc = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc->length());
3011     _args_on_stack_cc = SharedRuntime::java_calling_convention(_sig_cc, _regs_cc);
3012 
3013     _regs_cc_ro = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc_ro->length());
3014     _args_on_stack_cc_ro = SharedRuntime::java_calling_convention(_sig_cc_ro, _regs_cc_ro);
3015 
3016     _c1_needs_stack_repair = (_args_on_stack_cc < _args_on_stack) || (_args_on_stack_cc_ro < _args_on_stack);
3017     _c2_needs_stack_repair = (_args_on_stack_cc > _args_on_stack) || (_args_on_stack_cc > _args_on_stack_cc_ro);
3018 
3019     // Upper bound on stack arguments to avoid hitting the argument limit and
3020     // bailing out of compilation ("unsupported incoming calling sequence").
3021     // TODO we need a reasonable limit (flag?) here
3022     if (MAX2(_args_on_stack_cc, _args_on_stack_cc_ro) <= 60) {
3023       return; // Success
3024     }
3025   }
3026 
3027   // No scalarized args
3028   _sig_cc = _sig;
3029   _regs_cc = _regs;
3030   _args_on_stack_cc = _args_on_stack;
3031 
3032   _sig_cc_ro = _sig;
3033   _regs_cc_ro = _regs;
3034   _args_on_stack_cc_ro = _args_on_stack;
3035 }
3036 
3037 AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(const methodHandle& method) {
3038   // Use customized signature handler.  Need to lock around updates to
3039   // the AdapterHandlerTable (it is not safe for concurrent readers
3040   // and a single writer: this could be fixed if it becomes a
3041   // problem).
3042   assert(_adapters != NULL, "Uninitialized");
3043 
3044   // Fast-path for trivial adapters
3045   AdapterHandlerEntry* entry = get_simple_adapter(method);
3046   if (entry != NULL) {
3047     return entry;
3048   }
3049 
3050   ResourceMark rm;
3051   AdapterBlob* new_adapter = NULL;
3052 
3053   CompiledEntrySignature ces(method());
3054   ces.compute_calling_conventions();
3055   if (ces.has_scalarized_args()) {
3056     method->set_has_scalarized_args(true);
3057     method->set_c1_needs_stack_repair(ces.c1_needs_stack_repair());
3058     method->set_c2_needs_stack_repair(ces.c2_needs_stack_repair());
3059   } else if (method->is_abstract()) {
3060     return _abstract_method_handler;
3061   }
3062 




3063   {
3064     MutexLocker mu(AdapterHandlerLibrary_lock);
3065 
3066     if (ces.has_scalarized_args() && method->is_abstract()) {
3067       // Save a C heap allocated version of the signature for abstract methods with scalarized inline type arguments
3068       address wrong_method_abstract = SharedRuntime::get_handle_wrong_method_abstract_stub();
3069       entry = AdapterHandlerLibrary::new_entry(new AdapterFingerPrint(NULL),
3070                                                StubRoutines::throw_AbstractMethodError_entry(),
3071                                                wrong_method_abstract, wrong_method_abstract, wrong_method_abstract,
3072                                                wrong_method_abstract, wrong_method_abstract);
3073       GrowableArray<SigEntry>* heap_sig = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<SigEntry>(ces.sig_cc_ro().length(), mtInternal);
3074       heap_sig->appendAll(&ces.sig_cc_ro());
3075       entry->set_sig_cc(heap_sig);
3076       return entry;
3077     }
3078 
3079     // Lookup method signature's fingerprint
3080     entry = _adapters->lookup(&ces.sig_cc(), ces.has_inline_recv());
3081 
3082     if (entry != NULL) {
3083 #ifdef ASSERT
3084       if (VerifyAdapterSharing) {
3085         AdapterBlob* comparison_blob = NULL;
3086         AdapterHandlerEntry* comparison_entry = create_adapter(comparison_blob, ces, false);
3087         assert(comparison_blob == NULL, "no blob should be created when creating an adapter for comparison");
3088         assert(comparison_entry->compare_code(entry), "code must match");
3089         // Release the one just created and return the original
3090         _adapters->free_entry(comparison_entry);
3091       }
3092 #endif
3093       return entry;
3094     }
3095 
3096     entry = create_adapter(new_adapter, ces, /* allocate_code_blob */ true);
3097   }
3098 
3099   // Outside of the lock
3100   if (new_adapter != NULL) {
3101     post_adapter_creation(new_adapter, entry);
3102   }
3103   return entry;
3104 }
3105 
3106 AdapterHandlerEntry* AdapterHandlerLibrary::create_adapter(AdapterBlob*& new_adapter,
3107                                                            CompiledEntrySignature& ces,

3108                                                            bool allocate_code_blob) {
3109 
3110   // StubRoutines::code2() is initialized after this function can be called. As a result,
3111   // VerifyAdapterCalls and VerifyAdapterSharing can fail if we re-use code that generated
3112   // prior to StubRoutines::code2() being set. Checks refer to checks generated in an I2C
3113   // stub that ensure that an I2C stub is called from an interpreter frame.
3114   bool contains_all_checks = StubRoutines::code2() != NULL;
3115 





3116   BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
3117   CodeBuffer buffer(buf);
3118   short buffer_locs[20];
3119   buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs,
3120                                           sizeof(buffer_locs)/sizeof(relocInfo));
3121 
3122   // Make a C heap allocated version of the fingerprint to store in the adapter
3123   AdapterFingerPrint* fingerprint = new AdapterFingerPrint(&ces.sig_cc(), ces.has_inline_recv());
3124   MacroAssembler _masm(&buffer);
3125   AdapterHandlerEntry* entry = SharedRuntime::generate_i2c2i_adapters(&_masm,
3126                                                 ces.args_on_stack(),
3127                                                 &ces.sig(),
3128                                                 ces.regs(),
3129                                                 &ces.sig_cc(),
3130                                                 ces.regs_cc(),
3131                                                 &ces.sig_cc_ro(),
3132                                                 ces.regs_cc_ro(),
3133                                                 fingerprint,
3134                                                 new_adapter,
3135                                                 allocate_code_blob);
3136 
3137   if (ces.has_scalarized_args()) {
3138     // Save a C heap allocated version of the scalarized signature and store it in the adapter
3139     GrowableArray<SigEntry>* heap_sig = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<SigEntry>(ces.sig_cc().length(), mtInternal);
3140     heap_sig->appendAll(&ces.sig_cc());
3141     entry->set_sig_cc(heap_sig);
3142   }
3143 
3144 #ifdef ASSERT
3145   if (VerifyAdapterSharing) {
3146     entry->save_code(buf->code_begin(), buffer.insts_size());
3147     if (!allocate_code_blob) {
3148       return entry;
3149     }
3150   }
3151 #endif
3152 

3153   NOT_PRODUCT(int insts_size = buffer.insts_size());
3154   if (new_adapter == NULL) {
3155     // CodeCache is full, disable compilation
3156     // Ought to log this but compile log is only per compile thread
3157     // and we're some non descript Java thread.
3158     return NULL;
3159   }
3160   entry->relocate(new_adapter->content_begin());
3161 #ifndef PRODUCT
3162   // debugging suppport
3163   if (PrintAdapterHandlers || PrintStubCode) {
3164     ttyLocker ttyl;
3165     entry->print_adapter_on(tty);
3166     tty->print_cr("i2c argument handler #%d for: %s %s (%d bytes generated)",
3167                   _adapters->number_of_entries(), fingerprint->as_basic_args_string(),
3168                   fingerprint->as_string(), insts_size);
3169     tty->print_cr("c2i argument handler starts at %p", entry->get_c2i_entry());
3170     if (Verbose || PrintStubCode) {
3171       address first_pc = entry->base_address();
3172       if (first_pc != NULL) {
3173         Disassembler::decode(first_pc, first_pc + insts_size, tty
3174                              NOT_PRODUCT(COMMA &new_adapter->asm_remarks()));
3175         tty->cr();
3176       }
3177     }
3178   }
3179 #endif
3180 
3181   // Add the entry only if the entry contains all required checks (see sharedRuntime_xxx.cpp)
3182   // The checks are inserted only if -XX:+VerifyAdapterCalls is specified.
3183   if (contains_all_checks || !VerifyAdapterCalls) {
3184     _adapters->add(entry);
3185   }
3186   return entry;
3187 }
3188 
3189 address AdapterHandlerEntry::base_address() {
3190   address base = _i2c_entry;
3191   if (base == NULL)  base = _c2i_entry;
3192   assert(base <= _c2i_entry || _c2i_entry == NULL, "");
3193   assert(base <= _c2i_inline_entry || _c2i_inline_entry == NULL, "");
3194   assert(base <= _c2i_inline_ro_entry || _c2i_inline_ro_entry == NULL, "");
3195   assert(base <= _c2i_unverified_entry || _c2i_unverified_entry == NULL, "");
3196   assert(base <= _c2i_unverified_inline_entry || _c2i_unverified_inline_entry == NULL, "");
3197   assert(base <= _c2i_no_clinit_check_entry || _c2i_no_clinit_check_entry == NULL, "");
3198   return base;
3199 }
3200 
3201 void AdapterHandlerEntry::relocate(address new_base) {
3202   address old_base = base_address();
3203   assert(old_base != NULL, "");
3204   ptrdiff_t delta = new_base - old_base;
3205   if (_i2c_entry != NULL)
3206     _i2c_entry += delta;
3207   if (_c2i_entry != NULL)
3208     _c2i_entry += delta;
3209   if (_c2i_inline_entry != NULL)
3210     _c2i_inline_entry += delta;
3211   if (_c2i_inline_ro_entry != NULL)
3212     _c2i_inline_ro_entry += delta;
3213   if (_c2i_unverified_entry != NULL)
3214     _c2i_unverified_entry += delta;
3215   if (_c2i_unverified_inline_entry != NULL)
3216     _c2i_unverified_inline_entry += delta;
3217   if (_c2i_no_clinit_check_entry != NULL)
3218     _c2i_no_clinit_check_entry += delta;
3219   assert(base_address() == new_base, "");
3220 }
3221 
3222 
3223 void AdapterHandlerEntry::deallocate() {
3224   delete _fingerprint;
3225   if (_sig_cc != NULL) {
3226     delete _sig_cc;
3227   }
3228 #ifdef ASSERT
3229   FREE_C_HEAP_ARRAY(unsigned char, _saved_code);
3230 #endif
3231 }
3232 
3233 
3234 #ifdef ASSERT
3235 // Capture the code before relocation so that it can be compared
3236 // against other versions.  If the code is captured after relocation
3237 // then relative instructions won't be equivalent.
3238 void AdapterHandlerEntry::save_code(unsigned char* buffer, int length) {
3239   _saved_code = NEW_C_HEAP_ARRAY(unsigned char, length, mtCode);
3240   _saved_code_length = length;
3241   memcpy(_saved_code, buffer, length);
3242 }
3243 
3244 
3245 bool AdapterHandlerEntry::compare_code(AdapterHandlerEntry* other) {
3246   assert(_saved_code != NULL && other->_saved_code != NULL, "code not saved");
3247 

3280     assert(compile_id > 0, "Must generate native wrapper");
3281 
3282 
3283     ResourceMark rm;
3284     BufferBlob*  buf = buffer_blob(); // the temporary code buffer in CodeCache
3285     if (buf != NULL) {
3286       CodeBuffer buffer(buf);
3287       struct { double data[20]; } locs_buf;
3288       buffer.insts()->initialize_shared_locs((relocInfo*)&locs_buf, sizeof(locs_buf) / sizeof(relocInfo));
3289 #if defined(AARCH64)
3290       // On AArch64 with ZGC and nmethod entry barriers, we need all oops to be
3291       // in the constant pool to ensure ordering between the barrier and oops
3292       // accesses. For native_wrappers we need a constant.
3293       buffer.initialize_consts_size(8);
3294 #endif
3295       MacroAssembler _masm(&buffer);
3296 
3297       // Fill in the signature array, for the calling-convention call.
3298       const int total_args_passed = method->size_of_parameters();
3299 
3300       BasicType stack_sig_bt[16];
3301       VMRegPair stack_regs[16];
3302       BasicType* sig_bt = (total_args_passed <= 16) ? stack_sig_bt : NEW_RESOURCE_ARRAY(BasicType, total_args_passed);
3303       VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
3304 
3305       int i = 0;
3306       if (!method->is_static()) {  // Pass in receiver first
3307         sig_bt[i++] = T_OBJECT;
3308       }
3309       SignatureStream ss(method->signature());
3310       for (; !ss.at_return_type(); ss.next()) {
3311         sig_bt[i++] = ss.type();  // Collect remaining bits of signature
3312         if (ss.type() == T_LONG || ss.type() == T_DOUBLE) {
3313           sig_bt[i++] = T_VOID;   // Longs & doubles take 2 Java slots
3314         }
3315       }
3316       assert(i == total_args_passed, "");
3317       BasicType ret_type = ss.type();
3318 
3319       // Now get the compiled-Java arguments layout.
3320       int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
3321 
3322       // Generate the compiled-to-native wrapper code
3323       nm = SharedRuntime::generate_native_wrapper(&_masm, method, compile_id, sig_bt, regs, ret_type);
3324 
3325       if (nm != NULL) {
3326         {
3327           MutexLocker pl(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
3328           if (nm->make_in_use()) {
3329             method->set_code(method, nm);
3330           }
3331         }
3332 
3333         DirectiveSet* directive = DirectivesStack::getDefaultDirective(CompileBroker::compiler(CompLevel_simple));
3334         if (directive->PrintAssemblyOption) {
3335           nm->print_code();
3336         }
3337         DirectivesStack::release(directive);

3518   AdapterHandlerTableIterator iter(_adapters);
3519   while (iter.has_next()) {
3520     AdapterHandlerEntry* a = iter.next();
3521     if (b == CodeCache::find_blob(a->get_i2c_entry())) {
3522       st->print("Adapter for signature: ");
3523       a->print_adapter_on(tty);
3524       return;
3525     }
3526   }
3527   assert(false, "Should have found handler");
3528 }
3529 
3530 void AdapterHandlerEntry::print_adapter_on(outputStream* st) const {
3531   st->print("AHE@" INTPTR_FORMAT ": %s", p2i(this), fingerprint()->as_string());
3532   if (get_i2c_entry() != NULL) {
3533     st->print(" i2c: " INTPTR_FORMAT, p2i(get_i2c_entry()));
3534   }
3535   if (get_c2i_entry() != NULL) {
3536     st->print(" c2i: " INTPTR_FORMAT, p2i(get_c2i_entry()));
3537   }
3538   if (get_c2i_entry() != NULL) {
3539     st->print(" c2iVE: " INTPTR_FORMAT, p2i(get_c2i_inline_entry()));
3540   }
3541   if (get_c2i_entry() != NULL) {
3542     st->print(" c2iVROE: " INTPTR_FORMAT, p2i(get_c2i_inline_ro_entry()));
3543   }
3544   if (get_c2i_unverified_entry() != NULL) {
3545     st->print(" c2iUE: " INTPTR_FORMAT, p2i(get_c2i_unverified_entry()));
3546   }
3547   if (get_c2i_unverified_entry() != NULL) {
3548     st->print(" c2iUVE: " INTPTR_FORMAT, p2i(get_c2i_unverified_inline_entry()));
3549   }
3550   if (get_c2i_no_clinit_check_entry() != NULL) {
3551     st->print(" c2iNCI: " INTPTR_FORMAT, p2i(get_c2i_no_clinit_check_entry()));
3552   }
3553   st->cr();
3554 }
3555 
3556 #ifndef PRODUCT
3557 
3558 void AdapterHandlerLibrary::print_statistics() {
3559   _adapters->print_statistics();
3560 }
3561 
3562 #endif /* PRODUCT */
3563 
3564 JRT_LEAF(void, SharedRuntime::enable_stack_reserved_zone(JavaThread* current))
3565   StackOverflow* overflow_state = current->stack_overflow_state();
3566   overflow_state->enable_stack_reserved_zone(/*check_if_disabled*/true);
3567   overflow_state->set_reserved_stack_activation(current->stack_base());
3568 JRT_END

3613       break;
3614     } else {
3615       fr = fr.java_sender();
3616     }
3617   }
3618   return activation;
3619 }
3620 
3621 void SharedRuntime::on_slowpath_allocation_exit(JavaThread* current) {
3622   // After any safepoint, just before going back to compiled code,
3623   // we inform the GC that we will be doing initializing writes to
3624   // this object in the future without emitting card-marks, so
3625   // GC may take any compensating steps.
3626 
3627   oop new_obj = current->vm_result();
3628   if (new_obj == NULL) return;
3629 
3630   BarrierSet *bs = BarrierSet::barrier_set();
3631   bs->on_slowpath_allocation_exit(current, new_obj);
3632 }
3633 
3634 // We are at a compiled code to interpreter call. We need backing
3635 // buffers for all inline type arguments. Allocate an object array to
3636 // hold them (convenient because once we're done with it we don't have
3637 // to worry about freeing it).
3638 oop SharedRuntime::allocate_inline_types_impl(JavaThread* current, methodHandle callee, bool allocate_receiver, TRAPS) {
3639   assert(InlineTypePassFieldsAsArgs, "no reason to call this");
3640   ResourceMark rm;
3641 
3642   int nb_slots = 0;
3643   InstanceKlass* holder = callee->method_holder();
3644   allocate_receiver &= !callee->is_static() && holder->is_inline_klass() && callee->is_scalarized_arg(0);
3645   if (allocate_receiver) {
3646     nb_slots++;
3647   }
3648   int arg_num = callee->is_static() ? 0 : 1;
3649   for (SignatureStream ss(callee->signature()); !ss.at_return_type(); ss.next()) {
3650     BasicType bt = ss.type();
3651     if ((bt == T_OBJECT || bt == T_PRIMITIVE_OBJECT) && callee->is_scalarized_arg(arg_num)) {
3652       nb_slots++;
3653     }
3654     if (bt != T_VOID) {
3655       arg_num++;
3656     }
3657   }
3658   objArrayOop array_oop = oopFactory::new_objectArray(nb_slots, CHECK_NULL);
3659   objArrayHandle array(THREAD, array_oop);
3660   arg_num = callee->is_static() ? 0 : 1;
3661   int i = 0;
3662   if (allocate_receiver) {
3663     InlineKlass* vk = InlineKlass::cast(holder);
3664     oop res = vk->allocate_instance(CHECK_NULL);
3665     array->obj_at_put(i++, res);
3666   }
3667   for (SignatureStream ss(callee->signature()); !ss.at_return_type(); ss.next()) {
3668     BasicType bt = ss.type();
3669     if ((bt == T_OBJECT || bt == T_PRIMITIVE_OBJECT) && callee->is_scalarized_arg(arg_num)) {
3670       InlineKlass* vk = ss.as_inline_klass(holder);
3671       assert(vk != NULL, "Unexpected klass");
3672       oop res = vk->allocate_instance(CHECK_NULL);
3673       array->obj_at_put(i++, res);
3674     }
3675     if (bt != T_VOID) {
3676       arg_num++;
3677     }
3678   }
3679   return array();
3680 }
3681 
3682 JRT_ENTRY(void, SharedRuntime::allocate_inline_types(JavaThread* current, Method* callee_method, bool allocate_receiver))
3683   methodHandle callee(current, callee_method);
3684   oop array = SharedRuntime::allocate_inline_types_impl(current, callee, allocate_receiver, CHECK);
3685   current->set_vm_result(array);
3686   current->set_vm_result_2(callee()); // TODO: required to keep callee live?
3687 JRT_END
3688 
3689 // We're returning from an interpreted method: load each field into a
3690 // register following the calling convention
3691 JRT_LEAF(void, SharedRuntime::load_inline_type_fields_in_regs(JavaThread* current, oopDesc* res))
3692 {
3693   assert(res->klass()->is_inline_klass(), "only inline types here");
3694   ResourceMark rm;
3695   RegisterMap reg_map(current);
3696   frame stubFrame = current->last_frame();
3697   frame callerFrame = stubFrame.sender(&reg_map);
3698   assert(callerFrame.is_interpreted_frame(), "should be coming from interpreter");
3699 
3700   InlineKlass* vk = InlineKlass::cast(res->klass());
3701 
3702   const Array<SigEntry>* sig_vk = vk->extended_sig();
3703   const Array<VMRegPair>* regs = vk->return_regs();
3704 
3705   if (regs == NULL) {
3706     // The fields of the inline klass don't fit in registers, bail out
3707     return;
3708   }
3709 
3710   int j = 1;
3711   for (int i = 0; i < sig_vk->length(); i++) {
3712     BasicType bt = sig_vk->at(i)._bt;
3713     if (bt == T_PRIMITIVE_OBJECT) {
3714       continue;
3715     }
3716     if (bt == T_VOID) {
3717       if (sig_vk->at(i-1)._bt == T_LONG ||
3718           sig_vk->at(i-1)._bt == T_DOUBLE) {
3719         j++;
3720       }
3721       continue;
3722     }
3723     int off = sig_vk->at(i)._offset;
3724     assert(off > 0, "offset in object should be positive");
3725     VMRegPair pair = regs->at(j);
3726     address loc = reg_map.location(pair.first());
3727     switch(bt) {
3728     case T_BOOLEAN:
3729       *(jboolean*)loc = res->bool_field(off);
3730       break;
3731     case T_CHAR:
3732       *(jchar*)loc = res->char_field(off);
3733       break;
3734     case T_BYTE:
3735       *(jbyte*)loc = res->byte_field(off);
3736       break;
3737     case T_SHORT:
3738       *(jshort*)loc = res->short_field(off);
3739       break;
3740     case T_INT: {
3741       *(jint*)loc = res->int_field(off);
3742       break;
3743     }
3744     case T_LONG:
3745 #ifdef _LP64
3746       *(intptr_t*)loc = res->long_field(off);
3747 #else
3748       Unimplemented();
3749 #endif
3750       break;
3751     case T_OBJECT:
3752     case T_ARRAY: {
3753       *(oop*)loc = res->obj_field(off);
3754       break;
3755     }
3756     case T_FLOAT:
3757       *(jfloat*)loc = res->float_field(off);
3758       break;
3759     case T_DOUBLE:
3760       *(jdouble*)loc = res->double_field(off);
3761       break;
3762     default:
3763       ShouldNotReachHere();
3764     }
3765     j++;
3766   }
3767   assert(j == regs->length(), "missed a field?");
3768 
3769 #ifdef ASSERT
3770   VMRegPair pair = regs->at(0);
3771   address loc = reg_map.location(pair.first());
3772   assert(*(oopDesc**)loc == res, "overwritten object");
3773 #endif
3774 
3775   current->set_vm_result(res);
3776 }
3777 JRT_END
3778 
3779 // We've returned to an interpreted method, the interpreter needs a
3780 // reference to an inline type instance. Allocate it and initialize it
3781 // from field's values in registers.
3782 JRT_BLOCK_ENTRY(void, SharedRuntime::store_inline_type_fields_to_buf(JavaThread* current, intptr_t res))
3783 {
3784   ResourceMark rm;
3785   RegisterMap reg_map(current);
3786   frame stubFrame = current->last_frame();
3787   frame callerFrame = stubFrame.sender(&reg_map);
3788 
3789 #ifdef ASSERT
3790   InlineKlass* verif_vk = InlineKlass::returned_inline_klass(reg_map);
3791 #endif
3792 
3793   if (!is_set_nth_bit(res, 0)) {
3794     // We're not returning with inline type fields in registers (the
3795     // calling convention didn't allow it for this inline klass)
3796     assert(!Metaspace::contains((void*)res), "should be oop or pointer in buffer area");
3797     current->set_vm_result((oopDesc*)res);
3798     assert(verif_vk == NULL, "broken calling convention");
3799     return;
3800   }
3801 
3802   clear_nth_bit(res, 0);
3803   InlineKlass* vk = (InlineKlass*)res;
3804   assert(verif_vk == vk, "broken calling convention");
3805   assert(Metaspace::contains((void*)res), "should be klass");
3806 
3807   // Allocate handles for every oop field so they are safe in case of
3808   // a safepoint when allocating
3809   GrowableArray<Handle> handles;
3810   vk->save_oop_fields(reg_map, handles);
3811 
3812   // It's unsafe to safepoint until we are here
3813   JRT_BLOCK;
3814   {
3815     JavaThread* THREAD = current;
3816     oop vt = vk->realloc_result(reg_map, handles, CHECK);
3817     current->set_vm_result(vt);
3818   }
3819   JRT_BLOCK_END;
3820 }
3821 JRT_END
3822 
< prev index next >