< 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/exceptions.hpp"
  86 #include "utilities/globalDefinitions.hpp"
  87 #include "utilities/hashTable.hpp"
  88 #include "utilities/macros.hpp"
  89 #include "utilities/xmlstream.hpp"
  90 #ifdef COMPILER1
  91 #include "c1/c1_Runtime1.hpp"
  92 #endif
  93 #ifdef COMPILER2
  94 #include "opto/runtime.hpp"

1167 // for a call current in progress, i.e., arguments has been pushed on stack
1168 // but callee has not been invoked yet.  Caller frame must be compiled.
1169 Handle SharedRuntime::find_callee_info_helper(vframeStream& vfst, Bytecodes::Code& bc,
1170                                               CallInfo& callinfo, TRAPS) {
1171   Handle receiver;
1172   Handle nullHandle;  // create a handy null handle for exception returns
1173   JavaThread* current = THREAD;
1174 
1175   assert(!vfst.at_end(), "Java frame must exist");
1176 
1177   // Find caller and bci from vframe
1178   methodHandle caller(current, vfst.method());
1179   int          bci   = vfst.bci();
1180 
1181   if (caller->is_continuation_enter_intrinsic()) {
1182     bc = Bytecodes::_invokestatic;
1183     LinkResolver::resolve_continuation_enter(callinfo, CHECK_NH);
1184     return receiver;
1185   }
1186 
















1187   Bytecode_invoke bytecode(caller, bci);
1188   int bytecode_index = bytecode.index();
1189   bc = bytecode.invoke_code();
1190 
1191   methodHandle attached_method(current, extract_attached_method(vfst));
1192   if (attached_method.not_null()) {
1193     Method* callee = bytecode.static_target(CHECK_NH);
1194     vmIntrinsics::ID id = callee->intrinsic_id();
1195     // When VM replaces MH.invokeBasic/linkTo* call with a direct/virtual call,
1196     // it attaches statically resolved method to the call site.
1197     if (MethodHandles::is_signature_polymorphic(id) &&
1198         MethodHandles::is_signature_polymorphic_intrinsic(id)) {
1199       bc = MethodHandles::signature_polymorphic_intrinsic_bytecode(id);
1200 
1201       // Adjust invocation mode according to the attached method.
1202       switch (bc) {
1203         case Bytecodes::_invokevirtual:
1204           if (attached_method->method_holder()->is_interface()) {
1205             bc = Bytecodes::_invokeinterface;
1206           }
1207           break;
1208         case Bytecodes::_invokeinterface:
1209           if (!attached_method->method_holder()->is_interface()) {
1210             bc = Bytecodes::_invokevirtual;
1211           }
1212           break;
1213         case Bytecodes::_invokehandle:
1214           if (!MethodHandles::is_signature_polymorphic_method(attached_method())) {
1215             bc = attached_method->is_static() ? Bytecodes::_invokestatic
1216                                               : Bytecodes::_invokevirtual;
1217           }
1218           break;
1219         default:
1220           break;
1221       }






1222     }
1223   }
1224 
1225   assert(bc != Bytecodes::_illegal, "not initialized");
1226 
1227   bool has_receiver = bc != Bytecodes::_invokestatic &&
1228                       bc != Bytecodes::_invokedynamic &&
1229                       bc != Bytecodes::_invokehandle;

1230 
1231   // Find receiver for non-static call
1232   if (has_receiver) {
1233     // This register map must be update since we need to find the receiver for
1234     // compiled frames. The receiver might be in a register.
1235     RegisterMap reg_map2(current,
1236                          RegisterMap::UpdateMap::include,
1237                          RegisterMap::ProcessFrames::include,
1238                          RegisterMap::WalkContinuation::skip);
1239     frame stubFrame   = current->last_frame();
1240     // Caller-frame is a compiled frame
1241     frame callerFrame = stubFrame.sender(&reg_map2);
1242 
1243     if (attached_method.is_null()) {
1244       Method* callee = bytecode.static_target(CHECK_NH);

1245       if (callee == nullptr) {
1246         THROW_(vmSymbols::java_lang_NoSuchMethodException(), nullHandle);
1247       }
1248     }
1249 
1250     // Retrieve from a compiled argument list
1251     receiver = Handle(current, callerFrame.retrieve_receiver(&reg_map2));
1252     assert(oopDesc::is_oop_or_null(receiver()), "");
1253 
1254     if (receiver.is_null()) {
1255       THROW_(vmSymbols::java_lang_NullPointerException(), nullHandle);










1256     }
1257   }
1258 
1259   // Resolve method
1260   if (attached_method.not_null()) {
1261     // Parameterized by attached method.
1262     LinkResolver::resolve_invoke(callinfo, receiver, attached_method, bc, CHECK_NH);
1263   } else {
1264     // Parameterized by bytecode.
1265     constantPoolHandle constants(current, caller->constants());
1266     LinkResolver::resolve_invoke(callinfo, receiver, constants, bytecode_index, bc, CHECK_NH);
1267   }
1268 
1269 #ifdef ASSERT
1270   // Check that the receiver klass is of the right subtype and that it is initialized for virtual calls
1271   if (has_receiver) {
1272     assert(receiver.not_null(), "should have thrown exception");
1273     Klass* receiver_klass = receiver->klass();
1274     Klass* rk = nullptr;
1275     if (attached_method.not_null()) {
1276       // In case there's resolved method attached, use its holder during the check.
1277       rk = attached_method->method_holder();
1278     } else {
1279       // Klass is already loaded.
1280       constantPoolHandle constants(current, caller->constants());
1281       rk = constants->klass_ref_at(bytecode_index, bc, CHECK_NH);
1282     }
1283     Klass* static_receiver_klass = rk;
1284     assert(receiver_klass->is_subtype_of(static_receiver_klass),
1285            "actual receiver must be subclass of static receiver klass");
1286     if (receiver_klass->is_instance_klass()) {
1287       if (InstanceKlass::cast(receiver_klass)->is_not_initialized()) {
1288         tty->print_cr("ERROR: Klass not yet initialized!!");
1289         receiver_klass->print();
1290       }
1291       assert(!InstanceKlass::cast(receiver_klass)->is_not_initialized(), "receiver_klass must be initialized");
1292     }
1293   }
1294 #endif
1295 
1296   return receiver;
1297 }
1298 
1299 methodHandle SharedRuntime::find_callee_method(TRAPS) {
1300   JavaThread* current = THREAD;
1301   ResourceMark rm(current);
1302   // We need first to check if any Java activations (compiled, interpreted)
1303   // exist on the stack since last JavaCall.  If not, we need
1304   // to get the target method from the JavaCall wrapper.
1305   vframeStream vfst(current, true);  // Do not skip any javaCalls
1306   methodHandle callee_method;
1307   if (vfst.at_end()) {
1308     // No Java frames were found on stack since we did the JavaCall.
1309     // Hence the stack can only contain an entry_frame.  We need to
1310     // find the target method from the stub frame.
1311     RegisterMap reg_map(current,
1312                         RegisterMap::UpdateMap::skip,
1313                         RegisterMap::ProcessFrames::include,
1314                         RegisterMap::WalkContinuation::skip);
1315     frame fr = current->last_frame();
1316     assert(fr.is_runtime_frame(), "must be a runtimeStub");
1317     fr = fr.sender(&reg_map);
1318     assert(fr.is_entry_frame(), "must be");
1319     // fr is now pointing to the entry frame.
1320     callee_method = methodHandle(current, fr.entry_frame_call_wrapper()->callee_method());
1321   } else {
1322     Bytecodes::Code bc;
1323     CallInfo callinfo;
1324     find_callee_info_helper(vfst, bc, callinfo, CHECK_(methodHandle()));




1325     callee_method = methodHandle(current, callinfo.selected_method());
1326   }
1327   assert(callee_method()->is_method(), "must be");
1328   return callee_method;
1329 }
1330 
1331 // Resolves a call.
1332 methodHandle SharedRuntime::resolve_helper(bool is_virtual, bool is_optimized, TRAPS) {
1333   JavaThread* current = THREAD;
1334   ResourceMark rm(current);
1335   RegisterMap cbl_map(current,
1336                       RegisterMap::UpdateMap::skip,
1337                       RegisterMap::ProcessFrames::include,
1338                       RegisterMap::WalkContinuation::skip);
1339   frame caller_frame = current->last_frame().sender(&cbl_map);
1340 
1341   CodeBlob* caller_cb = caller_frame.cb();
1342   guarantee(caller_cb != nullptr && caller_cb->is_nmethod(), "must be called from compiled method");
1343   nmethod* caller_nm = caller_cb->as_nmethod();
1344 
1345   // determine call info & receiver
1346   // note: a) receiver is null for static calls
1347   //       b) an exception is thrown if receiver is null for non-static calls
1348   CallInfo call_info;
1349   Bytecodes::Code invoke_code = Bytecodes::_illegal;
1350   Handle receiver = find_callee_info(invoke_code, call_info, CHECK_(methodHandle()));
1351 
1352   NoSafepointVerifier nsv;
1353 
1354   methodHandle callee_method(current, call_info.selected_method());





1355 
1356   assert((!is_virtual && invoke_code == Bytecodes::_invokestatic ) ||
1357          (!is_virtual && invoke_code == Bytecodes::_invokespecial) ||
1358          (!is_virtual && invoke_code == Bytecodes::_invokehandle ) ||
1359          (!is_virtual && invoke_code == Bytecodes::_invokedynamic) ||
1360          ( is_virtual && invoke_code != Bytecodes::_invokestatic ), "inconsistent bytecode");
1361 
1362   assert(!caller_nm->is_unloading(), "It should not be unloading");
1363 
1364 #ifndef PRODUCT
1365   // tracing/debugging/statistics
1366   uint *addr = (is_optimized) ? (&_resolve_opt_virtual_ctr) :
1367                  (is_virtual) ? (&_resolve_virtual_ctr) :
1368                                 (&_resolve_static_ctr);
1369   AtomicAccess::inc(addr);
1370 
1371   if (TraceCallFixup) {
1372     ResourceMark rm(current);
1373     tty->print("resolving %s%s (%s) call to",
1374                (is_optimized) ? "optimized " : "", (is_virtual) ? "virtual" : "static",
1375                Bytecodes::name(invoke_code));
1376     callee_method->print_short_name(tty);
1377     tty->print_cr(" at pc: " INTPTR_FORMAT " to code: " INTPTR_FORMAT,
1378                   p2i(caller_frame.pc()), p2i(callee_method->code()));
1379   }
1380 #endif
1381 
1382   if (invoke_code == Bytecodes::_invokestatic) {
1383     assert(callee_method->method_holder()->is_initialized() ||
1384            callee_method->method_holder()->is_reentrant_initialization(current),
1385            "invalid class initialization state for invoke_static");
1386     if (!VM_Version::supports_fast_class_init_checks() && callee_method->needs_clinit_barrier()) {
1387       // In order to keep class initialization check, do not patch call
1388       // site for static call when the class is not fully initialized.
1389       // Proper check is enforced by call site re-resolution on every invocation.
1390       //
1391       // When fast class initialization checks are supported (VM_Version::supports_fast_class_init_checks() == true),
1392       // explicit class initialization check is put in nmethod entry (VEP).
1393       assert(callee_method->method_holder()->is_linked(), "must be");
1394       return callee_method;
1395     }
1396   }
1397 
1398 
1399   // JSR 292 key invariant:
1400   // If the resolved method is a MethodHandle invoke target, the call
1401   // site must be a MethodHandle call site, because the lambda form might tail-call
1402   // leaving the stack in a state unknown to either caller or callee
1403 
1404   // Compute entry points. The computation of the entry points is independent of
1405   // patching the call.
1406 
1407   // Make sure the callee nmethod does not get deoptimized and removed before
1408   // we are done patching the code.
1409 
1410 
1411   CompiledICLocker ml(caller_nm);
1412   if (is_virtual && !is_optimized) {
1413     CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1414     inline_cache->update(&call_info, receiver->klass());
1415   } else {
1416     // Callsite is a direct call - set it to the destination method
1417     CompiledDirectCall* callsite = CompiledDirectCall::before(caller_frame.pc());
1418     callsite->set(callee_method);
1419   }
1420 
1421   return callee_method;
1422 }
1423 
1424 // Inline caches exist only in compiled code
1425 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_ic_miss(JavaThread* current))
1426 #ifdef ASSERT
1427   RegisterMap reg_map(current,
1428                       RegisterMap::UpdateMap::skip,
1429                       RegisterMap::ProcessFrames::include,
1430                       RegisterMap::WalkContinuation::skip);
1431   frame stub_frame = current->last_frame();
1432   assert(stub_frame.is_runtime_frame(), "sanity check");
1433   frame caller_frame = stub_frame.sender(&reg_map);
1434   assert(!caller_frame.is_interpreted_frame() && !caller_frame.is_entry_frame() && !caller_frame.is_upcall_stub_frame(), "unexpected frame");
1435 #endif /* ASSERT */
1436 
1437   methodHandle callee_method;

1438   JRT_BLOCK
1439     callee_method = SharedRuntime::handle_ic_miss_helper(CHECK_NULL);
1440     // Return Method* through TLS
1441     current->set_vm_result_metadata(callee_method());
1442   JRT_BLOCK_END
1443   // return compiled code entry point after potential safepoints
1444   return get_resolved_entry(current, callee_method);
1445 JRT_END
1446 
1447 
1448 // Handle call site that has been made non-entrant
1449 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method(JavaThread* current))
1450   // 6243940 We might end up in here if the callee is deoptimized
1451   // as we race to call it.  We don't want to take a safepoint if
1452   // the caller was interpreted because the caller frame will look
1453   // interpreted to the stack walkers and arguments are now
1454   // "compiled" so it is much better to make this transition
1455   // invisible to the stack walking code. The i2c path will
1456   // place the callee method in the callee_target. It is stashed
1457   // there because if we try and find the callee by normal means a
1458   // safepoint is possible and have trouble gc'ing the compiled args.
1459   RegisterMap reg_map(current,
1460                       RegisterMap::UpdateMap::skip,
1461                       RegisterMap::ProcessFrames::include,
1462                       RegisterMap::WalkContinuation::skip);
1463   frame stub_frame = current->last_frame();
1464   assert(stub_frame.is_runtime_frame(), "sanity check");
1465   frame caller_frame = stub_frame.sender(&reg_map);
1466 
1467   if (caller_frame.is_interpreted_frame() ||
1468       caller_frame.is_entry_frame() ||
1469       caller_frame.is_upcall_stub_frame()) {
1470     Method* callee = current->callee_target();
1471     guarantee(callee != nullptr && callee->is_method(), "bad handshake");
1472     current->set_vm_result_metadata(callee);
1473     current->set_callee_target(nullptr);
1474     if (caller_frame.is_entry_frame() && VM_Version::supports_fast_class_init_checks()) {
1475       // Bypass class initialization checks in c2i when caller is in native.
1476       // JNI calls to static methods don't have class initialization checks.
1477       // Fast class initialization checks are present in c2i adapters and call into
1478       // SharedRuntime::handle_wrong_method() on the slow path.
1479       //
1480       // JVM upcalls may land here as well, but there's a proper check present in
1481       // LinkResolver::resolve_static_call (called from JavaCalls::call_static),
1482       // so bypassing it in c2i adapter is benign.
1483       return callee->get_c2i_no_clinit_check_entry();
1484     } else {
1485       return callee->get_c2i_entry();




1486     }
1487   }
1488 
1489   // Must be compiled to compiled path which is safe to stackwalk
1490   methodHandle callee_method;



1491   JRT_BLOCK
1492     // Force resolving of caller (if we called from compiled frame)
1493     callee_method = SharedRuntime::reresolve_call_site(CHECK_NULL);
1494     current->set_vm_result_metadata(callee_method());
1495   JRT_BLOCK_END
1496   // return compiled code entry point after potential safepoints
1497   return get_resolved_entry(current, callee_method);
1498 JRT_END
1499 
1500 // Handle abstract method call
1501 JRT_BLOCK_ENTRY(address, SharedRuntime::handle_wrong_method_abstract(JavaThread* current))
1502   // Verbose error message for AbstractMethodError.
1503   // Get the called method from the invoke bytecode.
1504   vframeStream vfst(current, true);
1505   assert(!vfst.at_end(), "Java frame must exist");
1506   methodHandle caller(current, vfst.method());
1507   Bytecode_invoke invoke(caller, vfst.bci());
1508   DEBUG_ONLY( invoke.verify(); )
1509 
1510   // Find the compiled caller frame.
1511   RegisterMap reg_map(current,
1512                       RegisterMap::UpdateMap::include,
1513                       RegisterMap::ProcessFrames::include,
1514                       RegisterMap::WalkContinuation::skip);
1515   frame stubFrame = current->last_frame();
1516   assert(stubFrame.is_runtime_frame(), "must be");
1517   frame callerFrame = stubFrame.sender(&reg_map);
1518   assert(callerFrame.is_compiled_frame(), "must be");
1519 
1520   // Install exception and return forward entry.
1521   address res = SharedRuntime::throw_AbstractMethodError_entry();
1522   JRT_BLOCK
1523     methodHandle callee(current, invoke.static_target(current));
1524     if (!callee.is_null()) {
1525       oop recv = callerFrame.retrieve_receiver(&reg_map);
1526       Klass *recv_klass = (recv != nullptr) ? recv->klass() : nullptr;
1527       res = StubRoutines::forward_exception_entry();
1528       LinkResolver::throw_abstract_method_error(callee, recv_klass, CHECK_(res));
1529     }
1530   JRT_BLOCK_END
1531   return res;
1532 JRT_END
1533 
1534 // return verified_code_entry if interp_only_mode is not set for the current thread;
1535 // otherwise return c2i entry.
1536 address SharedRuntime::get_resolved_entry(JavaThread* current, methodHandle callee_method) {
1537   if (current->is_interp_only_mode() && !callee_method->is_special_native_intrinsic()) {
1538     // In interp_only_mode we need to go to the interpreted entry
1539     // The c2i won't patch in this mode -- see fixup_callers_callsite
1540     return callee_method->get_c2i_entry();




















1541   }
1542   assert(callee_method->verified_code_entry() != nullptr, " Jump to zero!");
1543   return callee_method->verified_code_entry();
1544 }
1545 
1546 // resolve a static call and patch code
1547 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_static_call_C(JavaThread* current ))
1548   methodHandle callee_method;

1549   bool enter_special = false;
1550   JRT_BLOCK
1551     callee_method = SharedRuntime::resolve_helper(false, false, CHECK_NULL);
1552     current->set_vm_result_metadata(callee_method());
1553   JRT_BLOCK_END
1554   // return compiled code entry point after potential safepoints
1555   return get_resolved_entry(current, callee_method);
1556 JRT_END
1557 
1558 // resolve virtual call and update inline cache to monomorphic
1559 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_virtual_call_C(JavaThread* current))
1560   methodHandle callee_method;

1561   JRT_BLOCK
1562     callee_method = SharedRuntime::resolve_helper(true, false, CHECK_NULL);
1563     current->set_vm_result_metadata(callee_method());
1564   JRT_BLOCK_END
1565   // return compiled code entry point after potential safepoints
1566   return get_resolved_entry(current, callee_method);
1567 JRT_END
1568 
1569 
1570 // Resolve a virtual call that can be statically bound (e.g., always
1571 // monomorphic, so it has no inline cache).  Patch code to resolved target.
1572 JRT_BLOCK_ENTRY(address, SharedRuntime::resolve_opt_virtual_call_C(JavaThread* current))
1573   methodHandle callee_method;

1574   JRT_BLOCK
1575     callee_method = SharedRuntime::resolve_helper(true, true, CHECK_NULL);
1576     current->set_vm_result_metadata(callee_method());
1577   JRT_BLOCK_END
1578   // return compiled code entry point after potential safepoints
1579   return get_resolved_entry(current, callee_method);
1580 JRT_END
1581 
1582 methodHandle SharedRuntime::handle_ic_miss_helper(TRAPS) {
1583   JavaThread* current = THREAD;
1584   ResourceMark rm(current);
1585   CallInfo call_info;
1586   Bytecodes::Code bc;
1587 
1588   // receiver is null for static calls. An exception is thrown for null
1589   // receivers for non-static calls
1590   Handle receiver = find_callee_info(bc, call_info, CHECK_(methodHandle()));
1591 
1592   methodHandle callee_method(current, call_info.selected_method());
1593 
1594 #ifndef PRODUCT
1595   AtomicAccess::inc(&_ic_miss_ctr);
1596 
1597   // Statistics & Tracing
1598   if (TraceCallFixup) {
1599     ResourceMark rm(current);
1600     tty->print("IC miss (%s) call to", Bytecodes::name(bc));
1601     callee_method->print_short_name(tty);
1602     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1603   }
1604 
1605   if (ICMissHistogram) {
1606     MutexLocker m(VMStatistic_lock);
1607     RegisterMap reg_map(current,
1608                         RegisterMap::UpdateMap::skip,
1609                         RegisterMap::ProcessFrames::include,
1610                         RegisterMap::WalkContinuation::skip);
1611     frame f = current->last_frame().real_sender(&reg_map);// skip runtime stub
1612     // produce statistics under the lock
1613     trace_ic_miss(f.pc());
1614   }
1615 #endif
1616 
1617   // install an event collector so that when a vtable stub is created the
1618   // profiler can be notified via a DYNAMIC_CODE_GENERATED event. The
1619   // event can't be posted when the stub is created as locks are held
1620   // - instead the event will be deferred until the event collector goes
1621   // out of scope.
1622   JvmtiDynamicCodeEventCollector event_collector;
1623 
1624   // Update inline cache to megamorphic. Skip update if we are called from interpreted.
1625   RegisterMap reg_map(current,
1626                       RegisterMap::UpdateMap::skip,
1627                       RegisterMap::ProcessFrames::include,
1628                       RegisterMap::WalkContinuation::skip);
1629   frame caller_frame = current->last_frame().sender(&reg_map);
1630   CodeBlob* cb = caller_frame.cb();
1631   nmethod* caller_nm = cb->as_nmethod();




1632 
1633   CompiledICLocker ml(caller_nm);
1634   CompiledIC* inline_cache = CompiledIC_before(caller_nm, caller_frame.pc());
1635   inline_cache->update(&call_info, receiver()->klass());
1636 
1637   return callee_method;
1638 }
1639 
1640 //
1641 // Resets a call-site in compiled code so it will get resolved again.
1642 // This routines handles both virtual call sites, optimized virtual call
1643 // sites, and static call sites. Typically used to change a call sites
1644 // destination from compiled to interpreted.
1645 //
1646 methodHandle SharedRuntime::reresolve_call_site(TRAPS) {
1647   JavaThread* current = THREAD;
1648   ResourceMark rm(current);
1649   RegisterMap reg_map(current,
1650                       RegisterMap::UpdateMap::skip,
1651                       RegisterMap::ProcessFrames::include,
1652                       RegisterMap::WalkContinuation::skip);
1653   frame stub_frame = current->last_frame();
1654   assert(stub_frame.is_runtime_frame(), "must be a runtimeStub");
1655   frame caller = stub_frame.sender(&reg_map);
1656 
1657   // Do nothing if the frame isn't a live compiled frame.
1658   // nmethod could be deoptimized by the time we get here
1659   // so no update to the caller is needed.
1660 
1661   if ((caller.is_compiled_frame() && !caller.is_deoptimized_frame()) ||
1662       (caller.is_native_frame() && caller.cb()->as_nmethod()->method()->is_continuation_enter_intrinsic())) {
1663 













1664     address pc = caller.pc();
1665 
1666     nmethod* caller_nm = CodeCache::find_nmethod(pc);
1667     assert(caller_nm != nullptr, "did not find caller nmethod");
1668 
1669     // Default call_addr is the location of the "basic" call.
1670     // Determine the address of the call we a reresolving. With
1671     // Inline Caches we will always find a recognizable call.
1672     // With Inline Caches disabled we may or may not find a
1673     // recognizable call. We will always find a call for static
1674     // calls and for optimized virtual calls. For vanilla virtual
1675     // calls it depends on the state of the UseInlineCaches switch.
1676     //
1677     // With Inline Caches disabled we can get here for a virtual call
1678     // for two reasons:
1679     //   1 - calling an abstract method. The vtable for abstract methods
1680     //       will run us thru handle_wrong_method and we will eventually
1681     //       end up in the interpreter to throw the ame.
1682     //   2 - a racing deoptimization. We could be doing a vanilla vtable
1683     //       call and between the time we fetch the entry address and
1684     //       we jump to it the target gets deoptimized. Similar to 1
1685     //       we will wind up in the interprter (thru a c2i with c2).
1686     //
1687     CompiledICLocker ml(caller_nm);
1688     address call_addr = caller_nm->call_instruction_address(pc);
1689 
1690     if (call_addr != nullptr) {
1691       // On x86 the logic for finding a call instruction is blindly checking for a call opcode 5
1692       // bytes back in the instruction stream so we must also check for reloc info.
1693       RelocIterator iter(caller_nm, call_addr, call_addr+1);
1694       bool ret = iter.next(); // Get item
1695       if (ret) {

1696         switch (iter.type()) {
1697           case relocInfo::static_call_type:

1698           case relocInfo::opt_virtual_call_type: {
1699             CompiledDirectCall* cdc = CompiledDirectCall::at(call_addr);
1700             cdc->set_to_clean();



1701             break;
1702           }
1703 
1704           case relocInfo::virtual_call_type: {
1705             // compiled, dispatched call (which used to call an interpreted method)
1706             CompiledIC* inline_cache = CompiledIC_at(caller_nm, call_addr);
1707             inline_cache->set_to_clean();


1708             break;
1709           }
1710           default:
1711             break;
1712         }
1713       }
1714     }
1715   }
1716 
1717   methodHandle callee_method = find_callee_method(CHECK_(methodHandle()));
1718 
1719 
1720 #ifndef PRODUCT
1721   AtomicAccess::inc(&_wrong_method_ctr);
1722 
1723   if (TraceCallFixup) {
1724     ResourceMark rm(current);
1725     tty->print("handle_wrong_method reresolving call to");
1726     callee_method->print_short_name(tty);
1727     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1728   }
1729 #endif
1730 
1731   return callee_method;
1732 }
1733 
1734 address SharedRuntime::handle_unsafe_access(JavaThread* thread, address next_pc) {
1735   // The faulting unsafe accesses should be changed to throw the error
1736   // synchronously instead. Meanwhile the faulting instruction will be
1737   // skipped over (effectively turning it into a no-op) and an
1738   // asynchronous exception will be raised which the thread will
1739   // handle at a later point. If the instruction is a load it will
1740   // return garbage.
1741 
1742   // Request an async exception.
1743   thread->set_pending_unsafe_access_error();
1744 
1745   // Return address of next instruction to execute.

1911   msglen += strlen(caster_klass_description) + strlen(target_klass_description) + strlen(klass_separator) + 3;
1912 
1913   char* message = NEW_RESOURCE_ARRAY_RETURN_NULL(char, msglen);
1914   if (message == nullptr) {
1915     // Shouldn't happen, but don't cause even more problems if it does
1916     message = const_cast<char*>(caster_klass->external_name());
1917   } else {
1918     jio_snprintf(message,
1919                  msglen,
1920                  "class %s cannot be cast to class %s (%s%s%s)",
1921                  caster_name,
1922                  target_name,
1923                  caster_klass_description,
1924                  klass_separator,
1925                  target_klass_description
1926                  );
1927   }
1928   return message;
1929 }
1930 















1931 JRT_LEAF(void, SharedRuntime::reguard_yellow_pages())
1932   (void) JavaThread::current()->stack_overflow_state()->reguard_stack();
1933 JRT_END
1934 
1935 void SharedRuntime::monitor_enter_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) {
1936   if (!SafepointSynchronize::is_synchronizing()) {
1937     // Only try quick_enter() if we're not trying to reach a safepoint
1938     // so that the calling thread reaches the safepoint more quickly.
1939     if (ObjectSynchronizer::quick_enter(obj, lock, current)) {
1940       return;
1941     }
1942   }
1943   // NO_ASYNC required because an async exception on the state transition destructor
1944   // would leave you with the lock held and it would never be released.
1945   // The normal monitorenter NullPointerException is thrown without acquiring a lock
1946   // and the model is that an exception implies the method failed.
1947   JRT_BLOCK_NO_ASYNC
1948   Handle h_obj(THREAD, obj);
1949   ObjectSynchronizer::enter(h_obj, lock, current);
1950   assert(!HAS_PENDING_EXCEPTION, "Should have no exception here");

2144   tty->print_cr("Note 1: counter updates are not MT-safe.");
2145   tty->print_cr("Note 2: %% in major categories are relative to total non-inlined calls;");
2146   tty->print_cr("        %% in nested categories are relative to their category");
2147   tty->print_cr("        (and thus add up to more than 100%% with inlining)");
2148   tty->cr();
2149 
2150   MethodArityHistogram h;
2151 }
2152 #endif
2153 
2154 #ifndef PRODUCT
2155 static int _lookups; // number of calls to lookup
2156 static int _equals;  // number of buckets checked with matching hash
2157 static int _archived_hits; // number of successful lookups in archived table
2158 static int _runtime_hits;  // number of successful lookups in runtime table
2159 #endif
2160 
2161 // A simple wrapper class around the calling convention information
2162 // that allows sharing of adapters for the same calling convention.
2163 class AdapterFingerPrint : public MetaspaceObj {
2164  private:
2165   enum {
2166     _basic_type_bits = 4,
2167     _basic_type_mask = right_n_bits(_basic_type_bits),
2168     _basic_types_per_int = BitsPerInt / _basic_type_bits,

























2169   };
2170   // TO DO:  Consider integrating this with a more global scheme for compressing signatures.
2171   // For now, 4 bits per components (plus T_VOID gaps after double/long) is not excessive.
2172 
2173   int _length;


2174 
2175   static int data_offset() { return sizeof(AdapterFingerPrint); }
2176   int* data_pointer() {
2177     return (int*)((address)this + data_offset());






2178   }
2179 
2180   // Private construtor. Use allocate() to get an instance.
2181   AdapterFingerPrint(int total_args_passed, BasicType* sig_bt, int len) {
2182     int* data = data_pointer();
2183     // Pack the BasicTypes with 8 per int
2184     assert(len == length(total_args_passed), "sanity");
2185     _length = len;
2186     int sig_index = 0;
2187     for (int index = 0; index < _length; index++) {
2188       int value = 0;
2189       for (int byte = 0; sig_index < total_args_passed && byte < _basic_types_per_int; byte++) {
2190         int bt = adapter_encoding(sig_bt[sig_index++]);
2191         assert((bt & _basic_type_mask) == bt, "must fit in 4 bits");
2192         value = (value << _basic_type_bits) | bt;










2193       }
2194       data[index] = value;


2195     }

2196   }
2197 
2198   // Call deallocate instead
2199   ~AdapterFingerPrint() {
2200     ShouldNotCallThis();
2201   }
2202 
2203   static int length(int total_args) {
2204     return (total_args + (_basic_types_per_int-1)) / _basic_types_per_int;
2205   }
2206 
2207   static int compute_size_in_words(int len) {
2208     return (int)heap_word_size(sizeof(AdapterFingerPrint) + (len * sizeof(int)));
2209   }
2210 
2211   // Remap BasicTypes that are handled equivalently by the adapters.
2212   // These are correct for the current system but someday it might be
2213   // necessary to make this mapping platform dependent.
2214   static int adapter_encoding(BasicType in) {
2215     switch (in) {
2216       case T_BOOLEAN:
2217       case T_BYTE:
2218       case T_SHORT:
2219       case T_CHAR:
2220         // There are all promoted to T_INT in the calling convention
2221         return T_INT;
2222 
2223       case T_OBJECT:
2224       case T_ARRAY:
2225         // In other words, we assume that any register good enough for
2226         // an int or long is good enough for a managed pointer.
2227 #ifdef _LP64
2228         return T_LONG;
2229 #else
2230         return T_INT;
2231 #endif
2232 
2233       case T_INT:
2234       case T_LONG:
2235       case T_FLOAT:
2236       case T_DOUBLE:
2237       case T_VOID:
2238         return in;
2239 
2240       default:
2241         ShouldNotReachHere();
2242         return T_CONFLICT;
2243     }
2244   }
2245 
2246   void* operator new(size_t size, size_t fp_size) throw() {
2247     assert(fp_size >= size, "sanity check");
2248     void* p = AllocateHeap(fp_size, mtCode);
2249     memset(p, 0, fp_size);
2250     return p;
2251   }
2252 

2253   template<typename Function>
2254   void iterate_args(Function function) {
2255     for (int i = 0; i < length(); i++) {
2256       unsigned val = (unsigned)value(i);
2257       // args are packed so that first/lower arguments are in the highest
2258       // bits of each int value, so iterate from highest to the lowest
2259       for (int j = 32 - _basic_type_bits; j >= 0; j -= _basic_type_bits) {
2260         unsigned v = (val >> j) & _basic_type_mask;
2261         if (v == 0) {
2262           continue;
2263         }
2264         function(v);
2265       }
2266     }
2267   }
2268 
2269  public:
2270   static AdapterFingerPrint* allocate(int total_args_passed, BasicType* sig_bt) {
2271     int len = length(total_args_passed);
2272     int size_in_bytes = BytesPerWord * compute_size_in_words(len);
2273     AdapterFingerPrint* afp = new (size_in_bytes) AdapterFingerPrint(total_args_passed, sig_bt, len);
2274     assert((afp->size() * BytesPerWord) == size_in_bytes, "should match");
2275     return afp;
2276   }
2277 
2278   static void deallocate(AdapterFingerPrint* fp) {
2279     FreeHeap(fp);
2280   }
2281 
2282   int value(int index) {
2283     int* data = data_pointer();
2284     return data[index];
2285   }
2286 
2287   int length() {
2288     return _length;
2289   }
2290 
2291   unsigned int compute_hash() {
2292     int hash = 0;
2293     for (int i = 0; i < length(); i++) {
2294       int v = value(i);
2295       //Add arithmetic operation to the hash, like +3 to improve hashing
2296       hash = ((hash << 8) ^ v ^ (hash >> 5)) + 3;
2297     }
2298     return (unsigned int)hash;
2299   }
2300 
2301   const char* as_string() {
2302     stringStream st;
2303     st.print("0x");





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


2306     }

2307     return st.as_string();
2308   }
2309 
2310   const char* as_basic_args_string() {
2311     stringStream st;
2312     bool long_prev = false;
2313     iterate_args([&] (int arg) {
2314       if (long_prev) {
2315         long_prev = false;
2316         if (arg == T_VOID) {
2317           st.print("J");
2318         } else {
2319           st.print("L");
2320         }
2321       }
2322       switch (arg) {
2323         case T_INT:    st.print("I");    break;
2324         case T_LONG:   long_prev = true; break;
2325         case T_FLOAT:  st.print("F");    break;
2326         case T_DOUBLE: st.print("D");    break;
2327         case T_VOID:   break;
2328         default: ShouldNotReachHere();
2329       }
2330     });
2331     if (long_prev) {
2332       st.print("L");
2333     }
2334     return st.as_string();
2335   }
2336 
2337   BasicType* as_basic_type(int& nargs) {
2338     nargs = 0;
2339     GrowableArray<BasicType> btarray;
2340     bool long_prev = false;
2341 
2342     iterate_args([&] (int arg) {
2343       if (long_prev) {
2344         long_prev = false;
2345         if (arg == T_VOID) {
2346           btarray.append(T_LONG);
2347         } else {
2348           btarray.append(T_OBJECT); // it could be T_ARRAY; it shouldn't matter
2349         }
2350       }
2351       switch (arg) {
2352         case T_INT: // fallthrough
2353         case T_FLOAT: // fallthrough
2354         case T_DOUBLE:
2355         case T_VOID:
2356           btarray.append((BasicType)arg);
2357           break;
2358         case T_LONG:
2359           long_prev = true;
2360           break;
2361         default: ShouldNotReachHere();
2362       }
2363     });
2364 
2365     if (long_prev) {
2366       btarray.append(T_OBJECT);
2367     }
2368 
2369     nargs = btarray.length();
2370     BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, nargs);
2371     int index = 0;
2372     GrowableArrayIterator<BasicType> iter = btarray.begin();
2373     while (iter != btarray.end()) {
2374       sig_bt[index++] = *iter;
2375       ++iter;
2376     }
2377     assert(index == btarray.length(), "sanity check");
2378 #ifdef ASSERT
2379     {
2380       AdapterFingerPrint* compare_fp = AdapterFingerPrint::allocate(nargs, sig_bt);
2381       assert(this->equals(compare_fp), "sanity check");
2382       AdapterFingerPrint::deallocate(compare_fp);
2383     }
2384 #endif
2385     return sig_bt;
2386   }
2387 
2388   bool equals(AdapterFingerPrint* other) {
2389     if (other->_length != _length) {


2390       return false;
2391     } else {
2392       for (int i = 0; i < _length; i++) {
2393         if (value(i) != other->value(i)) {
2394           return false;
2395         }
2396       }
2397     }
2398     return true;
2399   }
2400 
2401   // methods required by virtue of being a MetaspaceObj
2402   void metaspace_pointers_do(MetaspaceClosure* it) { return; /* nothing to do here */ }
2403   int size() const { return compute_size_in_words(_length); }
2404   MetaspaceObj::Type type() const { return AdapterFingerPrintType; }
2405 
2406   static bool equals(AdapterFingerPrint* const& fp1, AdapterFingerPrint* const& fp2) {
2407     NOT_PRODUCT(_equals++);
2408     return fp1->equals(fp2);
2409   }
2410 
2411   static unsigned int compute_hash(AdapterFingerPrint* const& fp) {
2412     return fp->compute_hash();
2413   }

2416 #if INCLUDE_CDS
2417 static inline bool adapter_fp_equals_compact_hashtable_entry(AdapterHandlerEntry* entry, AdapterFingerPrint* fp, int len_unused) {
2418   return AdapterFingerPrint::equals(entry->fingerprint(), fp);
2419 }
2420 
2421 class ArchivedAdapterTable : public OffsetCompactHashtable<
2422   AdapterFingerPrint*,
2423   AdapterHandlerEntry*,
2424   adapter_fp_equals_compact_hashtable_entry> {};
2425 #endif // INCLUDE_CDS
2426 
2427 // A hashtable mapping from AdapterFingerPrints to AdapterHandlerEntries
2428 using AdapterHandlerTable = HashTable<AdapterFingerPrint*, AdapterHandlerEntry*, 293,
2429                   AnyObj::C_HEAP, mtCode,
2430                   AdapterFingerPrint::compute_hash,
2431                   AdapterFingerPrint::equals>;
2432 static AdapterHandlerTable* _adapter_handler_table;
2433 static GrowableArray<AdapterHandlerEntry*>* _adapter_handler_list = nullptr;
2434 
2435 // Find a entry with the same fingerprint if it exists
2436 AdapterHandlerEntry* AdapterHandlerLibrary::lookup(int total_args_passed, BasicType* sig_bt) {
2437   NOT_PRODUCT(_lookups++);
2438   assert_lock_strong(AdapterHandlerLibrary_lock);
2439   AdapterFingerPrint* fp = AdapterFingerPrint::allocate(total_args_passed, sig_bt);
2440   AdapterHandlerEntry* entry = nullptr;
2441 #if INCLUDE_CDS
2442   // if we are building the archive then the archived adapter table is
2443   // not valid and we need to use the ones added to the runtime table
2444   if (AOTCodeCache::is_using_adapter()) {
2445     // Search archived table first. It is read-only table so can be searched without lock
2446     entry = _aot_adapter_handler_table.lookup(fp, fp->compute_hash(), 0 /* unused */);
2447 #ifndef PRODUCT
2448     if (entry != nullptr) {
2449       _archived_hits++;
2450     }
2451 #endif
2452   }
2453 #endif // INCLUDE_CDS
2454   if (entry == nullptr) {
2455     assert_lock_strong(AdapterHandlerLibrary_lock);
2456     AdapterHandlerEntry** entry_p = _adapter_handler_table->get(fp);
2457     if (entry_p != nullptr) {
2458       entry = *entry_p;
2459       assert(entry->fingerprint()->equals(fp), "fingerprint mismatch key fp %s %s (hash=%d) != found fp %s %s (hash=%d)",

2476   TableStatistics ts = _adapter_handler_table->statistics_calculate(size);
2477   ts.print(tty, "AdapterHandlerTable");
2478   tty->print_cr("AdapterHandlerTable (table_size=%d, entries=%d)",
2479                 _adapter_handler_table->table_size(), _adapter_handler_table->number_of_entries());
2480   int total_hits = _archived_hits + _runtime_hits;
2481   tty->print_cr("AdapterHandlerTable: lookups %d equals %d hits %d (archived=%d+runtime=%d)",
2482                 _lookups, _equals, total_hits, _archived_hits, _runtime_hits);
2483 }
2484 #endif
2485 
2486 // ---------------------------------------------------------------------------
2487 // Implementation of AdapterHandlerLibrary
2488 AdapterHandlerEntry* AdapterHandlerLibrary::_no_arg_handler = nullptr;
2489 AdapterHandlerEntry* AdapterHandlerLibrary::_int_arg_handler = nullptr;
2490 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_arg_handler = nullptr;
2491 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_int_arg_handler = nullptr;
2492 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_obj_arg_handler = nullptr;
2493 #if INCLUDE_CDS
2494 ArchivedAdapterTable AdapterHandlerLibrary::_aot_adapter_handler_table;
2495 #endif // INCLUDE_CDS
2496 static const int AdapterHandlerLibrary_size = 16*K;
2497 BufferBlob* AdapterHandlerLibrary::_buffer = nullptr;
2498 volatile uint AdapterHandlerLibrary::_id_counter = 0;
2499 
2500 BufferBlob* AdapterHandlerLibrary::buffer_blob() {
2501   assert(_buffer != nullptr, "should be initialized");
2502   return _buffer;
2503 }
2504 
2505 static void post_adapter_creation(const AdapterHandlerEntry* entry) {
2506   if (Forte::is_enabled() || JvmtiExport::should_post_dynamic_code_generated()) {
2507     AdapterBlob* adapter_blob = entry->adapter_blob();
2508     char blob_id[256];
2509     jio_snprintf(blob_id,
2510                  sizeof(blob_id),
2511                  "%s(%s)",
2512                  adapter_blob->name(),
2513                  entry->fingerprint()->as_string());
2514     if (Forte::is_enabled()) {
2515       Forte::register_stub(blob_id, adapter_blob->content_begin(), adapter_blob->content_end());
2516     }

2524 void AdapterHandlerLibrary::initialize() {
2525   {
2526     ResourceMark rm;
2527     _adapter_handler_table = new (mtCode) AdapterHandlerTable();
2528     _buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size);
2529   }
2530 
2531 #if INCLUDE_CDS
2532   // Link adapters in AOT Cache to their code in AOT Code Cache
2533   if (AOTCodeCache::is_using_adapter() && !_aot_adapter_handler_table.empty()) {
2534     link_aot_adapters();
2535     lookup_simple_adapters();
2536     return;
2537   }
2538 #endif // INCLUDE_CDS
2539 
2540   ResourceMark rm;
2541   {
2542     MutexLocker mu(AdapterHandlerLibrary_lock);
2543 
2544     _no_arg_handler = create_adapter(0, nullptr);


2545 
2546     BasicType obj_args[] = { T_OBJECT };
2547     _obj_arg_handler = create_adapter(1, obj_args);


2548 
2549     BasicType int_args[] = { T_INT };
2550     _int_arg_handler = create_adapter(1, int_args);


2551 
2552     BasicType obj_int_args[] = { T_OBJECT, T_INT };
2553     _obj_int_arg_handler = create_adapter(2, obj_int_args);



2554 
2555     BasicType obj_obj_args[] = { T_OBJECT, T_OBJECT };
2556     _obj_obj_arg_handler = create_adapter(2, obj_obj_args);



2557 
2558     // we should always get an entry back but we don't have any
2559     // associated blob on Zero
2560     assert(_no_arg_handler != nullptr &&
2561            _obj_arg_handler != nullptr &&
2562            _int_arg_handler != nullptr &&
2563            _obj_int_arg_handler != nullptr &&
2564            _obj_obj_arg_handler != nullptr, "Initial adapter handlers must be properly created");
2565   }
2566 
2567   // Outside of the lock
2568 #ifndef ZERO
2569   // no blobs to register when we are on Zero
2570   post_adapter_creation(_no_arg_handler);
2571   post_adapter_creation(_obj_arg_handler);
2572   post_adapter_creation(_int_arg_handler);
2573   post_adapter_creation(_obj_int_arg_handler);
2574   post_adapter_creation(_obj_obj_arg_handler);
2575 #endif // ZERO
2576 }
2577 
2578 AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint) {
2579   uint id = (uint)AtomicAccess::add((int*)&_id_counter, 1);
2580   assert(id > 0, "we can never overflow because AOT cache cannot contain more than 2^32 methods");
2581   return AdapterHandlerEntry::allocate(id, fingerprint);
2582 }
2583 
2584 AdapterHandlerEntry* AdapterHandlerLibrary::get_simple_adapter(const methodHandle& method) {
2585   int total_args_passed = method->size_of_parameters(); // All args on stack
2586   if (total_args_passed == 0) {
2587     return _no_arg_handler;
2588   } else if (total_args_passed == 1) {
2589     if (!method->is_static()) {



2590       return _obj_arg_handler;
2591     }
2592     switch (method->signature()->char_at(1)) {
2593       case JVM_SIGNATURE_CLASS:









2594       case JVM_SIGNATURE_ARRAY:
2595         return _obj_arg_handler;
2596       case JVM_SIGNATURE_INT:
2597       case JVM_SIGNATURE_BOOLEAN:
2598       case JVM_SIGNATURE_CHAR:
2599       case JVM_SIGNATURE_BYTE:
2600       case JVM_SIGNATURE_SHORT:
2601         return _int_arg_handler;
2602     }
2603   } else if (total_args_passed == 2 &&
2604              !method->is_static()) {
2605     switch (method->signature()->char_at(1)) {
2606       case JVM_SIGNATURE_CLASS:









2607       case JVM_SIGNATURE_ARRAY:
2608         return _obj_obj_arg_handler;
2609       case JVM_SIGNATURE_INT:
2610       case JVM_SIGNATURE_BOOLEAN:
2611       case JVM_SIGNATURE_CHAR:
2612       case JVM_SIGNATURE_BYTE:
2613       case JVM_SIGNATURE_SHORT:
2614         return _obj_int_arg_handler;
2615     }
2616   }
2617   return nullptr;
2618 }
2619 
2620 class AdapterSignatureIterator : public SignatureIterator {
2621  private:
2622   BasicType stack_sig_bt[16];
2623   BasicType* sig_bt;
2624   int index;




2625 
2626  public:
2627   AdapterSignatureIterator(Symbol* signature,
2628                            fingerprint_t fingerprint,
2629                            bool is_static,
2630                            int total_args_passed) :
2631     SignatureIterator(signature, fingerprint),
2632     index(0)
2633   {
2634     sig_bt = (total_args_passed <= 16) ? stack_sig_bt : NEW_RESOURCE_ARRAY(BasicType, total_args_passed);
2635     if (!is_static) { // Pass in receiver first
2636       sig_bt[index++] = T_OBJECT;













2637     }
2638     do_parameters_on(this);
2639   }
2640 
2641   BasicType* basic_types() {
2642     return sig_bt;







2643   }

2644 

























































2645 #ifdef ASSERT
2646   int slots() {
2647     return index;





2648   }
2649 #endif
























2650 
2651  private:

2652 
2653   friend class SignatureIterator;  // so do_parameters_on can call do_type
2654   void do_type(BasicType type) {
2655     sig_bt[index++] = type;
2656     if (type == T_LONG || type == T_DOUBLE) {
2657       sig_bt[index++] = T_VOID; // Longs & doubles take 2 Java slots























































2658     }
2659   }
2660 };
2661 


























































































































































































2662 
2663 const char* AdapterHandlerEntry::_entry_names[] = {
2664   "i2c", "c2i", "c2i_unverified", "c2i_no_clinit_check"
2665 };
2666 
2667 #ifdef ASSERT
2668 void AdapterHandlerLibrary::verify_adapter_sharing(int total_args_passed, BasicType* sig_bt, AdapterHandlerEntry* cached_entry) {
2669   // we can only check for the same code if there is any
2670 #ifndef ZERO
2671   AdapterHandlerEntry* comparison_entry = create_adapter(total_args_passed, sig_bt, true);
2672   assert(comparison_entry->adapter_blob() == nullptr, "no blob should be created when creating an adapter for comparison");
2673   assert(comparison_entry->compare_code(cached_entry), "code must match");
2674   // Release the one just created
2675   AdapterHandlerEntry::deallocate(comparison_entry);
2676 # endif // ZERO
2677 }
2678 #endif /* ASSERT*/
2679 
2680 AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(const methodHandle& method) {
2681   assert(!method->is_abstract(), "abstract methods do not have adapters");
2682   // Use customized signature handler.  Need to lock around updates to
2683   // the _adapter_handler_table (it is not safe for concurrent readers
2684   // and a single writer: this could be fixed if it becomes a
2685   // problem).
2686 
2687   // Fast-path for trivial adapters
2688   AdapterHandlerEntry* entry = get_simple_adapter(method);
2689   if (entry != nullptr) {
2690     return entry;
2691   }
2692 
2693   ResourceMark rm;
2694   bool new_entry = false;
2695 
2696   // Fill in the signature array, for the calling-convention call.
2697   int total_args_passed = method->size_of_parameters(); // All args on stack











2698 
2699   AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(),
2700                               method->is_static(), total_args_passed);
2701   assert(si.slots() == total_args_passed, "");
2702   BasicType* sig_bt = si.basic_types();
2703   {
2704     MutexLocker mu(AdapterHandlerLibrary_lock);
2705 
2706     // Lookup method signature's fingerprint
2707     entry = lookup(total_args_passed, sig_bt);
2708 
2709     if (entry != nullptr) {
2710 #ifndef ZERO
2711       assert(entry->is_linked(), "AdapterHandlerEntry must have been linked");
2712 #endif
2713 #ifdef ASSERT
2714       if (!entry->in_aot_cache() && VerifyAdapterSharing) {
2715         verify_adapter_sharing(total_args_passed, sig_bt, entry);
2716       }
2717 #endif
2718     } else {
2719       entry = create_adapter(total_args_passed, sig_bt);
2720       if (entry != nullptr) {
2721         new_entry = true;
2722       }
2723     }
2724   }
2725 
2726   // Outside of the lock
2727   if (new_entry) {
2728     post_adapter_creation(entry);
2729   }
2730   return entry;
2731 }
2732 
2733 void AdapterHandlerLibrary::lookup_aot_cache(AdapterHandlerEntry* handler) {
2734   ResourceMark rm;
2735   const char* name = AdapterHandlerLibrary::name(handler);
2736   const uint32_t id = AdapterHandlerLibrary::id(handler);
2737 
2738   CodeBlob* blob = AOTCodeCache::load_code_blob(AOTCodeEntry::Adapter, id, name);
2739   if (blob != nullptr) {

2754   }
2755   insts_size = adapter_blob->code_size();
2756   st->print_cr("i2c argument handler for: %s %s (%d bytes generated)",
2757                 handler->fingerprint()->as_basic_args_string(),
2758                 handler->fingerprint()->as_string(), insts_size);
2759   st->print_cr("c2i argument handler starts at " INTPTR_FORMAT, p2i(handler->get_c2i_entry()));
2760   if (Verbose || PrintStubCode) {
2761     address first_pc = adapter_blob->content_begin();
2762     if (first_pc != nullptr) {
2763       Disassembler::decode(first_pc, first_pc + insts_size, st, &adapter_blob->asm_remarks());
2764       st->cr();
2765     }
2766   }
2767 }
2768 #endif // PRODUCT
2769 
2770 void AdapterHandlerLibrary::address_to_offset(address entry_address[AdapterBlob::ENTRY_COUNT],
2771                                               int entry_offset[AdapterBlob::ENTRY_COUNT]) {
2772   entry_offset[AdapterBlob::I2C] = 0;
2773   entry_offset[AdapterBlob::C2I] = entry_address[AdapterBlob::C2I] - entry_address[AdapterBlob::I2C];


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

2775   if (entry_address[AdapterBlob::C2I_No_Clinit_Check] == nullptr) {
2776     entry_offset[AdapterBlob::C2I_No_Clinit_Check] = -1;
2777   } else {
2778     entry_offset[AdapterBlob::C2I_No_Clinit_Check] = entry_address[AdapterBlob::C2I_No_Clinit_Check] - entry_address[AdapterBlob::I2C];
2779   }
2780 }
2781 
2782 bool AdapterHandlerLibrary::generate_adapter_code(AdapterHandlerEntry* handler,
2783                                                   int total_args_passed,
2784                                                   BasicType* sig_bt,
2785                                                   bool is_transient) {
2786   if (log_is_enabled(Info, perf, class, link)) {
2787     ClassLoader::perf_method_adapters_count()->inc();
2788   }
2789 
2790 #ifndef ZERO

2791   BufferBlob* buf = buffer_blob(); // the temporary code buffer in CodeCache
2792   CodeBuffer buffer(buf);
2793   short buffer_locs[20];
2794   buffer.insts()->initialize_shared_locs((relocInfo*)buffer_locs,
2795                                          sizeof(buffer_locs)/sizeof(relocInfo));
2796   MacroAssembler masm(&buffer);
2797   VMRegPair stack_regs[16];
2798   VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
2799 
2800   // Get a description of the compiled java calling convention and the largest used (VMReg) stack slot usage
2801   int comp_args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
2802   address entry_address[AdapterBlob::ENTRY_COUNT];
2803   SharedRuntime::generate_i2c2i_adapters(&masm,
2804                                          total_args_passed,
2805                                          comp_args_on_stack,
2806                                          sig_bt,
2807                                          regs,
2808                                          entry_address);















2809   // On zero there is no code to save and no need to create a blob and
2810   // or relocate the handler.
2811   int entry_offset[AdapterBlob::ENTRY_COUNT];
2812   address_to_offset(entry_address, entry_offset);
2813 #ifdef ASSERT
2814   if (VerifyAdapterSharing) {
2815     handler->save_code(buf->code_begin(), buffer.insts_size());
2816     if (is_transient) {
2817       return true;
2818     }
2819   }
2820 #endif
2821   AdapterBlob* adapter_blob = AdapterBlob::create(&buffer, entry_offset);
2822   if (adapter_blob == nullptr) {
2823     // CodeCache is full, disable compilation
2824     // Ought to log this but compile log is only per compile thread
2825     // and we're some non descript Java thread.
2826     return false;
2827   }
2828   handler->set_adapter_blob(adapter_blob);
2829   if (!is_transient && AOTCodeCache::is_dumping_adapter()) {
2830     // try to save generated code
2831     const char* name = AdapterHandlerLibrary::name(handler);
2832     const uint32_t id = AdapterHandlerLibrary::id(handler);
2833     bool success = AOTCodeCache::store_code_blob(*adapter_blob, AOTCodeEntry::Adapter, id, name);
2834     assert(success || !AOTCodeCache::is_dumping_adapter(), "caching of adapter must be disabled");
2835   }
2836 #endif // ZERO
2837 
2838 #ifndef PRODUCT
2839   // debugging support
2840   if (PrintAdapterHandlers || PrintStubCode) {
2841     print_adapter_handler_info(tty, handler);
2842   }
2843 #endif
2844 
2845   return true;
2846 }
2847 
2848 AdapterHandlerEntry* AdapterHandlerLibrary::create_adapter(int total_args_passed,
2849                                                            BasicType* sig_bt,
2850                                                            bool is_transient) {
2851   AdapterFingerPrint* fp = AdapterFingerPrint::allocate(total_args_passed, sig_bt);





2852   AdapterHandlerEntry* handler = AdapterHandlerLibrary::new_entry(fp);
2853   if (!generate_adapter_code(handler, total_args_passed, sig_bt, is_transient)) {
2854     AdapterHandlerEntry::deallocate(handler);
2855     return nullptr;
2856   }
2857   if (!is_transient) {
2858     assert_lock_strong(AdapterHandlerLibrary_lock);
2859     _adapter_handler_table->put(fp, handler);
2860   }
2861   return handler;
2862 }
2863 
2864 #if INCLUDE_CDS
2865 void AdapterHandlerEntry::remove_unshareable_info() {
2866 #ifdef ASSERT
2867    _saved_code = nullptr;
2868    _saved_code_length = 0;
2869 #endif // ASSERT
2870    _adapter_blob = nullptr;
2871    _linked = false;


2872 }
2873 
2874 class CopyAdapterTableToArchive : StackObj {
2875 private:
2876   CompactHashtableWriter* _writer;
2877   ArchiveBuilder* _builder;
2878 public:
2879   CopyAdapterTableToArchive(CompactHashtableWriter* writer) : _writer(writer),
2880                                                              _builder(ArchiveBuilder::current())
2881   {}
2882 
2883   bool do_entry(AdapterFingerPrint* fp, AdapterHandlerEntry* entry) {
2884     LogStreamHandle(Trace, aot) lsh;
2885     if (ArchiveBuilder::current()->has_been_archived((address)entry)) {
2886       assert(ArchiveBuilder::current()->has_been_archived((address)fp), "must be");
2887       AdapterFingerPrint* buffered_fp = ArchiveBuilder::current()->get_buffered_addr(fp);
2888       assert(buffered_fp != nullptr,"sanity check");
2889       AdapterHandlerEntry* buffered_entry = ArchiveBuilder::current()->get_buffered_addr(entry);
2890       assert(buffered_entry != nullptr,"sanity check");
2891 

2931   }
2932 #endif
2933 }
2934 
2935 // This method is used during production run to link archived adapters (stored in AOT Cache)
2936 // to their code in AOT Code Cache
2937 void AdapterHandlerEntry::link() {
2938   ResourceMark rm;
2939   assert(_fingerprint != nullptr, "_fingerprint must not be null");
2940   bool generate_code = false;
2941   // Generate code only if AOTCodeCache is not available, or
2942   // caching adapters is disabled, or we fail to link
2943   // the AdapterHandlerEntry to its code in the AOTCodeCache
2944   if (AOTCodeCache::is_using_adapter()) {
2945     AdapterHandlerLibrary::link_aot_adapter_handler(this);
2946     // If link_aot_adapter_handler() succeeds, _adapter_blob will be non-null
2947     if (_adapter_blob == nullptr) {
2948       log_warning(aot)("Failed to link AdapterHandlerEntry (fp=%s) to its code in the AOT code cache", _fingerprint->as_basic_args_string());
2949       generate_code = true;
2950     }

















2951   } else {
2952     generate_code = true;
2953   }
2954   if (generate_code) {
2955     int nargs;
2956     BasicType* bt = _fingerprint->as_basic_type(nargs);
2957     if (!AdapterHandlerLibrary::generate_adapter_code(this, nargs, bt, /* is_transient */ false)) {
2958       // Don't throw exceptions during VM initialization because java.lang.* classes
2959       // might not have been initialized, causing problems when constructing the
2960       // Java exception object.
2961       vm_exit_during_initialization("Out of space in CodeCache for adapters");
2962     }
2963   }
2964   if (_adapter_blob != nullptr) {
2965     post_adapter_creation(this);
2966   }
2967   assert(_linked, "AdapterHandlerEntry must now be linked");
2968 }
2969 
2970 void AdapterHandlerLibrary::link_aot_adapters() {
2971   uint max_id = 0;
2972   assert(AOTCodeCache::is_using_adapter(), "AOT adapters code should be available");
2973   /* It is possible that some adapters generated in assembly phase are not stored in the cache.
2974    * That implies adapter ids of the adapters in the cache may not be contiguous.
2975    * If the size of the _aot_adapter_handler_table is used to initialize _id_counter, then it may
2976    * result in collision of adapter ids between AOT stored handlers and runtime generated handlers.
2977    * To avoid such situation, initialize the _id_counter with the largest adapter id among the AOT stored handlers.
2978    */
2979   _aot_adapter_handler_table.iterate_all([&](AdapterHandlerEntry* entry) {
2980     assert(!entry->is_linked(), "AdapterHandlerEntry is already linked!");
2981     entry->link();
2982     max_id = MAX2(max_id, entry->id());
2983   });
2984   // Set adapter id to the maximum id found in the AOTCache
2985   assert(_id_counter == 0, "Did not expect new AdapterHandlerEntry to be created at this stage");
2986   _id_counter = max_id;
2987 }
2988 
2989 // This method is called during production run to lookup simple adapters
2990 // in the archived adapter handler table
2991 void AdapterHandlerLibrary::lookup_simple_adapters() {
2992   assert(!_aot_adapter_handler_table.empty(), "archived adapter handler table is empty");
2993 
2994   MutexLocker mu(AdapterHandlerLibrary_lock);
2995   _no_arg_handler = lookup(0, nullptr);
2996 
2997   BasicType obj_args[] = { T_OBJECT };
2998   _obj_arg_handler = lookup(1, obj_args);
2999 
3000   BasicType int_args[] = { T_INT };
3001   _int_arg_handler = lookup(1, int_args);
3002 
3003   BasicType obj_int_args[] = { T_OBJECT, T_INT };
3004   _obj_int_arg_handler = lookup(2, obj_int_args);
3005 
3006   BasicType obj_obj_args[] = { T_OBJECT, T_OBJECT };
3007   _obj_obj_arg_handler = lookup(2, obj_obj_args);













3008 
3009   assert(_no_arg_handler != nullptr &&
3010          _obj_arg_handler != nullptr &&
3011          _int_arg_handler != nullptr &&
3012          _obj_int_arg_handler != nullptr &&
3013          _obj_obj_arg_handler != nullptr, "Initial adapters not found in archived adapter handler table");
3014   assert(_no_arg_handler->is_linked() &&
3015          _obj_arg_handler->is_linked() &&
3016          _int_arg_handler->is_linked() &&
3017          _obj_int_arg_handler->is_linked() &&
3018          _obj_obj_arg_handler->is_linked(), "Initial adapters not in linked state");
3019 }
3020 #endif // INCLUDE_CDS
3021 
3022 void AdapterHandlerEntry::metaspace_pointers_do(MetaspaceClosure* it) {
3023   LogStreamHandle(Trace, aot) lsh;
3024   if (lsh.is_enabled()) {
3025     lsh.print("Iter(AdapterHandlerEntry): %p(%s)", this, _fingerprint->as_basic_args_string());
3026     lsh.cr();
3027   }
3028   it->push(&_fingerprint);
3029 }
3030 
3031 AdapterHandlerEntry::~AdapterHandlerEntry() {
3032   if (_fingerprint != nullptr) {
3033     AdapterFingerPrint::deallocate(_fingerprint);
3034     _fingerprint = nullptr;
3035   }






3036 #ifdef ASSERT
3037   FREE_C_HEAP_ARRAY(_saved_code);
3038 #endif
3039   FreeHeap(this);
3040 }
3041 
3042 
3043 #ifdef ASSERT
3044 // Capture the code before relocation so that it can be compared
3045 // against other versions.  If the code is captured after relocation
3046 // then relative instructions won't be equivalent.
3047 void AdapterHandlerEntry::save_code(unsigned char* buffer, int length) {
3048   _saved_code = NEW_C_HEAP_ARRAY(unsigned char, length, mtCode);
3049   _saved_code_length = length;
3050   memcpy(_saved_code, buffer, length);
3051 }
3052 
3053 
3054 bool AdapterHandlerEntry::compare_code(AdapterHandlerEntry* other) {
3055   assert(_saved_code != nullptr && other->_saved_code != nullptr, "code not saved");

3103 
3104       struct { double data[20]; } locs_buf;
3105       struct { double data[20]; } stubs_locs_buf;
3106       buffer.insts()->initialize_shared_locs((relocInfo*)&locs_buf, sizeof(locs_buf) / sizeof(relocInfo));
3107 #if defined(AARCH64) || defined(PPC64)
3108       // On AArch64 with ZGC and nmethod entry barriers, we need all oops to be
3109       // in the constant pool to ensure ordering between the barrier and oops
3110       // accesses. For native_wrappers we need a constant.
3111       // On PPC64 the continuation enter intrinsic needs the constant pool for the compiled
3112       // static java call that is resolved in the runtime.
3113       if (PPC64_ONLY(method->is_continuation_enter_intrinsic() &&) true) {
3114         buffer.initialize_consts_size(8 PPC64_ONLY(+ 24));
3115       }
3116 #endif
3117       buffer.stubs()->initialize_shared_locs((relocInfo*)&stubs_locs_buf, sizeof(stubs_locs_buf) / sizeof(relocInfo));
3118       MacroAssembler _masm(&buffer);
3119 
3120       // Fill in the signature array, for the calling-convention call.
3121       const int total_args_passed = method->size_of_parameters();
3122 

3123       VMRegPair stack_regs[16];

3124       VMRegPair* regs = (total_args_passed <= 16) ? stack_regs : NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
3125 
3126       AdapterSignatureIterator si(method->signature(), method->constMethod()->fingerprint(),
3127                               method->is_static(), total_args_passed);
3128       BasicType* sig_bt = si.basic_types();
3129       assert(si.slots() == total_args_passed, "");
3130       BasicType ret_type = si.return_type();








3131 
3132       // Now get the compiled-Java arguments layout.
3133       SharedRuntime::java_calling_convention(sig_bt, regs, total_args_passed);
3134 
3135       // Generate the compiled-to-native wrapper code
3136       nm = SharedRuntime::generate_native_wrapper(&_masm, method, compile_id, sig_bt, regs, ret_type);
3137 
3138       if (nm != nullptr) {
3139         {
3140           MutexLocker pl(NMethodState_lock, Mutex::_no_safepoint_check_flag);
3141           if (nm->make_in_use()) {
3142             method->set_code(method, nm);
3143           }
3144         }
3145 
3146         CompilerDirectiveMatcher matcher(method, CompLevel_simple);
3147         if (matcher.directive_set()->PrintAssemblyOption) {
3148           nm->print_code();
3149         }
3150       }

3357       if (b == handler->adapter_blob()) {
3358         found = true;
3359         st->print("Adapter for signature: ");
3360         handler->print_adapter_on(st);
3361         return false; // abort iteration
3362       } else {
3363         return true; // keep looking
3364       }
3365     };
3366     assert_locked_or_safepoint(AdapterHandlerLibrary_lock);
3367     _adapter_handler_table->iterate(findblob_runtime_table);
3368   }
3369   assert(found, "Should have found handler");
3370 }
3371 
3372 void AdapterHandlerEntry::print_adapter_on(outputStream* st) const {
3373   st->print("AHE@" INTPTR_FORMAT ": %s", p2i(this), fingerprint()->as_string());
3374   if (adapter_blob() != nullptr) {
3375     st->print(" i2c: " INTPTR_FORMAT, p2i(get_i2c_entry()));
3376     st->print(" c2i: " INTPTR_FORMAT, p2i(get_c2i_entry()));
3377     st->print(" c2iUV: " INTPTR_FORMAT, p2i(get_c2i_unverified_entry()));



3378     if (get_c2i_no_clinit_check_entry() != nullptr) {
3379       st->print(" c2iNCI: " INTPTR_FORMAT, p2i(get_c2i_no_clinit_check_entry()));
3380     }
3381   }
3382   st->cr();
3383 }
3384 
3385 #ifndef PRODUCT
3386 
3387 void AdapterHandlerLibrary::print_statistics() {
3388   print_table_statistics();
3389 }
3390 
3391 #endif /* PRODUCT */
3392 
3393 JRT_LEAF(void, SharedRuntime::enable_stack_reserved_zone(JavaThread* current))
3394   assert(current == JavaThread::current(), "pre-condition");
3395   StackOverflow* overflow_state = current->stack_overflow_state();
3396   overflow_state->enable_stack_reserved_zone(/*check_if_disabled*/true);
3397   overflow_state->set_reserved_stack_activation(current->stack_base());

3444         event.set_method(method);
3445         event.commit();
3446       }
3447     }
3448   }
3449   return activation;
3450 }
3451 
3452 void SharedRuntime::on_slowpath_allocation_exit(JavaThread* current) {
3453   // After any safepoint, just before going back to compiled code,
3454   // we inform the GC that we will be doing initializing writes to
3455   // this object in the future without emitting card-marks, so
3456   // GC may take any compensating steps.
3457 
3458   oop new_obj = current->vm_result_oop();
3459   if (new_obj == nullptr) return;
3460 
3461   BarrierSet *bs = BarrierSet::barrier_set();
3462   bs->on_slowpath_allocation_exit(current, new_obj);
3463 }





















































































































































































































































































  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/exceptions.hpp"
  92 #include "utilities/globalDefinitions.hpp"
  93 #include "utilities/hashTable.hpp"
  94 #include "utilities/macros.hpp"
  95 #include "utilities/xmlstream.hpp"
  96 #ifdef COMPILER1
  97 #include "c1/c1_Runtime1.hpp"
  98 #endif
  99 #ifdef COMPILER2
 100 #include "opto/runtime.hpp"

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


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



1819 #ifndef PRODUCT
1820   AtomicAccess::inc(&_wrong_method_ctr);
1821 
1822   if (TraceCallFixup) {
1823     ResourceMark rm(current);
1824     tty->print("handle_wrong_method reresolving %s call to", (caller_does_not_scalarize) ? "non-scalar" : "");
1825     callee_method->print_short_name(tty);
1826     tty->print_cr(" code: " INTPTR_FORMAT, p2i(callee_method->code()));
1827   }
1828 #endif
1829 
1830   return callee_method;
1831 }
1832 
1833 address SharedRuntime::handle_unsafe_access(JavaThread* thread, address next_pc) {
1834   // The faulting unsafe accesses should be changed to throw the error
1835   // synchronously instead. Meanwhile the faulting instruction will be
1836   // skipped over (effectively turning it into a no-op) and an
1837   // asynchronous exception will be raised which the thread will
1838   // handle at a later point. If the instruction is a load it will
1839   // return garbage.
1840 
1841   // Request an async exception.
1842   thread->set_pending_unsafe_access_error();
1843 
1844   // Return address of next instruction to execute.

2010   msglen += strlen(caster_klass_description) + strlen(target_klass_description) + strlen(klass_separator) + 3;
2011 
2012   char* message = NEW_RESOURCE_ARRAY_RETURN_NULL(char, msglen);
2013   if (message == nullptr) {
2014     // Shouldn't happen, but don't cause even more problems if it does
2015     message = const_cast<char*>(caster_klass->external_name());
2016   } else {
2017     jio_snprintf(message,
2018                  msglen,
2019                  "class %s cannot be cast to class %s (%s%s%s)",
2020                  caster_name,
2021                  target_name,
2022                  caster_klass_description,
2023                  klass_separator,
2024                  target_klass_description
2025                  );
2026   }
2027   return message;
2028 }
2029 
2030 char* SharedRuntime::generate_identity_exception_message(JavaThread* current, Klass* klass) {
2031   assert(klass->is_inline_klass(), "Must be a concrete value class");
2032   const char* desc = "Cannot synchronize on an instance of value class ";
2033   const char* className = klass->external_name();
2034   size_t msglen = strlen(desc) + strlen(className) + 1;
2035   char* message = NEW_RESOURCE_ARRAY(char, msglen);
2036   if (nullptr == message) {
2037     // Out of memory: can't create detailed error message
2038     message = const_cast<char*>(klass->external_name());
2039   } else {
2040     jio_snprintf(message, msglen, "%s%s", desc, className);
2041   }
2042   return message;
2043 }
2044 
2045 JRT_LEAF(void, SharedRuntime::reguard_yellow_pages())
2046   (void) JavaThread::current()->stack_overflow_state()->reguard_stack();
2047 JRT_END
2048 
2049 void SharedRuntime::monitor_enter_helper(oopDesc* obj, BasicLock* lock, JavaThread* current) {
2050   if (!SafepointSynchronize::is_synchronizing()) {
2051     // Only try quick_enter() if we're not trying to reach a safepoint
2052     // so that the calling thread reaches the safepoint more quickly.
2053     if (ObjectSynchronizer::quick_enter(obj, lock, current)) {
2054       return;
2055     }
2056   }
2057   // NO_ASYNC required because an async exception on the state transition destructor
2058   // would leave you with the lock held and it would never be released.
2059   // The normal monitorenter NullPointerException is thrown without acquiring a lock
2060   // and the model is that an exception implies the method failed.
2061   JRT_BLOCK_NO_ASYNC
2062   Handle h_obj(THREAD, obj);
2063   ObjectSynchronizer::enter(h_obj, lock, current);
2064   assert(!HAS_PENDING_EXCEPTION, "Should have no exception here");

2258   tty->print_cr("Note 1: counter updates are not MT-safe.");
2259   tty->print_cr("Note 2: %% in major categories are relative to total non-inlined calls;");
2260   tty->print_cr("        %% in nested categories are relative to their category");
2261   tty->print_cr("        (and thus add up to more than 100%% with inlining)");
2262   tty->cr();
2263 
2264   MethodArityHistogram h;
2265 }
2266 #endif
2267 
2268 #ifndef PRODUCT
2269 static int _lookups; // number of calls to lookup
2270 static int _equals;  // number of buckets checked with matching hash
2271 static int _archived_hits; // number of successful lookups in archived table
2272 static int _runtime_hits;  // number of successful lookups in runtime table
2273 #endif
2274 
2275 // A simple wrapper class around the calling convention information
2276 // that allows sharing of adapters for the same calling convention.
2277 class AdapterFingerPrint : public MetaspaceObj {
2278 public:
2279   class Element {
2280   private:
2281     // The highest byte is the type of the argument. The remaining bytes contain the offset of the
2282     // field if it is flattened in the calling convention, -1 otherwise.
2283     juint _payload;
2284 
2285     static constexpr int offset_bit_width = 24;
2286     static constexpr juint offset_bit_mask = (1 << offset_bit_width) - 1;
2287   public:
2288     Element(BasicType bt, int offset) : _payload((static_cast<juint>(bt) << offset_bit_width) | (juint(offset) & offset_bit_mask)) {
2289       assert(offset >= -1 && offset < jint(offset_bit_mask), "invalid offset %d", offset);
2290     }
2291 
2292     BasicType bt() const {
2293       return static_cast<BasicType>(_payload >> offset_bit_width);
2294     }
2295 
2296     int offset() const {
2297       juint res = _payload & offset_bit_mask;
2298       return res == offset_bit_mask ? -1 : res;
2299     }
2300 
2301     juint hash() const {
2302       return _payload;
2303     }
2304 
2305     bool operator!=(const Element& other) const {
2306       return _payload != other._payload;
2307     }
2308   };


2309 
2310 private:
2311   const bool _has_ro_adapter;
2312   const int _length;
2313 
2314   static int data_offset() { return sizeof(AdapterFingerPrint); }
2315   Element* data_pointer() {
2316     return reinterpret_cast<Element*>(reinterpret_cast<address>(this) + data_offset());
2317   }
2318 
2319   const Element& element_at(int index) {
2320     assert(index < length(), "index %d out of bounds for length %d", index, length());
2321     Element* data = data_pointer();
2322     return data[index];
2323   }
2324 
2325   // Private construtor. Use allocate() to get an instance.
2326   AdapterFingerPrint(const GrowableArray<SigEntry>* sig, bool has_ro_adapter)
2327     : _has_ro_adapter(has_ro_adapter), _length(total_args_passed_in_sig(sig)) {
2328     Element* data = data_pointer();
2329     BasicType prev_bt = T_ILLEGAL;
2330     int vt_count = 0;

2331     for (int index = 0; index < _length; index++) {
2332       const SigEntry& sig_entry = sig->at(index);
2333       BasicType bt = sig_entry._bt;
2334       if (bt == T_METADATA) {
2335         // Found start of inline type in signature
2336         assert(InlineTypePassFieldsAsArgs, "unexpected start of inline type");
2337         vt_count++;
2338       } else if (bt == T_VOID && prev_bt != T_LONG && prev_bt != T_DOUBLE) {
2339         // Found end of inline type in signature
2340         assert(InlineTypePassFieldsAsArgs, "unexpected end of inline type");
2341         vt_count--;
2342         assert(vt_count >= 0, "invalid vt_count");
2343       } else if (vt_count == 0) {
2344         // Widen fields that are not part of a scalarized inline type argument
2345         assert(sig_entry._offset == -1, "invalid offset for argument that is not a flattened field %d", sig_entry._offset);
2346         bt = adapter_encoding(bt);
2347       }
2348 
2349       ::new(&data[index]) Element(bt, sig_entry._offset);
2350       prev_bt = bt;
2351     }
2352     assert(vt_count == 0, "invalid vt_count");
2353   }
2354 
2355   // Call deallocate instead
2356   ~AdapterFingerPrint() {
2357     ShouldNotCallThis();
2358   }
2359 
2360   static int total_args_passed_in_sig(const GrowableArray<SigEntry>* sig) {
2361     return (sig != nullptr) ? sig->length() : 0;
2362   }
2363 
2364   static int compute_size_in_words(int len) {
2365     return (int)heap_word_size(sizeof(AdapterFingerPrint) + (len * sizeof(Element)));
2366   }
2367 
2368   // Remap BasicTypes that are handled equivalently by the adapters.
2369   // These are correct for the current system but someday it might be
2370   // necessary to make this mapping platform dependent.
2371   static BasicType adapter_encoding(BasicType in) {
2372     switch (in) {
2373       case T_BOOLEAN:
2374       case T_BYTE:
2375       case T_SHORT:
2376       case T_CHAR:
2377         // They are all promoted to T_INT in the calling convention
2378         return T_INT;
2379 
2380       case T_OBJECT:
2381       case T_ARRAY:
2382         // In other words, we assume that any register good enough for
2383         // an int or long is good enough for a managed pointer.
2384 #ifdef _LP64
2385         return T_LONG;
2386 #else
2387         return T_INT;
2388 #endif
2389 
2390       case T_INT:
2391       case T_LONG:
2392       case T_FLOAT:
2393       case T_DOUBLE:
2394       case T_VOID:
2395         return in;
2396 
2397       default:
2398         ShouldNotReachHere();
2399         return T_CONFLICT;
2400     }
2401   }
2402 
2403   void* operator new(size_t size, size_t fp_size) throw() {
2404     assert(fp_size >= size, "sanity check");
2405     void* p = AllocateHeap(fp_size, mtCode);
2406     memset(p, 0, fp_size);
2407     return p;
2408   }
2409 
2410 public:
2411   template<typename Function>
2412   void iterate_args(Function function) {
2413     for (int i = 0; i < length(); i++) {
2414       function(element_at(i));









2415     }
2416   }
2417 
2418   static AdapterFingerPrint* allocate(const GrowableArray<SigEntry>* sig, bool has_ro_adapter = false) {
2419     int len = total_args_passed_in_sig(sig);

2420     int size_in_bytes = BytesPerWord * compute_size_in_words(len);
2421     AdapterFingerPrint* afp = new (size_in_bytes) AdapterFingerPrint(sig, has_ro_adapter);
2422     assert((afp->size() * BytesPerWord) == size_in_bytes, "should match");
2423     return afp;
2424   }
2425 
2426   static void deallocate(AdapterFingerPrint* fp) {
2427     FreeHeap(fp);
2428   }
2429 
2430   bool has_ro_adapter() const {
2431     return _has_ro_adapter;

2432   }
2433 
2434   int length() const {
2435     return _length;
2436   }
2437 
2438   unsigned int compute_hash() {
2439     int hash = 0;
2440     for (int i = 0; i < length(); i++) {
2441       const Element& v = element_at(i);
2442       //Add arithmetic operation to the hash, like +3 to improve hashing
2443       hash = ((hash << 8) ^ v.hash() ^ (hash >> 5)) + 3;
2444     }
2445     return (unsigned int)hash;
2446   }
2447 
2448   const char* as_string() {
2449     stringStream st;
2450     st.print("{");
2451     if (_has_ro_adapter) {
2452       st.print("has_ro_adapter");
2453     } else {
2454       st.print("no_ro_adapter");
2455     }
2456     for (int i = 0; i < length(); i++) {
2457       st.print(", ");
2458       const Element& elem = element_at(i);
2459       st.print("{%s, %d}", type2name(elem.bt()), elem.offset());
2460     }
2461     st.print("}");
2462     return st.as_string();
2463   }
2464 
2465   const char* as_basic_args_string() {
2466     stringStream st;
2467     bool long_prev = false;
2468     iterate_args([&] (const Element& arg) {
2469       if (long_prev) {
2470         long_prev = false;
2471         if (arg.bt() == T_VOID) {
2472           st.print("J");
2473         } else {
2474           st.print("L");
2475         }
2476       }
2477       if (arg.bt() == T_LONG) {
2478         long_prev = true;
2479       } else if (arg.bt() != T_VOID) {
2480         st.print("%c", type2char(arg.bt()));



2481       }
2482     });
2483     if (long_prev) {
2484       st.print("L");
2485     }
2486     return st.as_string();
2487   }
2488 



















































2489   bool equals(AdapterFingerPrint* other) {
2490     if (other->_has_ro_adapter != _has_ro_adapter) {
2491       return false;
2492     } else if (other->_length != _length) {
2493       return false;
2494     } else {
2495       for (int i = 0; i < _length; i++) {
2496         if (element_at(i) != other->element_at(i)) {
2497           return false;
2498         }
2499       }
2500     }
2501     return true;
2502   }
2503 
2504   // methods required by virtue of being a MetaspaceObj
2505   void metaspace_pointers_do(MetaspaceClosure* it) { return; /* nothing to do here */ }
2506   int size() const { return compute_size_in_words(_length); }
2507   MetaspaceObj::Type type() const { return AdapterFingerPrintType; }
2508 
2509   static bool equals(AdapterFingerPrint* const& fp1, AdapterFingerPrint* const& fp2) {
2510     NOT_PRODUCT(_equals++);
2511     return fp1->equals(fp2);
2512   }
2513 
2514   static unsigned int compute_hash(AdapterFingerPrint* const& fp) {
2515     return fp->compute_hash();
2516   }

2519 #if INCLUDE_CDS
2520 static inline bool adapter_fp_equals_compact_hashtable_entry(AdapterHandlerEntry* entry, AdapterFingerPrint* fp, int len_unused) {
2521   return AdapterFingerPrint::equals(entry->fingerprint(), fp);
2522 }
2523 
2524 class ArchivedAdapterTable : public OffsetCompactHashtable<
2525   AdapterFingerPrint*,
2526   AdapterHandlerEntry*,
2527   adapter_fp_equals_compact_hashtable_entry> {};
2528 #endif // INCLUDE_CDS
2529 
2530 // A hashtable mapping from AdapterFingerPrints to AdapterHandlerEntries
2531 using AdapterHandlerTable = HashTable<AdapterFingerPrint*, AdapterHandlerEntry*, 293,
2532                   AnyObj::C_HEAP, mtCode,
2533                   AdapterFingerPrint::compute_hash,
2534                   AdapterFingerPrint::equals>;
2535 static AdapterHandlerTable* _adapter_handler_table;
2536 static GrowableArray<AdapterHandlerEntry*>* _adapter_handler_list = nullptr;
2537 
2538 // Find a entry with the same fingerprint if it exists
2539 AdapterHandlerEntry* AdapterHandlerLibrary::lookup(const GrowableArray<SigEntry>* sig, bool has_ro_adapter) {
2540   NOT_PRODUCT(_lookups++);
2541   assert_lock_strong(AdapterHandlerLibrary_lock);
2542   AdapterFingerPrint* fp = AdapterFingerPrint::allocate(sig, has_ro_adapter);
2543   AdapterHandlerEntry* entry = nullptr;
2544 #if INCLUDE_CDS
2545   // if we are building the archive then the archived adapter table is
2546   // not valid and we need to use the ones added to the runtime table
2547   if (AOTCodeCache::is_using_adapter()) {
2548     // Search archived table first. It is read-only table so can be searched without lock
2549     entry = _aot_adapter_handler_table.lookup(fp, fp->compute_hash(), 0 /* unused */);
2550 #ifndef PRODUCT
2551     if (entry != nullptr) {
2552       _archived_hits++;
2553     }
2554 #endif
2555   }
2556 #endif // INCLUDE_CDS
2557   if (entry == nullptr) {
2558     assert_lock_strong(AdapterHandlerLibrary_lock);
2559     AdapterHandlerEntry** entry_p = _adapter_handler_table->get(fp);
2560     if (entry_p != nullptr) {
2561       entry = *entry_p;
2562       assert(entry->fingerprint()->equals(fp), "fingerprint mismatch key fp %s %s (hash=%d) != found fp %s %s (hash=%d)",

2579   TableStatistics ts = _adapter_handler_table->statistics_calculate(size);
2580   ts.print(tty, "AdapterHandlerTable");
2581   tty->print_cr("AdapterHandlerTable (table_size=%d, entries=%d)",
2582                 _adapter_handler_table->table_size(), _adapter_handler_table->number_of_entries());
2583   int total_hits = _archived_hits + _runtime_hits;
2584   tty->print_cr("AdapterHandlerTable: lookups %d equals %d hits %d (archived=%d+runtime=%d)",
2585                 _lookups, _equals, total_hits, _archived_hits, _runtime_hits);
2586 }
2587 #endif
2588 
2589 // ---------------------------------------------------------------------------
2590 // Implementation of AdapterHandlerLibrary
2591 AdapterHandlerEntry* AdapterHandlerLibrary::_no_arg_handler = nullptr;
2592 AdapterHandlerEntry* AdapterHandlerLibrary::_int_arg_handler = nullptr;
2593 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_arg_handler = nullptr;
2594 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_int_arg_handler = nullptr;
2595 AdapterHandlerEntry* AdapterHandlerLibrary::_obj_obj_arg_handler = nullptr;
2596 #if INCLUDE_CDS
2597 ArchivedAdapterTable AdapterHandlerLibrary::_aot_adapter_handler_table;
2598 #endif // INCLUDE_CDS
2599 static const int AdapterHandlerLibrary_size = 48*K;
2600 BufferBlob* AdapterHandlerLibrary::_buffer = nullptr;
2601 volatile uint AdapterHandlerLibrary::_id_counter = 0;
2602 
2603 BufferBlob* AdapterHandlerLibrary::buffer_blob() {
2604   assert(_buffer != nullptr, "should be initialized");
2605   return _buffer;
2606 }
2607 
2608 static void post_adapter_creation(const AdapterHandlerEntry* entry) {
2609   if (Forte::is_enabled() || JvmtiExport::should_post_dynamic_code_generated()) {
2610     AdapterBlob* adapter_blob = entry->adapter_blob();
2611     char blob_id[256];
2612     jio_snprintf(blob_id,
2613                  sizeof(blob_id),
2614                  "%s(%s)",
2615                  adapter_blob->name(),
2616                  entry->fingerprint()->as_string());
2617     if (Forte::is_enabled()) {
2618       Forte::register_stub(blob_id, adapter_blob->content_begin(), adapter_blob->content_end());
2619     }

2627 void AdapterHandlerLibrary::initialize() {
2628   {
2629     ResourceMark rm;
2630     _adapter_handler_table = new (mtCode) AdapterHandlerTable();
2631     _buffer = BufferBlob::create("adapters", AdapterHandlerLibrary_size);
2632   }
2633 
2634 #if INCLUDE_CDS
2635   // Link adapters in AOT Cache to their code in AOT Code Cache
2636   if (AOTCodeCache::is_using_adapter() && !_aot_adapter_handler_table.empty()) {
2637     link_aot_adapters();
2638     lookup_simple_adapters();
2639     return;
2640   }
2641 #endif // INCLUDE_CDS
2642 
2643   ResourceMark rm;
2644   {
2645     MutexLocker mu(AdapterHandlerLibrary_lock);
2646 
2647     CompiledEntrySignature no_args;
2648     no_args.compute_calling_conventions();
2649     _no_arg_handler = create_adapter(no_args, true);
2650 
2651     CompiledEntrySignature obj_args;
2652     SigEntry::add_entry(obj_args.sig(), T_OBJECT);
2653     obj_args.compute_calling_conventions();
2654     _obj_arg_handler = create_adapter(obj_args, true);
2655 
2656     CompiledEntrySignature int_args;
2657     SigEntry::add_entry(int_args.sig(), T_INT);
2658     int_args.compute_calling_conventions();
2659     _int_arg_handler = create_adapter(int_args, true);
2660 
2661     CompiledEntrySignature obj_int_args;
2662     SigEntry::add_entry(obj_int_args.sig(), T_OBJECT);
2663     SigEntry::add_entry(obj_int_args.sig(), T_INT);
2664     obj_int_args.compute_calling_conventions();
2665     _obj_int_arg_handler = create_adapter(obj_int_args, true);
2666 
2667     CompiledEntrySignature obj_obj_args;
2668     SigEntry::add_entry(obj_obj_args.sig(), T_OBJECT);
2669     SigEntry::add_entry(obj_obj_args.sig(), T_OBJECT);
2670     obj_obj_args.compute_calling_conventions();
2671     _obj_obj_arg_handler = create_adapter(obj_obj_args, true);
2672 
2673     // we should always get an entry back but we don't have any
2674     // associated blob on Zero
2675     assert(_no_arg_handler != nullptr &&
2676            _obj_arg_handler != nullptr &&
2677            _int_arg_handler != nullptr &&
2678            _obj_int_arg_handler != nullptr &&
2679            _obj_obj_arg_handler != nullptr, "Initial adapter handlers must be properly created");
2680   }
2681 
2682   // Outside of the lock
2683 #ifndef ZERO
2684   // no blobs to register when we are on Zero
2685   post_adapter_creation(_no_arg_handler);
2686   post_adapter_creation(_obj_arg_handler);
2687   post_adapter_creation(_int_arg_handler);
2688   post_adapter_creation(_obj_int_arg_handler);
2689   post_adapter_creation(_obj_obj_arg_handler);
2690 #endif // ZERO
2691 }
2692 
2693 AdapterHandlerEntry* AdapterHandlerLibrary::new_entry(AdapterFingerPrint* fingerprint) {
2694   uint id = (uint)AtomicAccess::add((int*)&_id_counter, 1);
2695   assert(id > 0, "we can never overflow because AOT cache cannot contain more than 2^32 methods");
2696   return AdapterHandlerEntry::allocate(id, fingerprint);
2697 }
2698 
2699 AdapterHandlerEntry* AdapterHandlerLibrary::get_simple_adapter(const methodHandle& method) {
2700   int total_args_passed = method->size_of_parameters(); // All args on stack
2701   if (total_args_passed == 0) {
2702     return _no_arg_handler;
2703   } else if (total_args_passed == 1) {
2704     if (!method->is_static()) {
2705       if (InlineTypePassFieldsAsArgs && method->method_holder()->is_inline_klass()) {
2706         return nullptr;
2707       }
2708       return _obj_arg_handler;
2709     }
2710     switch (method->signature()->char_at(1)) {
2711       case JVM_SIGNATURE_CLASS: {
2712         if (InlineTypePassFieldsAsArgs) {
2713           SignatureStream ss(method->signature());
2714           InlineKlass* vk = ss.as_inline_klass(method->method_holder());
2715           if (vk != nullptr) {
2716             return nullptr;
2717           }
2718         }
2719         return _obj_arg_handler;
2720       }
2721       case JVM_SIGNATURE_ARRAY:
2722         return _obj_arg_handler;
2723       case JVM_SIGNATURE_INT:
2724       case JVM_SIGNATURE_BOOLEAN:
2725       case JVM_SIGNATURE_CHAR:
2726       case JVM_SIGNATURE_BYTE:
2727       case JVM_SIGNATURE_SHORT:
2728         return _int_arg_handler;
2729     }
2730   } else if (total_args_passed == 2 &&
2731              !method->is_static() && (!InlineTypePassFieldsAsArgs || !method->method_holder()->is_inline_klass())) {
2732     switch (method->signature()->char_at(1)) {
2733       case JVM_SIGNATURE_CLASS: {
2734         if (InlineTypePassFieldsAsArgs) {
2735           SignatureStream ss(method->signature());
2736           InlineKlass* vk = ss.as_inline_klass(method->method_holder());
2737           if (vk != nullptr) {
2738             return nullptr;
2739           }
2740         }
2741         return _obj_obj_arg_handler;
2742       }
2743       case JVM_SIGNATURE_ARRAY:
2744         return _obj_obj_arg_handler;
2745       case JVM_SIGNATURE_INT:
2746       case JVM_SIGNATURE_BOOLEAN:
2747       case JVM_SIGNATURE_CHAR:
2748       case JVM_SIGNATURE_BYTE:
2749       case JVM_SIGNATURE_SHORT:
2750         return _obj_int_arg_handler;
2751     }
2752   }
2753   return nullptr;
2754 }
2755 
2756 CompiledEntrySignature::CompiledEntrySignature(Method* method) :
2757   _method(method), _num_inline_args(0), _has_inline_recv(false),
2758   _regs(nullptr), _regs_cc(nullptr), _regs_cc_ro(nullptr),
2759   _args_on_stack(0), _args_on_stack_cc(0), _args_on_stack_cc_ro(0),
2760   _c1_needs_stack_repair(false), _c2_needs_stack_repair(false), _supers(nullptr) {
2761   _sig = new GrowableArray<SigEntry>((method != nullptr) ? method->size_of_parameters() : 1);
2762   _sig_cc = new GrowableArray<SigEntry>((method != nullptr) ? method->size_of_parameters() : 1);
2763   _sig_cc_ro = new GrowableArray<SigEntry>((method != nullptr) ? method->size_of_parameters() : 1);
2764 }
2765 
2766 // See if we can save space by sharing the same entry for VIEP and VIEP(RO),
2767 // or the same entry for VEP and VIEP(RO).
2768 CodeOffsets::Entries CompiledEntrySignature::c1_inline_ro_entry_type() const {
2769   if (!has_scalarized_args()) {
2770     // VEP/VIEP/VIEP(RO) all share the same entry. There's no packing.
2771     return CodeOffsets::Verified_Entry;
2772   }
2773   if (_method->is_static()) {
2774     // Static methods don't need VIEP(RO)
2775     return CodeOffsets::Verified_Entry;
2776   }
2777 
2778   if (has_inline_recv()) {
2779     if (num_inline_args() == 1) {
2780       // Share same entry for VIEP and VIEP(RO).
2781       // This is quite common: we have an instance method in an InlineKlass that has
2782       // no inline type args other than <this>.
2783       return CodeOffsets::Verified_Inline_Entry;
2784     } else {
2785       assert(num_inline_args() > 1, "must be");
2786       // No sharing:
2787       //   VIEP(RO) -- <this> is passed as object
2788       //   VEP      -- <this> is passed as fields
2789       return CodeOffsets::Verified_Inline_Entry_RO;
2790     }

2791   }
2792 
2793   // Either a static method, or <this> is not an inline type
2794   if (args_on_stack_cc() != args_on_stack_cc_ro()) {
2795     // No sharing:
2796     // Some arguments are passed on the stack, and we have inserted reserved entries
2797     // into the VEP, but we never insert reserved entries into the VIEP(RO).
2798     return CodeOffsets::Verified_Inline_Entry_RO;
2799   } else {
2800     // Share same entry for VEP and VIEP(RO).
2801     return CodeOffsets::Verified_Entry;
2802   }
2803 }
2804 
2805 // Returns all super methods (transitive) in classes and interfaces that are overridden by the current method.
2806 GrowableArray<Method*>* CompiledEntrySignature::get_supers() {
2807   if (_supers != nullptr) {
2808     return _supers;
2809   }
2810   _supers = new GrowableArray<Method*>();
2811   // Skip private, static, and <init> methods
2812   if (_method->is_private() || _method->is_static() || _method->is_object_constructor()) {
2813     return _supers;
2814   }
2815   Symbol* name = _method->name();
2816   Symbol* signature = _method->signature();
2817   const Klass* holder = _method->method_holder()->super();
2818   Symbol* holder_name = holder->name();
2819   JavaThread* current = JavaThread::current();
2820   HandleMark hm(current);
2821   Handle loader(current, _method->method_holder()->class_loader());
2822 
2823   // Walk up the class hierarchy and search for super methods
2824   while (holder != nullptr) {
2825     Method* super_method = holder->lookup_method(name, signature);
2826     if (super_method == nullptr) {
2827       break;
2828     }
2829     if (!super_method->is_static() && !super_method->is_private() &&
2830         (!super_method->is_package_private() ||
2831          super_method->method_holder()->is_same_class_package(loader(), holder_name))) {
2832       _supers->push(super_method);
2833     }
2834     holder = super_method->method_holder()->super();
2835   }
2836   // Search interfaces for super methods
2837   Array<InstanceKlass*>* interfaces = _method->method_holder()->transitive_interfaces();
2838   for (int i = 0; i < interfaces->length(); ++i) {
2839     Method* m = interfaces->at(i)->lookup_method(name, signature);
2840     if (m != nullptr && !m->is_static() && m->is_public()) {
2841       _supers->push(m);
2842     }
2843   }
2844   return _supers;
2845 }
2846 
2847 bool CompiledEntrySignature::check_supers_and_deoptimize(int arg_num) {
2848   assert(JavaThread::current()->thread_state() == _thread_in_vm, "must be in vm state");
2849 
2850   bool scalar_super = false;
2851   bool non_scalar_super = false;
2852 
2853   GrowableArray<Method*>* supers = get_supers();
2854   for (int i = 0; i < supers->length(); ++i) {
2855     Method* super_method = supers->at(i);
2856     if (super_method->is_scalarized_arg(arg_num)) {
2857       scalar_super = true;
2858     } else {
2859       non_scalar_super = true;
2860     }
2861   }
2862 #ifdef ASSERT
2863   // Randomly enable below code paths for stress testing
2864   bool stress = StressCallingConvention;
2865   if (stress && (os::random() & 1) == 1) {
2866     non_scalar_super = true;
2867     if ((os::random() & 1) == 1) {
2868       scalar_super = true;
2869     }
2870   }
2871 #endif
2872   if (non_scalar_super) {
2873     // Found a super method with a non-scalarized argument. Fall back to the non-scalarized calling convention.
2874     if (scalar_super) {
2875       // Found non-scalar *and* scalar super methods. We can't handle both.
2876       // Mark the scalar method as mismatch and re-compile call sites to use non-scalarized calling convention.
2877       for (int i = 0; i < supers->length(); ++i) {
2878         Method* super_method = supers->at(i);
2879         if (super_method->is_scalarized_arg(arg_num) DEBUG_ONLY(|| (stress && (os::random() & 1) == 1))) {
2880           JavaThread* thread = JavaThread::current();
2881           HandleMark hm(thread);
2882           methodHandle mh(thread, super_method);
2883           DeoptimizationScope deopt_scope;
2884           {
2885             // Keep the lock scope minimal. Prevent interference with other
2886             // dependency checks by setting mismatch and marking within the lock.
2887             MutexLocker ml(Compile_lock, Mutex::_safepoint_check_flag);
2888             super_method->set_mismatch();
2889             CodeCache::mark_for_deoptimization(&deopt_scope, mh());
2890           }
2891           deopt_scope.deoptimize_marked();
2892         }
2893       }
2894     }
2895   }
2896 
2897   return non_scalar_super;
2898 }
2899 
2900 // Iterate over arguments and compute scalarized and non-scalarized signatures
2901 void CompiledEntrySignature::compute_calling_conventions(bool link_time) {
2902   assert(JavaThread::current()->thread_state() != _thread_in_native, "must not be in native");
2903   assert(link_time || (_method != nullptr && _method->adapter() != nullptr), "invariant");
2904   bool has_scalarized = false;
2905   if (_method != nullptr) {
2906     InstanceKlass* holder = _method->method_holder();
2907     int arg_num = 0;
2908     if (!_method->is_static()) {
2909       // We shouldn't scalarize 'this' in a value class constructor
2910       if (holder->is_inline_klass() && InlineKlass::cast(holder)->can_be_passed_as_fields() &&
2911           !_method->is_object_constructor() && (link_time || _method->is_scalarized_arg(arg_num))) {
2912         _sig_cc->appendAll(InlineKlass::cast(holder)->extended_sig());
2913         _sig_cc->insert_before(1, SigEntry(T_OBJECT, 0, nullptr, false, true)); // buffer argument
2914         has_scalarized = true;
2915         _has_inline_recv = true;
2916         _num_inline_args++;
2917       } else {
2918         SigEntry::add_entry(_sig_cc, T_OBJECT, holder->name());
2919       }
2920       SigEntry::add_entry(_sig, T_OBJECT, holder->name());
2921       SigEntry::add_entry(_sig_cc_ro, T_OBJECT, holder->name());
2922       arg_num++;
2923     }
2924     for (SignatureStream ss(_method->signature()); !ss.at_return_type(); ss.next()) {
2925       const BasicType bt = ss.type();
2926       if (InlineTypePassFieldsAsArgs && bt == T_OBJECT) {
2927         InlineKlass* vk = ss.as_inline_klass(holder);
2928         if (vk != nullptr && vk->can_be_passed_as_fields() && (link_time || _method->is_scalarized_arg(arg_num))) {
2929           // Check for a calling convention mismatch with super method(s)
2930           if (link_time && check_supers_and_deoptimize(arg_num)) {
2931             // Fall back to non-scalarized calling convention
2932             SigEntry::add_entry(_sig_cc, T_OBJECT, ss.as_symbol());
2933             SigEntry::add_entry(_sig_cc_ro, T_OBJECT, ss.as_symbol());
2934           } else {
2935             _num_inline_args++;
2936             has_scalarized = true;
2937             int last = _sig_cc->length();
2938             int last_ro = _sig_cc_ro->length();
2939             _sig_cc->appendAll(vk->extended_sig());
2940             _sig_cc_ro->appendAll(vk->extended_sig());
2941             // buffer argument
2942             _sig_cc->insert_before(last + 1, SigEntry(T_OBJECT, 0, nullptr, false, true));
2943             _sig_cc_ro->insert_before(last_ro + 1, SigEntry(T_OBJECT, 0, nullptr, false, true));
2944             // Insert InlineTypeNode::NullMarker field right after T_METADATA delimiter
2945             _sig_cc->insert_before(last + 2, SigEntry(T_BOOLEAN, -1, nullptr, true, false));
2946             _sig_cc_ro->insert_before(last_ro + 2, SigEntry(T_BOOLEAN, -1, nullptr, true, false));
2947           }
2948         } else {
2949           SigEntry::add_entry(_sig_cc, T_OBJECT, ss.as_symbol());
2950           SigEntry::add_entry(_sig_cc_ro, T_OBJECT, ss.as_symbol());
2951         }
2952       } else {
2953         SigEntry::add_entry(_sig_cc, ss.type(), ss.as_symbol());
2954         SigEntry::add_entry(_sig_cc_ro, ss.type(), ss.as_symbol());
2955       }
2956       SigEntry::add_entry(_sig, bt, ss.as_symbol());
2957       if (bt != T_VOID) {
2958         arg_num++;
2959       }
2960     }
2961   }

2962 
2963   // Compute the non-scalarized calling convention
2964   _regs = NEW_RESOURCE_ARRAY(VMRegPair, _sig->length());
2965   _args_on_stack = SharedRuntime::java_calling_convention(_sig, _regs);
2966 
2967   // Compute the scalarized calling conventions if there are scalarized inline types in the signature
2968   if (has_scalarized && !_method->is_native()) {
2969     _regs_cc = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc->length());
2970     _args_on_stack_cc = SharedRuntime::java_calling_convention(_sig_cc, _regs_cc);
2971 
2972     _regs_cc_ro = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc_ro->length());
2973     _args_on_stack_cc_ro = SharedRuntime::java_calling_convention(_sig_cc_ro, _regs_cc_ro);
2974 
2975     _c1_needs_stack_repair = (_args_on_stack_cc < _args_on_stack) || (_args_on_stack_cc_ro < _args_on_stack);
2976     _c2_needs_stack_repair = (_args_on_stack_cc > _args_on_stack) || (_args_on_stack_cc > _args_on_stack_cc_ro);
2977 
2978     // Upper bound on stack arguments to avoid hitting the argument limit and
2979     // bailing out of compilation ("unsupported incoming calling sequence").
2980     // TODO 8281260 We need a reasonable limit (flag?) here
2981     if (MAX2(_args_on_stack_cc, _args_on_stack_cc_ro) <= 75) {
2982       return; // Success
2983     }
2984   }
2985 
2986   // No scalarized args
2987   _sig_cc = _sig;
2988   _regs_cc = _regs;
2989   _args_on_stack_cc = _args_on_stack;
2990 
2991   _sig_cc_ro = _sig;
2992   _regs_cc_ro = _regs;
2993   _args_on_stack_cc_ro = _args_on_stack;
2994 }
2995 
2996 void CompiledEntrySignature::initialize_from_fingerprint(AdapterFingerPrint* fingerprint) {
2997   _has_inline_recv = fingerprint->has_ro_adapter();
2998 
2999   int value_object_count = 0;
3000   BasicType prev_bt = T_ILLEGAL;
3001   bool has_scalarized_arguments = false;
3002   bool long_prev = false;
3003   int long_prev_offset = -1;
3004   bool skipping_inline_recv = false;
3005   bool receiver_handled = false;
3006 
3007   fingerprint->iterate_args([&] (const AdapterFingerPrint::Element& arg) {
3008     BasicType bt = arg.bt();
3009     int offset = arg.offset();
3010 
3011     if (long_prev) {
3012       long_prev = false;
3013       BasicType bt_to_add;
3014       if (bt == T_VOID) {
3015         bt_to_add = T_LONG;
3016       } else {
3017         bt_to_add = T_OBJECT;
3018       }
3019       if (value_object_count == 0) {
3020         SigEntry::add_entry(_sig, bt_to_add);
3021       }
3022       assert(long_prev_offset != 0, "no buffer argument here");
3023       SigEntry::add_entry(_sig_cc, bt_to_add, nullptr, long_prev_offset);
3024       if (!skipping_inline_recv) {
3025         SigEntry::add_entry(_sig_cc_ro, bt_to_add, nullptr, long_prev_offset);
3026       }
3027     }
3028 
3029     switch (bt) {
3030       case T_VOID:
3031         if (prev_bt != T_LONG && prev_bt != T_DOUBLE) {
3032           assert(InlineTypePassFieldsAsArgs, "unexpected end of inline type");
3033           value_object_count--;
3034           SigEntry::add_entry(_sig_cc, T_VOID, nullptr, offset);
3035           if (!skipping_inline_recv) {
3036             SigEntry::add_entry(_sig_cc_ro, T_VOID, nullptr, offset);
3037           } else if (value_object_count == 0) {
3038             skipping_inline_recv = false;
3039           }
3040           assert(value_object_count >= 0, "invalid value object count");
3041         } else {
3042           // Nothing to add for _sig: We already added an addition T_VOID in add_entry() when adding T_LONG or T_DOUBLE.
3043         }
3044         break;
3045       case T_INT:
3046       case T_FLOAT:
3047       case T_DOUBLE:
3048         if (value_object_count == 0) {
3049           SigEntry::add_entry(_sig, bt);
3050         }
3051         SigEntry::add_entry(_sig_cc, bt, nullptr, offset);
3052         if (!skipping_inline_recv) {
3053           SigEntry::add_entry(_sig_cc_ro, bt, nullptr, offset);
3054         }
3055         break;
3056       case T_LONG:
3057         long_prev = true;
3058         long_prev_offset = offset;
3059         break;
3060       case T_BOOLEAN:
3061       case T_CHAR:
3062       case T_BYTE:
3063       case T_SHORT:
3064       case T_OBJECT:
3065       case T_ARRAY:
3066         assert(value_object_count > 0, "must be value object field");
3067         assert(offset != 0 || (bt == T_OBJECT && prev_bt == T_METADATA), "buffer input expected here");
3068         SigEntry::add_entry(_sig_cc, bt, nullptr, offset, offset == -1, offset == 0);
3069         if (!skipping_inline_recv) {
3070           SigEntry::add_entry(_sig_cc_ro, bt, nullptr, offset, offset == -1, offset == 0);
3071         }
3072         break;
3073       case T_METADATA:
3074         assert(InlineTypePassFieldsAsArgs, "unexpected start of inline type");
3075         if (value_object_count == 0) {
3076           SigEntry::add_entry(_sig, T_OBJECT);
3077         }
3078         SigEntry::add_entry(_sig_cc, T_METADATA, nullptr, offset);
3079         if (!skipping_inline_recv) {
3080           if (!receiver_handled && _has_inline_recv && value_object_count == 0) {
3081             SigEntry::add_entry(_sig_cc_ro, T_OBJECT);
3082             skipping_inline_recv = true;
3083             receiver_handled = true;
3084           } else {
3085             SigEntry::add_entry(_sig_cc_ro, T_METADATA, nullptr, offset);
3086           }
3087         }
3088         value_object_count++;
3089         has_scalarized_arguments = true;
3090         break;
3091       default: {
3092         fatal("Unexpected BasicType: %s", basictype_to_str(bt));
3093       }
3094     }
3095     prev_bt = bt;
3096   });
3097 
3098   if (long_prev) {
3099     // If previous bt was T_LONG and we reached the end of the signature, we know that it must be a T_OBJECT.
3100     SigEntry::add_entry(_sig, T_OBJECT);
3101     SigEntry::add_entry(_sig_cc, T_OBJECT);
3102     SigEntry::add_entry(_sig_cc_ro, T_OBJECT);
3103   }
3104   assert(value_object_count == 0, "invalid value object count");
3105 
3106 #ifdef ASSERT
3107   if (_has_inline_recv) {
3108     // In RO signatures, inline receivers must be represented as a single T_OBJECT
3109     assert(_sig_cc_ro->length() >= 1, "sig_cc_ro must include receiver");
3110     assert(_sig_cc_ro->at(0)._bt == T_OBJECT,
3111            "sig_cc_ro must represent inline receiver as T_OBJECT");
3112     assert(_sig_cc_ro->length() <= _sig_cc->length(),
3113            "sig_cc_ro must not be longer than sig_cc");
3114   }
3115 #endif
3116 
3117   _regs = NEW_RESOURCE_ARRAY(VMRegPair, _sig->length());
3118   _args_on_stack = SharedRuntime::java_calling_convention(_sig, _regs);
3119 
3120   // Compute the scalarized calling conventions if there are scalarized inline types in the signature
3121   if (has_scalarized_arguments) {
3122     _regs_cc = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc->length());
3123     _args_on_stack_cc = SharedRuntime::java_calling_convention(_sig_cc, _regs_cc);
3124 
3125     _regs_cc_ro = NEW_RESOURCE_ARRAY(VMRegPair, _sig_cc_ro->length());
3126     _args_on_stack_cc_ro = SharedRuntime::java_calling_convention(_sig_cc_ro, _regs_cc_ro);
3127 
3128     _c1_needs_stack_repair = (_args_on_stack_cc < _args_on_stack) || (_args_on_stack_cc_ro < _args_on_stack);
3129     _c2_needs_stack_repair = (_args_on_stack_cc > _args_on_stack) || (_args_on_stack_cc > _args_on_stack_cc_ro);
3130   } else {
3131     // No scalarized args
3132     _sig_cc = _sig;
3133     _regs_cc = _regs;
3134     _args_on_stack_cc = _args_on_stack;
3135 
3136     _sig_cc_ro = _sig;
3137     _regs_cc_ro = _regs;
3138     _args_on_stack_cc_ro = _args_on_stack;
3139   }
3140 
3141 #ifdef ASSERT
3142   {
3143     AdapterFingerPrint* compare_fp = AdapterFingerPrint::allocate(_sig_cc, _has_inline_recv);
3144     assert(fingerprint->equals(compare_fp), "%s - %s", fingerprint->as_string(), compare_fp->as_string());
3145     AdapterFingerPrint::deallocate(compare_fp);
3146   }
3147 #endif
3148 }
3149 
3150 const char* AdapterHandlerEntry::_entry_names[] = {
3151   "i2c", "c2i", "c2i_unverified", "c2i_no_clinit_check"
3152 };
3153 
3154 #ifdef ASSERT
3155 void AdapterHandlerLibrary::verify_adapter_sharing(CompiledEntrySignature& ces, AdapterHandlerEntry* cached_entry) {
3156   // we can only check for the same code if there is any
3157 #ifndef ZERO
3158   AdapterHandlerEntry* comparison_entry = create_adapter(ces, false, true);
3159   assert(comparison_entry->adapter_blob() == nullptr, "no blob should be created when creating an adapter for comparison");
3160   assert(comparison_entry->compare_code(cached_entry), "code must match");
3161   // Release the one just created
3162   AdapterHandlerEntry::deallocate(comparison_entry);
3163 # endif // ZERO
3164 }
3165 #endif /* ASSERT*/
3166 
3167 AdapterHandlerEntry* AdapterHandlerLibrary::get_adapter(const methodHandle& method) {
3168   assert(!method->is_abstract() || InlineTypePassFieldsAsArgs, "abstract methods do not have adapters");
3169   // Use customized signature handler.  Need to lock around updates to
3170   // the _adapter_handler_table (it is not safe for concurrent readers
3171   // and a single writer: this could be fixed if it becomes a
3172   // problem).
3173 
3174   // Fast-path for trivial adapters
3175   AdapterHandlerEntry* entry = get_simple_adapter(method);
3176   if (entry != nullptr) {
3177     return entry;
3178   }
3179 
3180   ResourceMark rm;
3181   bool new_entry = false;
3182 
3183   CompiledEntrySignature ces(method());
3184   ces.compute_calling_conventions();
3185   if (ces.has_scalarized_args()) {
3186     if (!method->has_scalarized_args()) {
3187       method->set_has_scalarized_args();
3188     }
3189     if (ces.c1_needs_stack_repair()) {
3190       method->set_c1_needs_stack_repair();
3191     }
3192     if (ces.c2_needs_stack_repair() && !method->c2_needs_stack_repair()) {
3193       method->set_c2_needs_stack_repair();
3194     }
3195   }
3196 




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

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

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


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

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

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

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

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

4009         event.set_method(method);
4010         event.commit();
4011       }
4012     }
4013   }
4014   return activation;
4015 }
4016 
4017 void SharedRuntime::on_slowpath_allocation_exit(JavaThread* current) {
4018   // After any safepoint, just before going back to compiled code,
4019   // we inform the GC that we will be doing initializing writes to
4020   // this object in the future without emitting card-marks, so
4021   // GC may take any compensating steps.
4022 
4023   oop new_obj = current->vm_result_oop();
4024   if (new_obj == nullptr) return;
4025 
4026   BarrierSet *bs = BarrierSet::barrier_set();
4027   bs->on_slowpath_allocation_exit(current, new_obj);
4028 }
4029 
4030 // We are at a compiled code to interpreter call. We need backing
4031 // buffers for all inline type arguments. Allocate an object array to
4032 // hold them (convenient because once we're done with it we don't have
4033 // to worry about freeing it).
4034 oop SharedRuntime::allocate_inline_types_impl(JavaThread* current, methodHandle callee, bool allocate_receiver, bool from_c1, TRAPS) {
4035   assert(InlineTypePassFieldsAsArgs, "no reason to call this");
4036   ResourceMark rm;
4037 
4038   // Retrieve arguments passed at the call
4039   RegisterMap reg_map2(THREAD,
4040                        RegisterMap::UpdateMap::include,
4041                        RegisterMap::ProcessFrames::include,
4042                        RegisterMap::WalkContinuation::skip);
4043   frame stubFrame = THREAD->last_frame();
4044   frame callerFrame = stubFrame.sender(&reg_map2);
4045   if (from_c1) {
4046     callerFrame = callerFrame.sender(&reg_map2);
4047   }
4048   int arg_size;
4049   const GrowableArray<SigEntry>* sig = allocate_receiver ? callee->adapter()->get_sig_cc() : callee->adapter()->get_sig_cc_ro();
4050   assert(sig != nullptr, "sig should never be null");
4051   TempNewSymbol tmp_sig = SigEntry::create_symbol(sig);
4052   VMRegPair* reg_pairs = find_callee_arguments(tmp_sig, false, false, &arg_size);
4053 
4054   int nb_slots = 0;
4055   InstanceKlass* holder = callee->method_holder();
4056   allocate_receiver &= !callee->is_static() && holder->is_inline_klass() && callee->is_scalarized_arg(0);
4057   if (allocate_receiver) {
4058     nb_slots++;
4059   }
4060   int arg_num = callee->is_static() ? 0 : 1;
4061   for (SignatureStream ss(callee->signature()); !ss.at_return_type(); ss.next()) {
4062     BasicType bt = ss.type();
4063     if (bt == T_OBJECT && callee->is_scalarized_arg(arg_num)) {
4064       nb_slots++;
4065     }
4066     if (bt != T_VOID) {
4067       arg_num++;
4068     }
4069   }
4070   objArrayOop array_oop = nullptr;
4071   objArrayHandle array;
4072   arg_num = callee->is_static() ? 0 : 1;
4073   int i = 0;
4074   uint pos = 0;
4075   uint depth = 0;
4076   uint ignored = 0;
4077   if (allocate_receiver) {
4078     assert(sig->at(pos)._bt == T_METADATA, "scalarized value expected");
4079     pos++;
4080     ignored++;
4081     depth++;
4082     assert(sig->at(pos)._bt == T_OBJECT, "buffer argument");
4083     uint reg_pos = 0;
4084     assert(reg_pos < (uint)arg_size, "");
4085     VMRegPair reg_pair = reg_pairs[reg_pos];
4086     oop* buffer = callerFrame.oopmapreg_to_oop_location(reg_pair.first(), &reg_map2);
4087     instanceHandle h_buffer(THREAD, (instanceOop)*buffer);
4088     InlineKlass* vk = InlineKlass::cast(holder);
4089     if (h_buffer.not_null()) {
4090       assert(h_buffer->klass() == vk, "buffer not of expected class");
4091     } else {
4092       // Only allocate if buffer passed at the call is null
4093       if (array_oop == nullptr) {
4094         array_oop = oopFactory::new_objectArray(nb_slots, CHECK_NULL);
4095         array = objArrayHandle(THREAD, array_oop);
4096       }
4097       oop res = vk->allocate_instance(CHECK_NULL);
4098       array->obj_at_put(i, res);
4099     }
4100     i++;
4101   }
4102   for (SignatureStream ss(callee->signature()); !ss.at_return_type(); ss.next()) {
4103     BasicType bt = ss.type();
4104     if (bt == T_OBJECT && callee->is_scalarized_arg(arg_num)) {
4105       while (true) {
4106         BasicType bt = sig->at(pos)._bt;
4107         if (bt == T_METADATA) {
4108           depth++;
4109           ignored++;
4110           if (depth == 1) {
4111             break;
4112           }
4113         } else if (bt == T_VOID && sig->at(pos - 1)._bt != T_LONG && sig->at(pos - 1)._bt != T_DOUBLE) {
4114           ignored++;
4115           depth--;
4116         }
4117         pos++;
4118       }
4119       pos++;
4120       assert(sig->at(pos)._bt == T_OBJECT, "buffer argument expected");
4121       uint reg_pos = pos - ignored;
4122       assert(reg_pos < (uint)arg_size, "out of bound register?");
4123       VMRegPair reg_pair = reg_pairs[reg_pos];
4124       oop* buffer = callerFrame.oopmapreg_to_oop_location(reg_pair.first(), &reg_map2);
4125       instanceHandle h_buffer(THREAD, (instanceOop)*buffer);
4126       InlineKlass* vk = ss.as_inline_klass(holder);
4127       assert(vk != nullptr, "Unexpected klass");
4128       if (h_buffer.not_null()) {
4129         assert(h_buffer->klass() == vk, "buffer not of expected class");
4130       } else {
4131         // Only allocate if buffer passed at the call is null
4132         if (array_oop == nullptr) {
4133           array_oop = oopFactory::new_objectArray(nb_slots, CHECK_NULL);
4134           array = objArrayHandle(THREAD, array_oop);
4135         }
4136         oop res = vk->allocate_instance(CHECK_NULL);
4137         array->obj_at_put(i, res);
4138       }
4139       i++;
4140     }
4141     if (bt != T_VOID) {
4142       arg_num++;
4143     }
4144   }
4145   return array();
4146 }
4147 
4148 JRT_ENTRY(void, SharedRuntime::allocate_inline_types(JavaThread* current, Method* callee_method, bool allocate_receiver))
4149   methodHandle callee(current, callee_method);
4150   oop array = SharedRuntime::allocate_inline_types_impl(current, callee, allocate_receiver, false, CHECK);
4151   current->set_vm_result_oop(array);
4152 JRT_END
4153 
4154 // We're returning from an interpreted method: load each field into a
4155 // register following the calling convention
4156 JRT_LEAF(void, SharedRuntime::load_inline_type_fields_in_regs(JavaThread* current, oopDesc* res))
4157 {
4158   assert(res->klass()->is_inline_klass(), "only inline types here");
4159   ResourceMark rm;
4160   RegisterMap reg_map(current,
4161                       RegisterMap::UpdateMap::include,
4162                       RegisterMap::ProcessFrames::include,
4163                       RegisterMap::WalkContinuation::skip);
4164   frame stubFrame = current->last_frame();
4165   frame callerFrame = stubFrame.sender(&reg_map);
4166   assert(callerFrame.is_interpreted_frame(), "should be coming from interpreter");
4167 
4168   InlineKlass* vk = InlineKlass::cast(res->klass());
4169 
4170   const Array<SigEntry>* sig_vk = vk->extended_sig();
4171   const Array<VMRegPair>* regs = vk->return_regs();
4172 
4173   if (regs == nullptr) {
4174     // The fields of the inline klass don't fit in registers, bail out
4175     return;
4176   }
4177 
4178   int j = 1;
4179   for (int i = 0; i < sig_vk->length(); i++) {
4180     BasicType bt = sig_vk->at(i)._bt;
4181     if (bt == T_METADATA) {
4182       continue;
4183     }
4184     if (bt == T_VOID) {
4185       if (sig_vk->at(i-1)._bt == T_LONG ||
4186           sig_vk->at(i-1)._bt == T_DOUBLE) {
4187         j++;
4188       }
4189       continue;
4190     }
4191     int off = sig_vk->at(i)._offset;
4192     assert(off > 0, "offset in object should be positive");
4193     VMRegPair pair = regs->at(j);
4194     address loc = reg_map.location(pair.first(), nullptr);
4195     guarantee(loc != nullptr, "bad register save location");
4196     switch(bt) {
4197     case T_BOOLEAN:
4198       *(jboolean*)loc = res->bool_field(off);
4199       break;
4200     case T_CHAR:
4201       *(jchar*)loc = res->char_field(off);
4202       break;
4203     case T_BYTE:
4204       *(jbyte*)loc = res->byte_field(off);
4205       break;
4206     case T_SHORT:
4207       *(jshort*)loc = res->short_field(off);
4208       break;
4209     case T_INT: {
4210       *(jint*)loc = res->int_field(off);
4211       break;
4212     }
4213     case T_LONG:
4214 #ifdef _LP64
4215       *(intptr_t*)loc = res->long_field(off);
4216 #else
4217       Unimplemented();
4218 #endif
4219       break;
4220     case T_OBJECT:
4221     case T_ARRAY: {
4222       *(oop*)loc = res->obj_field(off);
4223       break;
4224     }
4225     case T_FLOAT:
4226       *(jfloat*)loc = res->float_field(off);
4227       break;
4228     case T_DOUBLE:
4229       *(jdouble*)loc = res->double_field(off);
4230       break;
4231     default:
4232       ShouldNotReachHere();
4233     }
4234     j++;
4235   }
4236   assert(j == regs->length(), "missed a field?");
4237 
4238 #ifdef ASSERT
4239   VMRegPair pair = regs->at(0);
4240   address loc = reg_map.location(pair.first(), nullptr);
4241   assert(*(oopDesc**)loc == res, "overwritten object");
4242 #endif
4243 
4244   current->set_vm_result_oop(res);
4245 }
4246 JRT_END
4247 
4248 // We've returned to an interpreted method, the interpreter needs a
4249 // reference to an inline type instance. Allocate it and initialize it
4250 // from field's values in registers.
4251 JRT_BLOCK_ENTRY(void, SharedRuntime::store_inline_type_fields_to_buf(JavaThread* current, intptr_t res))
4252 {
4253   if (!is_set_nth_bit(res, 0)) {
4254     // We're not returning with inline type fields in registers (the
4255     // calling convention didn't allow it for this inline klass)
4256     assert(!Metaspace::contains((void*)res), "should be oop or pointer in buffer area");
4257     current->set_vm_result_oop((oopDesc*)res);
4258     current->set_vm_result_metadata(nullptr);
4259     return;
4260   }
4261 
4262   clear_nth_bit(res, 0);
4263   InlineKlass* vk = (InlineKlass*)res;
4264   assert(Metaspace::contains((void*)res), "should be klass");
4265 
4266   if (!vk->contains_oops()) {
4267     // No oop fields. Initialize the fields by calling the pack handler from
4268     // the stub which is much faster (see 'generate_return_value_stub').
4269     // Signal this by setting the metadata result to the value klass.
4270     JRT_BLOCK;
4271     {
4272       oop vt = vk->allocate_instance(CHECK);
4273       current->set_vm_result_oop(vt);
4274       current->set_vm_result_metadata(vk);
4275     }
4276     JRT_BLOCK_END;
4277     return;
4278   }
4279 
4280   ResourceMark rm;
4281   RegisterMap reg_map(current,
4282                       RegisterMap::UpdateMap::include,
4283                       RegisterMap::ProcessFrames::include,
4284                       RegisterMap::WalkContinuation::skip);
4285   frame stubFrame = current->last_frame();
4286   stubFrame.sender(&reg_map);
4287 
4288   assert(vk == InlineKlass::returned_inline_klass(reg_map), "broken calling convention");
4289 
4290   // Allocate handles for every oop field so they are safe in case of
4291   // a safepoint when allocating
4292   GrowableArray<Handle> handles;
4293   vk->save_oop_fields(reg_map, handles);
4294 
4295   // It's unsafe to safepoint until we are here
4296   JRT_BLOCK;
4297   {
4298     oop vt = vk->realloc_result(reg_map, handles, CHECK);
4299     current->set_vm_result_oop(vt);
4300     current->set_vm_result_metadata(nullptr);
4301   }
4302   JRT_BLOCK_END;
4303 }
4304 JRT_END
< prev index next >