< prev index next >

src/hotspot/share/runtime/sharedRuntime.cpp

Print this page

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

  50 #include "memory/resourceArea.hpp"
  51 #include "memory/universe.hpp"
  52 #include "metaprogramming/primitiveConversions.hpp"



  53 #include "oops/klass.hpp"
  54 #include "oops/method.inline.hpp"
  55 #include "oops/objArrayKlass.hpp"

  56 #include "oops/oop.inline.hpp"
  57 #include "prims/forte.hpp"
  58 #include "prims/jvmtiExport.hpp"
  59 #include "prims/jvmtiThreadState.hpp"
  60 #include "prims/methodHandles.hpp"
  61 #include "prims/nativeLookup.hpp"
  62 #include "runtime/arguments.hpp"
  63 #include "runtime/atomicAccess.hpp"
  64 #include "runtime/basicLock.inline.hpp"
  65 #include "runtime/frame.inline.hpp"
  66 #include "runtime/handles.inline.hpp"
  67 #include "runtime/init.hpp"
  68 #include "runtime/interfaceSupport.inline.hpp"
  69 #include "runtime/java.hpp"
  70 #include "runtime/javaCalls.hpp"
  71 #include "runtime/jniHandles.inline.hpp"
  72 #include "runtime/osThread.hpp"
  73 #include "runtime/perfData.hpp"
  74 #include "runtime/sharedRuntime.hpp"

  75 #include "runtime/stackWatermarkSet.hpp"
  76 #include "runtime/stubRoutines.hpp"
  77 #include "runtime/synchronizer.hpp"
  78 #include "runtime/timerTrace.hpp"
  79 #include "runtime/vframe.inline.hpp"
  80 #include "runtime/vframeArray.hpp"
  81 #include "runtime/vm_version.hpp"
  82 #include "utilities/copy.hpp"
  83 #include "utilities/dtrace.hpp"
  84 #include "utilities/events.hpp"
  85 #include "utilities/globalDefinitions.hpp"
  86 #include "utilities/hashTable.hpp"
  87 #include "utilities/macros.hpp"
  88 #include "utilities/xmlstream.hpp"
  89 #ifdef COMPILER1
  90 #include "c1/c1_Runtime1.hpp"
  91 #endif
  92 #ifdef COMPILER2
  93 #include "opto/runtime.hpp"
  94 #endif

1212 // for a call current in progress, i.e., arguments has been pushed on stack
1213 // but callee has not been invoked yet.  Caller frame must be compiled.
1214 Handle SharedRuntime::find_callee_info_helper(vframeStream& vfst, Bytecodes::Code& bc,
1215                                               CallInfo& callinfo, TRAPS) {
1216   Handle receiver;
1217   Handle nullHandle;  // create a handy null handle for exception returns
1218   JavaThread* current = THREAD;
1219 
1220   assert(!vfst.at_end(), "Java frame must exist");
1221 
1222   // Find caller and bci from vframe
1223   methodHandle caller(current, vfst.method());
1224   int          bci   = vfst.bci();
1225 
1226   if (caller->is_continuation_enter_intrinsic()) {
1227     bc = Bytecodes::_invokestatic;
1228     LinkResolver::resolve_continuation_enter(callinfo, CHECK_NH);
1229     return receiver;
1230   }
1231 
















1232   Bytecode_invoke bytecode(caller, bci);
1233   int bytecode_index = bytecode.index();
1234   bc = bytecode.invoke_code();
1235 
1236   methodHandle attached_method(current, extract_attached_method(vfst));
1237   if (attached_method.not_null()) {
1238     Method* callee = bytecode.static_target(CHECK_NH);
1239     vmIntrinsics::ID id = callee->intrinsic_id();
1240     // When VM replaces MH.invokeBasic/linkTo* call with a direct/virtual call,
1241     // it attaches statically resolved method to the call site.
1242     if (MethodHandles::is_signature_polymorphic(id) &&
1243         MethodHandles::is_signature_polymorphic_intrinsic(id)) {
1244       bc = MethodHandles::signature_polymorphic_intrinsic_bytecode(id);
1245 
1246       // Adjust invocation mode according to the attached method.
1247       switch (bc) {
1248         case Bytecodes::_invokevirtual:
1249           if (attached_method->method_holder()->is_interface()) {
1250             bc = Bytecodes::_invokeinterface;
1251           }
1252           break;
1253         case Bytecodes::_invokeinterface:
1254           if (!attached_method->method_holder()->is_interface()) {
1255             bc = Bytecodes::_invokevirtual;
1256           }
1257           break;
1258         case Bytecodes::_invokehandle:
1259           if (!MethodHandles::is_signature_polymorphic_method(attached_method())) {
1260             bc = attached_method->is_static() ? Bytecodes::_invokestatic
1261                                               : Bytecodes::_invokevirtual;
1262           }
1263           break;
1264         default:
1265           break;
1266       }






1267     }
1268   }
1269 
1270   assert(bc != Bytecodes::_illegal, "not initialized");
1271 
1272   bool has_receiver = bc != Bytecodes::_invokestatic &&
1273                       bc != Bytecodes::_invokedynamic &&
1274                       bc != Bytecodes::_invokehandle;

1275 
1276   // Find receiver for non-static call
1277   if (has_receiver) {
1278     // This register map must be update since we need to find the receiver for
1279     // compiled frames. The receiver might be in a register.
1280     RegisterMap reg_map2(current,
1281                          RegisterMap::UpdateMap::include,
1282                          RegisterMap::ProcessFrames::include,
1283                          RegisterMap::WalkContinuation::skip);
1284     frame stubFrame   = current->last_frame();
1285     // Caller-frame is a compiled frame
1286     frame callerFrame = stubFrame.sender(&reg_map2);
1287 
1288     if (attached_method.is_null()) {
1289       Method* callee = bytecode.static_target(CHECK_NH);

1290       if (callee == nullptr) {
1291         THROW_(vmSymbols::java_lang_NoSuchMethodException(), nullHandle);
1292       }
1293     }
1294 
1295     // Retrieve from a compiled argument list
1296     receiver = Handle(current, callerFrame.retrieve_receiver(&reg_map2));
1297     assert(oopDesc::is_oop_or_null(receiver()), "");
1298 
1299     if (receiver.is_null()) {
1300       THROW_(vmSymbols::java_lang_NullPointerException(), nullHandle);










1301     }
1302   }
1303 
1304   // Resolve method
1305   if (attached_method.not_null()) {
1306     // Parameterized by attached method.
1307     LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, CHECK_NH);
1308   } else {
1309     // Parameterized by bytecode.
1310     constantPoolHandle constants(current, caller->constants());
1311     LinkResolver::resolve_invoke(callinfo, receiver, constants, bytecode_index, bc, CHECK_NH);
1312   }
1313 
1314 #ifdef ASSERT
1315   // Check that the receiver klass is of the right subtype and that it is initialized for virtual calls
1316   if (has_receiver) {
1317     assert(receiver.not_null(), "should have thrown exception");
1318     Klass* receiver_klass = receiver->klass();
1319     Klass* rk = nullptr;
1320     if (attached_method.not_null()) {
1321       // In case there's resolved method attached, use its holder during the check.
1322       rk = attached_method->method_holder();
1323     } else {
1324       // Klass is already loaded.
1325       constantPoolHandle constants(current, caller->constants());
1326       rk = constants->klass_ref_at(bytecode_index, bc, CHECK_NH);
1327     }
1328     Klass* static_receiver_klass = rk;
1329     assert(receiver_klass->is_subtype_of(static_receiver_klass),
1330            "actual receiver must be subclass of static receiver klass");
1331     if (receiver_klass->is_instance_klass()) {
1332       if (InstanceKlass::cast(receiver_klass)->is_not_initialized()) {
1333         tty->print_cr("ERROR: Klass not yet initialized!!");
1334         receiver_klass->print();
1335       }
1336       assert(!InstanceKlass::cast(receiver_klass)->is_not_initialized(), "receiver_klass must be initialized");
1337     }
1338   }
1339 #endif
1340 
1341   return receiver;
1342 }
1343 
1344 methodHandle SharedRuntime::find_callee_method(TRAPS) {
1345   JavaThread* current = THREAD;
1346   ResourceMark rm(current);
1347   // We need first to check if any Java activations (compiled, interpreted)
1348   // exist on the stack since last JavaCall.  If not, we need
1349   // to get the target method from the JavaCall wrapper.
1350   vframeStream vfst(current, true);  // Do not skip any javaCalls
1351   methodHandle callee_method;
1352   if (vfst.at_end()) {
1353     // No Java frames were found on stack since we did the JavaCall.
1354     // Hence the stack can only contain an entry_frame.  We need to
1355     // find the target method from the stub frame.
1356     RegisterMap reg_map(current,
1357                         RegisterMap::UpdateMap::skip,
1358                         RegisterMap::ProcessFrames::include,
1359                         RegisterMap::WalkContinuation::skip);
1360     frame fr = current->last_frame();
1361     assert(fr.is_runtime_frame(), "must be a runtimeStub");
1362     fr = fr.sender(&reg_map);
1363     assert(fr.is_entry_frame(), "must be");
1364     // fr is now pointing to the entry frame.
1365     callee_method = methodHandle(current, fr.entry_frame_call_wrapper()->callee_method());
1366   } else {
1367     Bytecodes::Code bc;
1368     CallInfo callinfo;
1369     find_callee_info_helper(vfst, bc, callinfo, CHECK_(methodHandle()));




1370     callee_method = methodHandle(current, callinfo.selected_method());
1371   }
1372   assert(callee_method()->is_method(), "must be");
1373   return callee_method;
1374 }
1375 
1376 // Resolves a call.
1377 methodHandle SharedRuntime::resolve_helper(bool is_virtual, bool is_optimized, TRAPS) {
1378   JavaThread* current = THREAD;
1379   ResourceMark rm(current);
1380   RegisterMap cbl_map(current,
1381                       RegisterMap::UpdateMap::skip,
1382                       RegisterMap::ProcessFrames::include,
1383                       RegisterMap::WalkContinuation::skip);
1384   frame caller_frame = current->last_frame().sender(&cbl_map);
1385 
1386   CodeBlob* caller_cb = caller_frame.cb();
1387   guarantee(caller_cb != nullptr && caller_cb->is_nmethod(), "must be called from compiled method");
1388   nmethod* caller_nm = caller_cb->as_nmethod();
1389 
1390   // determine call info & receiver
1391   // note: a) receiver is null for static calls
1392   //       b) an exception is thrown if receiver is null for non-static calls
1393   CallInfo call_info;
1394   Bytecodes::Code invoke_code = Bytecodes::_illegal;
1395   Handle receiver = find_callee_info(invoke_code, call_info, CHECK_(methodHandle()));
1396 
1397   NoSafepointVerifier nsv;
1398 
1399   methodHandle callee_method(current, call_info.selected_method());




1400 
1401   assert((!is_virtual && invoke_code == Bytecodes::_invokestatic ) ||
1402          (!is_virtual && invoke_code == Bytecodes::_invokespecial) ||
1403          (!is_virtual && invoke_code == Bytecodes::_invokehandle ) ||
1404          (!is_virtual && invoke_code == Bytecodes::_invokedynamic) ||
1405          ( is_virtual && invoke_code != Bytecodes::_invokestatic ), "inconsistent bytecode");
1406 
1407   assert(!caller_nm->is_unloading(), "It should not be unloading");
1408 
1409 #ifndef PRODUCT
1410   // tracing/debugging/statistics
1411   uint *addr = (is_optimized) ? (&_resolve_opt_virtual_ctr) :
1412                  (is_virtual) ? (&_resolve_virtual_ctr) :
1413                                 (&_resolve_static_ctr);
1414   AtomicAccess::inc(addr);
1415 
1416   if (TraceCallFixup) {
1417     ResourceMark rm(current);
1418     tty->print("resolving %s%s (%s) call to",
1419                (is_optimized) ? "optimized " : "", (is_virtual) ? "virtual" : "static",
1420                Bytecodes::name(invoke_code));
1421     callee_method->print_short_name(tty);
1422     tty->print_cr(" at pc: " INTPTR_FORMAT " to code: " INTPTR_FORMAT,
1423                   p2i(caller_frame.pc()), p2i(callee_method->code()));
1424   }
1425 #endif
1426 
1427   if (invoke_code == Bytecodes::_invokestatic) {
1428     assert(callee_method->method_holder()->is_initialized() ||
1429            callee_method->method_holder()->is_reentrant_initialization(current),
1430            "invalid class initialization state for invoke_static");
1431     if (!VM_Version::supports_fast_class_init_checks() && callee_method->needs_clinit_barrier()) {
1432       // In order to keep class initialization check, do not patch call
1433       // site for static call when the class is not fully initialized.
1434       // Proper check is enforced by call site re-resolution on every invocation.
1435       //
1436       // When fast class initialization checks are supported (VM_Version::supports_fast_class_init_checks() == true),
1437       // explicit class initialization check is put in nmethod entry (VEP).
1438       assert(callee_method->method_holder()->is_linked(), "must be");
1439       return callee_method;
1440     }
1441   }
1442 
1443 
1444   // JSR 292 key invariant:
1445   // If the resolved method is a MethodHandle invoke target, the call
1446   // site must be a MethodHandle call site, because the lambda form might tail-call
1447   // leaving the stack in a state unknown to either caller or callee
1448 
1449   // Compute entry points. The computation of the entry points is independent of
1450   // patching the call.
1451 
1452   // Make sure the callee nmethod does not get deoptimized and removed before
1453   // we are done patching the code.
1454 
1455 
1456   CompiledICLocker ml(caller_nm);
1457   if (is_virtual && !is_optimized) {
1458     CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1459     inline_cache->update(&call_info, receiver->klass());
1460   } else {
1461     // Callsite is a direct call - set it to the destination method
1462     CompiledDirectCall* callsite = CompiledDirectCall::before(caller_frame.pc());
1463     callsite->set(callee_method);
1464   }
1465 
1466   return callee_method;
1467 }
1468 
1469 // Inline caches exist only in compiled code
1470 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_ic_miss(JavaThread* current))
1471 #ifdef ASSERT
1472   RegisterMap reg_map(current,
1473                       RegisterMap::UpdateMap::skip,
1474                       RegisterMap::ProcessFrames::include,
1475                       RegisterMap::WalkContinuation::skip);
1476   frame stub_frame = current->last_frame();
1477   assert(stub_frame.is_runtime_frame(), "sanity check");
1478   frame caller_frame = stub_frame.sender(&reg_map);
1479   assert(!caller_frame.is_interpreted_frame() && !caller_frame.is_entry_frame() && !caller_frame.is_upcall_stub_frame(), "unexpected frame");
1480 #endif /* ASSERT */
1481 
1482   methodHandle callee_method;

1483   JRT_BLOCK
1484     callee_method = SharedRuntime::handle_ic_miss_helper(CHECK_NULL);
1485     // Return Method* through TLS
1486     current->set_vm_result_metadata(callee_method());
1487   JRT_BLOCK_END
1488   // return compiled code entry point after potential safepoints
1489   return get_resolved_entry(current, callee_method);
1490 JRT_END
1491 
1492 
1493 // Handle call site that has been made non-entrant
1494 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method(JavaThread* current))
1495   // 6243940 We might end up in here if the callee is deoptimized
1496   // as we race to call it.  We don't want to take a safepoint if
1497   // the caller was interpreted because the caller frame will look
1498   // interpreted to the stack walkers and arguments are now
1499   // "compiled" so it is much better to make this transition
1500   // invisible to the stack walking code. The i2c path will
1501   // place the callee method in the callee_target. It is stashed
1502   // there because if we try and find the callee by normal means a
1503   // safepoint is possible and have trouble gc'ing the compiled args.
1504   RegisterMap reg_map(current,
1505                       RegisterMap::UpdateMap::skip,
1506                       RegisterMap::ProcessFrames::include,
1507                       RegisterMap::WalkContinuation::skip);
1508   frame stub_frame = current->last_frame();
1509   assert(stub_frame.is_runtime_frame(), "sanity check");
1510   frame caller_frame = stub_frame.sender(&reg_map);
1511 
1512   if (caller_frame.is_interpreted_frame() ||
1513       caller_frame.is_entry_frame() ||
1514       caller_frame.is_upcall_stub_frame()) {
1515     Method* callee = current->callee_target();
1516     guarantee(callee != nullptr && callee->is_method(), "bad handshake");
1517     current->set_vm_result_metadata(callee);
1518     current->set_callee_target(nullptr);
1519     if (caller_frame.is_entry_frame() && VM_Version::supports_fast_class_init_checks()) {
1520       // Bypass class initialization checks in c2i when caller is in native.
1521       // JNI calls to static methods don't have class initialization checks.
1522       // Fast class initialization checks are present in c2i adapters and call into
1523       // SharedRuntime::handle_wrong_method() on the slow path.
1524       //
1525       // JVM upcalls may land here as well, but there's a proper check present in
1526       // LinkResolver::resolve_static_call (called from JavaCalls::call_static),
1527       // so bypassing it in c2i adapter is benign.
1528       return callee->get_c2i_no_clinit_check_entry();
1529     } else {
1530       return callee->get_c2i_entry();




1531     }
1532   }
1533 
1534   // Must be compiled to compiled path which is safe to stackwalk
1535   methodHandle callee_method;



1536   JRT_BLOCK
1537     // Force resolving of caller (if we called from compiled frame)
1538     callee_method = SharedRuntime::reresolve_call_site(CHECK_NULL);
1539     current->set_vm_result_metadata(callee_method());
1540   JRT_BLOCK_END
1541   // return compiled code entry point after potential safepoints
1542   return get_resolved_entry(current, callee_method);
1543 JRT_END
1544 
1545 // Handle abstract method call
1546 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_abstract(JavaThread* current))
1547   // Verbose error message for AbstractMethodError.
1548   // Get the called method from the invoke bytecode.
1549   vframeStream vfst(current, true);
1550   assert(!vfst.at_end(), "Java frame must exist");
1551   methodHandle caller(current, vfst.method());
1552   Bytecode_invoke invoke(caller, vfst.bci());
1553   DEBUG_ONLY( invoke.verify(); )
1554 
1555   // Find the compiled caller frame.
1556   RegisterMap reg_map(current,
1557                       RegisterMap::UpdateMap::include,
1558                       RegisterMap::ProcessFrames::include,
1559                       RegisterMap::WalkContinuation::skip);
1560   frame stubFrame = current->last_frame();
1561   assert(stubFrame.is_runtime_frame(), "must be");
1562   frame callerFrame = stubFrame.sender(&reg_map);
1563   assert(callerFrame.is_compiled_frame(), "must be");
1564 
1565   // Install exception and return forward entry.
1566   address res = SharedRuntime::throw_AbstractMethodError_entry();
1567   JRT_BLOCK
1568     methodHandle callee(current, invoke.static_target(current));
1569     if (!callee.is_null()) {
1570       oop recv = callerFrame.retrieve_receiver(&reg_map);
1571       Klass *recv_klass = (recv != nullptr) ? recv->klass() : nullptr;
1572       res = StubRoutines::forward_exception_entry();
1573       LinkResolver::throw_abstract_method_error(callee, recv_klass, CHECK_(res));
1574     }
1575   JRT_BLOCK_END
1576   return res;
1577 JRT_END
1578 
1579 // return verified_code_entry if interp_only_mode is not set for the current thread;
1580 // otherwise return c2i entry.
1581 address SharedRuntime::get_resolved_entry(JavaThread* current, methodHandle callee_method) {
1582   if (current->is_interp_only_mode() && !callee_method->is_special_native_intrinsic()) {
1583     // In interp_only_mode we need to go to the interpreted entry
1584     // The c2i won't patch in this mode -- see fixup_callers_callsite
1585     return callee_method->get_c2i_entry();




















1586   }
1587   assert(callee_method->verified_code_entry() != nullptr, " Jump to zero!");
1588   return callee_method->verified_code_entry();
1589 }
1590 
1591 // resolve a static call and patch code
1592 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_call_C(JavaThread* current ))
1593   methodHandle callee_method;

1594   bool enter_special = false;
1595   JRT_BLOCK
1596     callee_method = SharedRuntime::resolve_helper(false, false, CHECK_NULL);
1597     current->set_vm_result_metadata(callee_method());
1598   JRT_BLOCK_END
1599   // return compiled code entry point after potential safepoints
1600   return get_resolved_entry(current, callee_method);
1601 JRT_END
1602 
1603 // resolve virtual call and update inline cache to monomorphic
1604 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_virtual_call_C(JavaThread* current))
1605   methodHandle callee_method;

1606   JRT_BLOCK
1607     callee_method = SharedRuntime::resolve_helper(true, false, CHECK_NULL);
1608     current->set_vm_result_metadata(callee_method());
1609   JRT_BLOCK_END
1610   // return compiled code entry point after potential safepoints
1611   return get_resolved_entry(current, callee_method);
1612 JRT_END
1613 
1614 
1615 // Resolve a virtual call that can be statically bound (e.g., always
1616 // monomorphic, so it has no inline cache).  Patch code to resolved target.
1617 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_opt_virtual_call_C(JavaThread* current))
1618   methodHandle callee_method;

1619   JRT_BLOCK
1620     callee_method = SharedRuntime::resolve_helper(true, true, CHECK_NULL);
1621     current->set_vm_result_metadata(callee_method());
1622   JRT_BLOCK_END
1623   // return compiled code entry point after potential safepoints
1624   return get_resolved_entry(current, callee_method);
1625 JRT_END
1626 
1627 methodHandle SharedRuntime::handle_ic_miss_helper(TRAPS) {


1628   JavaThread* current = THREAD;
1629   ResourceMark rm(current);
1630   CallInfo call_info;
1631   Bytecodes::Code bc;
1632 
1633   // receiver is null for static calls. An exception is thrown for null
1634   // receivers for non-static calls
1635   Handle receiver = find_callee_info(bc, call_info, CHECK_(methodHandle()));
1636 
1637   methodHandle callee_method(current, call_info.selected_method());
1638 
1639 #ifndef PRODUCT
1640   AtomicAccess::inc(&_ic_miss_ctr);
1641 
1642   // Statistics & Tracing
1643   if (TraceCallFixup) {
1644     ResourceMark rm(current);
1645     tty->print("IC miss (%s) call to", Bytecodes::name(bc));
1646     callee_method->print_short_name(tty);
1647     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1648   }
1649 
1650   if (ICMissHistogram) {
1651     MutexLocker m(VMStatistic_lock);
1652     RegisterMap reg_map(current,
1653                         RegisterMap::UpdateMap::skip,
1654                         RegisterMap::ProcessFrames::include,
1655                         RegisterMap::WalkContinuation::skip);
1656     frame f = current->last_frame().real_sender(&reg_map);// skip runtime stub
1657     // produce statistics under the lock
1658     trace_ic_miss(f.pc());
1659   }
1660 #endif
1661 
1662   // install an event collector so that when a vtable stub is created the
1663   // profiler can be notified via a DYNAMIC_CODE_GENERATED event. The
1664   // event can't be posted when the stub is created as locks are held
1665   // - instead the event will be deferred until the event collector goes
1666   // out of scope.
1667   JvmtiDynamicCodeEventCollector event_collector;
1668 
1669   // Update inline cache to megamorphic. Skip update if we are called from interpreted.
1670   RegisterMap reg_map(current,
1671                       RegisterMap::UpdateMap::skip,
1672                       RegisterMap::ProcessFrames::include,
1673                       RegisterMap::WalkContinuation::skip);
1674   frame caller_frame = current->last_frame().sender(&reg_map);
1675   CodeBlob* cb = caller_frame.cb();
1676   nmethod* caller_nm = cb->as_nmethod();




1677 
1678   CompiledICLocker ml(caller_nm);
1679   CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1680   inline_cache->update(&call_info, receiver()->klass());
1681 
1682   return callee_method;
1683 }
1684 
1685 //
1686 // Resets a call-site in compiled code so it will get resolved again.
1687 // This routines handles both virtual call sites, optimized virtual call
1688 // sites, and static call sites. Typically used to change a call sites
1689 // destination from compiled to interpreted.
1690 //
1691 methodHandle SharedRuntime::reresolve_call_site(TRAPS) {
1692   JavaThread* current = THREAD;
1693   ResourceMark rm(current);
1694   RegisterMap reg_map(current,
1695                       RegisterMap::UpdateMap::skip,
1696                       RegisterMap::ProcessFrames::include,
1697                       RegisterMap::WalkContinuation::skip);
1698   frame stub_frame = current->last_frame();
1699   assert(stub_frame.is_runtime_frame(), "must be a runtimeStub");
1700   frame caller = stub_frame.sender(&reg_map);
1701 
1702   // Do nothing if the frame isn't a live compiled frame.
1703   // nmethod could be deoptimized by the time we get here
1704   // so no update to the caller is needed.
1705 
1706   if ((caller.is_compiled_frame() && !caller.is_deoptimized_frame()) ||
1707       (caller.is_native_frame() && caller.cb()->as_nmethod()->method()->is_continuation_enter_intrinsic())) {
1708 













1709     address pc = caller.pc();
1710 
1711     nmethod* caller_nm = CodeCache::find_nmethod(pc);
1712     assert(caller_nm != nullptr, "did not find caller nmethod");
1713 
1714     // Default call_addr is the location of the "basic" call.
1715     // Determine the address of the call we a reresolving. With
1716     // Inline Caches we will always find a recognizable call.
1717     // With Inline Caches disabled we may or may not find a
1718     // recognizable call. We will always find a call for static
1719     // calls and for optimized virtual calls. For vanilla virtual
1720     // calls it depends on the state of the UseInlineCaches switch.
1721     //
1722     // With Inline Caches disabled we can get here for a virtual call
1723     // for two reasons:
1724     //   1 - calling an abstract method. The vtable for abstract methods
1725     //       will run us thru handle_wrong_method and we will eventually
1726     //       end up in the interpreter to throw the ame.
1727     //   2 - a racing deoptimization. We could be doing a vanilla vtable
1728     //       call and between the time we fetch the entry address and
1729     //       we jump to it the target gets deoptimized. Similar to 1
1730     //       we will wind up in the interprter (thru a c2i with c2).
1731     //
1732     CompiledICLocker ml(caller_nm);
1733     address call_addr = caller_nm->call_instruction_address(pc);
1734 
1735     if (call_addr != nullptr) {
1736       // On x86 the logic for finding a call instruction is blindly checking for a call opcode 5
1737       // bytes back in the instruction stream so we must also check for reloc info.
1738       RelocIterator iter(caller_nm, call_addr, call_addr+1);
1739       bool ret = iter.next(); // Get item
1740       if (ret) {

1741         switch (iter.type()) {
1742           case relocInfo::static_call_type:

1743           case relocInfo::opt_virtual_call_type: {
1744             CompiledDirectCall* cdc = CompiledDirectCall::at(call_addr);
1745             cdc->set_to_clean();



1746             break;
1747           }
1748 
1749           case relocInfo::virtual_call_type: {
1750             // compiled, dispatched call (which used to call an interpreted method)
1751             CompiledIC* inline_cache = CompiledIC_at(caller_nm, call_addr);
1752             inline_cache->set_to_clean();


1753             break;
1754           }
1755           default:
1756             break;
1757         }
1758       }
1759     }
1760   }
1761 
1762   methodHandle callee_method = find_callee_method(CHECK_(methodHandle()));
1763 
1764 
1765 #ifndef PRODUCT
1766   AtomicAccess::inc(&_wrong_method_ctr);
1767 
1768   if (TraceCallFixup) {
1769     ResourceMark rm(current);
1770     tty->print("handle_wrong_method reresolving call to");
1771     callee_method->print_short_name(tty);
1772     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1773   }
1774 #endif
1775 
1776   return callee_method;
1777 }
1778 
1779 address SharedRuntime::handle_unsafe_access(JavaThread* thread, address next_pc) {
1780   // The faulting unsafe accesses should be changed to throw the error
1781   // synchronously instead. Meanwhile the faulting instruction will be
1782   // skipped over (effectively turning it into a no-op) and an
1783   // asynchronous exception will be raised which the thread will
1784   // handle at a later point. If the instruction is a load it will
1785   // return garbage.
1786 
1787   // Request an async exception.
1788   thread->set_pending_unsafe_access_error();
1789 
1790   // Return address of next instruction to execute.

1956   msglen += strlen(caster_klass_description) + strlen(target_klass_description) + strlen(klass_separator) + 3;
1957 
1958   char* message = NEW_RESOURCE_ARRAY_RETURN_NULL(char, msglen);
1959   if (message == nullptr) {
1960     // Shouldn't happen, but don't cause even more problems if it does
1961     message = const_cast<char*>(caster_klass->external_name());
1962   } else {
1963     jio_snprintf(message,
1964                  msglen,
1965                  "class %s cannot be cast to class %s (%s%s%s)",
1966                  caster_name,
1967                  target_name,
1968                  caster_klass_description,
1969                  klass_separator,
1970                  target_klass_description
1971                  );
1972   }
1973   return message;
1974 }
1975 















1976 JRT_LEAF(void, SharedRuntime::reguard_yellow_pages())
1977   (void) JavaThread::current()->stack_overflow_state()->reguard_stack();
1978 JRT_END
1979 
1980 void SharedRuntime::monitor_enter_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) {
1981   if (!SafepointSynchronize::is_synchronizing()) {
1982     // Only try quick_enter() if we're not trying to reach a safepoint
1983     // so that the calling thread reaches the safepoint more quickly.
1984     if (ObjectSynchronizer::quick_enter(obj, lock, current)) {
1985       return;
1986     }
1987   }
1988   // NO_ASYNC required because an async exception on the state transition destructor
1989   // would leave you with the lock held and it would never be released.
1990   // The normal monitorenter NullPointerException is thrown without acquiring a lock
1991   // and the model is that an exception implies the method failed.
1992   JRT_BLOCK_NO_ASYNC
1993   Handle h_obj(THREAD, obj);
1994   ObjectSynchronizer::enter(h_obj, lock, current);
1995   assert(!HAS_PENDING_EXCEPTION, "Should have no exception here");

2189   tty->print_cr("Note 1: counter updates are not MT-safe.");
2190   tty->print_cr("Note 2: %% in major categories are relative to total non-inlined calls;");
2191   tty->print_cr("        %% in nested categories are relative to their category");
2192   tty->print_cr("        (and thus add up to more than 100%% with inlining)");
2193   tty->cr();
2194 
2195   MethodArityHistogram h;
2196 }
2197 #endif
2198 
2199 #ifndef PRODUCT
2200 static int _lookups; // number of calls to lookup
2201 static int _equals;  // number of buckets checked with matching hash
2202 static int _archived_hits; // number of successful lookups in archived table
2203 static int _runtime_hits;  // number of successful lookups in runtime table
2204 #endif
2205 
2206 // A simple wrapper class around the calling convention information
2207 // that allows sharing of adapters for the same calling convention.
2208 class AdapterFingerPrint : public MetaspaceObj {
2209  private:
2210   enum {
2211     _basic_type_bits = 4,
2212     _basic_type_mask = right_n_bits(_basic_type_bits),
2213     _basic_types_per_int = BitsPerInt / _basic_type_bits,

























2214   };
2215   // TO DO:  Consider integrating this with a more global scheme for compressing signatures.
2216   // For now, 4 bits per components (plus T_VOID gaps after double/long) is not excessive.
2217 
2218   int _length;


2219 
2220   static int data_offset() { return sizeof(AdapterFingerPrint); }
2221   int* data_pointer() {
2222     return (int*)((address)this + data_offset());






2223   }
2224 
2225   // Private construtor. Use allocate() to get an instance.
2226   AdapterFingerPrint(int total_args_passed, BasicType* sig_bt, int len) {
2227     int* data = data_pointer();
2228     // Pack the BasicTypes with 8 per int
2229     assert(len == length(total_args_passed), "sanity");
2230     _length = len;
2231     int sig_index = 0;
2232     for (int index = 0; index < _length; index++) {
2233       int value = 0;
2234       for (int byte = 0; sig_index < total_args_passed && byte < _basic_types_per_int; byte++) {
2235         int bt = adapter_encoding(sig_bt[sig_index++]);
2236         assert((bt & _basic_type_mask) == bt, "must fit in 4 bits");
2237         value = (value << _basic_type_bits) | bt;










2238       }
2239       data[index] = value;


2240     }

2241   }
2242 
2243   // Call deallocate instead
2244   ~AdapterFingerPrint() {
2245     ShouldNotCallThis();
2246   }
2247 
2248   static int length(int total_args) {
2249     return (total_args + (_basic_types_per_int-1)) / _basic_types_per_int;
2250   }
2251 
2252   static int compute_size_in_words(int len) {
2253     return (int)heap_word_size(sizeof(AdapterFingerPrint) + (len * sizeof(int)));
2254   }
2255 
2256   // Remap BasicTypes that are handled equivalently by the adapters.
2257   // These are correct for the current system but someday it might be
2258   // necessary to make this mapping platform dependent.
2259   static int adapter_encoding(BasicType in) {
2260     switch (in) {
2261       case T_BOOLEAN:
2262       case T_BYTE:
2263       case T_SHORT:
2264       case T_CHAR:
2265         // There are all promoted to T_INT in the calling convention
2266         return T_INT;
2267 
2268       case T_OBJECT:
2269       case T_ARRAY:
2270         // In other words, we assume that any register good enough for
2271         // an int or long is good enough for a managed pointer.
2272 #ifdef _LP64
2273         return T_LONG;
2274 #else
2275         return T_INT;
2276 #endif
2277 
2278       case T_INT:
2279       case T_LONG:
2280       case T_FLOAT:
2281       case T_DOUBLE:
2282       case T_VOID:
2283         return in;
2284 
2285       default:
2286         ShouldNotReachHere();
2287         return T_CONFLICT;
2288     }
2289   }
2290 
2291   void* operator new(size_t size, size_t fp_size) throw() {
2292     assert(fp_size >= size, "sanity check");
2293     void* p = AllocateHeap(fp_size, mtCode);
2294     memset(p, 0, fp_size);
2295     return p;
2296   }
2297 

2298   template<typename Function>
2299   void iterate_args(Function function) {
2300     for (int i = 0; i < length(); i++) {
2301       unsigned val = (unsigned)value(i);
2302       // args are packed so that first/lower arguments are in the highest
2303       // bits of each int value, so iterate from highest to the lowest
2304       for (int j = 32 - _basic_type_bits; j >= 0; j -= _basic_type_bits) {
2305         unsigned v = (val >> j) & _basic_type_mask;
2306         if (v == 0) {
2307           continue;
2308         }
2309         function(v);
2310       }
2311     }
2312   }
2313 
2314  public:
2315   static AdapterFingerPrint* allocate(int total_args_passed, BasicType* sig_bt) {
2316     int len = length(total_args_passed);
2317     int size_in_bytes = BytesPerWord * compute_size_in_words(len);
2318     AdapterFingerPrint* afp = new (size_in_bytes) AdapterFingerPrint(total_args_passed, sig_bt, len);
2319     assert((afp->size() * BytesPerWord) == size_in_bytes, "should match");
2320     return afp;
2321   }
2322 
2323   static void deallocate(AdapterFingerPrint* fp) {
2324     FreeHeap(fp);
2325   }
2326 
2327   int value(int index) {
2328     int* data = data_pointer();
2329     return data[index];
2330   }
2331 
2332   int length() {
2333     return _length;
2334   }
2335 
2336   unsigned int compute_hash() {
2337     int hash = 0;
2338     for (int i = 0; i < length(); i++) {
2339       int v = value(i);
2340       //Add arithmetic operation to the hash, like +3 to improve hashing
2341       hash = ((hash << 8) ^ v ^ (hash >> 5)) + 3;
2342     }
2343     return (unsigned int)hash;
2344   }
2345 
2346   const char* as_string() {
2347     stringStream st;
2348     st.print("0x");





2349     for (int i = 0; i < length(); i++) {
2350       st.print("%x", value(i));


2351     }

2352     return st.as_string();
2353   }
2354 
2355   const char* as_basic_args_string() {
2356     stringStream st;
2357     bool long_prev = false;
2358     iterate_args([&] (int arg) {
2359       if (long_prev) {
2360         long_prev = false;
2361         if (arg == T_VOID) {
2362           st.print("J");
2363         } else {
2364           st.print("L");
2365         }
2366       }
2367       switch (arg) {
2368         case T_INT:    st.print("I");    break;
2369         case T_LONG:   long_prev = true; break;
2370         case T_FLOAT:  st.print("F");    break;
2371         case T_DOUBLE: st.print("D");    break;
2372         case T_VOID:   break;
2373         default: ShouldNotReachHere();
2374       }
2375     });
2376     if (long_prev) {
2377       st.print("L");
2378     }
2379     return st.as_string();
2380   }
2381 
2382   BasicType* as_basic_type(int& nargs) {
2383     nargs = 0;
2384     GrowableArray<BasicType> btarray;
2385     bool long_prev = false;
2386 
2387     iterate_args([&] (int arg) {
2388       if (long_prev) {
2389         long_prev = false;
2390         if (arg == T_VOID) {
2391           btarray.append(T_LONG);
2392         } else {
2393           btarray.append(T_OBJECT); // it could be T_ARRAY; it shouldn't matter
2394         }
2395       }
2396       switch (arg) {
2397         case T_INT: // fallthrough
2398         case T_FLOAT: // fallthrough
2399         case T_DOUBLE:
2400         case T_VOID:
2401           btarray.append((BasicType)arg);
2402           break;
2403         case T_LONG:
2404           long_prev = true;
2405           break;
2406         default: ShouldNotReachHere();
2407       }
2408     });
2409 
2410     if (long_prev) {
2411       btarray.append(T_OBJECT);
2412     }
2413 
2414     nargs = btarray.length();
2415     BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, nargs);
2416     int index = 0;
2417     GrowableArrayIterator<BasicType> iter = btarray.begin();
2418     while (iter != btarray.end()) {
2419       sig_bt[index++] = *iter;
2420       ++iter;
2421     }
2422     assert(index == btarray.length(), "sanity check");
2423 #ifdef ASSERT
2424     {
2425       AdapterFingerPrint* compare_fp = AdapterFingerPrint::allocate(nargs, sig_bt);
2426       assert(this->equals(compare_fp), "sanity check");
2427       AdapterFingerPrint::deallocate(compare_fp);
2428     }
2429 #endif
2430     return sig_bt;
2431   }
2432 
2433   bool equals(AdapterFingerPrint* other) {
2434     if (other->_length != _length) {


2435       return false;
2436     } else {
2437       for (int i = 0; i < _length; i++) {
2438         if (value(i) != other->value(i)) {
2439           return false;
2440         }
2441       }
2442     }
2443     return true;
2444   }
2445 
2446   // methods required by virtue of being a MetaspaceObj
2447   void metaspace_pointers_do(MetaspaceClosure* it) { return; /* nothing to do here */ }
2448   int size() const { return compute_size_in_words(_length); }
2449   MetaspaceObj::Type type() const { return AdapterFingerPrintType; }
2450 
2451   static bool equals(AdapterFingerPrint* const& fp1, AdapterFingerPrint* const& fp2) {
2452     NOT_PRODUCT(_equals++);
2453     return fp1->equals(fp2);
2454   }
2455 
2456   static unsigned int compute_hash(AdapterFingerPrint* const& fp) {
2457     return fp->compute_hash();
2458   }

2461 #if INCLUDE_CDS
2462 static inline bool adapter_fp_equals_compact_hashtable_entry(AdapterHandlerEntry* entry, AdapterFingerPrint* fp, int len_unused) {
2463   return AdapterFingerPrint::equals(entry->fingerprint(), fp);
2464 }
2465 
2466 class ArchivedAdapterTable : public OffsetCompactHashtable<
2467   AdapterFingerPrint*,
2468   AdapterHandlerEntry*,
2469   adapter_fp_equals_compact_hashtable_entry> {};
2470 #endif // INCLUDE_CDS
2471 
2472 // A hashtable mapping from AdapterFingerPrints to AdapterHandlerEntries
2473 using AdapterHandlerTable = HashTable<AdapterFingerPrint*, AdapterHandlerEntry*, 293,
2474                   AnyObj::C_HEAP, mtCode,
2475                   AdapterFingerPrint::compute_hash,
2476                   AdapterFingerPrint::equals>;
2477 static AdapterHandlerTable* _adapter_handler_table;
2478 static GrowableArray<AdapterHandlerEntry*>* _adapter_handler_list = nullptr;
2479 
2480 // Find a entry with the same fingerprint if it exists
2481 AdapterHandlerEntry* AdapterHandlerLibrary::lookup(int total_args_passed, BasicType* sig_bt) {
2482   NOT_PRODUCT(_lookups++);
2483   assert_lock_strong(AdapterHandlerLibrary_lock);
2484   AdapterFingerPrint* fp = AdapterFingerPrint::allocate(total_args_passed, sig_bt);
2485   AdapterHandlerEntry* entry = nullptr;
2486 #if INCLUDE_CDS
2487   // if we are building the archive then the archived adapter table is
2488   // not valid and we need to use the ones added to the runtime table
2489   if (AOTCodeCache::is_using_adapter()) {
2490     // Search archived table first. It is read-only table so can be searched without lock
2491     entry = _aot_adapter_handler_table.lookup(fp, fp->compute_hash(), 0 /* unused */);
2492 #ifndef PRODUCT
2493     if (entry != nullptr) {
2494       _archived_hits++;
2495     }
2496 #endif
2497   }
2498 #endif // INCLUDE_CDS
2499   if (entry == nullptr) {
2500     assert_lock_strong(AdapterHandlerLibrary_lock);
2501     AdapterHandlerEntry** entry_p = _adapter_handler_table->get(fp);
2502     if (entry_p != nullptr) {
2503       entry = *entry_p;
2504       assert(entry->fingerprint()->equals(fp), "fingerprint mismatch key fp %s %s (hash=%d) != found fp %s %s (hash=%d)",

2521   TableStatistics ts = _adapter_handler_table->statistics_calculate(size);
2522   ts.print(tty, "AdapterHandlerTable");
2523   tty->print_cr("AdapterHandlerTable (table_size=%d, entries=%d)",
2524                 _adapter_handler_table->table_size(), _adapter_handler_table->number_of_entries());
2525   int total_hits = _archived_hits + _runtime_hits;
2526   tty->print_cr("AdapterHandlerTable: lookups %d equals %d hits %d (archived=%d+runtime=%d)",
2527                 _lookups, _equals, total_hits, _archived_hits, _runtime_hits);
2528 }
2529 #endif
2530 
2531 // ---------------------------------------------------------------------------
2532 // Implementation of AdapterHandlerLibrary
2533 AdapterHandlerEntry* AdapterHandlerLibrary::_no_arg_handler = nullptr;
2534 AdapterHandlerEntry* AdapterHandlerLibrary::_int_arg_handler = nullptr;
2535 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_arg_handler = nullptr;
2536 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_int_arg_handler = nullptr;
2537 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_obj_arg_handler = nullptr;
2538 #if INCLUDE_CDS
2539 ArchivedAdapterTable AdapterHandlerLibrary::_aot_adapter_handler_table;
2540 #endif // INCLUDE_CDS
2541 static const int AdapterHandlerLibrary_size = 16*K;
2542 BufferBlob* AdapterHandlerLibrary::_buffer = nullptr;
2543 volatile uint AdapterHandlerLibrary::_id_counter = 0;
2544 
2545 BufferBlob* AdapterHandlerLibrary::buffer_blob() {
2546   assert(_buffer != nullptr, "should be initialized");
2547   return _buffer;
2548 }
2549 
2550 static void post_adapter_creation(const AdapterHandlerEntry* entry) {
2551   if (Forte::is_enabled() || JvmtiExport::should_post_dynamic_code_generated()) {
2552     AdapterBlob* adapter_blob = entry->adapter_blob();
2553     char blob_id[256];
2554     jio_snprintf(blob_id,
2555                  sizeof(blob_id),
2556                  "%s(%s)",
2557                  adapter_blob->name(),
2558                  entry->fingerprint()->as_string());
2559     if (Forte::is_enabled()) {
2560       Forte::register_stub(blob_id, adapter_blob->content_begin(), adapter_blob->content_end());
2561     }

2569 void AdapterHandlerLibrary::initialize() {
2570   {
2571     ResourceMark rm;
2572     _adapter_handler_table = new (mtCode) AdapterHandlerTable();
2573     _buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size);
2574   }
2575 
2576 #if INCLUDE_CDS
2577   // Link adapters in AOT Cache to their code in AOT Code Cache
2578   if (AOTCodeCache::is_using_adapter() && !_aot_adapter_handler_table.empty()) {
2579     link_aot_adapters();
2580     lookup_simple_adapters();
2581     return;
2582   }
2583 #endif // INCLUDE_CDS
2584 
2585   ResourceMark rm;
2586   {
2587     MutexLocker mu(AdapterHandlerLibrary_lock);
2588 
2589     _no_arg_handler = create_adapter(0, nullptr);


2590 
2591     BasicType obj_args[] = { T_OBJECT };
2592     _obj_arg_handler = create_adapter(1, obj_args);


2593 
2594     BasicType int_args[] = { T_INT };
2595     _int_arg_handler = create_adapter(1, int_args);


2596 
2597     BasicType obj_int_args[] = { T_OBJECT, T_INT };
2598     _obj_int_arg_handler = create_adapter(2, obj_int_args);



2599 
2600     BasicType obj_obj_args[] = { T_OBJECT, T_OBJECT };
2601     _obj_obj_arg_handler = create_adapter(2, obj_obj_args);



2602 
2603     // we should always get an entry back but we don't have any
2604     // associated blob on Zero
2605     assert(_no_arg_handler != nullptr &&
2606            _obj_arg_handler != nullptr &&
2607            _int_arg_handler != nullptr &&
2608            _obj_int_arg_handler != nullptr &&
2609            _obj_obj_arg_handler != nullptr, "Initial adapter handlers must be properly created");
2610   }
2611 
2612   // Outside of the lock
2613 #ifndef ZERO
2614   // no blobs to register when we are on Zero
2615   post_adapter_creation(_no_arg_handler);
2616   post_adapter_creation(_obj_arg_handler);
2617   post_adapter_creation(_int_arg_handler);
2618   post_adapter_creation(_obj_int_arg_handler);
2619   post_adapter_creation(_obj_obj_arg_handler);
2620 #endif // ZERO
2621 }
2622 
2623 AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint) {
2624   uint id = (uint)AtomicAccess::add((int*)&_id_counter, 1);
2625   assert(id > 0, "we can never overflow because AOT cache cannot contain more than 2^32 methods");
2626   return AdapterHandlerEntry::allocate(id, fingerprint);
2627 }
2628 
2629 AdapterHandlerEntry* AdapterHandlerLibrary::get_simple_adapter(const methodHandle& method) {
2630   int total_args_passed = method->size_of_parameters(); // All args on stack
2631   if (total_args_passed == 0) {
2632     return _no_arg_handler;
2633   } else if (total_args_passed == 1) {
2634     if (!method->is_static()) {



2635       return _obj_arg_handler;
2636     }
2637     switch (method->signature()->char_at(1)) {
2638       case JVM_SIGNATURE_CLASS:









2639       case JVM_SIGNATURE_ARRAY:
2640         return _obj_arg_handler;
2641       case JVM_SIGNATURE_INT:
2642       case JVM_SIGNATURE_BOOLEAN:
2643       case JVM_SIGNATURE_CHAR:
2644       case JVM_SIGNATURE_BYTE:
2645       case JVM_SIGNATURE_SHORT:
2646         return _int_arg_handler;
2647     }
2648   } else if (total_args_passed == 2 &&
2649              !method->is_static()) {
2650     switch (method->signature()->char_at(1)) {
2651       case JVM_SIGNATURE_CLASS:









2652       case JVM_SIGNATURE_ARRAY:
2653         return _obj_obj_arg_handler;
2654       case JVM_SIGNATURE_INT:
2655       case JVM_SIGNATURE_BOOLEAN:
2656       case JVM_SIGNATURE_CHAR:
2657       case JVM_SIGNATURE_BYTE:
2658       case JVM_SIGNATURE_SHORT:
2659         return _obj_int_arg_handler;
2660     }
2661   }
2662   return nullptr;
2663 }
2664 
2665 class AdapterSignatureIterator : public SignatureIterator {
2666  private:
2667   BasicType stack_sig_bt[16];
2668   BasicType* sig_bt;
2669   int index;




2670 
2671  public:
2672   AdapterSignatureIterator(Symbol* signature,
2673                            fingerprint_t fingerprint,
2674                            bool is_static,
2675                            int total_args_passed) :
2676     SignatureIterator(signature, fingerprint),
2677     index(0)
2678   {
2679     sig_bt = (total_args_passed <= 16) ? stack_sig_bt : NEW_RESOURCE_ARRAY(BasicType, total_args_passed);
2680     if (!is_static) { // Pass in receiver first
2681       sig_bt[index++] = T_OBJECT;













2682     }
2683     do_parameters_on(this);
2684   }
2685 
2686   BasicType* basic_types() {
2687     return sig_bt;







2688   }

2689 
2690 #ifdef ASSERT
2691   int slots() {
2692     return index;




































2693   }


















































2694 #endif




















































2695 
2696  private:










2697 
2698   friend class SignatureIterator;  // so do_parameters_on can call do_type
2699   void do_type(BasicType type) {
2700     sig_bt[index++] = type;
2701     if (type == T_LONG || type == T_DOUBLE) {
2702       sig_bt[index++] = T_VOID; // Longs & doubles take 2 Java slots



2703     }
2704   }
2705 };
2706 


































































































































2707 
2708 const char* AdapterHandlerEntry::_entry_names[] = {
2709   "i2c", "c2i", "c2i_unverified", "c2i_no_clinit_check"
2710 };
2711 
2712 #ifdef ASSERT
2713 void AdapterHandlerLibrary::verify_adapter_sharing(int total_args_passed, BasicType* sig_bt, AdapterHandlerEntry* cached_entry) {
2714   // we can only check for the same code if there is any
2715 #ifndef ZERO
2716   AdapterHandlerEntry* comparison_entry = create_adapter(total_args_passed, sig_bt, true);
2717   assert(comparison_entry->adapter_blob() == nullptr, "no blob should be created when creating an adapter for comparison");
2718   assert(comparison_entry->compare_code(cached_entry), "code must match");
2719   // Release the one just created
2720   AdapterHandlerEntry::deallocate(comparison_entry);
2721 # endif // ZERO
2722 }
2723 #endif /* ASSERT*/
2724 
2725 AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(const methodHandle& method) {
2726   assert(!method->is_abstract(), "abstract methods do not have adapters");
2727   // Use customized signature handler.  Need to lock around updates to
2728   // the _adapter_handler_table (it is not safe for concurrent readers
2729   // and a single writer: this could be fixed if it becomes a
2730   // problem).
2731 
2732   // Fast-path for trivial adapters
2733   AdapterHandlerEntry* entry = get_simple_adapter(method);
2734   if (entry != nullptr) {
2735     return entry;
2736   }
2737 
2738   ResourceMark rm;
2739   bool new_entry = false;
2740 
2741   // Fill in the signature array, for the calling-convention call.
2742   int total_args_passed = method->size_of_parameters(); // All args on stack











2743 
2744   AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(),
2745                               method->is_static(), total_args_passed);
2746   assert(si.slots() == total_args_passed, "");
2747   BasicType* sig_bt = si.basic_types();
2748   {
2749     MutexLocker mu(AdapterHandlerLibrary_lock);
2750 
2751     // Lookup method signature's fingerprint
2752     entry = lookup(total_args_passed, sig_bt);
2753 
2754     if (entry != nullptr) {
2755 #ifndef ZERO
2756       assert(entry->is_linked(), "AdapterHandlerEntry must have been linked");
2757 #endif
2758 #ifdef ASSERT
2759       if (!entry->in_aot_cache() && VerifyAdapterSharing) {
2760         verify_adapter_sharing(total_args_passed, sig_bt, entry);
2761       }
2762 #endif
2763     } else {
2764       entry = create_adapter(total_args_passed, sig_bt);
2765       if (entry != nullptr) {
2766         new_entry = true;
2767       }
2768     }
2769   }
2770 
2771   // Outside of the lock
2772   if (new_entry) {
2773     post_adapter_creation(entry);
2774   }
2775   return entry;
2776 }
2777 
2778 void AdapterHandlerLibrary::lookup_aot_cache(AdapterHandlerEntry* handler) {
2779   ResourceMark rm;
2780   const char* name = AdapterHandlerLibrary::name(handler);
2781   const uint32_t id = AdapterHandlerLibrary::id(handler);
2782 
2783   CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::Adapter, id, name);
2784   if (blob != nullptr) {

2799   }
2800   insts_size = adapter_blob->code_size();
2801   st->print_cr("i2c argument handler for: %s %s (%d bytes generated)",
2802                 handler->fingerprint()->as_basic_args_string(),
2803                 handler->fingerprint()->as_string(), insts_size);
2804   st->print_cr("c2i argument handler starts at " INTPTR_FORMAT, p2i(handler->get_c2i_entry()));
2805   if (Verbose || PrintStubCode) {
2806     address first_pc = adapter_blob->content_begin();
2807     if (first_pc != nullptr) {
2808       Disassembler::decode(first_pc, first_pc + insts_size, st, &adapter_blob->asm_remarks());
2809       st->cr();
2810     }
2811   }
2812 }
2813 #endif // PRODUCT
2814 
2815 void AdapterHandlerLibrary::address_to_offset(address entry_address[AdapterBlob::ENTRY_COUNT],
2816                                               int entry_offset[AdapterBlob::ENTRY_COUNT]) {
2817   entry_offset[AdapterBlob::I2C] = 0;
2818   entry_offset[AdapterBlob::C2I] = entry_address[AdapterBlob::C2I] - entry_address[AdapterBlob::I2C];


2819   entry_offset[AdapterBlob::C2I_Unverified] = entry_address[AdapterBlob::C2I_Unverified] - entry_address[AdapterBlob::I2C];

2820   if (entry_address[AdapterBlob::C2I_No_Clinit_Check] == nullptr) {
2821     entry_offset[AdapterBlob::C2I_No_Clinit_Check] = -1;
2822   } else {
2823     entry_offset[AdapterBlob::C2I_No_Clinit_Check] = entry_address[AdapterBlob::C2I_No_Clinit_Check] - entry_address[AdapterBlob::I2C];
2824   }
2825 }
2826 
2827 bool AdapterHandlerLibrary::generate_adapter_code(AdapterHandlerEntry* handler,
2828                                                   int total_args_passed,
2829                                                   BasicType* sig_bt,
2830                                                   bool is_transient) {
2831   if (log_is_enabled(Info, perf, class, link)) {
2832     ClassLoader::perf_method_adapters_count()->inc();
2833   }
2834 
2835 #ifndef ZERO

2836   BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
2837   CodeBuffer buffer(buf);
2838   short buffer_locs[20];
2839   buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs,
2840                                          sizeof(buffer_locs)/sizeof(relocInfo));
2841   MacroAssembler masm(&buffer);
2842   VMRegPair stack_regs[16];
2843   VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
2844 
2845   // Get a description of the compiled java calling convention and the largest used (VMReg) stack slot usage
2846   int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
2847   address entry_address[AdapterBlob::ENTRY_COUNT];
2848   SharedRuntime::generate_i2c2i_adapters(&masm,
2849                                          total_args_passed,
2850                                          comp_args_on_stack,
2851                                          sig_bt,
2852                                          regs,
2853                                          entry_address);












2854   // On zero there is no code to save and no need to create a blob and
2855   // or relocate the handler.
2856   int entry_offset[AdapterBlob::ENTRY_COUNT];
2857   address_to_offset(entry_address, entry_offset);
2858 #ifdef ASSERT
2859   if (VerifyAdapterSharing) {
2860     handler->save_code(buf->code_begin(), buffer.insts_size());
2861     if (is_transient) {
2862       return true;
2863     }
2864   }
2865 #endif
2866   AdapterBlob* adapter_blob = AdapterBlob::create(&buffer, entry_offset);
2867   if (adapter_blob == nullptr) {
2868     // CodeCache is full, disable compilation
2869     // Ought to log this but compile log is only per compile thread
2870     // and we're some non descript Java thread.
2871     return false;
2872   }
2873   handler->set_adapter_blob(adapter_blob);
2874   if (!is_transient && AOTCodeCache::is_dumping_adapter()) {
2875     // try to save generated code
2876     const char* name = AdapterHandlerLibrary::name(handler);
2877     const uint32_t id = AdapterHandlerLibrary::id(handler);
2878     bool success = AOTCodeCache::store_code_blob(*adapter_blob, AOTCodeEntry::Adapter, id, name);
2879     assert(success || !AOTCodeCache::is_dumping_adapter(), "caching of adapter must be disabled");
2880   }
2881 #endif // ZERO
2882 
2883 #ifndef PRODUCT
2884   // debugging support
2885   if (PrintAdapterHandlers || PrintStubCode) {
2886     print_adapter_handler_info(tty, handler);
2887   }
2888 #endif
2889 
2890   return true;
2891 }
2892 
2893 AdapterHandlerEntry* AdapterHandlerLibrary::create_adapter(int total_args_passed,
2894                                                            BasicType* sig_bt,
2895                                                            bool is_transient) {
2896   AdapterFingerPrint* fp = AdapterFingerPrint::allocate(total_args_passed, sig_bt);





2897   AdapterHandlerEntry* handler = AdapterHandlerLibrary::new_entry(fp);
2898   if (!generate_adapter_code(handler, total_args_passed, sig_bt, is_transient)) {
2899     AdapterHandlerEntry::deallocate(handler);
2900     return nullptr;
2901   }
2902   if (!is_transient) {
2903     assert_lock_strong(AdapterHandlerLibrary_lock);
2904     _adapter_handler_table->put(fp, handler);
2905   }
2906   return handler;
2907 }
2908 
2909 #if INCLUDE_CDS
2910 void AdapterHandlerEntry::remove_unshareable_info() {
2911 #ifdef ASSERT
2912    _saved_code = nullptr;
2913    _saved_code_length = 0;
2914 #endif // ASSERT
2915    _adapter_blob = nullptr;
2916    _linked = false;

2917 }
2918 
2919 class CopyAdapterTableToArchive : StackObj {
2920 private:
2921   CompactHashtableWriter* _writer;
2922   ArchiveBuilder* _builder;
2923 public:
2924   CopyAdapterTableToArchive(CompactHashtableWriter* writer) : _writer(writer),
2925                                                              _builder(ArchiveBuilder::current())
2926   {}
2927 
2928   bool do_entry(AdapterFingerPrint* fp, AdapterHandlerEntry* entry) {
2929     LogStreamHandle(Trace, aot) lsh;
2930     if (ArchiveBuilder::current()->has_been_archived((address)entry)) {
2931       assert(ArchiveBuilder::current()->has_been_archived((address)fp), "must be");
2932       AdapterFingerPrint* buffered_fp = ArchiveBuilder::current()->get_buffered_addr(fp);
2933       assert(buffered_fp != nullptr,"sanity check");
2934       AdapterHandlerEntry* buffered_entry = ArchiveBuilder::current()->get_buffered_addr(entry);
2935       assert(buffered_entry != nullptr,"sanity check");
2936 

2976   }
2977 #endif
2978 }
2979 
2980 // This method is used during production run to link archived adapters (stored in AOT Cache)
2981 // to their code in AOT Code Cache
2982 void AdapterHandlerEntry::link() {
2983   ResourceMark rm;
2984   assert(_fingerprint != nullptr, "_fingerprint must not be null");
2985   bool generate_code = false;
2986   // Generate code only if AOTCodeCache is not available, or
2987   // caching adapters is disabled, or we fail to link
2988   // the AdapterHandlerEntry to its code in the AOTCodeCache
2989   if (AOTCodeCache::is_using_adapter()) {
2990     AdapterHandlerLibrary::link_aot_adapter_handler(this);
2991     // If link_aot_adapter_handler() succeeds, _adapter_blob will be non-null
2992     if (_adapter_blob == nullptr) {
2993       log_warning(aot)("Failed to link AdapterHandlerEntry (fp=%s) to its code in the AOT code cache", _fingerprint->as_basic_args_string());
2994       generate_code = true;
2995     }














2996   } else {
2997     generate_code = true;
2998   }

2999   if (generate_code) {
3000     int nargs;
3001     BasicType* bt = _fingerprint->as_basic_type(nargs);
3002     if (!AdapterHandlerLibrary::generate_adapter_code(this, nargs, bt, /* is_transient */ false)) {
3003       // Don't throw exceptions during VM initialization because java.lang.* classes
3004       // might not have been initialized, causing problems when constructing the
3005       // Java exception object.
3006       vm_exit_during_initialization("Out of space in CodeCache for adapters");
3007     }
3008   }
3009   if (_adapter_blob != nullptr) {
3010     post_adapter_creation(this);
3011   }
3012   assert(_linked, "AdapterHandlerEntry must now be linked");
3013 }
3014 
3015 void AdapterHandlerLibrary::link_aot_adapters() {
3016   uint max_id = 0;
3017   assert(AOTCodeCache::is_using_adapter(), "AOT adapters code should be available");
3018   /* It is possible that some adapters generated in assembly phase are not stored in the cache.
3019    * That implies adapter ids of the adapters in the cache may not be contiguous.
3020    * If the size of the _aot_adapter_handler_table is used to initialize _id_counter, then it may
3021    * result in collision of adapter ids between AOT stored handlers and runtime generated handlers.
3022    * To avoid such situation, initialize the _id_counter with the largest adapter id among the AOT stored handlers.
3023    */
3024   _aot_adapter_handler_table.iterate_all([&](AdapterHandlerEntry* entry) {
3025     assert(!entry->is_linked(), "AdapterHandlerEntry is already linked!");
3026     entry->link();
3027     max_id = MAX2(max_id, entry->id());
3028   });
3029   // Set adapter id to the maximum id found in the AOTCache
3030   assert(_id_counter == 0, "Did not expect new AdapterHandlerEntry to be created at this stage");
3031   _id_counter = max_id;
3032 }
3033 
3034 // This method is called during production run to lookup simple adapters
3035 // in the archived adapter handler table
3036 void AdapterHandlerLibrary::lookup_simple_adapters() {
3037   assert(!_aot_adapter_handler_table.empty(), "archived adapter handler table is empty");
3038 
3039   MutexLocker mu(AdapterHandlerLibrary_lock);
3040   _no_arg_handler = lookup(0, nullptr);
3041 
3042   BasicType obj_args[] = { T_OBJECT };
3043   _obj_arg_handler = lookup(1, obj_args);
3044 
3045   BasicType int_args[] = { T_INT };
3046   _int_arg_handler = lookup(1, int_args);
3047 
3048   BasicType obj_int_args[] = { T_OBJECT, T_INT };
3049   _obj_int_arg_handler = lookup(2, obj_int_args);
3050 
3051   BasicType obj_obj_args[] = { T_OBJECT, T_OBJECT };
3052   _obj_obj_arg_handler = lookup(2, obj_obj_args);













3053 
3054   assert(_no_arg_handler != nullptr &&
3055          _obj_arg_handler != nullptr &&
3056          _int_arg_handler != nullptr &&
3057          _obj_int_arg_handler != nullptr &&
3058          _obj_obj_arg_handler != nullptr, "Initial adapters not found in archived adapter handler table");
3059   assert(_no_arg_handler->is_linked() &&
3060          _obj_arg_handler->is_linked() &&
3061          _int_arg_handler->is_linked() &&
3062          _obj_int_arg_handler->is_linked() &&
3063          _obj_obj_arg_handler->is_linked(), "Initial adapters not in linked state");
3064 }
3065 #endif // INCLUDE_CDS
3066 
3067 void AdapterHandlerEntry::metaspace_pointers_do(MetaspaceClosure* it) {
3068   LogStreamHandle(Trace, aot) lsh;
3069   if (lsh.is_enabled()) {
3070     lsh.print("Iter(AdapterHandlerEntry): %p(%s)", this, _fingerprint->as_basic_args_string());
3071     lsh.cr();
3072   }
3073   it->push(&_fingerprint);
3074 }
3075 
3076 AdapterHandlerEntry::~AdapterHandlerEntry() {
3077   if (_fingerprint != nullptr) {
3078     AdapterFingerPrint::deallocate(_fingerprint);
3079     _fingerprint = nullptr;
3080   }



3081 #ifdef ASSERT
3082   FREE_C_HEAP_ARRAY(unsigned char, _saved_code);
3083 #endif
3084   FreeHeap(this);
3085 }
3086 
3087 
3088 #ifdef ASSERT
3089 // Capture the code before relocation so that it can be compared
3090 // against other versions.  If the code is captured after relocation
3091 // then relative instructions won't be equivalent.
3092 void AdapterHandlerEntry::save_code(unsigned char* buffer, int length) {
3093   _saved_code = NEW_C_HEAP_ARRAY(unsigned char, length, mtCode);
3094   _saved_code_length = length;
3095   memcpy(_saved_code, buffer, length);
3096 }
3097 
3098 
3099 bool AdapterHandlerEntry::compare_code(AdapterHandlerEntry* other) {
3100   assert(_saved_code != nullptr && other->_saved_code != nullptr, "code not saved");

3148 
3149       struct { double data[20]; } locs_buf;
3150       struct { double data[20]; } stubs_locs_buf;
3151       buffer.insts()->initialize_shared_locs((relocInfo*)&locs_buf, sizeof(locs_buf) / sizeof(relocInfo));
3152 #if defined(AARCH64) || defined(PPC64)
3153       // On AArch64 with ZGC and nmethod entry barriers, we need all oops to be
3154       // in the constant pool to ensure ordering between the barrier and oops
3155       // accesses. For native_wrappers we need a constant.
3156       // On PPC64 the continuation enter intrinsic needs the constant pool for the compiled
3157       // static java call that is resolved in the runtime.
3158       if (PPC64_ONLY(method->is_continuation_enter_intrinsic() &&) true) {
3159         buffer.initialize_consts_size(8 PPC64_ONLY(+ 24));
3160       }
3161 #endif
3162       buffer.stubs()->initialize_shared_locs((relocInfo*)&stubs_locs_buf, sizeof(stubs_locs_buf) / sizeof(relocInfo));
3163       MacroAssembler _masm(&buffer);
3164 
3165       // Fill in the signature array, for the calling-convention call.
3166       const int total_args_passed = method->size_of_parameters();
3167 

3168       VMRegPair stack_regs[16];

3169       VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
3170 
3171       AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(),
3172                               method->is_static(), total_args_passed);
3173       BasicType* sig_bt = si.basic_types();
3174       assert(si.slots() == total_args_passed, "");
3175       BasicType ret_type = si.return_type();








3176 
3177       // Now get the compiled-Java arguments layout.
3178       SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
3179 
3180       // Generate the compiled-to-native wrapper code
3181       nm = SharedRuntime::generate_native_wrapper(&_masm, method, compile_id, sig_bt, regs, ret_type);
3182 
3183       if (nm != nullptr) {
3184         {
3185           MutexLocker pl(NMethodState_lock, Mutex::_no_safepoint_check_flag);
3186           if (nm->make_in_use()) {
3187             method->set_code(method, nm);
3188           }
3189         }
3190 
3191         DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, CompileBroker::compiler(CompLevel_simple));
3192         if (directive->PrintAssemblyOption) {
3193           nm->print_code();
3194         }
3195         DirectivesStack::release(directive);

3403       if (b == handler->adapter_blob()) {
3404         found = true;
3405         st->print("Adapter for signature: ");
3406         handler->print_adapter_on(st);
3407         return false; // abort iteration
3408       } else {
3409         return true; // keep looking
3410       }
3411     };
3412     assert_locked_or_safepoint(AdapterHandlerLibrary_lock);
3413     _adapter_handler_table->iterate(findblob_runtime_table);
3414   }
3415   assert(found, "Should have found handler");
3416 }
3417 
3418 void AdapterHandlerEntry::print_adapter_on(outputStream* st) const {
3419   st->print("AHE@" INTPTR_FORMAT ": %s", p2i(this), fingerprint()->as_string());
3420   if (adapter_blob() != nullptr) {
3421     st->print(" i2c: " INTPTR_FORMAT, p2i(get_i2c_entry()));
3422     st->print(" c2i: " INTPTR_FORMAT, p2i(get_c2i_entry()));
3423     st->print(" c2iUV: " INTPTR_FORMAT, p2i(get_c2i_unverified_entry()));



3424     if (get_c2i_no_clinit_check_entry() != nullptr) {
3425       st->print(" c2iNCI: " INTPTR_FORMAT, p2i(get_c2i_no_clinit_check_entry()));
3426     }
3427   }
3428   st->cr();
3429 }
3430 
3431 #ifndef PRODUCT
3432 
3433 void AdapterHandlerLibrary::print_statistics() {
3434   print_table_statistics();
3435 }
3436 
3437 #endif /* PRODUCT */
3438 
3439 JRT_LEAF(void, SharedRuntime::enable_stack_reserved_zone(JavaThread* current))
3440   assert(current == JavaThread::current(), "pre-condition");
3441   StackOverflow* overflow_state = current->stack_overflow_state();
3442   overflow_state->enable_stack_reserved_zone(/*check_if_disabled*/true);
3443   overflow_state->set_reserved_stack_activation(current->stack_base());

3490         event.set_method(method);
3491         event.commit();
3492       }
3493     }
3494   }
3495   return activation;
3496 }
3497 
3498 void SharedRuntime::on_slowpath_allocation_exit(JavaThread* current) {
3499   // After any safepoint, just before going back to compiled code,
3500   // we inform the GC that we will be doing initializing writes to
3501   // this object in the future without emitting card-marks, so
3502   // GC may take any compensating steps.
3503 
3504   oop new_obj = current->vm_result_oop();
3505   if (new_obj == nullptr) return;
3506 
3507   BarrierSet *bs = BarrierSet::barrier_set();
3508   bs->on_slowpath_allocation_exit(current, new_obj);
3509 }





































































































































































































  30 #include "classfile/javaClasses.inline.hpp"
  31 #include "classfile/stringTable.hpp"
  32 #include "classfile/vmClasses.hpp"
  33 #include "classfile/vmSymbols.hpp"
  34 #include "code/aotCodeCache.hpp"
  35 #include "code/codeCache.hpp"
  36 #include "code/compiledIC.hpp"
  37 #include "code/nmethod.inline.hpp"
  38 #include "code/scopeDesc.hpp"
  39 #include "code/vtableStubs.hpp"
  40 #include "compiler/abstractCompiler.hpp"
  41 #include "compiler/compileBroker.hpp"
  42 #include "compiler/disassembler.hpp"
  43 #include "gc/shared/barrierSet.hpp"
  44 #include "gc/shared/collectedHeap.hpp"
  45 #include "interpreter/interpreter.hpp"
  46 #include "interpreter/interpreterRuntime.hpp"
  47 #include "jfr/jfrEvents.hpp"
  48 #include "jvm.h"
  49 #include "logging/log.hpp"
  50 #include "memory/oopFactory.hpp"
  51 #include "memory/resourceArea.hpp"
  52 #include "memory/universe.hpp"
  53 #include "metaprogramming/primitiveConversions.hpp"
  54 #include "oops/access.hpp"
  55 #include "oops/fieldStreams.inline.hpp"
  56 #include "oops/inlineKlass.inline.hpp"
  57 #include "oops/klass.hpp"
  58 #include "oops/method.inline.hpp"
  59 #include "oops/objArrayKlass.hpp"
  60 #include "oops/objArrayOop.inline.hpp"
  61 #include "oops/oop.inline.hpp"
  62 #include "prims/forte.hpp"
  63 #include "prims/jvmtiExport.hpp"
  64 #include "prims/jvmtiThreadState.hpp"
  65 #include "prims/methodHandles.hpp"
  66 #include "prims/nativeLookup.hpp"
  67 #include "runtime/arguments.hpp"
  68 #include "runtime/atomicAccess.hpp"
  69 #include "runtime/basicLock.inline.hpp"
  70 #include "runtime/frame.inline.hpp"
  71 #include "runtime/handles.inline.hpp"
  72 #include "runtime/init.hpp"
  73 #include "runtime/interfaceSupport.inline.hpp"
  74 #include "runtime/java.hpp"
  75 #include "runtime/javaCalls.hpp"
  76 #include "runtime/jniHandles.inline.hpp"
  77 #include "runtime/osThread.hpp"
  78 #include "runtime/perfData.hpp"
  79 #include "runtime/sharedRuntime.hpp"
  80 #include "runtime/signature.hpp"
  81 #include "runtime/stackWatermarkSet.hpp"
  82 #include "runtime/stubRoutines.hpp"
  83 #include "runtime/synchronizer.hpp"
  84 #include "runtime/timerTrace.hpp"
  85 #include "runtime/vframe.inline.hpp"
  86 #include "runtime/vframeArray.hpp"
  87 #include "runtime/vm_version.hpp"
  88 #include "utilities/copy.hpp"
  89 #include "utilities/dtrace.hpp"
  90 #include "utilities/events.hpp"
  91 #include "utilities/globalDefinitions.hpp"
  92 #include "utilities/hashTable.hpp"
  93 #include "utilities/macros.hpp"
  94 #include "utilities/xmlstream.hpp"
  95 #ifdef COMPILER1
  96 #include "c1/c1_Runtime1.hpp"
  97 #endif
  98 #ifdef COMPILER2
  99 #include "opto/runtime.hpp"
 100 #endif

1218 // for a call current in progress, i.e., arguments has been pushed on stack
1219 // but callee has not been invoked yet.  Caller frame must be compiled.
1220 Handle SharedRuntime::find_callee_info_helper(vframeStream& vfst, Bytecodes::Code& bc,
1221                                               CallInfo& callinfo, TRAPS) {
1222   Handle receiver;
1223   Handle nullHandle;  // create a handy null handle for exception returns
1224   JavaThread* current = THREAD;
1225 
1226   assert(!vfst.at_end(), "Java frame must exist");
1227 
1228   // Find caller and bci from vframe
1229   methodHandle caller(current, vfst.method());
1230   int          bci   = vfst.bci();
1231 
1232   if (caller->is_continuation_enter_intrinsic()) {
1233     bc = Bytecodes::_invokestatic;
1234     LinkResolver::resolve_continuation_enter(callinfo, CHECK_NH);
1235     return receiver;
1236   }
1237 
1238   // Substitutability test implementation piggy backs on static call resolution
1239   Bytecodes::Code code = caller->java_code_at(bci);
1240   if (code == Bytecodes::_if_acmpeq || code == Bytecodes::_if_acmpne) {
1241     bc = Bytecodes::_invokestatic;
1242     methodHandle attached_method(THREAD, extract_attached_method(vfst));
1243     assert(attached_method.not_null(), "must have attached method");
1244     vmClasses::ValueObjectMethods_klass()->initialize(CHECK_NH);
1245     LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, false, CHECK_NH);
1246 #ifdef ASSERT
1247     Symbol* subst_method_name = vmSymbols::isSubstitutable_name();
1248     Method* is_subst = vmClasses::ValueObjectMethods_klass()->find_method(subst_method_name, vmSymbols::object_object_boolean_signature());
1249     assert(callinfo.selected_method() == is_subst, "must be isSubstitutable method");
1250 #endif
1251     return receiver;
1252   }
1253 
1254   Bytecode_invoke bytecode(caller, bci);
1255   int bytecode_index = bytecode.index();
1256   bc = bytecode.invoke_code();
1257 
1258   methodHandle attached_method(current, extract_attached_method(vfst));
1259   if (attached_method.not_null()) {
1260     Method* callee = bytecode.static_target(CHECK_NH);
1261     vmIntrinsics::ID id = callee->intrinsic_id();
1262     // When VM replaces MH.invokeBasic/linkTo* call with a direct/virtual call,
1263     // it attaches statically resolved method to the call site.
1264     if (MethodHandles::is_signature_polymorphic(id) &&
1265         MethodHandles::is_signature_polymorphic_intrinsic(id)) {
1266       bc = MethodHandles::signature_polymorphic_intrinsic_bytecode(id);
1267 
1268       // Adjust invocation mode according to the attached method.
1269       switch (bc) {
1270         case Bytecodes::_invokevirtual:
1271           if (attached_method->method_holder()->is_interface()) {
1272             bc = Bytecodes::_invokeinterface;
1273           }
1274           break;
1275         case Bytecodes::_invokeinterface:
1276           if (!attached_method->method_holder()->is_interface()) {
1277             bc = Bytecodes::_invokevirtual;
1278           }
1279           break;
1280         case Bytecodes::_invokehandle:
1281           if (!MethodHandles::is_signature_polymorphic_method(attached_method())) {
1282             bc = attached_method->is_static() ? Bytecodes::_invokestatic
1283                                               : Bytecodes::_invokevirtual;
1284           }
1285           break;
1286         default:
1287           break;
1288       }
1289     } else {
1290       assert(attached_method->has_scalarized_args(), "invalid use of attached method");
1291       if (!attached_method->method_holder()->is_inline_klass()) {
1292         // Ignore the attached method in this case to not confuse below code
1293         attached_method = methodHandle(current, nullptr);
1294       }
1295     }
1296   }
1297 
1298   assert(bc != Bytecodes::_illegal, "not initialized");
1299 
1300   bool has_receiver = bc != Bytecodes::_invokestatic &&
1301                       bc != Bytecodes::_invokedynamic &&
1302                       bc != Bytecodes::_invokehandle;
1303   bool check_null_and_abstract = true;
1304 
1305   // Find receiver for non-static call
1306   if (has_receiver) {
1307     // This register map must be update since we need to find the receiver for
1308     // compiled frames. The receiver might be in a register.
1309     RegisterMap reg_map2(current,
1310                          RegisterMap::UpdateMap::include,
1311                          RegisterMap::ProcessFrames::include,
1312                          RegisterMap::WalkContinuation::skip);
1313     frame stubFrame   = current->last_frame();
1314     // Caller-frame is a compiled frame
1315     frame callerFrame = stubFrame.sender(&reg_map2);
1316 
1317     Method* callee = attached_method();
1318     if (callee == nullptr) {
1319       callee = bytecode.static_target(CHECK_NH);
1320       if (callee == nullptr) {
1321         THROW_(vmSymbols::java_lang_NoSuchMethodException(), nullHandle);
1322       }
1323     }
1324     bool caller_is_c1 = callerFrame.is_compiled_frame() && callerFrame.cb()->as_nmethod()->is_compiled_by_c1();
1325     if (!caller_is_c1 && callee->is_scalarized_arg(0)) {
1326       // If the receiver is an inline type that is passed as fields, no oop is available
1327       // Resolve the call without receiver null checking.
1328       assert(!callee->mismatch(), "calls with inline type receivers should never mismatch");
1329       assert(attached_method.not_null() && !attached_method->is_abstract(), "must have non-abstract attached method");
1330       if (bc == Bytecodes::_invokeinterface) {
1331         bc = Bytecodes::_invokevirtual; // C2 optimistically replaces interface calls by virtual calls
1332       }
1333       check_null_and_abstract = false;
1334     } else {
1335       // Retrieve from a compiled argument list
1336       receiver = Handle(current, callerFrame.retrieve_receiver(&reg_map2));
1337       assert(oopDesc::is_oop_or_null(receiver()), "");
1338       if (receiver.is_null()) {
1339         THROW_(vmSymbols::java_lang_NullPointerException(), nullHandle);
1340       }
1341     }
1342   }
1343 
1344   // Resolve method
1345   if (attached_method.not_null()) {
1346     // Parameterized by attached method.
1347     LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, check_null_and_abstract, CHECK_NH);
1348   } else {
1349     // Parameterized by bytecode.
1350     constantPoolHandle constants(current, caller->constants());
1351     LinkResolver::resolve_invoke(callinfo, receiver, constants, bytecode_index, bc, CHECK_NH);
1352   }
1353 
1354 #ifdef ASSERT
1355   // Check that the receiver klass is of the right subtype and that it is initialized for virtual calls
1356   if (has_receiver && check_null_and_abstract) {
1357     assert(receiver.not_null(), "should have thrown exception");
1358     Klass* receiver_klass = receiver->klass();
1359     Klass* rk = nullptr;
1360     if (attached_method.not_null()) {
1361       // In case there's resolved method attached, use its holder during the check.
1362       rk = attached_method->method_holder();
1363     } else {
1364       // Klass is already loaded.
1365       constantPoolHandle constants(current, caller->constants());
1366       rk = constants->klass_ref_at(bytecode_index, bc, CHECK_NH);
1367     }
1368     Klass* static_receiver_klass = rk;
1369     assert(receiver_klass->is_subtype_of(static_receiver_klass),
1370            "actual receiver must be subclass of static receiver klass");
1371     if (receiver_klass->is_instance_klass()) {
1372       if (InstanceKlass::cast(receiver_klass)->is_not_initialized()) {
1373         tty->print_cr("ERROR: Klass not yet initialized!!");
1374         receiver_klass->print();
1375       }
1376       assert(!InstanceKlass::cast(receiver_klass)->is_not_initialized(), "receiver_klass must be initialized");
1377     }
1378   }
1379 #endif
1380 
1381   return receiver;
1382 }
1383 
1384 methodHandle SharedRuntime::find_callee_method(bool& caller_does_not_scalarize, TRAPS) {
1385   JavaThread* current = THREAD;
1386   ResourceMark rm(current);
1387   // We need first to check if any Java activations (compiled, interpreted)
1388   // exist on the stack since last JavaCall.  If not, we need
1389   // to get the target method from the JavaCall wrapper.
1390   vframeStream vfst(current, true);  // Do not skip any javaCalls
1391   methodHandle callee_method;
1392   if (vfst.at_end()) {
1393     // No Java frames were found on stack since we did the JavaCall.
1394     // Hence the stack can only contain an entry_frame.  We need to
1395     // find the target method from the stub frame.
1396     RegisterMap reg_map(current,
1397                         RegisterMap::UpdateMap::skip,
1398                         RegisterMap::ProcessFrames::include,
1399                         RegisterMap::WalkContinuation::skip);
1400     frame fr = current->last_frame();
1401     assert(fr.is_runtime_frame(), "must be a runtimeStub");
1402     fr = fr.sender(&reg_map);
1403     assert(fr.is_entry_frame(), "must be");
1404     // fr is now pointing to the entry frame.
1405     callee_method = methodHandle(current, fr.entry_frame_call_wrapper()->callee_method());
1406   } else {
1407     Bytecodes::Code bc;
1408     CallInfo callinfo;
1409     find_callee_info_helper(vfst, bc, callinfo, CHECK_(methodHandle()));
1410     // Calls via mismatching methods are always non-scalarized
1411     if (callinfo.resolved_method()->mismatch()) {
1412       caller_does_not_scalarize = true;
1413     }
1414     callee_method = methodHandle(current, callinfo.selected_method());
1415   }
1416   assert(callee_method()->is_method(), "must be");
1417   return callee_method;
1418 }
1419 
1420 // Resolves a call.
1421 methodHandle SharedRuntime::resolve_helper(bool is_virtual, bool is_optimized, bool& caller_does_not_scalarize, TRAPS) {
1422   JavaThread* current = THREAD;
1423   ResourceMark rm(current);
1424   RegisterMap cbl_map(current,
1425                       RegisterMap::UpdateMap::skip,
1426                       RegisterMap::ProcessFrames::include,
1427                       RegisterMap::WalkContinuation::skip);
1428   frame caller_frame = current->last_frame().sender(&cbl_map);
1429 
1430   CodeBlob* caller_cb = caller_frame.cb();
1431   guarantee(caller_cb != nullptr && caller_cb->is_nmethod(), "must be called from compiled method");
1432   nmethod* caller_nm = caller_cb->as_nmethod();
1433 
1434   // determine call info & receiver
1435   // note: a) receiver is null for static calls
1436   //       b) an exception is thrown if receiver is null for non-static calls
1437   CallInfo call_info;
1438   Bytecodes::Code invoke_code = Bytecodes::_illegal;
1439   Handle receiver = find_callee_info(invoke_code, call_info, CHECK_(methodHandle()));
1440 
1441   NoSafepointVerifier nsv;
1442 
1443   methodHandle callee_method(current, call_info.selected_method());
1444   // Calls via mismatching methods are always non-scalarized
1445   if (caller_nm->is_compiled_by_c1() || call_info.resolved_method()->mismatch()) {
1446     caller_does_not_scalarize = true;
1447   }
1448 
1449   assert((!is_virtual && invoke_code == Bytecodes::_invokestatic ) ||
1450          (!is_virtual && invoke_code == Bytecodes::_invokespecial) ||
1451          (!is_virtual && invoke_code == Bytecodes::_invokehandle ) ||
1452          (!is_virtual && invoke_code == Bytecodes::_invokedynamic) ||
1453          ( is_virtual && invoke_code != Bytecodes::_invokestatic ), "inconsistent bytecode");
1454 
1455   assert(!caller_nm->is_unloading(), "It should not be unloading");
1456 
1457 #ifndef PRODUCT
1458   // tracing/debugging/statistics
1459   uint *addr = (is_optimized) ? (&_resolve_opt_virtual_ctr) :
1460                  (is_virtual) ? (&_resolve_virtual_ctr) :
1461                                 (&_resolve_static_ctr);
1462   AtomicAccess::inc(addr);
1463 
1464   if (TraceCallFixup) {
1465     ResourceMark rm(current);
1466     tty->print("resolving %s%s (%s) %s call to",
1467                (is_optimized) ? "optimized " : "", (is_virtual) ? "virtual" : "static",
1468                Bytecodes::name(invoke_code), (caller_does_not_scalarize) ? "non-scalar" : "");
1469     callee_method->print_short_name(tty);
1470     tty->print_cr(" at pc: " INTPTR_FORMAT " to code: " INTPTR_FORMAT,
1471                   p2i(caller_frame.pc()), p2i(callee_method->code()));
1472   }
1473 #endif
1474 
1475   if (invoke_code == Bytecodes::_invokestatic) {
1476     assert(callee_method->method_holder()->is_initialized() ||
1477            callee_method->method_holder()->is_reentrant_initialization(current),
1478            "invalid class initialization state for invoke_static");
1479     if (!VM_Version::supports_fast_class_init_checks() && callee_method->needs_clinit_barrier()) {
1480       // In order to keep class initialization check, do not patch call
1481       // site for static call when the class is not fully initialized.
1482       // Proper check is enforced by call site re-resolution on every invocation.
1483       //
1484       // When fast class initialization checks are supported (VM_Version::supports_fast_class_init_checks() == true),
1485       // explicit class initialization check is put in nmethod entry (VEP).
1486       assert(callee_method->method_holder()->is_linked(), "must be");
1487       return callee_method;
1488     }
1489   }
1490 
1491 
1492   // JSR 292 key invariant:
1493   // If the resolved method is a MethodHandle invoke target, the call
1494   // site must be a MethodHandle call site, because the lambda form might tail-call
1495   // leaving the stack in a state unknown to either caller or callee
1496 
1497   // Compute entry points. The computation of the entry points is independent of
1498   // patching the call.
1499 
1500   // Make sure the callee nmethod does not get deoptimized and removed before
1501   // we are done patching the code.
1502 
1503 
1504   CompiledICLocker ml(caller_nm);
1505   if (is_virtual && !is_optimized) {
1506     CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1507     inline_cache->update(&call_info, receiver->klass(), caller_does_not_scalarize);
1508   } else {
1509     // Callsite is a direct call - set it to the destination method
1510     CompiledDirectCall* callsite = CompiledDirectCall::before(caller_frame.pc());
1511     callsite->set(callee_method, caller_does_not_scalarize);
1512   }
1513 
1514   return callee_method;
1515 }
1516 
1517 // Inline caches exist only in compiled code
1518 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_ic_miss(JavaThread* current))
1519 #ifdef ASSERT
1520   RegisterMap reg_map(current,
1521                       RegisterMap::UpdateMap::skip,
1522                       RegisterMap::ProcessFrames::include,
1523                       RegisterMap::WalkContinuation::skip);
1524   frame stub_frame = current->last_frame();
1525   assert(stub_frame.is_runtime_frame(), "sanity check");
1526   frame caller_frame = stub_frame.sender(&reg_map);
1527   assert(!caller_frame.is_interpreted_frame() && !caller_frame.is_entry_frame() && !caller_frame.is_upcall_stub_frame(), "unexpected frame");
1528 #endif /* ASSERT */
1529 
1530   methodHandle callee_method;
1531   bool caller_does_not_scalarize = false;
1532   JRT_BLOCK
1533     callee_method = SharedRuntime::handle_ic_miss_helper(caller_does_not_scalarize, CHECK_NULL);
1534     // Return Method* through TLS
1535     current->set_vm_result_metadata(callee_method());
1536   JRT_BLOCK_END
1537   // return compiled code entry point after potential safepoints
1538   return get_resolved_entry(current, callee_method, false, false, caller_does_not_scalarize);
1539 JRT_END
1540 
1541 
1542 // Handle call site that has been made non-entrant
1543 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method(JavaThread* current))
1544   // 6243940 We might end up in here if the callee is deoptimized
1545   // as we race to call it.  We don't want to take a safepoint if
1546   // the caller was interpreted because the caller frame will look
1547   // interpreted to the stack walkers and arguments are now
1548   // "compiled" so it is much better to make this transition
1549   // invisible to the stack walking code. The i2c path will
1550   // place the callee method in the callee_target. It is stashed
1551   // there because if we try and find the callee by normal means a
1552   // safepoint is possible and have trouble gc'ing the compiled args.
1553   RegisterMap reg_map(current,
1554                       RegisterMap::UpdateMap::skip,
1555                       RegisterMap::ProcessFrames::include,
1556                       RegisterMap::WalkContinuation::skip);
1557   frame stub_frame = current->last_frame();
1558   assert(stub_frame.is_runtime_frame(), "sanity check");
1559   frame caller_frame = stub_frame.sender(&reg_map);
1560 
1561   if (caller_frame.is_interpreted_frame() ||
1562       caller_frame.is_entry_frame() ||
1563       caller_frame.is_upcall_stub_frame()) {
1564     Method* callee = current->callee_target();
1565     guarantee(callee != nullptr && callee->is_method(), "bad handshake");
1566     current->set_vm_result_metadata(callee);
1567     current->set_callee_target(nullptr);
1568     if (caller_frame.is_entry_frame() && VM_Version::supports_fast_class_init_checks()) {
1569       // Bypass class initialization checks in c2i when caller is in native.
1570       // JNI calls to static methods don't have class initialization checks.
1571       // Fast class initialization checks are present in c2i adapters and call into
1572       // SharedRuntime::handle_wrong_method() on the slow path.
1573       //
1574       // JVM upcalls may land here as well, but there's a proper check present in
1575       // LinkResolver::resolve_static_call (called from JavaCalls::call_static),
1576       // so bypassing it in c2i adapter is benign.
1577       return callee->get_c2i_no_clinit_check_entry();
1578     } else {
1579       if (caller_frame.is_interpreted_frame()) {
1580         return callee->get_c2i_inline_entry();
1581       } else {
1582         return callee->get_c2i_entry();
1583       }
1584     }
1585   }
1586 
1587   // Must be compiled to compiled path which is safe to stackwalk
1588   methodHandle callee_method;
1589   bool is_static_call = false;
1590   bool is_optimized = false;
1591   bool caller_does_not_scalarize = false;
1592   JRT_BLOCK
1593     // Force resolving of caller (if we called from compiled frame)
1594     callee_method = SharedRuntime::reresolve_call_site(is_optimized, caller_does_not_scalarize, CHECK_NULL);
1595     current->set_vm_result_metadata(callee_method());
1596   JRT_BLOCK_END
1597   // return compiled code entry point after potential safepoints
1598   return get_resolved_entry(current, callee_method, callee_method->is_static(), is_optimized, caller_does_not_scalarize);
1599 JRT_END
1600 
1601 // Handle abstract method call
1602 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_abstract(JavaThread* current))
1603   // Verbose error message for AbstractMethodError.
1604   // Get the called method from the invoke bytecode.
1605   vframeStream vfst(current, true);
1606   assert(!vfst.at_end(), "Java frame must exist");
1607   methodHandle caller(current, vfst.method());
1608   Bytecode_invoke invoke(caller, vfst.bci());
1609   DEBUG_ONLY( invoke.verify(); )
1610 
1611   // Find the compiled caller frame.
1612   RegisterMap reg_map(current,
1613                       RegisterMap::UpdateMap::include,
1614                       RegisterMap::ProcessFrames::include,
1615                       RegisterMap::WalkContinuation::skip);
1616   frame stubFrame = current->last_frame();
1617   assert(stubFrame.is_runtime_frame(), "must be");
1618   frame callerFrame = stubFrame.sender(&reg_map);
1619   assert(callerFrame.is_compiled_frame(), "must be");
1620 
1621   // Install exception and return forward entry.
1622   address res = SharedRuntime::throw_AbstractMethodError_entry();
1623   JRT_BLOCK
1624     methodHandle callee(current, invoke.static_target(current));
1625     if (!callee.is_null()) {
1626       oop recv = callerFrame.retrieve_receiver(&reg_map);
1627       Klass *recv_klass = (recv != nullptr) ? recv->klass() : nullptr;
1628       res = StubRoutines::forward_exception_entry();
1629       LinkResolver::throw_abstract_method_error(callee, recv_klass, CHECK_(res));
1630     }
1631   JRT_BLOCK_END
1632   return res;
1633 JRT_END
1634 
1635 // return verified_code_entry if interp_only_mode is not set for the current thread;
1636 // otherwise return c2i entry.
1637 address SharedRuntime::get_resolved_entry(JavaThread* current, methodHandle callee_method,
1638                                           bool is_static_call, bool is_optimized, bool caller_does_not_scalarize) {
1639   bool is_interp_only_mode = (StressCallingConvention && (os::random() % (1 << 10)) == 0) || current->is_interp_only_mode();
1640   // In interp_only_mode we need to go to the interpreted entry
1641   // The c2i won't patch in this mode -- see fixup_callers_callsite
1642   bool go_to_interpreter = is_interp_only_mode && !callee_method->is_special_native_intrinsic();
1643 
1644   if (caller_does_not_scalarize) {
1645     if (go_to_interpreter) {
1646       return callee_method->get_c2i_inline_entry();
1647     }
1648     assert(callee_method->verified_inline_code_entry() != nullptr, "Jump to zero!");
1649     return callee_method->verified_inline_code_entry();
1650   } else if (is_static_call || is_optimized) {
1651     if (go_to_interpreter) {
1652       return callee_method->get_c2i_entry();
1653     }
1654     assert(callee_method->verified_code_entry() != nullptr, "Jump to zero!");
1655     return callee_method->verified_code_entry();
1656   } else {
1657     if (go_to_interpreter) {
1658       return callee_method->get_c2i_inline_ro_entry();
1659     }
1660     assert(callee_method->verified_inline_ro_code_entry() != nullptr, "Jump to zero!");
1661     return callee_method->verified_inline_ro_code_entry();
1662   }


1663 }
1664 
1665 // resolve a static call and patch code
1666 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_call_C(JavaThread* current ))
1667   methodHandle callee_method;
1668   bool caller_does_not_scalarize = false;
1669   bool enter_special = false;
1670   JRT_BLOCK
1671     callee_method = SharedRuntime::resolve_helper(false, false, caller_does_not_scalarize, CHECK_NULL);
1672     current->set_vm_result_metadata(callee_method());
1673   JRT_BLOCK_END
1674   // return compiled code entry point after potential safepoints
1675   return get_resolved_entry(current, callee_method, true, false, caller_does_not_scalarize);
1676 JRT_END
1677 
1678 // resolve virtual call and update inline cache to monomorphic
1679 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_virtual_call_C(JavaThread* current))
1680   methodHandle callee_method;
1681   bool caller_does_not_scalarize = false;
1682   JRT_BLOCK
1683     callee_method = SharedRuntime::resolve_helper(true, false, caller_does_not_scalarize, CHECK_NULL);
1684     current->set_vm_result_metadata(callee_method());
1685   JRT_BLOCK_END
1686   // return compiled code entry point after potential safepoints
1687   return get_resolved_entry(current, callee_method, false, false, caller_does_not_scalarize);
1688 JRT_END
1689 
1690 
1691 // Resolve a virtual call that can be statically bound (e.g., always
1692 // monomorphic, so it has no inline cache).  Patch code to resolved target.
1693 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_opt_virtual_call_C(JavaThread* current))
1694   methodHandle callee_method;
1695   bool caller_does_not_scalarize = false;
1696   JRT_BLOCK
1697     callee_method = SharedRuntime::resolve_helper(true, true, caller_does_not_scalarize, CHECK_NULL);
1698     current->set_vm_result_metadata(callee_method());
1699   JRT_BLOCK_END
1700   // return compiled code entry point after potential safepoints
1701   return get_resolved_entry(current, callee_method, false, true, caller_does_not_scalarize);
1702 JRT_END
1703 
1704 
1705 
1706 methodHandle SharedRuntime::handle_ic_miss_helper(bool& caller_does_not_scalarize, TRAPS) {
1707   JavaThread* current = THREAD;
1708   ResourceMark rm(current);
1709   CallInfo call_info;
1710   Bytecodes::Code bc;
1711 
1712   // receiver is null for static calls. An exception is thrown for null
1713   // receivers for non-static calls
1714   Handle receiver = find_callee_info(bc, call_info, CHECK_(methodHandle()));
1715 
1716   methodHandle callee_method(current, call_info.selected_method());
1717 
1718 #ifndef PRODUCT
1719   AtomicAccess::inc(&_ic_miss_ctr);
1720 
1721   // Statistics & Tracing
1722   if (TraceCallFixup) {
1723     ResourceMark rm(current);
1724     tty->print("IC miss (%s) %s call to", Bytecodes::name(bc), (caller_does_not_scalarize) ? "non-scalar" : "");
1725     callee_method->print_short_name(tty);
1726     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1727   }
1728 
1729   if (ICMissHistogram) {
1730     MutexLocker m(VMStatistic_lock);
1731     RegisterMap reg_map(current,
1732                         RegisterMap::UpdateMap::skip,
1733                         RegisterMap::ProcessFrames::include,
1734                         RegisterMap::WalkContinuation::skip);
1735     frame f = current->last_frame().real_sender(&reg_map);// skip runtime stub
1736     // produce statistics under the lock
1737     trace_ic_miss(f.pc());
1738   }
1739 #endif
1740 
1741   // install an event collector so that when a vtable stub is created the
1742   // profiler can be notified via a DYNAMIC_CODE_GENERATED event. The
1743   // event can't be posted when the stub is created as locks are held
1744   // - instead the event will be deferred until the event collector goes
1745   // out of scope.
1746   JvmtiDynamicCodeEventCollector event_collector;
1747 
1748   // Update inline cache to megamorphic. Skip update if we are called from interpreted.
1749   RegisterMap reg_map(current,
1750                       RegisterMap::UpdateMap::skip,
1751                       RegisterMap::ProcessFrames::include,
1752                       RegisterMap::WalkContinuation::skip);
1753   frame caller_frame = current->last_frame().sender(&reg_map);
1754   CodeBlob* cb = caller_frame.cb();
1755   nmethod* caller_nm = cb->as_nmethod();
1756   // Calls via mismatching methods are always non-scalarized
1757   if (caller_nm->is_compiled_by_c1() || call_info.resolved_method()->mismatch()) {
1758     caller_does_not_scalarize = true;
1759   }
1760 
1761   CompiledICLocker ml(caller_nm);
1762   CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1763   inline_cache->update(&call_info, receiver()->klass(), caller_does_not_scalarize);
1764 
1765   return callee_method;
1766 }
1767 
1768 //
1769 // Resets a call-site in compiled code so it will get resolved again.
1770 // This routines handles both virtual call sites, optimized virtual call
1771 // sites, and static call sites. Typically used to change a call sites
1772 // destination from compiled to interpreted.
1773 //
1774 methodHandle SharedRuntime::reresolve_call_site(bool& is_optimized, bool& caller_does_not_scalarize, TRAPS) {
1775   JavaThread* current = THREAD;
1776   ResourceMark rm(current);
1777   RegisterMap reg_map(current,
1778                       RegisterMap::UpdateMap::skip,
1779                       RegisterMap::ProcessFrames::include,
1780                       RegisterMap::WalkContinuation::skip);
1781   frame stub_frame = current->last_frame();
1782   assert(stub_frame.is_runtime_frame(), "must be a runtimeStub");
1783   frame caller = stub_frame.sender(&reg_map);
1784   if (caller.is_compiled_frame()) {
1785     caller_does_not_scalarize = caller.cb()->as_nmethod()->is_compiled_by_c1();
1786   }
1787   assert(!caller.is_interpreted_frame(), "must be compiled");
1788 
1789   // If the frame isn't a live compiled frame (i.e. deoptimized by the time we get here), no IC clearing must be done
1790   // for the caller. However, when the caller is C2 compiled and the callee a C1 or C2 compiled method, then we still
1791   // need to figure out whether it was an optimized virtual call with an inline type receiver. Otherwise, we end up
1792   // using the wrong method entry point and accidentally skip the buffering of the receiver.
1793   methodHandle callee_method = find_callee_method(caller_does_not_scalarize, CHECK_(methodHandle()));
1794   const bool caller_is_compiled_and_not_deoptimized = caller.is_compiled_frame() && !caller.is_deoptimized_frame();
1795   const bool caller_is_continuation_enter_intrinsic =
1796     caller.is_native_frame() && caller.cb()->as_nmethod()->method()->is_continuation_enter_intrinsic();
1797   const bool do_IC_clearing = caller_is_compiled_and_not_deoptimized || caller_is_continuation_enter_intrinsic;
1798 
1799   const bool callee_compiled_with_scalarized_receiver = callee_method->has_compiled_code() &&
1800                                                         !callee_method()->is_static() &&
1801                                                         callee_method()->is_scalarized_arg(0);
1802   const bool compute_is_optimized = !caller_does_not_scalarize && callee_compiled_with_scalarized_receiver;
1803 
1804   if (do_IC_clearing || compute_is_optimized) {
1805     address pc = caller.pc();
1806 
1807     nmethod* caller_nm = CodeCache::find_nmethod(pc);
1808     assert(caller_nm != nullptr, "did not find caller nmethod");
1809 
1810     // Default call_addr is the location of the "basic" call.
1811     // Determine the address of the call we a reresolving. With
1812     // Inline Caches we will always find a recognizable call.
1813     // With Inline Caches disabled we may or may not find a
1814     // recognizable call. We will always find a call for static
1815     // calls and for optimized virtual calls. For vanilla virtual
1816     // calls it depends on the state of the UseInlineCaches switch.
1817     //
1818     // With Inline Caches disabled we can get here for a virtual call
1819     // for two reasons:
1820     //   1 - calling an abstract method. The vtable for abstract methods
1821     //       will run us thru handle_wrong_method and we will eventually
1822     //       end up in the interpreter to throw the ame.
1823     //   2 - a racing deoptimization. We could be doing a vanilla vtable
1824     //       call and between the time we fetch the entry address and
1825     //       we jump to it the target gets deoptimized. Similar to 1
1826     //       we will wind up in the interprter (thru a c2i with c2).
1827     //
1828     CompiledICLocker ml(caller_nm);
1829     address call_addr = caller_nm->call_instruction_address(pc);
1830 
1831     if (call_addr != nullptr) {
1832       // On x86 the logic for finding a call instruction is blindly checking for a call opcode 5
1833       // bytes back in the instruction stream so we must also check for reloc info.
1834       RelocIterator iter(caller_nm, call_addr, call_addr+1);
1835       bool ret = iter.next(); // Get item
1836       if (ret) {
1837         is_optimized = false;
1838         switch (iter.type()) {
1839           case relocInfo::static_call_type:
1840             assert(callee_method->is_static(), "must be");
1841           case relocInfo::opt_virtual_call_type: {
1842             is_optimized = (iter.type() == relocInfo::opt_virtual_call_type);
1843             if (do_IC_clearing) {
1844               CompiledDirectCall* cdc = CompiledDirectCall::at(call_addr);
1845               cdc->set_to_clean();
1846             }
1847             break;
1848           }

1849           case relocInfo::virtual_call_type: {
1850             if (do_IC_clearing) {
1851               // compiled, dispatched call (which used to call an interpreted method)
1852               CompiledIC* inline_cache = CompiledIC_at(caller_nm, call_addr);
1853               inline_cache->set_to_clean();
1854             }
1855             break;
1856           }
1857           default:
1858             break;
1859         }
1860       }
1861     }
1862   }
1863 



1864 #ifndef PRODUCT
1865   AtomicAccess::inc(&_wrong_method_ctr);
1866 
1867   if (TraceCallFixup) {
1868     ResourceMark rm(current);
1869     tty->print("handle_wrong_method reresolving %s call to", (caller_does_not_scalarize) ? "non-scalar" : "");
1870     callee_method->print_short_name(tty);
1871     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1872   }
1873 #endif
1874 
1875   return callee_method;
1876 }
1877 
1878 address SharedRuntime::handle_unsafe_access(JavaThread* thread, address next_pc) {
1879   // The faulting unsafe accesses should be changed to throw the error
1880   // synchronously instead. Meanwhile the faulting instruction will be
1881   // skipped over (effectively turning it into a no-op) and an
1882   // asynchronous exception will be raised which the thread will
1883   // handle at a later point. If the instruction is a load it will
1884   // return garbage.
1885 
1886   // Request an async exception.
1887   thread->set_pending_unsafe_access_error();
1888 
1889   // Return address of next instruction to execute.

2055   msglen += strlen(caster_klass_description) + strlen(target_klass_description) + strlen(klass_separator) + 3;
2056 
2057   char* message = NEW_RESOURCE_ARRAY_RETURN_NULL(char, msglen);
2058   if (message == nullptr) {
2059     // Shouldn't happen, but don't cause even more problems if it does
2060     message = const_cast<char*>(caster_klass->external_name());
2061   } else {
2062     jio_snprintf(message,
2063                  msglen,
2064                  "class %s cannot be cast to class %s (%s%s%s)",
2065                  caster_name,
2066                  target_name,
2067                  caster_klass_description,
2068                  klass_separator,
2069                  target_klass_description
2070                  );
2071   }
2072   return message;
2073 }
2074 
2075 char* SharedRuntime::generate_identity_exception_message(JavaThread* current, Klass* klass) {
2076   assert(klass->is_inline_klass(), "Must be a concrete value class");
2077   const char* desc = "Cannot synchronize on an instance of value class ";
2078   const char* className = klass->external_name();
2079   size_t msglen = strlen(desc) + strlen(className) + 1;
2080   char* message = NEW_RESOURCE_ARRAY(char, msglen);
2081   if (nullptr == message) {
2082     // Out of memory: can't create detailed error message
2083     message = const_cast<char*>(klass->external_name());
2084   } else {
2085     jio_snprintf(message, msglen, "%s%s", desc, className);
2086   }
2087   return message;
2088 }
2089 
2090 JRT_LEAF(void, SharedRuntime::reguard_yellow_pages())
2091   (void) JavaThread::current()->stack_overflow_state()->reguard_stack();
2092 JRT_END
2093 
2094 void SharedRuntime::monitor_enter_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) {
2095   if (!SafepointSynchronize::is_synchronizing()) {
2096     // Only try quick_enter() if we're not trying to reach a safepoint
2097     // so that the calling thread reaches the safepoint more quickly.
2098     if (ObjectSynchronizer::quick_enter(obj, lock, current)) {
2099       return;
2100     }
2101   }
2102   // NO_ASYNC required because an async exception on the state transition destructor
2103   // would leave you with the lock held and it would never be released.
2104   // The normal monitorenter NullPointerException is thrown without acquiring a lock
2105   // and the model is that an exception implies the method failed.
2106   JRT_BLOCK_NO_ASYNC
2107   Handle h_obj(THREAD, obj);
2108   ObjectSynchronizer::enter(h_obj, lock, current);
2109   assert(!HAS_PENDING_EXCEPTION, "Should have no exception here");

2303   tty->print_cr("Note 1: counter updates are not MT-safe.");
2304   tty->print_cr("Note 2: %% in major categories are relative to total non-inlined calls;");
2305   tty->print_cr("        %% in nested categories are relative to their category");
2306   tty->print_cr("        (and thus add up to more than 100%% with inlining)");
2307   tty->cr();
2308 
2309   MethodArityHistogram h;
2310 }
2311 #endif
2312 
2313 #ifndef PRODUCT
2314 static int _lookups; // number of calls to lookup
2315 static int _equals;  // number of buckets checked with matching hash
2316 static int _archived_hits; // number of successful lookups in archived table
2317 static int _runtime_hits;  // number of successful lookups in runtime table
2318 #endif
2319 
2320 // A simple wrapper class around the calling convention information
2321 // that allows sharing of adapters for the same calling convention.
2322 class AdapterFingerPrint : public MetaspaceObj {
2323 public:
2324   class Element {
2325   private:
2326     // The highest byte is the type of the argument. The remaining bytes contain the offset of the
2327     // field if it is flattened in the calling convention, -1 otherwise.
2328     juint _payload;
2329 
2330     static constexpr int offset_bit_width = 24;
2331     static constexpr juint offset_bit_mask = (1 << offset_bit_width) - 1;
2332   public:
2333     Element(BasicType bt, int offset) : _payload((static_cast<juint>(bt) << offset_bit_width) | (juint(offset) & offset_bit_mask)) {
2334       assert(offset >= -1 && offset < jint(offset_bit_mask), "invalid offset %d", offset);
2335     }
2336 
2337     BasicType bt() const {
2338       return static_cast<BasicType>(_payload >> offset_bit_width);
2339     }
2340 
2341     int offset() const {
2342       juint res = _payload & offset_bit_mask;
2343       return res == offset_bit_mask ? -1 : res;
2344     }
2345 
2346     juint hash() const {
2347       return _payload;
2348     }
2349 
2350     bool operator!=(const Element& other) const {
2351       return _payload != other._payload;
2352     }
2353   };


2354 
2355 private:
2356   const bool _has_ro_adapter;
2357   const int _length;
2358 
2359   static int data_offset() { return sizeof(AdapterFingerPrint); }
2360   Element* data_pointer() {
2361     return reinterpret_cast<Element*>(reinterpret_cast<address>(this) + data_offset());
2362   }
2363 
2364   const Element& element_at(int index) {
2365     assert(index < length(), "index %d out of bounds for length %d", index, length());
2366     Element* data = data_pointer();
2367     return data[index];
2368   }
2369 
2370   // Private construtor. Use allocate() to get an instance.
2371   AdapterFingerPrint(const GrowableArray<SigEntry>* sig, bool has_ro_adapter)
2372     : _has_ro_adapter(has_ro_adapter), _length(total_args_passed_in_sig(sig)) {
2373     Element* data = data_pointer();
2374     BasicType prev_bt = T_ILLEGAL;
2375     int vt_count = 0;

2376     for (int index = 0; index < _length; index++) {
2377       const SigEntry& sig_entry = sig->at(index);
2378       BasicType bt = sig_entry._bt;
2379       if (bt == T_METADATA) {
2380         // Found start of inline type in signature
2381         assert(InlineTypePassFieldsAsArgs, "unexpected start of inline type");
2382         vt_count++;
2383       } else if (bt == T_VOID && prev_bt != T_LONG && prev_bt != T_DOUBLE) {
2384         // Found end of inline type in signature
2385         assert(InlineTypePassFieldsAsArgs, "unexpected end of inline type");
2386         vt_count--;
2387         assert(vt_count >= 0, "invalid vt_count");
2388       } else if (vt_count == 0) {
2389         // Widen fields that are not part of a scalarized inline type argument
2390         assert(sig_entry._offset == -1, "invalid offset for argument that is not a flattened field %d", sig_entry._offset);
2391         bt = adapter_encoding(bt);
2392       }
2393 
2394       ::new(&data[index]) Element(bt, sig_entry._offset);
2395       prev_bt = bt;
2396     }
2397     assert(vt_count == 0, "invalid vt_count");
2398   }
2399 
2400   // Call deallocate instead
2401   ~AdapterFingerPrint() {
2402     ShouldNotCallThis();
2403   }
2404 
2405   static int total_args_passed_in_sig(const GrowableArray<SigEntry>* sig) {
2406     return (sig != nullptr) ? sig->length() : 0;
2407   }
2408 
2409   static int compute_size_in_words(int len) {
2410     return (int)heap_word_size(sizeof(AdapterFingerPrint) + (len * sizeof(Element)));
2411   }
2412 
2413   // Remap BasicTypes that are handled equivalently by the adapters.
2414   // These are correct for the current system but someday it might be
2415   // necessary to make this mapping platform dependent.
2416   static BasicType adapter_encoding(BasicType in) {
2417     switch (in) {
2418       case T_BOOLEAN:
2419       case T_BYTE:
2420       case T_SHORT:
2421       case T_CHAR:
2422         // They are all promoted to T_INT in the calling convention
2423         return T_INT;
2424 
2425       case T_OBJECT:
2426       case T_ARRAY:
2427         // In other words, we assume that any register good enough for
2428         // an int or long is good enough for a managed pointer.
2429 #ifdef _LP64
2430         return T_LONG;
2431 #else
2432         return T_INT;
2433 #endif
2434 
2435       case T_INT:
2436       case T_LONG:
2437       case T_FLOAT:
2438       case T_DOUBLE:
2439       case T_VOID:
2440         return in;
2441 
2442       default:
2443         ShouldNotReachHere();
2444         return T_CONFLICT;
2445     }
2446   }
2447 
2448   void* operator new(size_t size, size_t fp_size) throw() {
2449     assert(fp_size >= size, "sanity check");
2450     void* p = AllocateHeap(fp_size, mtCode);
2451     memset(p, 0, fp_size);
2452     return p;
2453   }
2454 
2455 public:
2456   template<typename Function>
2457   void iterate_args(Function function) {
2458     for (int i = 0; i < length(); i++) {
2459       function(element_at(i));









2460     }
2461   }
2462 
2463   static AdapterFingerPrint* allocate(const GrowableArray<SigEntry>* sig, bool has_ro_adapter = false) {
2464     int len = total_args_passed_in_sig(sig);

2465     int size_in_bytes = BytesPerWord * compute_size_in_words(len);
2466     AdapterFingerPrint* afp = new (size_in_bytes) AdapterFingerPrint(sig, has_ro_adapter);
2467     assert((afp->size() * BytesPerWord) == size_in_bytes, "should match");
2468     return afp;
2469   }
2470 
2471   static void deallocate(AdapterFingerPrint* fp) {
2472     FreeHeap(fp);
2473   }
2474 
2475   bool has_ro_adapter() const {
2476     return _has_ro_adapter;

2477   }
2478 
2479   int length() const {
2480     return _length;
2481   }
2482 
2483   unsigned int compute_hash() {
2484     int hash = 0;
2485     for (int i = 0; i < length(); i++) {
2486       const Element& v = element_at(i);
2487       //Add arithmetic operation to the hash, like +3 to improve hashing
2488       hash = ((hash << 8) ^ v.hash() ^ (hash >> 5)) + 3;
2489     }
2490     return (unsigned int)hash;
2491   }
2492 
2493   const char* as_string() {
2494     stringStream st;
2495     st.print("{");
2496     if (_has_ro_adapter) {
2497       st.print("has_ro_adapter");
2498     } else {
2499       st.print("no_ro_adapter");
2500     }
2501     for (int i = 0; i < length(); i++) {
2502       st.print(", ");
2503       const Element& elem = element_at(i);
2504       st.print("{%s, %d}", type2name(elem.bt()), elem.offset());
2505     }
2506     st.print("}");
2507     return st.as_string();
2508   }
2509 
2510   const char* as_basic_args_string() {
2511     stringStream st;
2512     bool long_prev = false;
2513     iterate_args([&] (const Element& arg) {
2514       if (long_prev) {
2515         long_prev = false;
2516         if (arg.bt() == T_VOID) {
2517           st.print("J");
2518         } else {
2519           st.print("L");
2520         }
2521       }
2522       if (arg.bt() == T_LONG) {
2523         long_prev = true;
2524       } else if (arg.bt() != T_VOID) {
2525         st.print("%c", type2char(arg.bt()));



2526       }
2527     });
2528     if (long_prev) {
2529       st.print("L");
2530     }
2531     return st.as_string();
2532   }
2533 



















































2534   bool equals(AdapterFingerPrint* other) {
2535     if (other->_has_ro_adapter != _has_ro_adapter) {
2536       return false;
2537     } else if (other->_length != _length) {
2538       return false;
2539     } else {
2540       for (int i = 0; i < _length; i++) {
2541         if (element_at(i) != other->element_at(i)) {
2542           return false;
2543         }
2544       }
2545     }
2546     return true;
2547   }
2548 
2549   // methods required by virtue of being a MetaspaceObj
2550   void metaspace_pointers_do(MetaspaceClosure* it) { return; /* nothing to do here */ }
2551   int size() const { return compute_size_in_words(_length); }
2552   MetaspaceObj::Type type() const { return AdapterFingerPrintType; }
2553 
2554   static bool equals(AdapterFingerPrint* const& fp1, AdapterFingerPrint* const& fp2) {
2555     NOT_PRODUCT(_equals++);
2556     return fp1->equals(fp2);
2557   }
2558 
2559   static unsigned int compute_hash(AdapterFingerPrint* const& fp) {
2560     return fp->compute_hash();
2561   }

2564 #if INCLUDE_CDS
2565 static inline bool adapter_fp_equals_compact_hashtable_entry(AdapterHandlerEntry* entry, AdapterFingerPrint* fp, int len_unused) {
2566   return AdapterFingerPrint::equals(entry->fingerprint(), fp);
2567 }
2568 
2569 class ArchivedAdapterTable : public OffsetCompactHashtable<
2570   AdapterFingerPrint*,
2571   AdapterHandlerEntry*,
2572   adapter_fp_equals_compact_hashtable_entry> {};
2573 #endif // INCLUDE_CDS
2574 
2575 // A hashtable mapping from AdapterFingerPrints to AdapterHandlerEntries
2576 using AdapterHandlerTable = HashTable<AdapterFingerPrint*, AdapterHandlerEntry*, 293,
2577                   AnyObj::C_HEAP, mtCode,
2578                   AdapterFingerPrint::compute_hash,
2579                   AdapterFingerPrint::equals>;
2580 static AdapterHandlerTable* _adapter_handler_table;
2581 static GrowableArray<AdapterHandlerEntry*>* _adapter_handler_list = nullptr;
2582 
2583 // Find a entry with the same fingerprint if it exists
2584 AdapterHandlerEntry* AdapterHandlerLibrary::lookup(const GrowableArray<SigEntry>* sig, bool has_ro_adapter) {
2585   NOT_PRODUCT(_lookups++);
2586   assert_lock_strong(AdapterHandlerLibrary_lock);
2587   AdapterFingerPrint* fp = AdapterFingerPrint::allocate(sig, has_ro_adapter);
2588   AdapterHandlerEntry* entry = nullptr;
2589 #if INCLUDE_CDS
2590   // if we are building the archive then the archived adapter table is
2591   // not valid and we need to use the ones added to the runtime table
2592   if (AOTCodeCache::is_using_adapter()) {
2593     // Search archived table first. It is read-only table so can be searched without lock
2594     entry = _aot_adapter_handler_table.lookup(fp, fp->compute_hash(), 0 /* unused */);
2595 #ifndef PRODUCT
2596     if (entry != nullptr) {
2597       _archived_hits++;
2598     }
2599 #endif
2600   }
2601 #endif // INCLUDE_CDS
2602   if (entry == nullptr) {
2603     assert_lock_strong(AdapterHandlerLibrary_lock);
2604     AdapterHandlerEntry** entry_p = _adapter_handler_table->get(fp);
2605     if (entry_p != nullptr) {
2606       entry = *entry_p;
2607       assert(entry->fingerprint()->equals(fp), "fingerprint mismatch key fp %s %s (hash=%d) != found fp %s %s (hash=%d)",

2624   TableStatistics ts = _adapter_handler_table->statistics_calculate(size);
2625   ts.print(tty, "AdapterHandlerTable");
2626   tty->print_cr("AdapterHandlerTable (table_size=%d, entries=%d)",
2627                 _adapter_handler_table->table_size(), _adapter_handler_table->number_of_entries());
2628   int total_hits = _archived_hits + _runtime_hits;
2629   tty->print_cr("AdapterHandlerTable: lookups %d equals %d hits %d (archived=%d+runtime=%d)",
2630                 _lookups, _equals, total_hits, _archived_hits, _runtime_hits);
2631 }
2632 #endif
2633 
2634 // ---------------------------------------------------------------------------
2635 // Implementation of AdapterHandlerLibrary
2636 AdapterHandlerEntry* AdapterHandlerLibrary::_no_arg_handler = nullptr;
2637 AdapterHandlerEntry* AdapterHandlerLibrary::_int_arg_handler = nullptr;
2638 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_arg_handler = nullptr;
2639 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_int_arg_handler = nullptr;
2640 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_obj_arg_handler = nullptr;
2641 #if INCLUDE_CDS
2642 ArchivedAdapterTable AdapterHandlerLibrary::_aot_adapter_handler_table;
2643 #endif // INCLUDE_CDS
2644 static const int AdapterHandlerLibrary_size = 48*K;
2645 BufferBlob* AdapterHandlerLibrary::_buffer = nullptr;
2646 volatile uint AdapterHandlerLibrary::_id_counter = 0;
2647 
2648 BufferBlob* AdapterHandlerLibrary::buffer_blob() {
2649   assert(_buffer != nullptr, "should be initialized");
2650   return _buffer;
2651 }
2652 
2653 static void post_adapter_creation(const AdapterHandlerEntry* entry) {
2654   if (Forte::is_enabled() || JvmtiExport::should_post_dynamic_code_generated()) {
2655     AdapterBlob* adapter_blob = entry->adapter_blob();
2656     char blob_id[256];
2657     jio_snprintf(blob_id,
2658                  sizeof(blob_id),
2659                  "%s(%s)",
2660                  adapter_blob->name(),
2661                  entry->fingerprint()->as_string());
2662     if (Forte::is_enabled()) {
2663       Forte::register_stub(blob_id, adapter_blob->content_begin(), adapter_blob->content_end());
2664     }

2672 void AdapterHandlerLibrary::initialize() {
2673   {
2674     ResourceMark rm;
2675     _adapter_handler_table = new (mtCode) AdapterHandlerTable();
2676     _buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size);
2677   }
2678 
2679 #if INCLUDE_CDS
2680   // Link adapters in AOT Cache to their code in AOT Code Cache
2681   if (AOTCodeCache::is_using_adapter() && !_aot_adapter_handler_table.empty()) {
2682     link_aot_adapters();
2683     lookup_simple_adapters();
2684     return;
2685   }
2686 #endif // INCLUDE_CDS
2687 
2688   ResourceMark rm;
2689   {
2690     MutexLocker mu(AdapterHandlerLibrary_lock);
2691 
2692     CompiledEntrySignature no_args;
2693     no_args.compute_calling_conventions();
2694     _no_arg_handler = create_adapter(no_args, true);
2695 
2696     CompiledEntrySignature obj_args;
2697     SigEntry::add_entry(obj_args.sig(), T_OBJECT);
2698     obj_args.compute_calling_conventions();
2699     _obj_arg_handler = create_adapter(obj_args, true);
2700 
2701     CompiledEntrySignature int_args;
2702     SigEntry::add_entry(int_args.sig(), T_INT);
2703     int_args.compute_calling_conventions();
2704     _int_arg_handler = create_adapter(int_args, true);
2705 
2706     CompiledEntrySignature obj_int_args;
2707     SigEntry::add_entry(obj_int_args.sig(), T_OBJECT);
2708     SigEntry::add_entry(obj_int_args.sig(), T_INT);
2709     obj_int_args.compute_calling_conventions();
2710     _obj_int_arg_handler = create_adapter(obj_int_args, true);
2711 
2712     CompiledEntrySignature obj_obj_args;
2713     SigEntry::add_entry(obj_obj_args.sig(), T_OBJECT);
2714     SigEntry::add_entry(obj_obj_args.sig(), T_OBJECT);
2715     obj_obj_args.compute_calling_conventions();
2716     _obj_obj_arg_handler = create_adapter(obj_obj_args, true);
2717 
2718     // we should always get an entry back but we don't have any
2719     // associated blob on Zero
2720     assert(_no_arg_handler != nullptr &&
2721            _obj_arg_handler != nullptr &&
2722            _int_arg_handler != nullptr &&
2723            _obj_int_arg_handler != nullptr &&
2724            _obj_obj_arg_handler != nullptr, "Initial adapter handlers must be properly created");
2725   }
2726 
2727   // Outside of the lock
2728 #ifndef ZERO
2729   // no blobs to register when we are on Zero
2730   post_adapter_creation(_no_arg_handler);
2731   post_adapter_creation(_obj_arg_handler);
2732   post_adapter_creation(_int_arg_handler);
2733   post_adapter_creation(_obj_int_arg_handler);
2734   post_adapter_creation(_obj_obj_arg_handler);
2735 #endif // ZERO
2736 }
2737 
2738 AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint) {
2739   uint id = (uint)AtomicAccess::add((int*)&_id_counter, 1);
2740   assert(id > 0, "we can never overflow because AOT cache cannot contain more than 2^32 methods");
2741   return AdapterHandlerEntry::allocate(id, fingerprint);
2742 }
2743 
2744 AdapterHandlerEntry* AdapterHandlerLibrary::get_simple_adapter(const methodHandle& method) {
2745   int total_args_passed = method->size_of_parameters(); // All args on stack
2746   if (total_args_passed == 0) {
2747     return _no_arg_handler;
2748   } else if (total_args_passed == 1) {
2749     if (!method->is_static()) {
2750       if (InlineTypePassFieldsAsArgs && method->method_holder()->is_inline_klass()) {
2751         return nullptr;
2752       }
2753       return _obj_arg_handler;
2754     }
2755     switch (method->signature()->char_at(1)) {
2756       case JVM_SIGNATURE_CLASS: {
2757         if (InlineTypePassFieldsAsArgs) {
2758           SignatureStream ss(method->signature());
2759           InlineKlass* vk = ss.as_inline_klass(method->method_holder());
2760           if (vk != nullptr) {
2761             return nullptr;
2762           }
2763         }
2764         return _obj_arg_handler;
2765       }
2766       case JVM_SIGNATURE_ARRAY:
2767         return _obj_arg_handler;
2768       case JVM_SIGNATURE_INT:
2769       case JVM_SIGNATURE_BOOLEAN:
2770       case JVM_SIGNATURE_CHAR:
2771       case JVM_SIGNATURE_BYTE:
2772       case JVM_SIGNATURE_SHORT:
2773         return _int_arg_handler;
2774     }
2775   } else if (total_args_passed == 2 &&
2776              !method->is_static() && (!InlineTypePassFieldsAsArgs || !method->method_holder()->is_inline_klass())) {
2777     switch (method->signature()->char_at(1)) {
2778       case JVM_SIGNATURE_CLASS: {
2779         if (InlineTypePassFieldsAsArgs) {
2780           SignatureStream ss(method->signature());
2781           InlineKlass* vk = ss.as_inline_klass(method->method_holder());
2782           if (vk != nullptr) {
2783             return nullptr;
2784           }
2785         }
2786         return _obj_obj_arg_handler;
2787       }
2788       case JVM_SIGNATURE_ARRAY:
2789         return _obj_obj_arg_handler;
2790       case JVM_SIGNATURE_INT:
2791       case JVM_SIGNATURE_BOOLEAN:
2792       case JVM_SIGNATURE_CHAR:
2793       case JVM_SIGNATURE_BYTE:
2794       case JVM_SIGNATURE_SHORT:
2795         return _obj_int_arg_handler;
2796     }
2797   }
2798   return nullptr;
2799 }
2800 
2801 CompiledEntrySignature::CompiledEntrySignature(Method* method) :
2802   _method(method), _num_inline_args(0), _has_inline_recv(false),
2803   _regs(nullptr), _regs_cc(nullptr), _regs_cc_ro(nullptr),
2804   _args_on_stack(0), _args_on_stack_cc(0), _args_on_stack_cc_ro(0),
2805   _c1_needs_stack_repair(false), _c2_needs_stack_repair(false), _supers(nullptr) {
2806   _sig = new GrowableArray<SigEntry>((method != nullptr) ? method->size_of_parameters() : 1);
2807   _sig_cc = new GrowableArray<SigEntry>((method != nullptr) ? method->size_of_parameters() : 1);
2808   _sig_cc_ro = new GrowableArray<SigEntry>((method != nullptr) ? method->size_of_parameters() : 1);
2809 }
2810 
2811 // See if we can save space by sharing the same entry for VIEP and VIEP(RO),
2812 // or the same entry for VEP and VIEP(RO).
2813 CodeOffsets::Entries CompiledEntrySignature::c1_inline_ro_entry_type() const {
2814   if (!has_scalarized_args()) {
2815     // VEP/VIEP/VIEP(RO) all share the same entry. There's no packing.
2816     return CodeOffsets::Verified_Entry;
2817   }
2818   if (_method->is_static()) {
2819     // Static methods don't need VIEP(RO)
2820     return CodeOffsets::Verified_Entry;
2821   }
2822 
2823   if (has_inline_recv()) {
2824     if (num_inline_args() == 1) {
2825       // Share same entry for VIEP and VIEP(RO).
2826       // This is quite common: we have an instance method in an InlineKlass that has
2827       // no inline type args other than <this>.
2828       return CodeOffsets::Verified_Inline_Entry;
2829     } else {
2830       assert(num_inline_args() > 1, "must be");
2831       // No sharing:
2832       //   VIEP(RO) -- <this> is passed as object
2833       //   VEP      -- <this> is passed as fields
2834       return CodeOffsets::Verified_Inline_Entry_RO;
2835     }

2836   }
2837 
2838   // Either a static method, or <this> is not an inline type
2839   if (args_on_stack_cc() != args_on_stack_cc_ro()) {
2840     // No sharing:
2841     // Some arguments are passed on the stack, and we have inserted reserved entries
2842     // into the VEP, but we never insert reserved entries into the VIEP(RO).
2843     return CodeOffsets::Verified_Inline_Entry_RO;
2844   } else {
2845     // Share same entry for VEP and VIEP(RO).
2846     return CodeOffsets::Verified_Entry;
2847   }
2848 }
2849 
2850 // Returns all super methods (transitive) in classes and interfaces that are overridden by the current method.
2851 GrowableArray<Method*>* CompiledEntrySignature::get_supers() {
2852   if (_supers != nullptr) {
2853     return _supers;
2854   }
2855   _supers = new GrowableArray<Method*>();
2856   // Skip private, static, and <init> methods
2857   if (_method->is_private() || _method->is_static() || _method->is_object_constructor()) {
2858     return _supers;
2859   }
2860   Symbol* name = _method->name();
2861   Symbol* signature = _method->signature();
2862   const Klass* holder = _method->method_holder()->super();
2863   Symbol* holder_name = holder->name();
2864   ThreadInVMfromUnknown tiv;
2865   JavaThread* current = JavaThread::current();
2866   HandleMark hm(current);
2867   Handle loader(current, _method->method_holder()->class_loader());
2868 
2869   // Walk up the class hierarchy and search for super methods
2870   while (holder != nullptr) {
2871     Method* super_method = holder->lookup_method(name, signature);
2872     if (super_method == nullptr) {
2873       break;
2874     }
2875     if (!super_method->is_static() && !super_method->is_private() &&
2876         (!super_method->is_package_private() ||
2877          super_method->method_holder()->is_same_class_package(loader(), holder_name))) {
2878       _supers->push(super_method);
2879     }
2880     holder = super_method->method_holder()->super();
2881   }
2882   // Search interfaces for super methods
2883   Array<InstanceKlass*>* interfaces = _method->method_holder()->transitive_interfaces();
2884   for (int i = 0; i < interfaces->length(); ++i) {
2885     Method* m = interfaces->at(i)->lookup_method(name, signature);
2886     if (m != nullptr && !m->is_static() && m->is_public()) {
2887       _supers->push(m);
2888     }
2889   }
2890   return _supers;
2891 }
2892 
2893 // Iterate over arguments and compute scalarized and non-scalarized signatures
2894 void CompiledEntrySignature::compute_calling_conventions(bool init) {
2895   bool has_scalarized = false;
2896   if (_method != nullptr) {
2897     InstanceKlass* holder = _method->method_holder();
2898     int arg_num = 0;
2899     if (!_method->is_static()) {
2900       // We shouldn't scalarize 'this' in a value class constructor
2901       if (holder->is_inline_klass() && InlineKlass::cast(holder)->can_be_passed_as_fields() && !_method->is_object_constructor() &&
2902           (init || _method->is_scalarized_arg(arg_num))) {
2903         _sig_cc->appendAll(InlineKlass::cast(holder)->extended_sig());
2904         has_scalarized = true;
2905         _has_inline_recv = true;
2906         _num_inline_args++;
2907       } else {
2908         SigEntry::add_entry(_sig_cc, T_OBJECT, holder->name());
2909       }
2910       SigEntry::add_entry(_sig, T_OBJECT, holder->name());
2911       SigEntry::add_entry(_sig_cc_ro, T_OBJECT, holder->name());
2912       arg_num++;
2913     }
2914     for (SignatureStream ss(_method->signature()); !ss.at_return_type(); ss.next()) {
2915       BasicType bt = ss.type();
2916       if (bt == T_OBJECT) {
2917         InlineKlass* vk = ss.as_inline_klass(holder);
2918         if (vk != nullptr && vk->can_be_passed_as_fields() && (init || _method->is_scalarized_arg(arg_num))) {
2919           // Check for a calling convention mismatch with super method(s)
2920           bool scalar_super = false;
2921           bool non_scalar_super = false;
2922           GrowableArray<Method*>* supers = get_supers();
2923           for (int i = 0; i < supers->length(); ++i) {
2924             Method* super_method = supers->at(i);
2925             if (super_method->is_scalarized_arg(arg_num)) {
2926               scalar_super = true;
2927             } else {
2928               non_scalar_super = true;
2929             }
2930           }
2931 #ifdef ASSERT
2932           // Randomly enable below code paths for stress testing
2933           bool stress = init && StressCallingConvention;
2934           if (stress && (os::random() & 1) == 1) {
2935             non_scalar_super = true;
2936             if ((os::random() & 1) == 1) {
2937               scalar_super = true;
2938             }
2939           }
2940 #endif
2941           if (non_scalar_super) {
2942             // Found a super method with a non-scalarized argument. Fall back to the non-scalarized calling convention.
2943             if (scalar_super) {
2944               // Found non-scalar *and* scalar super methods. We can't handle both.
2945               // Mark the scalar method as mismatch and re-compile call sites to use non-scalarized calling convention.
2946               for (int i = 0; i < supers->length(); ++i) {
2947                 Method* super_method = supers->at(i);
2948                 if (super_method->is_scalarized_arg(arg_num) DEBUG_ONLY(|| (stress && (os::random() & 1) == 1))) {
2949                   JavaThread* thread = JavaThread::current();
2950                   HandleMark hm(thread);
2951                   methodHandle mh(thread, super_method);
2952                   DeoptimizationScope deopt_scope;
2953                   {
2954                     // Keep the lock scope minimal. Prevent interference with other
2955                     // dependency checks by setting mismatch and marking within the lock.
2956                     MutexLocker ml(Compile_lock, Mutex::_safepoint_check_flag);
2957                     super_method->set_mismatch();
2958                     CodeCache::mark_for_deoptimization(&deopt_scope, mh());
2959                   }
2960                   deopt_scope.deoptimize_marked();
2961                 }
2962               }
2963             }
2964             // Fall back to non-scalarized calling convention
2965             SigEntry::add_entry(_sig_cc, T_OBJECT, ss.as_symbol());
2966             SigEntry::add_entry(_sig_cc_ro, T_OBJECT, ss.as_symbol());
2967           } else {
2968             _num_inline_args++;
2969             has_scalarized = true;
2970             int last = _sig_cc->length();
2971             int last_ro = _sig_cc_ro->length();
2972             _sig_cc->appendAll(vk->extended_sig());
2973             _sig_cc_ro->appendAll(vk->extended_sig());
2974             // Insert InlineTypeNode::NullMarker field right after T_METADATA delimiter
2975             _sig_cc->insert_before(last+1, SigEntry(T_BOOLEAN, -1, nullptr, true));
2976             _sig_cc_ro->insert_before(last_ro+1, SigEntry(T_BOOLEAN, -1, nullptr, true));
2977           }
2978         } else {
2979           SigEntry::add_entry(_sig_cc, T_OBJECT, ss.as_symbol());
2980           SigEntry::add_entry(_sig_cc_ro, T_OBJECT, ss.as_symbol());
2981         }
2982         bt = T_OBJECT;
2983       } else {
2984         SigEntry::add_entry(_sig_cc, ss.type(), ss.as_symbol());
2985         SigEntry::add_entry(_sig_cc_ro, ss.type(), ss.as_symbol());
2986       }
2987       SigEntry::add_entry(_sig, bt, ss.as_symbol());
2988       if (bt != T_VOID) {
2989         arg_num++;
2990       }
2991     }
2992   }
2993 
2994   // Compute the non-scalarized calling convention
2995   _regs = NEW_RESOURCE_ARRAY(VMRegPair, _sig->length());
2996   _args_on_stack = SharedRuntime::java_calling_convention(_sig, _regs);
2997 
2998   // Compute the scalarized calling conventions if there are scalarized inline types in the signature
2999   if (has_scalarized && !_method->is_native()) {
3000     _regs_cc = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc->length());
3001     _args_on_stack_cc = SharedRuntime::java_calling_convention(_sig_cc, _regs_cc);
3002 
3003     _regs_cc_ro = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc_ro->length());
3004     _args_on_stack_cc_ro = SharedRuntime::java_calling_convention(_sig_cc_ro, _regs_cc_ro);
3005 
3006     _c1_needs_stack_repair = (_args_on_stack_cc < _args_on_stack) || (_args_on_stack_cc_ro < _args_on_stack);
3007     _c2_needs_stack_repair = (_args_on_stack_cc > _args_on_stack) || (_args_on_stack_cc > _args_on_stack_cc_ro);
3008 
3009     // Upper bound on stack arguments to avoid hitting the argument limit and
3010     // bailing out of compilation ("unsupported incoming calling sequence").
3011     // TODO we need a reasonable limit (flag?) here
3012     if (MAX2(_args_on_stack_cc, _args_on_stack_cc_ro) <= 60) {
3013       return; // Success
3014     }
3015   }

3016 
3017   // No scalarized args
3018   _sig_cc = _sig;
3019   _regs_cc = _regs;
3020   _args_on_stack_cc = _args_on_stack;
3021 
3022   _sig_cc_ro = _sig;
3023   _regs_cc_ro = _regs;
3024   _args_on_stack_cc_ro = _args_on_stack;
3025 }
3026 
3027 void CompiledEntrySignature::initialize_from_fingerprint(AdapterFingerPrint* fingerprint) {
3028   _has_inline_recv = fingerprint->has_ro_adapter();
3029 
3030   int value_object_count = 0;
3031   BasicType prev_bt = T_ILLEGAL;
3032   bool has_scalarized_arguments = false;
3033   bool long_prev = false;
3034   int long_prev_offset = -1;
3035 
3036   fingerprint->iterate_args([&] (const AdapterFingerPrint::Element& arg) {
3037     BasicType bt = arg.bt();
3038     int offset = arg.offset();
3039 
3040     if (long_prev) {
3041       long_prev = false;
3042       BasicType bt_to_add;
3043       if (bt == T_VOID) {
3044         bt_to_add = T_LONG;
3045       } else {
3046         bt_to_add = T_OBJECT;
3047       }
3048       if (value_object_count == 0) {
3049         SigEntry::add_entry(_sig, bt_to_add);
3050       }
3051       SigEntry::add_entry(_sig_cc, bt_to_add, nullptr, long_prev_offset);
3052       SigEntry::add_entry(_sig_cc_ro, bt_to_add, nullptr, long_prev_offset);
3053     }
3054 
3055     switch (bt) {
3056       case T_VOID:
3057         if (prev_bt != T_LONG && prev_bt != T_DOUBLE) {
3058           assert(InlineTypePassFieldsAsArgs, "unexpected end of inline type");
3059           value_object_count--;
3060           SigEntry::add_entry(_sig_cc, T_VOID, nullptr, offset);
3061           SigEntry::add_entry(_sig_cc_ro, T_VOID, nullptr, offset);
3062           assert(value_object_count >= 0, "invalid value object count");
3063         } else {
3064           // Nothing to add for _sig: We already added an addition T_VOID in add_entry() when adding T_LONG or T_DOUBLE.
3065         }
3066         break;
3067       case T_INT:
3068       case T_FLOAT:
3069       case T_DOUBLE:
3070         if (value_object_count == 0) {
3071           SigEntry::add_entry(_sig, bt);
3072         }
3073         SigEntry::add_entry(_sig_cc, bt, nullptr, offset);
3074         SigEntry::add_entry(_sig_cc_ro, bt, nullptr, offset);
3075         break;
3076       case T_LONG:
3077         long_prev = true;
3078         long_prev_offset = offset;
3079         break;
3080       case T_BOOLEAN:
3081       case T_CHAR:
3082       case T_BYTE:
3083       case T_SHORT:
3084       case T_OBJECT:
3085       case T_ARRAY:
3086         assert(value_object_count > 0, "must be value object field");
3087         SigEntry::add_entry(_sig_cc, bt, nullptr, offset);
3088         SigEntry::add_entry(_sig_cc_ro, bt, nullptr, offset);
3089         break;
3090       case T_METADATA:
3091         assert(InlineTypePassFieldsAsArgs, "unexpected start of inline type");
3092         if (value_object_count == 0) {
3093           SigEntry::add_entry(_sig, T_OBJECT);
3094         }
3095         SigEntry::add_entry(_sig_cc, T_METADATA, nullptr, offset);
3096         SigEntry::add_entry(_sig_cc_ro, T_METADATA, nullptr, offset);
3097         value_object_count++;
3098         has_scalarized_arguments = true;
3099         break;
3100       default: {
3101         fatal("Unexpected BasicType: %s", basictype_to_str(bt));
3102       }
3103     }
3104     prev_bt = bt;
3105   });
3106 
3107   if (long_prev) {
3108     // If previous bt was T_LONG and we reached the end of the signature, we know that it must be a T_OBJECT.
3109     SigEntry::add_entry(_sig, T_OBJECT);
3110     SigEntry::add_entry(_sig_cc, T_OBJECT);
3111     SigEntry::add_entry(_sig_cc_ro, T_OBJECT);
3112   }
3113   assert(value_object_count == 0, "invalid value object count");
3114 
3115   _regs = NEW_RESOURCE_ARRAY(VMRegPair, _sig->length());
3116   _args_on_stack = SharedRuntime::java_calling_convention(_sig, _regs);
3117 
3118   // Compute the scalarized calling conventions if there are scalarized inline types in the signature
3119   if (has_scalarized_arguments) {
3120     _regs_cc = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc->length());
3121     _args_on_stack_cc = SharedRuntime::java_calling_convention(_sig_cc, _regs_cc);
3122 
3123     _regs_cc_ro = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc_ro->length());
3124     _args_on_stack_cc_ro = SharedRuntime::java_calling_convention(_sig_cc_ro, _regs_cc_ro);
3125 
3126     _c1_needs_stack_repair = (_args_on_stack_cc < _args_on_stack) || (_args_on_stack_cc_ro < _args_on_stack);
3127     _c2_needs_stack_repair = (_args_on_stack_cc > _args_on_stack) || (_args_on_stack_cc > _args_on_stack_cc_ro);
3128   } else {
3129     // No scalarized args
3130     _sig_cc = _sig;
3131     _regs_cc = _regs;
3132     _args_on_stack_cc = _args_on_stack;
3133 
3134     _sig_cc_ro = _sig;
3135     _regs_cc_ro = _regs;
3136     _args_on_stack_cc_ro = _args_on_stack;
3137   }
3138 
3139 #ifdef ASSERT
3140   {
3141     AdapterFingerPrint* compare_fp = AdapterFingerPrint::allocate(_sig_cc, _has_inline_recv);
3142     assert(fingerprint->equals(compare_fp), "%s - %s", fingerprint->as_string(), compare_fp->as_string());
3143     AdapterFingerPrint::deallocate(compare_fp);
3144   }
3145 #endif
3146 }
3147 
3148 const char* AdapterHandlerEntry::_entry_names[] = {
3149   "i2c", "c2i", "c2i_unverified", "c2i_no_clinit_check"
3150 };
3151 
3152 #ifdef ASSERT
3153 void AdapterHandlerLibrary::verify_adapter_sharing(CompiledEntrySignature& ces, AdapterHandlerEntry* cached_entry) {
3154   // we can only check for the same code if there is any
3155 #ifndef ZERO
3156   AdapterHandlerEntry* comparison_entry = create_adapter(ces, false, true);
3157   assert(comparison_entry->adapter_blob() == nullptr, "no blob should be created when creating an adapter for comparison");
3158   assert(comparison_entry->compare_code(cached_entry), "code must match");
3159   // Release the one just created
3160   AdapterHandlerEntry::deallocate(comparison_entry);
3161 # endif // ZERO
3162 }
3163 #endif /* ASSERT*/
3164 
3165 AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(const methodHandle& method) {
3166   assert(!method->is_abstract(), "abstract methods do not have adapters");
3167   // Use customized signature handler.  Need to lock around updates to
3168   // the _adapter_handler_table (it is not safe for concurrent readers
3169   // and a single writer: this could be fixed if it becomes a
3170   // problem).
3171 
3172   // Fast-path for trivial adapters
3173   AdapterHandlerEntry* entry = get_simple_adapter(method);
3174   if (entry != nullptr) {
3175     return entry;
3176   }
3177 
3178   ResourceMark rm;
3179   bool new_entry = false;
3180 
3181   CompiledEntrySignature ces(method());
3182   ces.compute_calling_conventions();
3183   if (ces.has_scalarized_args()) {
3184     if (!method->has_scalarized_args()) {
3185       method->set_has_scalarized_args();
3186     }
3187     if (ces.c1_needs_stack_repair()) {
3188       method->set_c1_needs_stack_repair();
3189     }
3190     if (ces.c2_needs_stack_repair() && !method->c2_needs_stack_repair()) {
3191       method->set_c2_needs_stack_repair();
3192     }
3193   }
3194 




3195   {
3196     MutexLocker mu(AdapterHandlerLibrary_lock);
3197 
3198     // Lookup method signature's fingerprint
3199     entry = lookup(ces.sig_cc(), ces.has_inline_recv());
3200 
3201     if (entry != nullptr) {
3202 #ifndef ZERO
3203       assert(entry->is_linked(), "AdapterHandlerEntry must have been linked");
3204 #endif
3205 #ifdef ASSERT
3206       if (!entry->in_aot_cache() && VerifyAdapterSharing) {
3207         verify_adapter_sharing(ces, entry);
3208       }
3209 #endif
3210     } else {
3211       entry = create_adapter(ces, /* allocate_code_blob */ true);
3212       if (entry != nullptr) {
3213         new_entry = true;
3214       }
3215     }
3216   }
3217 
3218   // Outside of the lock
3219   if (new_entry) {
3220     post_adapter_creation(entry);
3221   }
3222   return entry;
3223 }
3224 
3225 void AdapterHandlerLibrary::lookup_aot_cache(AdapterHandlerEntry* handler) {
3226   ResourceMark rm;
3227   const char* name = AdapterHandlerLibrary::name(handler);
3228   const uint32_t id = AdapterHandlerLibrary::id(handler);
3229 
3230   CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::Adapter, id, name);
3231   if (blob != nullptr) {

3246   }
3247   insts_size = adapter_blob->code_size();
3248   st->print_cr("i2c argument handler for: %s %s (%d bytes generated)",
3249                 handler->fingerprint()->as_basic_args_string(),
3250                 handler->fingerprint()->as_string(), insts_size);
3251   st->print_cr("c2i argument handler starts at " INTPTR_FORMAT, p2i(handler->get_c2i_entry()));
3252   if (Verbose || PrintStubCode) {
3253     address first_pc = adapter_blob->content_begin();
3254     if (first_pc != nullptr) {
3255       Disassembler::decode(first_pc, first_pc + insts_size, st, &adapter_blob->asm_remarks());
3256       st->cr();
3257     }
3258   }
3259 }
3260 #endif // PRODUCT
3261 
3262 void AdapterHandlerLibrary::address_to_offset(address entry_address[AdapterBlob::ENTRY_COUNT],
3263                                               int entry_offset[AdapterBlob::ENTRY_COUNT]) {
3264   entry_offset[AdapterBlob::I2C] = 0;
3265   entry_offset[AdapterBlob::C2I] = entry_address[AdapterBlob::C2I] - entry_address[AdapterBlob::I2C];
3266   entry_offset[AdapterBlob::C2I_Inline] = entry_address[AdapterBlob::C2I_Inline] - entry_address[AdapterBlob::I2C];
3267   entry_offset[AdapterBlob::C2I_Inline_RO] = entry_address[AdapterBlob::C2I_Inline_RO] - entry_address[AdapterBlob::I2C];
3268   entry_offset[AdapterBlob::C2I_Unverified] = entry_address[AdapterBlob::C2I_Unverified] - entry_address[AdapterBlob::I2C];
3269   entry_offset[AdapterBlob::C2I_Unverified_Inline] = entry_address[AdapterBlob::C2I_Unverified_Inline] - entry_address[AdapterBlob::I2C];
3270   if (entry_address[AdapterBlob::C2I_No_Clinit_Check] == nullptr) {
3271     entry_offset[AdapterBlob::C2I_No_Clinit_Check] = -1;
3272   } else {
3273     entry_offset[AdapterBlob::C2I_No_Clinit_Check] = entry_address[AdapterBlob::C2I_No_Clinit_Check] - entry_address[AdapterBlob::I2C];
3274   }
3275 }
3276 
3277 bool AdapterHandlerLibrary::generate_adapter_code(AdapterHandlerEntry* handler,
3278                                                   CompiledEntrySignature& ces,
3279                                                   bool allocate_code_blob,
3280                                                   bool is_transient) {
3281   if (log_is_enabled(Info, perf, class, link)) {
3282     ClassLoader::perf_method_adapters_count()->inc();
3283   }
3284 
3285 #ifndef ZERO
3286   AdapterBlob* adapter_blob = nullptr;
3287   BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
3288   CodeBuffer buffer(buf);
3289   short buffer_locs[20];
3290   buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs,
3291                                          sizeof(buffer_locs)/sizeof(relocInfo));
3292   MacroAssembler masm(&buffer);
3293   address entry_address[AdapterBlob::ENTRY_COUNT];

3294 
3295   // Get a description of the compiled java calling convention and the largest used (VMReg) stack slot usage


3296   SharedRuntime::generate_i2c2i_adapters(&masm,
3297                                          ces.args_on_stack(),
3298                                          ces.sig(),
3299                                          ces.regs(),
3300                                          ces.sig_cc(),
3301                                          ces.regs_cc(),
3302                                          ces.sig_cc_ro(),
3303                                          ces.regs_cc_ro(),
3304                                          entry_address,
3305                                          adapter_blob,
3306                                          allocate_code_blob);
3307 
3308   if (ces.has_scalarized_args()) {
3309     // Save a C heap allocated version of the scalarized signature and store it in the adapter
3310     GrowableArray<SigEntry>* heap_sig = new (mtInternal) GrowableArray<SigEntry>(ces.sig_cc()->length(), mtInternal);
3311     heap_sig->appendAll(ces.sig_cc());
3312     handler->set_sig_cc(heap_sig);
3313   }
3314   // On zero there is no code to save and no need to create a blob and
3315   // or relocate the handler.
3316   int entry_offset[AdapterBlob::ENTRY_COUNT];
3317   address_to_offset(entry_address, entry_offset);
3318 #ifdef ASSERT
3319   if (VerifyAdapterSharing) {
3320     handler->save_code(buf->code_begin(), buffer.insts_size());
3321     if (is_transient) {
3322       return true;
3323     }
3324   }
3325 #endif

3326   if (adapter_blob == nullptr) {
3327     // CodeCache is full, disable compilation
3328     // Ought to log this but compile log is only per compile thread
3329     // and we're some non descript Java thread.
3330     return false;
3331   }
3332   handler->set_adapter_blob(adapter_blob);
3333   if (!is_transient && AOTCodeCache::is_dumping_adapter()) {
3334     // try to save generated code
3335     const char* name = AdapterHandlerLibrary::name(handler);
3336     const uint32_t id = AdapterHandlerLibrary::id(handler);
3337     bool success = AOTCodeCache::store_code_blob(*adapter_blob, AOTCodeEntry::Adapter, id, name);
3338     assert(success || !AOTCodeCache::is_dumping_adapter(), "caching of adapter must be disabled");
3339   }
3340 #endif // ZERO
3341 
3342 #ifndef PRODUCT
3343   // debugging support
3344   if (PrintAdapterHandlers || PrintStubCode) {
3345     print_adapter_handler_info(tty, handler);
3346   }
3347 #endif
3348 
3349   return true;
3350 }
3351 
3352 AdapterHandlerEntry* AdapterHandlerLibrary::create_adapter(CompiledEntrySignature& ces,
3353                                                            bool allocate_code_blob,
3354                                                            bool is_transient) {
3355   AdapterFingerPrint* fp = AdapterFingerPrint::allocate(ces.sig_cc(), ces.has_inline_recv());
3356 #ifdef ASSERT
3357   // Verify that we can successfully restore the compiled entry signature object.
3358   CompiledEntrySignature ces_verify;
3359   ces_verify.initialize_from_fingerprint(fp);
3360 #endif
3361   AdapterHandlerEntry* handler = AdapterHandlerLibrary::new_entry(fp);
3362   if (!generate_adapter_code(handler, ces, allocate_code_blob, is_transient)) {
3363     AdapterHandlerEntry::deallocate(handler);
3364     return nullptr;
3365   }
3366   if (!is_transient) {
3367     assert_lock_strong(AdapterHandlerLibrary_lock);
3368     _adapter_handler_table->put(fp, handler);
3369   }
3370   return handler;
3371 }
3372 
3373 #if INCLUDE_CDS
3374 void AdapterHandlerEntry::remove_unshareable_info() {
3375 #ifdef ASSERT
3376    _saved_code = nullptr;
3377    _saved_code_length = 0;
3378 #endif // ASSERT
3379    _adapter_blob = nullptr;
3380    _linked = false;
3381    _sig_cc = nullptr;
3382 }
3383 
3384 class CopyAdapterTableToArchive : StackObj {
3385 private:
3386   CompactHashtableWriter* _writer;
3387   ArchiveBuilder* _builder;
3388 public:
3389   CopyAdapterTableToArchive(CompactHashtableWriter* writer) : _writer(writer),
3390                                                              _builder(ArchiveBuilder::current())
3391   {}
3392 
3393   bool do_entry(AdapterFingerPrint* fp, AdapterHandlerEntry* entry) {
3394     LogStreamHandle(Trace, aot) lsh;
3395     if (ArchiveBuilder::current()->has_been_archived((address)entry)) {
3396       assert(ArchiveBuilder::current()->has_been_archived((address)fp), "must be");
3397       AdapterFingerPrint* buffered_fp = ArchiveBuilder::current()->get_buffered_addr(fp);
3398       assert(buffered_fp != nullptr,"sanity check");
3399       AdapterHandlerEntry* buffered_entry = ArchiveBuilder::current()->get_buffered_addr(entry);
3400       assert(buffered_entry != nullptr,"sanity check");
3401 

3441   }
3442 #endif
3443 }
3444 
3445 // This method is used during production run to link archived adapters (stored in AOT Cache)
3446 // to their code in AOT Code Cache
3447 void AdapterHandlerEntry::link() {
3448   ResourceMark rm;
3449   assert(_fingerprint != nullptr, "_fingerprint must not be null");
3450   bool generate_code = false;
3451   // Generate code only if AOTCodeCache is not available, or
3452   // caching adapters is disabled, or we fail to link
3453   // the AdapterHandlerEntry to its code in the AOTCodeCache
3454   if (AOTCodeCache::is_using_adapter()) {
3455     AdapterHandlerLibrary::link_aot_adapter_handler(this);
3456     // If link_aot_adapter_handler() succeeds, _adapter_blob will be non-null
3457     if (_adapter_blob == nullptr) {
3458       log_warning(aot)("Failed to link AdapterHandlerEntry (fp=%s) to its code in the AOT code cache", _fingerprint->as_basic_args_string());
3459       generate_code = true;
3460     }
3461 
3462     if (get_sig_cc() == nullptr) {
3463       // Calling conventions have to be regenerated at runtime and are accessed through method adapters,
3464       // which are archived in the AOT code cache. If the adapters are not regenerated, the
3465       // calling conventions should be regenerated here.
3466       CompiledEntrySignature ces;
3467       ces.initialize_from_fingerprint(_fingerprint);
3468       if (ces.has_scalarized_args()) {
3469         // Save a C heap allocated version of the scalarized signature and store it in the adapter
3470         GrowableArray<SigEntry>* heap_sig = new (mtInternal) GrowableArray<SigEntry>(ces.sig_cc()->length(), mtInternal);
3471         heap_sig->appendAll(ces.sig_cc());
3472         set_sig_cc(heap_sig);
3473       }
3474     }
3475   } else {
3476     generate_code = true;
3477   }
3478 
3479   if (generate_code) {
3480     CompiledEntrySignature ces;
3481     ces.initialize_from_fingerprint(_fingerprint);
3482     if (!AdapterHandlerLibrary::generate_adapter_code(this, ces, true, false)) {
3483       // Don't throw exceptions during VM initialization because java.lang.* classes
3484       // might not have been initialized, causing problems when constructing the
3485       // Java exception object.
3486       vm_exit_during_initialization("Out of space in CodeCache for adapters");
3487     }
3488   }
3489   if (_adapter_blob != nullptr) {
3490     post_adapter_creation(this);
3491   }
3492   assert(_linked, "AdapterHandlerEntry must now be linked");
3493 }
3494 
3495 void AdapterHandlerLibrary::link_aot_adapters() {
3496   uint max_id = 0;
3497   assert(AOTCodeCache::is_using_adapter(), "AOT adapters code should be available");
3498   /* It is possible that some adapters generated in assembly phase are not stored in the cache.
3499    * That implies adapter ids of the adapters in the cache may not be contiguous.
3500    * If the size of the _aot_adapter_handler_table is used to initialize _id_counter, then it may
3501    * result in collision of adapter ids between AOT stored handlers and runtime generated handlers.
3502    * To avoid such situation, initialize the _id_counter with the largest adapter id among the AOT stored handlers.
3503    */
3504   _aot_adapter_handler_table.iterate_all([&](AdapterHandlerEntry* entry) {
3505     assert(!entry->is_linked(), "AdapterHandlerEntry is already linked!");
3506     entry->link();
3507     max_id = MAX2(max_id, entry->id());
3508   });
3509   // Set adapter id to the maximum id found in the AOTCache
3510   assert(_id_counter == 0, "Did not expect new AdapterHandlerEntry to be created at this stage");
3511   _id_counter = max_id;
3512 }
3513 
3514 // This method is called during production run to lookup simple adapters
3515 // in the archived adapter handler table
3516 void AdapterHandlerLibrary::lookup_simple_adapters() {
3517   assert(!_aot_adapter_handler_table.empty(), "archived adapter handler table is empty");
3518 
3519   MutexLocker mu(AdapterHandlerLibrary_lock);
3520   ResourceMark rm;
3521   CompiledEntrySignature no_args;
3522   no_args.compute_calling_conventions();
3523   _no_arg_handler = lookup(no_args.sig_cc(), no_args.has_inline_recv());
3524 
3525   CompiledEntrySignature obj_args;
3526   SigEntry::add_entry(obj_args.sig(), T_OBJECT);
3527   obj_args.compute_calling_conventions();
3528   _obj_arg_handler = lookup(obj_args.sig_cc(), obj_args.has_inline_recv());
3529 
3530   CompiledEntrySignature int_args;
3531   SigEntry::add_entry(int_args.sig(), T_INT);
3532   int_args.compute_calling_conventions();
3533   _int_arg_handler = lookup(int_args.sig_cc(), int_args.has_inline_recv());
3534 
3535   CompiledEntrySignature obj_int_args;
3536   SigEntry::add_entry(obj_int_args.sig(), T_OBJECT);
3537   SigEntry::add_entry(obj_int_args.sig(), T_INT);
3538   obj_int_args.compute_calling_conventions();
3539   _obj_int_arg_handler = lookup(obj_int_args.sig_cc(), obj_int_args.has_inline_recv());
3540 
3541   CompiledEntrySignature obj_obj_args;
3542   SigEntry::add_entry(obj_obj_args.sig(), T_OBJECT);
3543   SigEntry::add_entry(obj_obj_args.sig(), T_OBJECT);
3544   obj_obj_args.compute_calling_conventions();
3545   _obj_obj_arg_handler = lookup(obj_obj_args.sig_cc(), obj_obj_args.has_inline_recv());
3546 
3547   assert(_no_arg_handler != nullptr &&
3548          _obj_arg_handler != nullptr &&
3549          _int_arg_handler != nullptr &&
3550          _obj_int_arg_handler != nullptr &&
3551          _obj_obj_arg_handler != nullptr, "Initial adapters not found in archived adapter handler table");
3552   assert(_no_arg_handler->is_linked() &&
3553          _obj_arg_handler->is_linked() &&
3554          _int_arg_handler->is_linked() &&
3555          _obj_int_arg_handler->is_linked() &&
3556          _obj_obj_arg_handler->is_linked(), "Initial adapters not in linked state");
3557 }
3558 #endif // INCLUDE_CDS
3559 
3560 void AdapterHandlerEntry::metaspace_pointers_do(MetaspaceClosure* it) {
3561   LogStreamHandle(Trace, aot) lsh;
3562   if (lsh.is_enabled()) {
3563     lsh.print("Iter(AdapterHandlerEntry): %p(%s)", this, _fingerprint->as_basic_args_string());
3564     lsh.cr();
3565   }
3566   it->push(&_fingerprint);
3567 }
3568 
3569 AdapterHandlerEntry::~AdapterHandlerEntry() {
3570   if (_fingerprint != nullptr) {
3571     AdapterFingerPrint::deallocate(_fingerprint);
3572     _fingerprint = nullptr;
3573   }
3574   if (_sig_cc != nullptr) {
3575     delete _sig_cc;
3576   }
3577 #ifdef ASSERT
3578   FREE_C_HEAP_ARRAY(unsigned char, _saved_code);
3579 #endif
3580   FreeHeap(this);
3581 }
3582 
3583 
3584 #ifdef ASSERT
3585 // Capture the code before relocation so that it can be compared
3586 // against other versions.  If the code is captured after relocation
3587 // then relative instructions won't be equivalent.
3588 void AdapterHandlerEntry::save_code(unsigned char* buffer, int length) {
3589   _saved_code = NEW_C_HEAP_ARRAY(unsigned char, length, mtCode);
3590   _saved_code_length = length;
3591   memcpy(_saved_code, buffer, length);
3592 }
3593 
3594 
3595 bool AdapterHandlerEntry::compare_code(AdapterHandlerEntry* other) {
3596   assert(_saved_code != nullptr && other->_saved_code != nullptr, "code not saved");

3644 
3645       struct { double data[20]; } locs_buf;
3646       struct { double data[20]; } stubs_locs_buf;
3647       buffer.insts()->initialize_shared_locs((relocInfo*)&locs_buf, sizeof(locs_buf) / sizeof(relocInfo));
3648 #if defined(AARCH64) || defined(PPC64)
3649       // On AArch64 with ZGC and nmethod entry barriers, we need all oops to be
3650       // in the constant pool to ensure ordering between the barrier and oops
3651       // accesses. For native_wrappers we need a constant.
3652       // On PPC64 the continuation enter intrinsic needs the constant pool for the compiled
3653       // static java call that is resolved in the runtime.
3654       if (PPC64_ONLY(method->is_continuation_enter_intrinsic() &&) true) {
3655         buffer.initialize_consts_size(8 PPC64_ONLY(+ 24));
3656       }
3657 #endif
3658       buffer.stubs()->initialize_shared_locs((relocInfo*)&stubs_locs_buf, sizeof(stubs_locs_buf) / sizeof(relocInfo));
3659       MacroAssembler _masm(&buffer);
3660 
3661       // Fill in the signature array, for the calling-convention call.
3662       const int total_args_passed = method->size_of_parameters();
3663 
3664       BasicType stack_sig_bt[16];
3665       VMRegPair stack_regs[16];
3666       BasicType* sig_bt = (total_args_passed <= 16) ? stack_sig_bt : NEW_RESOURCE_ARRAY(BasicType, total_args_passed);
3667       VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
3668 
3669       int i = 0;
3670       if (!method->is_static()) {  // Pass in receiver first
3671         sig_bt[i++] = T_OBJECT;
3672       }
3673       SignatureStream ss(method->signature());
3674       for (; !ss.at_return_type(); ss.next()) {
3675         sig_bt[i++] = ss.type();  // Collect remaining bits of signature
3676         if (ss.type() == T_LONG || ss.type() == T_DOUBLE) {
3677           sig_bt[i++] = T_VOID;   // Longs & doubles take 2 Java slots
3678         }
3679       }
3680       assert(i == total_args_passed, "");
3681       BasicType ret_type = ss.type();
3682 
3683       // Now get the compiled-Java arguments layout.
3684       SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
3685 
3686       // Generate the compiled-to-native wrapper code
3687       nm = SharedRuntime::generate_native_wrapper(&_masm, method, compile_id, sig_bt, regs, ret_type);
3688 
3689       if (nm != nullptr) {
3690         {
3691           MutexLocker pl(NMethodState_lock, Mutex::_no_safepoint_check_flag);
3692           if (nm->make_in_use()) {
3693             method->set_code(method, nm);
3694           }
3695         }
3696 
3697         DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, CompileBroker::compiler(CompLevel_simple));
3698         if (directive->PrintAssemblyOption) {
3699           nm->print_code();
3700         }
3701         DirectivesStack::release(directive);

3909       if (b == handler->adapter_blob()) {
3910         found = true;
3911         st->print("Adapter for signature: ");
3912         handler->print_adapter_on(st);
3913         return false; // abort iteration
3914       } else {
3915         return true; // keep looking
3916       }
3917     };
3918     assert_locked_or_safepoint(AdapterHandlerLibrary_lock);
3919     _adapter_handler_table->iterate(findblob_runtime_table);
3920   }
3921   assert(found, "Should have found handler");
3922 }
3923 
3924 void AdapterHandlerEntry::print_adapter_on(outputStream* st) const {
3925   st->print("AHE@" INTPTR_FORMAT ": %s", p2i(this), fingerprint()->as_string());
3926   if (adapter_blob() != nullptr) {
3927     st->print(" i2c: " INTPTR_FORMAT, p2i(get_i2c_entry()));
3928     st->print(" c2i: " INTPTR_FORMAT, p2i(get_c2i_entry()));
3929     st->print(" c2iVE: " INTPTR_FORMAT, p2i(get_c2i_inline_entry()));
3930     st->print(" c2iVROE: " INTPTR_FORMAT, p2i(get_c2i_inline_ro_entry()));
3931     st->print(" c2iUE: " INTPTR_FORMAT, p2i(get_c2i_unverified_entry()));
3932     st->print(" c2iUVE: " INTPTR_FORMAT, p2i(get_c2i_unverified_inline_entry()));
3933     if (get_c2i_no_clinit_check_entry() != nullptr) {
3934       st->print(" c2iNCI: " INTPTR_FORMAT, p2i(get_c2i_no_clinit_check_entry()));
3935     }
3936   }
3937   st->cr();
3938 }
3939 
3940 #ifndef PRODUCT
3941 
3942 void AdapterHandlerLibrary::print_statistics() {
3943   print_table_statistics();
3944 }
3945 
3946 #endif /* PRODUCT */
3947 
3948 JRT_LEAF(void, SharedRuntime::enable_stack_reserved_zone(JavaThread* current))
3949   assert(current == JavaThread::current(), "pre-condition");
3950   StackOverflow* overflow_state = current->stack_overflow_state();
3951   overflow_state->enable_stack_reserved_zone(/*check_if_disabled*/true);
3952   overflow_state->set_reserved_stack_activation(current->stack_base());

3999         event.set_method(method);
4000         event.commit();
4001       }
4002     }
4003   }
4004   return activation;
4005 }
4006 
4007 void SharedRuntime::on_slowpath_allocation_exit(JavaThread* current) {
4008   // After any safepoint, just before going back to compiled code,
4009   // we inform the GC that we will be doing initializing writes to
4010   // this object in the future without emitting card-marks, so
4011   // GC may take any compensating steps.
4012 
4013   oop new_obj = current->vm_result_oop();
4014   if (new_obj == nullptr) return;
4015 
4016   BarrierSet *bs = BarrierSet::barrier_set();
4017   bs->on_slowpath_allocation_exit(current, new_obj);
4018 }
4019 
4020 // We are at a compiled code to interpreter call. We need backing
4021 // buffers for all inline type arguments. Allocate an object array to
4022 // hold them (convenient because once we're done with it we don't have
4023 // to worry about freeing it).
4024 oop SharedRuntime::allocate_inline_types_impl(JavaThread* current, methodHandle callee, bool allocate_receiver, TRAPS) {
4025   assert(InlineTypePassFieldsAsArgs, "no reason to call this");
4026   ResourceMark rm;
4027 
4028   int nb_slots = 0;
4029   InstanceKlass* holder = callee->method_holder();
4030   allocate_receiver &= !callee->is_static() && holder->is_inline_klass() && callee->is_scalarized_arg(0);
4031   if (allocate_receiver) {
4032     nb_slots++;
4033   }
4034   int arg_num = callee->is_static() ? 0 : 1;
4035   for (SignatureStream ss(callee->signature()); !ss.at_return_type(); ss.next()) {
4036     BasicType bt = ss.type();
4037     if (bt == T_OBJECT && callee->is_scalarized_arg(arg_num)) {
4038       nb_slots++;
4039     }
4040     if (bt != T_VOID) {
4041       arg_num++;
4042     }
4043   }
4044   objArrayOop array_oop = oopFactory::new_objectArray(nb_slots, CHECK_NULL);
4045   objArrayHandle array(THREAD, array_oop);
4046   arg_num = callee->is_static() ? 0 : 1;
4047   int i = 0;
4048   if (allocate_receiver) {
4049     InlineKlass* vk = InlineKlass::cast(holder);
4050     oop res = vk->allocate_instance(CHECK_NULL);
4051     array->obj_at_put(i++, res);
4052   }
4053   for (SignatureStream ss(callee->signature()); !ss.at_return_type(); ss.next()) {
4054     BasicType bt = ss.type();
4055     if (bt == T_OBJECT && callee->is_scalarized_arg(arg_num)) {
4056       InlineKlass* vk = ss.as_inline_klass(holder);
4057       assert(vk != nullptr, "Unexpected klass");
4058       oop res = vk->allocate_instance(CHECK_NULL);
4059       array->obj_at_put(i++, res);
4060     }
4061     if (bt != T_VOID) {
4062       arg_num++;
4063     }
4064   }
4065   return array();
4066 }
4067 
4068 JRT_ENTRY(void, SharedRuntime::allocate_inline_types(JavaThread* current, Method* callee_method, bool allocate_receiver))
4069   methodHandle callee(current, callee_method);
4070   oop array = SharedRuntime::allocate_inline_types_impl(current, callee, allocate_receiver, CHECK);
4071   current->set_vm_result_oop(array);
4072   current->set_vm_result_metadata(callee()); // TODO: required to keep callee live?
4073 JRT_END
4074 
4075 // We're returning from an interpreted method: load each field into a
4076 // register following the calling convention
4077 JRT_LEAF(void, SharedRuntime::load_inline_type_fields_in_regs(JavaThread* current, oopDesc* res))
4078 {
4079   assert(res->klass()->is_inline_klass(), "only inline types here");
4080   ResourceMark rm;
4081   RegisterMap reg_map(current,
4082                       RegisterMap::UpdateMap::include,
4083                       RegisterMap::ProcessFrames::include,
4084                       RegisterMap::WalkContinuation::skip);
4085   frame stubFrame = current->last_frame();
4086   frame callerFrame = stubFrame.sender(&reg_map);
4087   assert(callerFrame.is_interpreted_frame(), "should be coming from interpreter");
4088 
4089   InlineKlass* vk = InlineKlass::cast(res->klass());
4090 
4091   const Array<SigEntry>* sig_vk = vk->extended_sig();
4092   const Array<VMRegPair>* regs = vk->return_regs();
4093 
4094   if (regs == nullptr) {
4095     // The fields of the inline klass don't fit in registers, bail out
4096     return;
4097   }
4098 
4099   int j = 1;
4100   for (int i = 0; i < sig_vk->length(); i++) {
4101     BasicType bt = sig_vk->at(i)._bt;
4102     if (bt == T_METADATA) {
4103       continue;
4104     }
4105     if (bt == T_VOID) {
4106       if (sig_vk->at(i-1)._bt == T_LONG ||
4107           sig_vk->at(i-1)._bt == T_DOUBLE) {
4108         j++;
4109       }
4110       continue;
4111     }
4112     int off = sig_vk->at(i)._offset;
4113     assert(off > 0, "offset in object should be positive");
4114     VMRegPair pair = regs->at(j);
4115     address loc = reg_map.location(pair.first(), nullptr);
4116     guarantee(loc != nullptr, "bad register save location");
4117     switch(bt) {
4118     case T_BOOLEAN:
4119       *(jboolean*)loc = res->bool_field(off);
4120       break;
4121     case T_CHAR:
4122       *(jchar*)loc = res->char_field(off);
4123       break;
4124     case T_BYTE:
4125       *(jbyte*)loc = res->byte_field(off);
4126       break;
4127     case T_SHORT:
4128       *(jshort*)loc = res->short_field(off);
4129       break;
4130     case T_INT: {
4131       *(jint*)loc = res->int_field(off);
4132       break;
4133     }
4134     case T_LONG:
4135 #ifdef _LP64
4136       *(intptr_t*)loc = res->long_field(off);
4137 #else
4138       Unimplemented();
4139 #endif
4140       break;
4141     case T_OBJECT:
4142     case T_ARRAY: {
4143       *(oop*)loc = res->obj_field(off);
4144       break;
4145     }
4146     case T_FLOAT:
4147       *(jfloat*)loc = res->float_field(off);
4148       break;
4149     case T_DOUBLE:
4150       *(jdouble*)loc = res->double_field(off);
4151       break;
4152     default:
4153       ShouldNotReachHere();
4154     }
4155     j++;
4156   }
4157   assert(j == regs->length(), "missed a field?");
4158 
4159 #ifdef ASSERT
4160   VMRegPair pair = regs->at(0);
4161   address loc = reg_map.location(pair.first(), nullptr);
4162   assert(*(oopDesc**)loc == res, "overwritten object");
4163 #endif
4164 
4165   current->set_vm_result_oop(res);
4166 }
4167 JRT_END
4168 
4169 // We've returned to an interpreted method, the interpreter needs a
4170 // reference to an inline type instance. Allocate it and initialize it
4171 // from field's values in registers.
4172 JRT_BLOCK_ENTRY(void, SharedRuntime::store_inline_type_fields_to_buf(JavaThread* current, intptr_t res))
4173 {
4174   ResourceMark rm;
4175   RegisterMap reg_map(current,
4176                       RegisterMap::UpdateMap::include,
4177                       RegisterMap::ProcessFrames::include,
4178                       RegisterMap::WalkContinuation::skip);
4179   frame stubFrame = current->last_frame();
4180   frame callerFrame = stubFrame.sender(&reg_map);
4181 
4182 #ifdef ASSERT
4183   InlineKlass* verif_vk = InlineKlass::returned_inline_klass(reg_map);
4184 #endif
4185 
4186   if (!is_set_nth_bit(res, 0)) {
4187     // We're not returning with inline type fields in registers (the
4188     // calling convention didn't allow it for this inline klass)
4189     assert(!Metaspace::contains((void*)res), "should be oop or pointer in buffer area");
4190     current->set_vm_result_oop((oopDesc*)res);
4191     assert(verif_vk == nullptr, "broken calling convention");
4192     return;
4193   }
4194 
4195   clear_nth_bit(res, 0);
4196   InlineKlass* vk = (InlineKlass*)res;
4197   assert(verif_vk == vk, "broken calling convention");
4198   assert(Metaspace::contains((void*)res), "should be klass");
4199 
4200   // Allocate handles for every oop field so they are safe in case of
4201   // a safepoint when allocating
4202   GrowableArray<Handle> handles;
4203   vk->save_oop_fields(reg_map, handles);
4204 
4205   // It's unsafe to safepoint until we are here
4206   JRT_BLOCK;
4207   {
4208     JavaThread* THREAD = current;
4209     oop vt = vk->realloc_result(reg_map, handles, CHECK);
4210     current->set_vm_result_oop(vt);
4211   }
4212   JRT_BLOCK_END;
4213 }
4214 JRT_END
< prev index next >