6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "asm/register.hpp"
26 #include "ci/ciObjArray.hpp"
27 #include "ci/ciUtilities.hpp"
28 #include "classfile/javaClasses.hpp"
29 #include "compiler/compileLog.hpp"
30 #include "gc/shared/barrierSet.hpp"
31 #include "gc/shared/c2/barrierSetC2.hpp"
32 #include "interpreter/interpreter.hpp"
33 #include "memory/resourceArea.hpp"
34 #include "opto/addnode.hpp"
35 #include "opto/castnode.hpp"
36 #include "opto/convertnode.hpp"
37 #include "opto/graphKit.hpp"
38 #include "opto/idealKit.hpp"
39 #include "opto/intrinsicnode.hpp"
40 #include "opto/locknode.hpp"
41 #include "opto/machnode.hpp"
42 #include "opto/opaquenode.hpp"
43 #include "opto/parse.hpp"
44 #include "opto/rootnode.hpp"
45 #include "opto/runtime.hpp"
46 #include "opto/subtypenode.hpp"
47 #include "runtime/deoptimization.hpp"
48 #include "runtime/sharedRuntime.hpp"
49 #include "utilities/bitMap.inline.hpp"
50 #include "utilities/growableArray.hpp"
51 #include "utilities/powerOfTwo.hpp"
52
53 //----------------------------GraphKit-----------------------------------------
54 // Main utility constructor.
55 GraphKit::GraphKit(JVMState* jvms)
56 : Phase(Phase::Parser),
57 _env(C->env()),
58 _gvn(*C->initial_gvn()),
59 _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
60 {
61 _exceptions = jvms->map()->next_exception();
62 if (_exceptions != nullptr) jvms->map()->set_next_exception(nullptr);
63 set_jvms(jvms);
64 }
65
66 // Private constructor for parser.
67 GraphKit::GraphKit()
68 : Phase(Phase::Parser),
69 _env(C->env()),
70 _gvn(*C->initial_gvn()),
71 _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
72 {
73 _exceptions = nullptr;
74 set_map(nullptr);
75 DEBUG_ONLY(_sp = -99);
76 DEBUG_ONLY(set_bci(-99));
77 }
78
79
80
81 //---------------------------clean_stack---------------------------------------
82 // Clear away rubbish from the stack area of the JVM state.
83 // This destroys any arguments that may be waiting on the stack.
328 }
329 static inline void add_one_req(Node* dstphi, Node* src) {
330 assert(is_hidden_merge(dstphi), "must be a special merge node");
331 assert(!is_hidden_merge(src), "must not be a special merge node");
332 dstphi->add_req(src);
333 }
334
335 //-----------------------combine_exception_states------------------------------
336 // This helper function combines exception states by building phis on a
337 // specially marked state-merging region. These regions and phis are
338 // untransformed, and can build up gradually. The region is marked by
339 // having a control input of its exception map, rather than null. Such
340 // regions do not appear except in this function, and in use_exception_state.
341 void GraphKit::combine_exception_states(SafePointNode* ex_map, SafePointNode* phi_map) {
342 if (failing_internal()) {
343 return; // dying anyway...
344 }
345 JVMState* ex_jvms = ex_map->_jvms;
346 assert(ex_jvms->same_calls_as(phi_map->_jvms), "consistent call chains");
347 assert(ex_jvms->stkoff() == phi_map->_jvms->stkoff(), "matching locals");
348 assert(ex_jvms->sp() == phi_map->_jvms->sp(), "matching stack sizes");
349 assert(ex_jvms->monoff() == phi_map->_jvms->monoff(), "matching JVMS");
350 assert(ex_jvms->scloff() == phi_map->_jvms->scloff(), "matching scalar replaced objects");
351 assert(ex_map->req() == phi_map->req(), "matching maps");
352 uint tos = ex_jvms->stkoff() + ex_jvms->sp();
353 Node* hidden_merge_mark = root();
354 Node* region = phi_map->control();
355 MergeMemNode* phi_mem = phi_map->merged_memory();
356 MergeMemNode* ex_mem = ex_map->merged_memory();
357 if (region->in(0) != hidden_merge_mark) {
358 // The control input is not (yet) a specially-marked region in phi_map.
359 // Make it so, and build some phis.
360 region = new RegionNode(2);
361 _gvn.set_type(region, Type::CONTROL);
362 region->set_req(0, hidden_merge_mark); // marks an internal ex-state
363 region->init_req(1, phi_map->control());
364 phi_map->set_control(region);
365 Node* io_phi = PhiNode::make(region, phi_map->i_o(), Type::ABIO);
366 record_for_igvn(io_phi);
367 _gvn.set_type(io_phi, Type::ABIO);
368 phi_map->set_i_o(io_phi);
856 if (PrintMiscellaneous && (Verbose || WizardMode)) {
857 tty->print_cr("Zombie local %d: ", local);
858 jvms->dump();
859 }
860 return false;
861 }
862 }
863 }
864 return true;
865 }
866
867 #endif //ASSERT
868
869 // Helper function for enforcing certain bytecodes to reexecute if deoptimization happens.
870 static bool should_reexecute_implied_by_bytecode(JVMState *jvms, bool is_anewarray) {
871 ciMethod* cur_method = jvms->method();
872 int cur_bci = jvms->bci();
873 if (cur_method != nullptr && cur_bci != InvocationEntryBci) {
874 Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci);
875 return Interpreter::bytecode_should_reexecute(code) ||
876 (is_anewarray && code == Bytecodes::_multianewarray);
877 // Reexecute _multianewarray bytecode which was replaced with
878 // sequence of [a]newarray. See Parse::do_multianewarray().
879 //
880 // Note: interpreter should not have it set since this optimization
881 // is limited by dimensions and guarded by flag so in some cases
882 // multianewarray() runtime calls will be generated and
883 // the bytecode should not be reexecutes (stack will not be reset).
884 } else {
885 return false;
886 }
887 }
888
889 // Helper function for adding JVMState and debug information to node
890 void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) {
891 // Add the safepoint edges to the call (or other safepoint).
892
893 // Make sure dead locals are set to top. This
894 // should help register allocation time and cut down on the size
895 // of the deoptimization information.
896 assert(dead_locals_are_killed(), "garbage in debug info before safepoint");
924
925 if (env()->should_retain_local_variables()) {
926 // At any safepoint, this method can get breakpointed, which would
927 // then require an immediate deoptimization.
928 can_prune_locals = false; // do not prune locals
929 stack_slots_not_pruned = 0;
930 }
931
932 // do not scribble on the input jvms
933 JVMState* out_jvms = youngest_jvms->clone_deep(C);
934 call->set_jvms(out_jvms); // Start jvms list for call node
935
936 // For a known set of bytecodes, the interpreter should reexecute them if
937 // deoptimization happens. We set the reexecute state for them here
938 if (out_jvms->is_reexecute_undefined() && //don't change if already specified
939 should_reexecute_implied_by_bytecode(out_jvms, call->is_AllocateArray())) {
940 #ifdef ASSERT
941 int inputs = 0, not_used; // initialized by GraphKit::compute_stack_effects()
942 assert(method() == youngest_jvms->method(), "sanity");
943 assert(compute_stack_effects(inputs, not_used), "unknown bytecode: %s", Bytecodes::name(java_bc()));
944 assert(out_jvms->sp() >= (uint)inputs, "not enough operands for reexecution");
945 #endif // ASSERT
946 out_jvms->set_should_reexecute(true); //NOTE: youngest_jvms not changed
947 }
948
949 // Presize the call:
950 DEBUG_ONLY(uint non_debug_edges = call->req());
951 call->add_req_batch(top(), youngest_jvms->debug_depth());
952 assert(call->req() == non_debug_edges + youngest_jvms->debug_depth(), "");
953
954 // Set up edges so that the call looks like this:
955 // Call [state:] ctl io mem fptr retadr
956 // [parms:] parm0 ... parmN
957 // [root:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN
958 // [...mid:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN [...]
959 // [young:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN
960 // Note that caller debug info precedes callee debug info.
961
962 // Fill pointer walks backwards from "young:" to "root:" in the diagram above:
963 uint debug_ptr = call->req();
964
965 // Loop over the map input edges associated with jvms, add them
966 // to the call node, & reset all offsets to match call node array.
967 for (JVMState* in_jvms = youngest_jvms; in_jvms != nullptr; ) {
968 uint debug_end = debug_ptr;
969 uint debug_start = debug_ptr - in_jvms->debug_size();
970 debug_ptr = debug_start; // back up the ptr
971
972 uint p = debug_start; // walks forward in [debug_start, debug_end)
973 uint j, k, l;
974 SafePointNode* in_map = in_jvms->map();
975 out_jvms->set_map(call);
976
977 if (can_prune_locals) {
978 assert(in_jvms->method() == out_jvms->method(), "sanity");
979 // If the current throw can reach an exception handler in this JVMS,
980 // then we must keep everything live that can reach that handler.
981 // As a quick and dirty approximation, we look for any handlers at all.
982 if (in_jvms->method()->has_exception_handlers()) {
983 can_prune_locals = false;
984 }
985 }
986
987 // Add the Locals
988 k = in_jvms->locoff();
989 l = in_jvms->loc_size();
990 out_jvms->set_locoff(p);
991 if (!can_prune_locals) {
992 for (j = 0; j < l; j++)
993 call->set_req(p++, in_map->in(k+j));
994 } else {
995 p += l; // already set to top above by add_req_batch
996 }
997
998 // Add the Expression Stack
999 k = in_jvms->stkoff();
1000 l = in_jvms->sp();
1001 out_jvms->set_stkoff(p);
1002 if (!can_prune_locals) {
1003 for (j = 0; j < l; j++)
1004 call->set_req(p++, in_map->in(k+j));
1005 } else if (can_prune_locals && stack_slots_not_pruned != 0) {
1006 // Divide stack into {S0,...,S1}, where S0 is set to top.
1007 uint s1 = stack_slots_not_pruned;
1008 stack_slots_not_pruned = 0; // for next iteration
1009 if (s1 > l) s1 = l;
1010 uint s0 = l - s1;
1011 p += s0; // skip the tops preinstalled by add_req_batch
1012 for (j = s0; j < l; j++)
1013 call->set_req(p++, in_map->in(k+j));
1014 } else {
1015 p += l; // already set to top above by add_req_batch
1016 }
1017
1018 // Add the Monitors
1019 k = in_jvms->monoff();
1020 l = in_jvms->mon_size();
1021 out_jvms->set_monoff(p);
1022 for (j = 0; j < l; j++)
1023 call->set_req(p++, in_map->in(k+j));
1024
1025 // Copy any scalar object fields.
1026 k = in_jvms->scloff();
1027 l = in_jvms->scl_size();
1028 out_jvms->set_scloff(p);
1029 for (j = 0; j < l; j++)
1030 call->set_req(p++, in_map->in(k+j));
1031
1032 // Finish the new jvms.
1033 out_jvms->set_endoff(p);
1034
1035 assert(out_jvms->endoff() == debug_end, "fill ptr must match");
1036 assert(out_jvms->depth() == in_jvms->depth(), "depth must match");
1037 assert(out_jvms->loc_size() == in_jvms->loc_size(), "size must match");
1038 assert(out_jvms->mon_size() == in_jvms->mon_size(), "size must match");
1039 assert(out_jvms->scl_size() == in_jvms->scl_size(), "size must match");
1040 assert(out_jvms->debug_size() == in_jvms->debug_size(), "size must match");
1041
1042 // Update the two tail pointers in parallel.
1043 out_jvms = out_jvms->caller();
1044 in_jvms = in_jvms->caller();
1045 }
1046
1047 assert(debug_ptr == non_debug_edges, "debug info must fit exactly");
1048
1049 // Test the correctness of JVMState::debug_xxx accessors:
1050 assert(call->jvms()->debug_start() == non_debug_edges, "");
1051 assert(call->jvms()->debug_end() == call->req(), "");
1052 assert(call->jvms()->debug_depth() == call->req() - non_debug_edges, "");
1053 }
1054
1055 bool GraphKit::compute_stack_effects(int& inputs, int& depth) {
1056 Bytecodes::Code code = java_bc();
1057 if (code == Bytecodes::_wide) {
1058 code = method()->java_code_at_bci(bci() + 1);
1059 }
1060
1061 if (code != Bytecodes::_illegal) {
1062 depth = Bytecodes::depth(code); // checkcast=0, athrow=-1
1198 Node* conv = _gvn.transform( new ConvI2LNode(offset));
1199 Node* mask = _gvn.transform(ConLNode::make((julong) max_juint));
1200 return _gvn.transform( new AndLNode(conv, mask) );
1201 }
1202
1203 Node* GraphKit::ConvL2I(Node* offset) {
1204 // short-circuit a common case
1205 jlong offset_con = find_long_con(offset, (jlong)Type::OffsetBot);
1206 if (offset_con != (jlong)Type::OffsetBot) {
1207 return intcon((int) offset_con);
1208 }
1209 return _gvn.transform( new ConvL2INode(offset));
1210 }
1211
1212 //-------------------------load_object_klass-----------------------------------
1213 Node* GraphKit::load_object_klass(Node* obj) {
1214 // Special-case a fresh allocation to avoid building nodes:
1215 Node* akls = AllocateNode::Ideal_klass(obj, &_gvn);
1216 if (akls != nullptr) return akls;
1217 Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
1218 return _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), k_adr, TypeInstPtr::KLASS));
1219 }
1220
1221 //-------------------------load_array_length-----------------------------------
1222 Node* GraphKit::load_array_length(Node* array) {
1223 // Special-case a fresh allocation to avoid building nodes:
1224 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(array);
1225 Node *alen;
1226 if (alloc == nullptr) {
1227 Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes());
1228 alen = _gvn.transform( new LoadRangeNode(nullptr, immutable_memory(), r_adr, TypeInt::POS));
1229 } else {
1230 alen = array_ideal_length(alloc, _gvn.type(array)->is_oopptr(), false);
1231 }
1232 return alen;
1233 }
1234
1235 Node* GraphKit::array_ideal_length(AllocateArrayNode* alloc,
1236 const TypeOopPtr* oop_type,
1237 bool replace_length_in_map) {
1238 Node* length = alloc->Ideal_length();
1247 replace_in_map(length, ccast);
1248 }
1249 return ccast;
1250 }
1251 }
1252 return length;
1253 }
1254
1255 //------------------------------do_null_check----------------------------------
1256 // Helper function to do a null pointer check. Returned value is
1257 // the incoming address with null casted away. You are allowed to use the
1258 // not-null value only if you are control dependent on the test.
1259 #ifndef PRODUCT
1260 extern uint explicit_null_checks_inserted,
1261 explicit_null_checks_elided;
1262 #endif
1263 Node* GraphKit::null_check_common(Node* value, BasicType type,
1264 // optional arguments for variations:
1265 bool assert_null,
1266 Node* *null_control,
1267 bool speculative) {
1268 assert(!assert_null || null_control == nullptr, "not both at once");
1269 if (stopped()) return top();
1270 NOT_PRODUCT(explicit_null_checks_inserted++);
1271
1272 // Construct null check
1273 Node *chk = nullptr;
1274 switch(type) {
1275 case T_LONG : chk = new CmpLNode(value, _gvn.zerocon(T_LONG)); break;
1276 case T_INT : chk = new CmpINode(value, _gvn.intcon(0)); break;
1277 case T_ARRAY : // fall through
1278 type = T_OBJECT; // simplify further tests
1279 case T_OBJECT : {
1280 const Type *t = _gvn.type( value );
1281
1282 const TypeOopPtr* tp = t->isa_oopptr();
1283 if (tp != nullptr && !tp->is_loaded()
1284 // Only for do_null_check, not any of its siblings:
1285 && !assert_null && null_control == nullptr) {
1286 // Usually, any field access or invocation on an unloaded oop type
1287 // will simply fail to link, since the statically linked class is
1288 // likely also to be unloaded. However, in -Xcomp mode, sometimes
1289 // the static class is loaded but the sharper oop type is not.
1290 // Rather than checking for this obscure case in lots of places,
1291 // we simply observe that a null check on an unloaded class
1355 }
1356 Node *oldcontrol = control();
1357 set_control(cfg);
1358 Node *res = cast_not_null(value);
1359 set_control(oldcontrol);
1360 NOT_PRODUCT(explicit_null_checks_elided++);
1361 return res;
1362 }
1363 cfg = IfNode::up_one_dom(cfg, /*linear_only=*/ true);
1364 if (cfg == nullptr) break; // Quit at region nodes
1365 depth++;
1366 }
1367 }
1368
1369 //-----------
1370 // Branch to failure if null
1371 float ok_prob = PROB_MAX; // a priori estimate: nulls never happen
1372 Deoptimization::DeoptReason reason;
1373 if (assert_null) {
1374 reason = Deoptimization::reason_null_assert(speculative);
1375 } else if (type == T_OBJECT) {
1376 reason = Deoptimization::reason_null_check(speculative);
1377 } else {
1378 reason = Deoptimization::Reason_div0_check;
1379 }
1380 // %%% Since Reason_unhandled is not recorded on a per-bytecode basis,
1381 // ciMethodData::has_trap_at will return a conservative -1 if any
1382 // must-be-null assertion has failed. This could cause performance
1383 // problems for a method after its first do_null_assert failure.
1384 // Consider using 'Reason_class_check' instead?
1385
1386 // To cause an implicit null check, we set the not-null probability
1387 // to the maximum (PROB_MAX). For an explicit check the probability
1388 // is set to a smaller value.
1389 if (null_control != nullptr || too_many_traps(reason)) {
1390 // probability is less likely
1391 ok_prob = PROB_LIKELY_MAG(3);
1392 } else if (!assert_null &&
1393 (ImplicitNullCheckThreshold > 0) &&
1394 method() != nullptr &&
1395 (method()->method_data()->trap_count(reason)
1429 }
1430
1431 if (assert_null) {
1432 // Cast obj to null on this path.
1433 replace_in_map(value, zerocon(type));
1434 return zerocon(type);
1435 }
1436
1437 // Cast obj to not-null on this path, if there is no null_control.
1438 // (If there is a null_control, a non-null value may come back to haunt us.)
1439 if (type == T_OBJECT) {
1440 Node* cast = cast_not_null(value, false);
1441 if (null_control == nullptr || (*null_control) == top())
1442 replace_in_map(value, cast);
1443 value = cast;
1444 }
1445
1446 return value;
1447 }
1448
1449
1450 //------------------------------cast_not_null----------------------------------
1451 // Cast obj to not-null on this path
1452 Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) {
1453 const Type *t = _gvn.type(obj);
1454 const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL);
1455 // Object is already not-null?
1456 if( t == t_not_null ) return obj;
1457
1458 Node* cast = new CastPPNode(control(), obj,t_not_null);
1459 cast = _gvn.transform( cast );
1460
1461 // Scan for instances of 'obj' in the current JVM mapping.
1462 // These instances are known to be not-null after the test.
1463 if (do_replace_in_map)
1464 replace_in_map(obj, cast);
1465
1466 return cast; // Return casted value
1467 }
1468
1469 // Sometimes in intrinsics, we implicitly know an object is not null
1470 // (there's no actual null check) so we can cast it to not null. In
1471 // the course of optimizations, the input to the cast can become null.
1472 // In that case that data path will die and we need the control path
1473 // to become dead as well to keep the graph consistent. So we have to
1474 // add a check for null for which one branch can't be taken. It uses
1475 // an OpaqueNotNull node that will cause the check to be removed after loop
1476 // opts so the test goes away and the compiled code doesn't execute a
1477 // useless check.
1478 Node* GraphKit::must_be_not_null(Node* value, bool do_replace_in_map) {
1479 if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(value))) {
1480 return value;
1481 }
1482 Node* chk = _gvn.transform(new CmpPNode(value, null()));
1483 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
1484 Node* opaq = _gvn.transform(new OpaqueNotNullNode(C, tst));
1485 IfNode* iff = new IfNode(control(), opaq, PROB_MAX, COUNT_UNKNOWN);
1486 _gvn.set_type(iff, iff->Value(&_gvn));
1487 if (!tst->is_Con()) {
1488 record_for_igvn(iff);
1561 // These are layered on top of the factory methods in LoadNode and StoreNode,
1562 // and integrate with the parser's memory state and _gvn engine.
1563 //
1564
1565 // factory methods in "int adr_idx"
1566 Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,
1567 MemNode::MemOrd mo,
1568 LoadNode::ControlDependency control_dependency,
1569 bool require_atomic_access,
1570 bool unaligned,
1571 bool mismatched,
1572 bool unsafe,
1573 uint8_t barrier_data) {
1574 int adr_idx = C->get_alias_index(_gvn.type(adr)->isa_ptr());
1575 assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );
1576 const TypePtr* adr_type = nullptr; // debug-mode-only argument
1577 DEBUG_ONLY(adr_type = C->get_adr_type(adr_idx));
1578 Node* mem = memory(adr_idx);
1579 Node* ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, require_atomic_access, unaligned, mismatched, unsafe, barrier_data);
1580 ld = _gvn.transform(ld);
1581 if (((bt == T_OBJECT) && C->do_escape_analysis()) || C->eliminate_boxing()) {
1582 // Improve graph before escape analysis and boxing elimination.
1583 record_for_igvn(ld);
1584 if (ld->is_DecodeN()) {
1585 // Also record the actual load (LoadN) in case ld is DecodeN. In some
1586 // rare corner cases, ld->in(1) can be something other than LoadN (e.g.,
1587 // a Phi). Recording such cases is still perfectly sound, but may be
1588 // unnecessary and result in some minor IGVN overhead.
1589 record_for_igvn(ld->in(1));
1590 }
1591 }
1592 return ld;
1593 }
1594
1595 Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,
1596 MemNode::MemOrd mo,
1597 bool require_atomic_access,
1598 bool unaligned,
1599 bool mismatched,
1600 bool unsafe,
1614 if (unsafe) {
1615 st->as_Store()->set_unsafe_access();
1616 }
1617 st->as_Store()->set_barrier_data(barrier_data);
1618 st = _gvn.transform(st);
1619 set_memory(st, adr_idx);
1620 // Back-to-back stores can only remove intermediate store with DU info
1621 // so push on worklist for optimizer.
1622 if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))
1623 record_for_igvn(st);
1624
1625 return st;
1626 }
1627
1628 Node* GraphKit::access_store_at(Node* obj,
1629 Node* adr,
1630 const TypePtr* adr_type,
1631 Node* val,
1632 const Type* val_type,
1633 BasicType bt,
1634 DecoratorSet decorators) {
1635 // Transformation of a value which could be null pointer (CastPP #null)
1636 // could be delayed during Parse (for example, in adjust_map_after_if()).
1637 // Execute transformation here to avoid barrier generation in such case.
1638 if (_gvn.type(val) == TypePtr::NULL_PTR) {
1639 val = _gvn.makecon(TypePtr::NULL_PTR);
1640 }
1641
1642 if (stopped()) {
1643 return top(); // Dead path ?
1644 }
1645
1646 assert(val != nullptr, "not dead path");
1647
1648 C2AccessValuePtr addr(adr, adr_type);
1649 C2AccessValue value(val, val_type);
1650 C2ParseAccess access(this, decorators | C2_WRITE_ACCESS, bt, obj, addr);
1651 if (access.is_raw()) {
1652 return _barrier_set->BarrierSetC2::store_at(access, value);
1653 } else {
1654 return _barrier_set->store_at(access, value);
1655 }
1656 }
1657
1658 Node* GraphKit::access_load_at(Node* obj, // containing obj
1659 Node* adr, // actual address to store val at
1660 const TypePtr* adr_type,
1661 const Type* val_type,
1662 BasicType bt,
1663 DecoratorSet decorators) {
1664 if (stopped()) {
1665 return top(); // Dead path ?
1666 }
1667
1668 C2AccessValuePtr addr(adr, adr_type);
1669 C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, obj, addr);
1670 if (access.is_raw()) {
1671 return _barrier_set->BarrierSetC2::load_at(access, val_type);
1672 } else {
1673 return _barrier_set->load_at(access, val_type);
1674 }
1675 }
1676
1677 Node* GraphKit::access_load(Node* adr, // actual address to load val at
1678 const Type* val_type,
1679 BasicType bt,
1680 DecoratorSet decorators) {
1681 if (stopped()) {
1682 return top(); // Dead path ?
1683 }
1684
1685 C2AccessValuePtr addr(adr, adr->bottom_type()->is_ptr());
1686 C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, nullptr, addr);
1687 if (access.is_raw()) {
1688 return _barrier_set->BarrierSetC2::load_at(access, val_type);
1689 } else {
1754 Node* new_val,
1755 const Type* value_type,
1756 BasicType bt,
1757 DecoratorSet decorators) {
1758 C2AccessValuePtr addr(adr, adr_type);
1759 C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, bt, obj, addr, alias_idx);
1760 if (access.is_raw()) {
1761 return _barrier_set->BarrierSetC2::atomic_add_at(access, new_val, value_type);
1762 } else {
1763 return _barrier_set->atomic_add_at(access, new_val, value_type);
1764 }
1765 }
1766
1767 void GraphKit::access_clone(Node* src, Node* dst, Node* size, bool is_array) {
1768 return _barrier_set->clone(this, src, dst, size, is_array);
1769 }
1770
1771 //-------------------------array_element_address-------------------------
1772 Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,
1773 const TypeInt* sizetype, Node* ctrl) {
1774 uint shift = exact_log2(type2aelembytes(elembt));
1775 uint header = arrayOopDesc::base_offset_in_bytes(elembt);
1776
1777 // short-circuit a common case (saves lots of confusing waste motion)
1778 jint idx_con = find_int_con(idx, -1);
1779 if (idx_con >= 0) {
1780 intptr_t offset = header + ((intptr_t)idx_con << shift);
1781 return basic_plus_adr(ary, offset);
1782 }
1783
1784 // must be correct type for alignment purposes
1785 Node* base = basic_plus_adr(ary, header);
1786 idx = Compile::conv_I2X_index(&_gvn, idx, sizetype, ctrl);
1787 Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) );
1788 return basic_plus_adr(ary, base, scale);
1789 }
1790
1791 //-------------------------load_array_element-------------------------
1792 Node* GraphKit::load_array_element(Node* ary, Node* idx, const TypeAryPtr* arytype, bool set_ctrl) {
1793 const Type* elemtype = arytype->elem();
1794 BasicType elembt = elemtype->array_element_basic_type();
1795 Node* adr = array_element_address(ary, idx, elembt, arytype->size());
1796 if (elembt == T_NARROWOOP) {
1797 elembt = T_OBJECT; // To satisfy switch in LoadNode::make()
1798 }
1799 Node* ld = access_load_at(ary, adr, arytype, elemtype, elembt,
1800 IN_HEAP | IS_ARRAY | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0));
1801 return ld;
1802 }
1803
1804 //-------------------------set_arguments_for_java_call-------------------------
1805 // Arguments (pre-popped from the stack) are taken from the JVMS.
1806 void GraphKit::set_arguments_for_java_call(CallJavaNode* call) {
1807 // Add the call arguments:
1808 uint nargs = call->method()->arg_size();
1809 for (uint i = 0; i < nargs; i++) {
1810 Node* arg = argument(i);
1811 call->init_req(i + TypeFunc::Parms, arg);
1812 }
1813 }
1814
1815 //---------------------------set_edges_for_java_call---------------------------
1816 // Connect a newly created call into the current JVMS.
1817 // A return value node (if any) is returned from set_edges_for_java_call.
1818 void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) {
1819
1820 // Add the predefined inputs:
1821 call->init_req( TypeFunc::Control, control() );
1822 call->init_req( TypeFunc::I_O , i_o() );
1823 call->init_req( TypeFunc::Memory , reset_memory() );
1824 call->init_req( TypeFunc::FramePtr, frameptr() );
1825 call->init_req( TypeFunc::ReturnAdr, top() );
1826
1827 add_safepoint_edges(call, must_throw);
1828
1829 Node* xcall = _gvn.transform(call);
1830
1831 if (xcall == top()) {
1832 set_control(top());
1833 return;
1834 }
1835 assert(xcall == call, "call identity is stable");
1836
1837 // Re-use the current map to produce the result.
1838
1839 set_control(_gvn.transform(new ProjNode(call, TypeFunc::Control)));
1840 set_i_o( _gvn.transform(new ProjNode(call, TypeFunc::I_O , separate_io_proj)));
1841 set_all_memory_call(xcall, separate_io_proj);
1842
1843 //return xcall; // no need, caller already has it
1844 }
1845
1846 Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj, bool deoptimize) {
1847 if (stopped()) return top(); // maybe the call folded up?
1848
1849 // Capture the return value, if any.
1850 Node* ret;
1851 if (call->method() == nullptr ||
1852 call->method()->return_type()->basic_type() == T_VOID)
1853 ret = top();
1854 else ret = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1855
1856 // Note: Since any out-of-line call can produce an exception,
1857 // we always insert an I_O projection from the call into the result.
1858
1859 make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj, deoptimize);
1860
1861 if (separate_io_proj) {
1862 // The caller requested separate projections be used by the fall
1863 // through and exceptional paths, so replace the projections for
1864 // the fall through path.
1865 set_i_o(_gvn.transform( new ProjNode(call, TypeFunc::I_O) ));
1866 set_all_memory(_gvn.transform( new ProjNode(call, TypeFunc::Memory) ));
1867 }
1868 return ret;
1869 }
1870
1871 //--------------------set_predefined_input_for_runtime_call--------------------
1872 // Reading and setting the memory state is way conservative here.
1873 // The real problem is that I am not doing real Type analysis on memory,
1874 // so I cannot distinguish card mark stores from other stores. Across a GC
1875 // point the Store Barrier and the card mark memory has to agree. I cannot
1876 // have a card mark store and its barrier split across the GC point from
1877 // either above or below. Here I get that to happen by reading ALL of memory.
1878 // A better answer would be to separate out card marks from other memory.
1879 // For now, return the input memory state, so that it can be reused
1880 // after the call, if this call has restricted memory effects.
1881 Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) {
1882 // Set fixed predefined input arguments
1883 call->init_req(TypeFunc::Control, control());
1884 call->init_req(TypeFunc::I_O, top()); // does no i/o
1885 call->init_req(TypeFunc::ReturnAdr, top());
1886 if (call->is_CallLeafPure()) {
1887 call->init_req(TypeFunc::Memory, top());
1949 if (use->is_MergeMem()) {
1950 wl.push(use);
1951 }
1952 }
1953 }
1954
1955 // Replace the call with the current state of the kit.
1956 void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes, bool do_asserts) {
1957 JVMState* ejvms = nullptr;
1958 if (has_exceptions()) {
1959 ejvms = transfer_exceptions_into_jvms();
1960 }
1961
1962 ReplacedNodes replaced_nodes = map()->replaced_nodes();
1963 ReplacedNodes replaced_nodes_exception;
1964 Node* ex_ctl = top();
1965
1966 SafePointNode* final_state = stop();
1967
1968 // Find all the needed outputs of this call
1969 CallProjections callprojs;
1970 call->extract_projections(&callprojs, true, do_asserts);
1971
1972 Unique_Node_List wl;
1973 Node* init_mem = call->in(TypeFunc::Memory);
1974 Node* final_mem = final_state->in(TypeFunc::Memory);
1975 Node* final_ctl = final_state->in(TypeFunc::Control);
1976 Node* final_io = final_state->in(TypeFunc::I_O);
1977
1978 // Replace all the old call edges with the edges from the inlining result
1979 if (callprojs.fallthrough_catchproj != nullptr) {
1980 C->gvn_replace_by(callprojs.fallthrough_catchproj, final_ctl);
1981 }
1982 if (callprojs.fallthrough_memproj != nullptr) {
1983 if (final_mem->is_MergeMem()) {
1984 // Parser's exits MergeMem was not transformed but may be optimized
1985 final_mem = _gvn.transform(final_mem);
1986 }
1987 C->gvn_replace_by(callprojs.fallthrough_memproj, final_mem);
1988 add_mergemem_users_to_worklist(wl, final_mem);
1989 }
1990 if (callprojs.fallthrough_ioproj != nullptr) {
1991 C->gvn_replace_by(callprojs.fallthrough_ioproj, final_io);
1992 }
1993
1994 // Replace the result with the new result if it exists and is used
1995 if (callprojs.resproj != nullptr && result != nullptr) {
1996 C->gvn_replace_by(callprojs.resproj, result);
1997 }
1998
1999 if (ejvms == nullptr) {
2000 // No exception edges to simply kill off those paths
2001 if (callprojs.catchall_catchproj != nullptr) {
2002 C->gvn_replace_by(callprojs.catchall_catchproj, C->top());
2003 }
2004 if (callprojs.catchall_memproj != nullptr) {
2005 C->gvn_replace_by(callprojs.catchall_memproj, C->top());
2006 }
2007 if (callprojs.catchall_ioproj != nullptr) {
2008 C->gvn_replace_by(callprojs.catchall_ioproj, C->top());
2009 }
2010 // Replace the old exception object with top
2011 if (callprojs.exobj != nullptr) {
2012 C->gvn_replace_by(callprojs.exobj, C->top());
2013 }
2014 } else {
2015 GraphKit ekit(ejvms);
2016
2017 // Load my combined exception state into the kit, with all phis transformed:
2018 SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();
2019 replaced_nodes_exception = ex_map->replaced_nodes();
2020
2021 Node* ex_oop = ekit.use_exception_state(ex_map);
2022
2023 if (callprojs.catchall_catchproj != nullptr) {
2024 C->gvn_replace_by(callprojs.catchall_catchproj, ekit.control());
2025 ex_ctl = ekit.control();
2026 }
2027 if (callprojs.catchall_memproj != nullptr) {
2028 Node* ex_mem = ekit.reset_memory();
2029 C->gvn_replace_by(callprojs.catchall_memproj, ex_mem);
2030 add_mergemem_users_to_worklist(wl, ex_mem);
2031 }
2032 if (callprojs.catchall_ioproj != nullptr) {
2033 C->gvn_replace_by(callprojs.catchall_ioproj, ekit.i_o());
2034 }
2035
2036 // Replace the old exception object with the newly created one
2037 if (callprojs.exobj != nullptr) {
2038 C->gvn_replace_by(callprojs.exobj, ex_oop);
2039 }
2040 }
2041
2042 // Disconnect the call from the graph
2043 call->disconnect_inputs(C);
2044 C->gvn_replace_by(call, C->top());
2045
2046 // Clean up any MergeMems that feed other MergeMems since the
2047 // optimizer doesn't like that.
2048 while (wl.size() > 0) {
2049 _gvn.transform(wl.pop());
2050 }
2051
2052 if (callprojs.fallthrough_catchproj != nullptr && !final_ctl->is_top() && do_replaced_nodes) {
2053 replaced_nodes.apply(C, final_ctl);
2054 }
2055 if (!ex_ctl->is_top() && do_replaced_nodes) {
2056 replaced_nodes_exception.apply(C, ex_ctl);
2057 }
2058 }
2059
2060
2061 //------------------------------increment_counter------------------------------
2062 // for statistics: increment a VM counter by 1
2063
2064 void GraphKit::increment_counter(address counter_addr) {
2065 Node* adr1 = makecon(TypeRawPtr::make(counter_addr));
2066 increment_counter(adr1);
2067 }
2068
2069 void GraphKit::increment_counter(Node* counter_addr) {
2070 Node* ctrl = control();
2071 Node* cnt = make_load(ctrl, counter_addr, TypeLong::LONG, T_LONG, MemNode::unordered);
2072 Node* incr = _gvn.transform(new AddLNode(cnt, _gvn.longcon(1)));
2232 *
2233 * @param n node that the type applies to
2234 * @param exact_kls type from profiling
2235 * @param maybe_null did profiling see null?
2236 *
2237 * @return node with improved type
2238 */
2239 Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, ProfilePtrKind ptr_kind) {
2240 const Type* current_type = _gvn.type(n);
2241 assert(UseTypeSpeculation, "type speculation must be on");
2242
2243 const TypePtr* speculative = current_type->speculative();
2244
2245 // Should the klass from the profile be recorded in the speculative type?
2246 if (current_type->would_improve_type(exact_kls, jvms()->depth())) {
2247 const TypeKlassPtr* tklass = TypeKlassPtr::make(exact_kls, Type::trust_interfaces);
2248 const TypeOopPtr* xtype = tklass->as_instance_type();
2249 assert(xtype->klass_is_exact(), "Should be exact");
2250 // Any reason to believe n is not null (from this profiling or a previous one)?
2251 assert(ptr_kind != ProfileAlwaysNull, "impossible here");
2252 const TypePtr* ptr = (ptr_kind == ProfileMaybeNull && current_type->speculative_maybe_null()) ? TypePtr::BOTTOM : TypePtr::NOTNULL;
2253 // record the new speculative type's depth
2254 speculative = xtype->cast_to_ptr_type(ptr->ptr())->is_ptr();
2255 speculative = speculative->with_inline_depth(jvms()->depth());
2256 } else if (current_type->would_improve_ptr(ptr_kind)) {
2257 // Profiling report that null was never seen so we can change the
2258 // speculative type to non null ptr.
2259 if (ptr_kind == ProfileAlwaysNull) {
2260 speculative = TypePtr::NULL_PTR;
2261 } else {
2262 assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement");
2263 const TypePtr* ptr = TypePtr::NOTNULL;
2264 if (speculative != nullptr) {
2265 speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr();
2266 } else {
2267 speculative = ptr;
2268 }
2269 }
2270 }
2271
2272 if (speculative != current_type->speculative()) {
2273 // Build a type with a speculative type (what we think we know
2274 // about the type but will need a guard when we use it)
2275 const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::OffsetBot, TypeOopPtr::InstanceBot, speculative);
2276 // We're changing the type, we need a new CheckCast node to carry
2277 // the new type. The new type depends on the control: what
2278 // profiling tells us is only valid from here as far as we can
2279 // tell.
2280 Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));
2281 cast = _gvn.transform(cast);
2282 replace_in_map(n, cast);
2283 n = cast;
2284 }
2285
2286 return n;
2287 }
2288
2289 /**
2290 * Record profiling data from receiver profiling at an invoke with the
2291 * type system so that it can propagate it (speculation)
2292 *
2293 * @param n receiver node
2294 *
2295 * @return node with improved type
2296 */
2297 Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {
2298 if (!UseTypeSpeculation) {
2299 return n;
2300 }
2301 ciKlass* exact_kls = profile_has_unique_klass();
2302 ProfilePtrKind ptr_kind = ProfileMaybeNull;
2303 if ((java_bc() == Bytecodes::_checkcast ||
2304 java_bc() == Bytecodes::_instanceof ||
2305 java_bc() == Bytecodes::_aastore) &&
2306 method()->method_data()->is_mature()) {
2307 ciProfileData* data = method()->method_data()->bci_to_data(bci());
2308 if (data != nullptr) {
2309 if (!data->as_BitData()->null_seen()) {
2310 ptr_kind = ProfileNeverNull;
2311 } else {
2312 if (TypeProfileCasts) {
2313 assert(data->is_ReceiverTypeData(), "bad profile data type");
2314 ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
2315 uint i = 0;
2316 for (; i < call->row_limit(); i++) {
2317 ciKlass* receiver = call->receiver(i);
2318 if (receiver != nullptr) {
2319 break;
2320 }
2321 }
2322 ptr_kind = (i == call->row_limit()) ? ProfileAlwaysNull : ProfileMaybeNull;
2323 }
2324 }
2325 }
2326 }
2327 return record_profile_for_speculation(n, exact_kls, ptr_kind);
2328 }
2329
2330 /**
2331 * Record profiling data from argument profiling at an invoke with the
2332 * type system so that it can propagate it (speculation)
2333 *
2334 * @param dest_method target method for the call
2335 * @param bc what invoke bytecode is this?
2336 */
2337 void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {
2338 if (!UseTypeSpeculation) {
2339 return;
2340 }
2341 const TypeFunc* tf = TypeFunc::make(dest_method);
2342 int nargs = tf->domain()->cnt() - TypeFunc::Parms;
2343 int skip = Bytecodes::has_receiver(bc) ? 1 : 0;
2344 for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {
2345 const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);
2346 if (is_reference_type(targ->basic_type())) {
2347 ProfilePtrKind ptr_kind = ProfileMaybeNull;
2348 ciKlass* better_type = nullptr;
2349 if (method()->argument_profiled_type(bci(), i, better_type, ptr_kind)) {
2350 record_profile_for_speculation(argument(j), better_type, ptr_kind);
2351 }
2352 i++;
2353 }
2354 }
2355 }
2356
2357 /**
2358 * Record profiling data from parameter profiling at an invoke with
2359 * the type system so that it can propagate it (speculation)
2360 */
2361 void GraphKit::record_profiled_parameters_for_speculation() {
2362 if (!UseTypeSpeculation) {
2363 return;
2364 }
2365 for (int i = 0, j = 0; i < method()->arg_size() ; i++) {
2485 // The first null ends the list.
2486 Node* parm0, Node* parm1,
2487 Node* parm2, Node* parm3,
2488 Node* parm4, Node* parm5,
2489 Node* parm6, Node* parm7) {
2490 assert(call_addr != nullptr, "must not call null targets");
2491
2492 // Slow-path call
2493 bool is_leaf = !(flags & RC_NO_LEAF);
2494 bool has_io = (!is_leaf && !(flags & RC_NO_IO));
2495 if (call_name == nullptr) {
2496 assert(!is_leaf, "must supply name for leaf");
2497 call_name = OptoRuntime::stub_name(call_addr);
2498 }
2499 CallNode* call;
2500 if (!is_leaf) {
2501 call = new CallStaticJavaNode(call_type, call_addr, call_name, adr_type);
2502 } else if (flags & RC_NO_FP) {
2503 call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
2504 } else if (flags & RC_VECTOR){
2505 uint num_bits = call_type->range()->field_at(TypeFunc::Parms)->is_vect()->length_in_bytes() * BitsPerByte;
2506 call = new CallLeafVectorNode(call_type, call_addr, call_name, adr_type, num_bits);
2507 } else if (flags & RC_PURE) {
2508 assert(adr_type == nullptr, "pure call does not touch memory");
2509 call = new CallLeafPureNode(call_type, call_addr, call_name);
2510 } else {
2511 call = new CallLeafNode(call_type, call_addr, call_name, adr_type);
2512 }
2513
2514 // The following is similar to set_edges_for_java_call,
2515 // except that the memory effects of the call are restricted to AliasIdxRaw.
2516
2517 // Slow path call has no side-effects, uses few values
2518 bool wide_in = !(flags & RC_NARROW_MEM);
2519 bool wide_out = (C->get_alias_index(adr_type) == Compile::AliasIdxBot);
2520
2521 Node* prev_mem = nullptr;
2522 if (wide_in) {
2523 prev_mem = set_predefined_input_for_runtime_call(call);
2524 } else {
2525 assert(!wide_out, "narrow in => narrow out");
2526 Node* narrow_mem = memory(adr_type);
2527 prev_mem = set_predefined_input_for_runtime_call(call, narrow_mem);
2528 }
2529
2530 // Hook each parm in order. Stop looking at the first null.
2531 if (parm0 != nullptr) { call->init_req(TypeFunc::Parms+0, parm0);
2532 if (parm1 != nullptr) { call->init_req(TypeFunc::Parms+1, parm1);
2533 if (parm2 != nullptr) { call->init_req(TypeFunc::Parms+2, parm2);
2534 if (parm3 != nullptr) { call->init_req(TypeFunc::Parms+3, parm3);
2535 if (parm4 != nullptr) { call->init_req(TypeFunc::Parms+4, parm4);
2536 if (parm5 != nullptr) { call->init_req(TypeFunc::Parms+5, parm5);
2537 if (parm6 != nullptr) { call->init_req(TypeFunc::Parms+6, parm6);
2538 if (parm7 != nullptr) { call->init_req(TypeFunc::Parms+7, parm7);
2539 /* close each nested if ===> */ } } } } } } } }
2540 assert(call->in(call->req()-1) != nullptr, "must initialize all parms");
2541
2542 if (!is_leaf) {
2543 // Non-leaves can block and take safepoints:
2544 add_safepoint_edges(call, ((flags & RC_MUST_THROW) != 0));
2545 }
2546 // Non-leaves can throw exceptions:
2547 if (has_io) {
2548 call->set_req(TypeFunc::I_O, i_o());
2549 }
2550
2551 if (flags & RC_UNCOMMON) {
2552 // Set the count to a tiny probability. Cf. Estimate_Block_Frequency.
2553 // (An "if" probability corresponds roughly to an unconditional count.
2554 // Sort of.)
2555 call->set_cnt(PROB_UNLIKELY_MAG(4));
2556 }
2557
2558 Node* c = _gvn.transform(call);
2559 assert(c == call, "cannot disappear");
2560
2568
2569 if (has_io) {
2570 set_i_o(_gvn.transform(new ProjNode(call, TypeFunc::I_O)));
2571 }
2572 return call;
2573
2574 }
2575
2576 // i2b
2577 Node* GraphKit::sign_extend_byte(Node* in) {
2578 Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(24)));
2579 return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(24)));
2580 }
2581
2582 // i2s
2583 Node* GraphKit::sign_extend_short(Node* in) {
2584 Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(16)));
2585 return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(16)));
2586 }
2587
2588 //------------------------------merge_memory-----------------------------------
2589 // Merge memory from one path into the current memory state.
2590 void GraphKit::merge_memory(Node* new_mem, Node* region, int new_path) {
2591 for (MergeMemStream mms(merged_memory(), new_mem->as_MergeMem()); mms.next_non_empty2(); ) {
2592 Node* old_slice = mms.force_memory();
2593 Node* new_slice = mms.memory2();
2594 if (old_slice != new_slice) {
2595 PhiNode* phi;
2596 if (old_slice->is_Phi() && old_slice->as_Phi()->region() == region) {
2597 if (mms.is_empty()) {
2598 // clone base memory Phi's inputs for this memory slice
2599 assert(old_slice == mms.base_memory(), "sanity");
2600 phi = PhiNode::make(region, nullptr, Type::MEMORY, mms.adr_type(C));
2601 _gvn.set_type(phi, Type::MEMORY);
2602 for (uint i = 1; i < phi->req(); i++) {
2603 phi->init_req(i, old_slice->in(i));
2604 }
2605 } else {
2606 phi = old_slice->as_Phi(); // Phi was generated already
2607 }
2664 gvn.transform(iff);
2665 if (!bol->is_Con()) gvn.record_for_igvn(iff);
2666 return iff;
2667 }
2668
2669 //-------------------------------gen_subtype_check-----------------------------
2670 // Generate a subtyping check. Takes as input the subtype and supertype.
2671 // Returns 2 values: sets the default control() to the true path and returns
2672 // the false path. Only reads invariant memory; sets no (visible) memory.
2673 // The PartialSubtypeCheckNode sets the hidden 1-word cache in the encoding
2674 // but that's not exposed to the optimizer. This call also doesn't take in an
2675 // Object; if you wish to check an Object you need to load the Object's class
2676 // prior to coming here.
2677 Node* Phase::gen_subtype_check(Node* subklass, Node* superklass, Node** ctrl, Node* mem, PhaseGVN& gvn,
2678 ciMethod* method, int bci) {
2679 Compile* C = gvn.C;
2680 if ((*ctrl)->is_top()) {
2681 return C->top();
2682 }
2683
2684 // Fast check for identical types, perhaps identical constants.
2685 // The types can even be identical non-constants, in cases
2686 // involving Array.newInstance, Object.clone, etc.
2687 if (subklass == superklass)
2688 return C->top(); // false path is dead; no test needed.
2689
2690 if (gvn.type(superklass)->singleton()) {
2691 const TypeKlassPtr* superk = gvn.type(superklass)->is_klassptr();
2692 const TypeKlassPtr* subk = gvn.type(subklass)->is_klassptr();
2693
2694 // In the common case of an exact superklass, try to fold up the
2695 // test before generating code. You may ask, why not just generate
2696 // the code and then let it fold up? The answer is that the generated
2697 // code will necessarily include null checks, which do not always
2698 // completely fold away. If they are also needless, then they turn
2699 // into a performance loss. Example:
2700 // Foo[] fa = blah(); Foo x = fa[0]; fa[1] = x;
2701 // Here, the type of 'fa' is often exact, so the store check
2702 // of fa[1]=x will fold up, without testing the nullness of x.
2703 //
2704 // At macro expansion, we would have already folded the SubTypeCheckNode
2705 // being expanded here because we always perform the static sub type
2706 // check in SubTypeCheckNode::sub() regardless of whether
2707 // StressReflectiveCode is set or not. We can therefore skip this
2708 // static check when StressReflectiveCode is on.
2709 switch (C->static_subtype_check(superk, subk)) {
2710 case Compile::SSC_always_false:
2711 {
2712 Node* always_fail = *ctrl;
2713 *ctrl = gvn.C->top();
2714 return always_fail;
2715 }
2716 case Compile::SSC_always_true:
2717 return C->top();
2718 case Compile::SSC_easy_test:
2719 {
2720 // Just do a direct pointer compare and be done.
2721 IfNode* iff = gen_subtype_check_compare(*ctrl, subklass, superklass, BoolTest::eq, PROB_STATIC_FREQUENT, gvn, T_ADDRESS);
2722 *ctrl = gvn.transform(new IfTrueNode(iff));
2723 return gvn.transform(new IfFalseNode(iff));
2724 }
2725 case Compile::SSC_full_test:
2726 break;
2727 default:
2728 ShouldNotReachHere();
2729 }
2730 }
2731
2732 // %%% Possible further optimization: Even if the superklass is not exact,
2733 // if the subklass is the unique subtype of the superklass, the check
2734 // will always succeed. We could leave a dependency behind to ensure this.
2735
2736 // First load the super-klass's check-offset
2737 Node *p1 = gvn.transform(new AddPNode(superklass, superklass, gvn.MakeConX(in_bytes(Klass::super_check_offset_offset()))));
2738 Node* m = C->immutable_memory();
2739 Node *chk_off = gvn.transform(new LoadINode(nullptr, m, p1, gvn.type(p1)->is_ptr(), TypeInt::INT, MemNode::unordered));
2740 int cacheoff_con = in_bytes(Klass::secondary_super_cache_offset());
2741 const TypeInt* chk_off_t = chk_off->Value(&gvn)->isa_int();
2779 gvn.record_for_igvn(r_ok_subtype);
2780
2781 // If we might perform an expensive check, first try to take advantage of profile data that was attached to the
2782 // SubTypeCheck node
2783 if (might_be_cache && method != nullptr && VM_Version::profile_all_receivers_at_type_check()) {
2784 ciCallProfile profile = method->call_profile_at_bci(bci);
2785 float total_prob = 0;
2786 for (int i = 0; profile.has_receiver(i); ++i) {
2787 float prob = profile.receiver_prob(i);
2788 total_prob += prob;
2789 }
2790 if (total_prob * 100. >= TypeProfileSubTypeCheckCommonThreshold) {
2791 const TypeKlassPtr* superk = gvn.type(superklass)->is_klassptr();
2792 for (int i = 0; profile.has_receiver(i); ++i) {
2793 ciKlass* klass = profile.receiver(i);
2794 const TypeKlassPtr* klass_t = TypeKlassPtr::make(klass);
2795 Compile::SubTypeCheckResult result = C->static_subtype_check(superk, klass_t);
2796 if (result != Compile::SSC_always_true && result != Compile::SSC_always_false) {
2797 continue;
2798 }
2799 float prob = profile.receiver_prob(i);
2800 ConNode* klass_node = gvn.makecon(klass_t);
2801 IfNode* iff = gen_subtype_check_compare(*ctrl, subklass, klass_node, BoolTest::eq, prob, gvn, T_ADDRESS);
2802 Node* iftrue = gvn.transform(new IfTrueNode(iff));
2803
2804 if (result == Compile::SSC_always_true) {
2805 r_ok_subtype->add_req(iftrue);
2806 } else {
2807 assert(result == Compile::SSC_always_false, "");
2808 r_not_subtype->add_req(iftrue);
2809 }
2810 *ctrl = gvn.transform(new IfFalseNode(iff));
2811 }
2812 }
2813 }
2814
2815 // See if we get an immediate positive hit. Happens roughly 83% of the
2816 // time. Test to see if the value loaded just previously from the subklass
2817 // is exactly the superklass.
2818 IfNode *iff1 = gen_subtype_check_compare(*ctrl, superklass, nkls, BoolTest::eq, PROB_LIKELY(0.83f), gvn, T_ADDRESS);
2832 igvn->remove_globally_dead_node(r_not_subtype);
2833 }
2834 return not_subtype_ctrl;
2835 }
2836
2837 r_ok_subtype->init_req(1, iftrue1);
2838
2839 // Check for immediate negative hit. Happens roughly 11% of the time (which
2840 // is roughly 63% of the remaining cases). Test to see if the loaded
2841 // check-offset points into the subklass display list or the 1-element
2842 // cache. If it points to the display (and NOT the cache) and the display
2843 // missed then it's not a subtype.
2844 Node *cacheoff = gvn.intcon(cacheoff_con);
2845 IfNode *iff2 = gen_subtype_check_compare(*ctrl, chk_off, cacheoff, BoolTest::ne, PROB_LIKELY(0.63f), gvn, T_INT);
2846 r_not_subtype->init_req(1, gvn.transform(new IfTrueNode (iff2)));
2847 *ctrl = gvn.transform(new IfFalseNode(iff2));
2848
2849 // Check for self. Very rare to get here, but it is taken 1/3 the time.
2850 // No performance impact (too rare) but allows sharing of secondary arrays
2851 // which has some footprint reduction.
2852 IfNode *iff3 = gen_subtype_check_compare(*ctrl, subklass, superklass, BoolTest::eq, PROB_LIKELY(0.36f), gvn, T_ADDRESS);
2853 r_ok_subtype->init_req(2, gvn.transform(new IfTrueNode(iff3)));
2854 *ctrl = gvn.transform(new IfFalseNode(iff3));
2855
2856 // -- Roads not taken here: --
2857 // We could also have chosen to perform the self-check at the beginning
2858 // of this code sequence, as the assembler does. This would not pay off
2859 // the same way, since the optimizer, unlike the assembler, can perform
2860 // static type analysis to fold away many successful self-checks.
2861 // Non-foldable self checks work better here in second position, because
2862 // the initial primary superclass check subsumes a self-check for most
2863 // types. An exception would be a secondary type like array-of-interface,
2864 // which does not appear in its own primary supertype display.
2865 // Finally, we could have chosen to move the self-check into the
2866 // PartialSubtypeCheckNode, and from there out-of-line in a platform
2867 // dependent manner. But it is worthwhile to have the check here,
2868 // where it can be perhaps be optimized. The cost in code space is
2869 // small (register compare, branch).
2870
2871 // Now do a linear scan of the secondary super-klass array. Again, no real
2872 // performance impact (too rare) but it's gotta be done.
2873 // Since the code is rarely used, there is no penalty for moving it
2874 // out of line, and it can only improve I-cache density.
2875 // The decision to inline or out-of-line this final check is platform
2876 // dependent, and is found in the AD file definition of PartialSubtypeCheck.
2877 Node* psc = gvn.transform(
2878 new PartialSubtypeCheckNode(*ctrl, subklass, superklass));
2879
2880 IfNode *iff4 = gen_subtype_check_compare(*ctrl, psc, gvn.zerocon(T_OBJECT), BoolTest::ne, PROB_FAIR, gvn, T_ADDRESS);
2881 r_not_subtype->init_req(2, gvn.transform(new IfTrueNode (iff4)));
2882 r_ok_subtype ->init_req(3, gvn.transform(new IfFalseNode(iff4)));
2883
2884 // Return false path; set default control to true path.
2885 *ctrl = gvn.transform(r_ok_subtype);
2886 return gvn.transform(r_not_subtype);
2887 }
2888
2889 Node* GraphKit::gen_subtype_check(Node* obj_or_subklass, Node* superklass) {
2890 bool expand_subtype_check = C->post_loop_opts_phase(); // macro node expansion is over
2891 if (expand_subtype_check) {
2892 MergeMemNode* mem = merged_memory();
2893 Node* ctrl = control();
2894 Node* subklass = obj_or_subklass;
2895 if (!_gvn.type(obj_or_subklass)->isa_klassptr()) {
2896 subklass = load_object_klass(obj_or_subklass);
2897 }
2898
2899 Node* n = Phase::gen_subtype_check(subklass, superklass, &ctrl, mem, _gvn, method(), bci());
2900 set_control(ctrl);
2901 return n;
2902 }
2903
2904 Node* check = _gvn.transform(new SubTypeCheckNode(C, obj_or_subklass, superklass, method(), bci()));
2905 Node* bol = _gvn.transform(new BoolNode(check, BoolTest::eq));
2906 IfNode* iff = create_and_xform_if(control(), bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
2907 set_control(_gvn.transform(new IfTrueNode(iff)));
2908 return _gvn.transform(new IfFalseNode(iff));
2909 }
2910
2911 // Profile-driven exact type check:
2912 Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,
2913 float prob,
2914 Node* *casted_receiver) {
2915 assert(!klass->is_interface(), "no exact type check on interfaces");
2916
2917 const TypeKlassPtr* tklass = TypeKlassPtr::make(klass, Type::trust_interfaces);
2918 Node* recv_klass = load_object_klass(receiver);
2919 Node* want_klass = makecon(tklass);
2920 Node* cmp = _gvn.transform(new CmpPNode(recv_klass, want_klass));
2921 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
2922 IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);
2923 set_control( _gvn.transform(new IfTrueNode (iff)));
2924 Node* fail = _gvn.transform(new IfFalseNode(iff));
2925
2926 if (!stopped()) {
2927 const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
2928 const TypeOopPtr* recvx_type = tklass->as_instance_type();
2929 assert(recvx_type->klass_is_exact(), "");
2930
2931 if (!receiver_type->higher_equal(recvx_type)) { // ignore redundant casts
2932 // Subsume downstream occurrences of receiver with a cast to
2933 // recv_xtype, since now we know what the type will be.
2934 Node* cast = new CheckCastPPNode(control(), receiver, recvx_type);
2935 (*casted_receiver) = _gvn.transform(cast);
2936 assert(!(*casted_receiver)->is_top(), "that path should be unreachable");
2937 // (User must make the replace_in_map call.)
2938 }
2939 }
2940
2941 return fail;
2942 }
2943
2944 //------------------------------subtype_check_receiver-------------------------
2945 Node* GraphKit::subtype_check_receiver(Node* receiver, ciKlass* klass,
2946 Node** casted_receiver) {
2947 const TypeKlassPtr* tklass = TypeKlassPtr::make(klass, Type::trust_interfaces)->try_improve();
2948 Node* want_klass = makecon(tklass);
2949
2950 Node* slow_ctl = gen_subtype_check(receiver, want_klass);
2951
2952 // Ignore interface type information until interface types are properly tracked.
2953 if (!stopped() && !klass->is_interface()) {
2954 const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
2955 const TypeOopPtr* recv_type = tklass->cast_to_exactness(false)->is_klassptr()->as_instance_type();
2956 if (!receiver_type->higher_equal(recv_type)) { // ignore redundant casts
2957 Node* cast = new CheckCastPPNode(control(), receiver, recv_type);
2958 (*casted_receiver) = _gvn.transform(cast);
2959 }
2960 }
2961
2962 return slow_ctl;
2963 }
2964
2965 //------------------------------seems_never_null-------------------------------
2966 // Use null_seen information if it is available from the profile.
2967 // If we see an unexpected null at a type check we record it and force a
2968 // recompile; the offending check will be recompiled to handle nulls.
2969 // If we see several offending BCIs, then all checks in the
2970 // method will be recompiled.
2971 bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) {
2972 speculating = !_gvn.type(obj)->speculative_maybe_null();
2973 Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating);
2974 if (UncommonNullCast // Cutout for this technique
2975 && obj != null() // And not the -Xcomp stupid case?
2976 && !too_many_traps(reason)
2977 ) {
2978 if (speculating) {
3047
3048 //------------------------maybe_cast_profiled_receiver-------------------------
3049 // If the profile has seen exactly one type, narrow to exactly that type.
3050 // Subsequent type checks will always fold up.
3051 Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,
3052 const TypeKlassPtr* require_klass,
3053 ciKlass* spec_klass,
3054 bool safe_for_replace) {
3055 if (!UseTypeProfile || !TypeProfileCasts) return nullptr;
3056
3057 Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != nullptr);
3058
3059 // Make sure we haven't already deoptimized from this tactic.
3060 if (too_many_traps_or_recompiles(reason))
3061 return nullptr;
3062
3063 // (No, this isn't a call, but it's enough like a virtual call
3064 // to use the same ciMethod accessor to get the profile info...)
3065 // If we have a speculative type use it instead of profiling (which
3066 // may not help us)
3067 ciKlass* exact_kls = spec_klass == nullptr ? profile_has_unique_klass() : spec_klass;
3068 if (exact_kls != nullptr) {// no cast failures here
3069 if (require_klass == nullptr ||
3070 C->static_subtype_check(require_klass, TypeKlassPtr::make(exact_kls, Type::trust_interfaces)) == Compile::SSC_always_true) {
3071 // If we narrow the type to match what the type profile sees or
3072 // the speculative type, we can then remove the rest of the
3073 // cast.
3074 // This is a win, even if the exact_kls is very specific,
3075 // because downstream operations, such as method calls,
3076 // will often benefit from the sharper type.
3077 Node* exact_obj = not_null_obj; // will get updated in place...
3078 Node* slow_ctl = type_check_receiver(exact_obj, exact_kls, 1.0,
3079 &exact_obj);
3080 { PreserveJVMState pjvms(this);
3081 set_control(slow_ctl);
3082 uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
3083 }
3084 if (safe_for_replace) {
3085 replace_in_map(not_null_obj, exact_obj);
3086 }
3087 return exact_obj;
3177 // If not_null_obj is dead, only null-path is taken
3178 if (stopped()) { // Doing instance-of on a null?
3179 set_control(null_ctl);
3180 return intcon(0);
3181 }
3182 region->init_req(_null_path, null_ctl);
3183 phi ->init_req(_null_path, intcon(0)); // Set null path value
3184 if (null_ctl == top()) {
3185 // Do this eagerly, so that pattern matches like is_diamond_phi
3186 // will work even during parsing.
3187 assert(_null_path == PATH_LIMIT-1, "delete last");
3188 region->del_req(_null_path);
3189 phi ->del_req(_null_path);
3190 }
3191
3192 // Do we know the type check always succeed?
3193 bool known_statically = false;
3194 if (_gvn.type(superklass)->singleton()) {
3195 const TypeKlassPtr* superk = _gvn.type(superklass)->is_klassptr();
3196 const TypeKlassPtr* subk = _gvn.type(obj)->is_oopptr()->as_klass_type();
3197 if (subk->is_loaded()) {
3198 int static_res = C->static_subtype_check(superk, subk);
3199 known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false);
3200 }
3201 }
3202
3203 if (!known_statically) {
3204 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3205 // We may not have profiling here or it may not help us. If we
3206 // have a speculative type use it to perform an exact cast.
3207 ciKlass* spec_obj_type = obj_type->speculative_type();
3208 if (spec_obj_type != nullptr || (ProfileDynamicTypes && data != nullptr)) {
3209 Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, nullptr, spec_obj_type, safe_for_replace);
3210 if (stopped()) { // Profile disagrees with this path.
3211 set_control(null_ctl); // Null is the only remaining possibility.
3212 return intcon(0);
3213 }
3214 if (cast_obj != nullptr) {
3215 not_null_obj = cast_obj;
3216 }
3217 }
3233 record_for_igvn(region);
3234
3235 // If we know the type check always succeeds then we don't use the
3236 // profiling data at this bytecode. Don't lose it, feed it to the
3237 // type system as a speculative type.
3238 if (safe_for_replace) {
3239 Node* casted_obj = record_profiled_receiver_for_speculation(obj);
3240 replace_in_map(obj, casted_obj);
3241 }
3242
3243 return _gvn.transform(phi);
3244 }
3245
3246 //-------------------------------gen_checkcast---------------------------------
3247 // Generate a checkcast idiom. Used by both the checkcast bytecode and the
3248 // array store bytecode. Stack must be as-if BEFORE doing the bytecode so the
3249 // uncommon-trap paths work. Adjust stack after this call.
3250 // If failure_control is supplied and not null, it is filled in with
3251 // the control edge for the cast failure. Otherwise, an appropriate
3252 // uncommon trap or exception is thrown.
3253 Node* GraphKit::gen_checkcast(Node *obj, Node* superklass,
3254 Node* *failure_control) {
3255 kill_dead_locals(); // Benefit all the uncommon traps
3256 const TypeKlassPtr* klass_ptr_type = _gvn.type(superklass)->is_klassptr();
3257 const TypeKlassPtr* improved_klass_ptr_type = klass_ptr_type->try_improve();
3258 const TypeOopPtr* toop = improved_klass_ptr_type->cast_to_exactness(false)->as_instance_type();
3259
3260 // Fast cutout: Check the case that the cast is vacuously true.
3261 // This detects the common cases where the test will short-circuit
3262 // away completely. We do this before we perform the null check,
3263 // because if the test is going to turn into zero code, we don't
3264 // want a residual null check left around. (Causes a slowdown,
3265 // for example, in some objArray manipulations, such as a[i]=a[j].)
3266 if (improved_klass_ptr_type->singleton()) {
3267 const TypeOopPtr* objtp = _gvn.type(obj)->isa_oopptr();
3268 if (objtp != nullptr) {
3269 switch (C->static_subtype_check(improved_klass_ptr_type, objtp->as_klass_type())) {
3270 case Compile::SSC_always_true:
3271 // If we know the type check always succeed then we don't use
3272 // the profiling data at this bytecode. Don't lose it, feed it
3273 // to the type system as a speculative type.
3274 return record_profiled_receiver_for_speculation(obj);
3275 case Compile::SSC_always_false:
3276 // It needs a null check because a null will *pass* the cast check.
3277 // A non-null value will always produce an exception.
3278 if (!objtp->maybe_null()) {
3279 bool is_aastore = (java_bc() == Bytecodes::_aastore);
3280 Deoptimization::DeoptReason reason = is_aastore ?
3281 Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3282 builtin_throw(reason);
3283 return top();
3284 } else if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
3285 return null_assert(obj);
3286 }
3287 break; // Fall through to full check
3288 default:
3289 break;
3290 }
3291 }
3292 }
3293
3294 ciProfileData* data = nullptr;
3295 bool safe_for_replace = false;
3296 if (failure_control == nullptr) { // use MDO in regular case only
3297 assert(java_bc() == Bytecodes::_aastore ||
3298 java_bc() == Bytecodes::_checkcast,
3299 "interpreter profiles type checks only for these BCs");
3300 data = method()->method_data()->bci_to_data(bci());
3301 safe_for_replace = true;
3302 }
3303
3304 // Make the merge point
3305 enum { _obj_path = 1, _null_path, PATH_LIMIT };
3306 RegionNode* region = new RegionNode(PATH_LIMIT);
3307 Node* phi = new PhiNode(region, toop);
3308 C->set_has_split_ifs(true); // Has chance for split-if optimization
3309
3310 // Use null-cast information if it is available
3311 bool speculative_not_null = false;
3312 bool never_see_null = ((failure_control == nullptr) // regular case only
3313 && seems_never_null(obj, data, speculative_not_null));
3314
3315 // Null check; get casted pointer; set region slot 3
3316 Node* null_ctl = top();
3317 Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3318
3319 // If not_null_obj is dead, only null-path is taken
3320 if (stopped()) { // Doing instance-of on a null?
3321 set_control(null_ctl);
3322 return null();
3323 }
3324 region->init_req(_null_path, null_ctl);
3325 phi ->init_req(_null_path, null()); // Set null path value
3326 if (null_ctl == top()) {
3327 // Do this eagerly, so that pattern matches like is_diamond_phi
3328 // will work even during parsing.
3329 assert(_null_path == PATH_LIMIT-1, "delete last");
3330 region->del_req(_null_path);
3331 phi ->del_req(_null_path);
3332 }
3333
3334 Node* cast_obj = nullptr;
3335 if (improved_klass_ptr_type->klass_is_exact()) {
3336 // The following optimization tries to statically cast the speculative type of the object
3337 // (for example obtained during profiling) to the type of the superklass and then do a
3338 // dynamic check that the type of the object is what we expect. To work correctly
3339 // for checkcast and aastore the type of superklass should be exact.
3340 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3341 // We may not have profiling here or it may not help us. If we have
3342 // a speculative type use it to perform an exact cast.
3343 ciKlass* spec_obj_type = obj_type->speculative_type();
3344 if (spec_obj_type != nullptr || data != nullptr) {
3345 cast_obj = maybe_cast_profiled_receiver(not_null_obj, improved_klass_ptr_type, spec_obj_type, safe_for_replace);
3346 if (cast_obj != nullptr) {
3347 if (failure_control != nullptr) // failure is now impossible
3348 (*failure_control) = top();
3349 // adjust the type of the phi to the exact klass:
3350 phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
3351 }
3352 }
3353 }
3354
3355 if (cast_obj == nullptr) {
3356 // Generate the subtype check
3357 Node* improved_superklass = superklass;
3358 if (improved_klass_ptr_type != klass_ptr_type && improved_klass_ptr_type->singleton()) {
3359 improved_superklass = makecon(improved_klass_ptr_type);
3360 }
3361 Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, improved_superklass);
3362
3363 // Plug in success path into the merge
3364 cast_obj = _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop));
3365 // Failure path ends in uncommon trap (or may be dead - failure impossible)
3366 if (failure_control == nullptr) {
3367 if (not_subtype_ctrl != top()) { // If failure is possible
3368 PreserveJVMState pjvms(this);
3369 set_control(not_subtype_ctrl);
3370 bool is_aastore = (java_bc() == Bytecodes::_aastore);
3371 Deoptimization::DeoptReason reason = is_aastore ?
3372 Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3373 builtin_throw(reason);
3374 }
3375 } else {
3376 (*failure_control) = not_subtype_ctrl;
3377 }
3378 }
3379
3380 region->init_req(_obj_path, control());
3381 phi ->init_req(_obj_path, cast_obj);
3382
3383 // A merge of null or Casted-NotNull obj
3384 Node* res = _gvn.transform(phi);
3385
3386 // Note I do NOT always 'replace_in_map(obj,result)' here.
3387 // if( tk->klass()->can_be_primary_super() )
3388 // This means that if I successfully store an Object into an array-of-String
3389 // I 'forget' that the Object is really now known to be a String. I have to
3390 // do this because we don't have true union types for interfaces - if I store
3391 // a Baz into an array-of-Interface and then tell the optimizer it's an
3392 // Interface, I forget that it's also a Baz and cannot do Baz-like field
3393 // references to it. FIX THIS WHEN UNION TYPES APPEAR!
3394 // replace_in_map( obj, res );
3395
3396 // Return final merged results
3397 set_control( _gvn.transform(region) );
3398 record_for_igvn(region);
3399
3400 return record_profiled_receiver_for_speculation(res);
3401 }
3402
3403 //------------------------------next_monitor-----------------------------------
3404 // What number should be given to the next monitor?
3405 int GraphKit::next_monitor() {
3406 int current = jvms()->monitor_depth()* C->sync_stack_slots();
3407 int next = current + C->sync_stack_slots();
3408 // Keep the toplevel high water mark current:
3409 if (C->fixed_slots() < next) C->set_fixed_slots(next);
3410 return current;
3411 }
3412
3413 //------------------------------insert_mem_bar---------------------------------
3414 // Memory barrier to avoid floating things around
3415 // The membar serves as a pinch point between both control and all memory slices.
3416 Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {
3417 MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
3418 mb->init_req(TypeFunc::Control, control());
3419 mb->init_req(TypeFunc::Memory, reset_memory());
3420 Node* membar = _gvn.transform(mb);
3514 lock->create_lock_counter(map()->jvms());
3515 increment_counter(lock->counter()->addr());
3516 }
3517 #endif
3518
3519 return flock;
3520 }
3521
3522
3523 //------------------------------shared_unlock----------------------------------
3524 // Emit unlocking code.
3525 void GraphKit::shared_unlock(Node* box, Node* obj) {
3526 // bci is either a monitorenter bc or InvocationEntryBci
3527 // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3528 assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3529
3530 if (stopped()) { // Dead monitor?
3531 map()->pop_monitor(); // Kill monitor from debug info
3532 return;
3533 }
3534
3535 // Memory barrier to avoid floating things down past the locked region
3536 insert_mem_bar(Op_MemBarReleaseLock);
3537
3538 const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();
3539 UnlockNode *unlock = new UnlockNode(C, tf);
3540 #ifdef ASSERT
3541 unlock->set_dbg_jvms(sync_jvms());
3542 #endif
3543 uint raw_idx = Compile::AliasIdxRaw;
3544 unlock->init_req( TypeFunc::Control, control() );
3545 unlock->init_req( TypeFunc::Memory , memory(raw_idx) );
3546 unlock->init_req( TypeFunc::I_O , top() ) ; // does no i/o
3547 unlock->init_req( TypeFunc::FramePtr, frameptr() );
3548 unlock->init_req( TypeFunc::ReturnAdr, top() );
3549
3550 unlock->init_req(TypeFunc::Parms + 0, obj);
3551 unlock->init_req(TypeFunc::Parms + 1, box);
3552 unlock = _gvn.transform(unlock)->as_Unlock();
3553
3554 Node* mem = reset_memory();
3555
3556 // unlock has no side-effects, sets few values
3557 set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);
3558
3559 // Kill monitor from debug info
3560 map()->pop_monitor( );
3561 }
3562
3563 //-------------------------------get_layout_helper-----------------------------
3564 // If the given klass is a constant or known to be an array,
3565 // fetch the constant layout helper value into constant_value
3566 // and return null. Otherwise, load the non-constant
3567 // layout helper value, and return the node which represents it.
3568 // This two-faced routine is useful because allocation sites
3569 // almost always feature constant types.
3570 Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {
3571 const TypeKlassPtr* klass_t = _gvn.type(klass_node)->isa_klassptr();
3572 if (!StressReflectiveCode && klass_t != nullptr) {
3573 bool xklass = klass_t->klass_is_exact();
3574 if (xklass || (klass_t->isa_aryklassptr() && klass_t->is_aryklassptr()->elem() != Type::BOTTOM)) {
3575 jint lhelper;
3576 if (klass_t->isa_aryklassptr()) {
3577 BasicType elem = klass_t->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type();
3578 if (is_reference_type(elem, true)) {
3579 elem = T_OBJECT;
3580 }
3581 lhelper = Klass::array_layout_helper(elem);
3582 } else {
3583 lhelper = klass_t->is_instklassptr()->exact_klass()->layout_helper();
3584 }
3585 if (lhelper != Klass::_lh_neutral_value) {
3586 constant_value = lhelper;
3587 return (Node*) nullptr;
3588 }
3589 }
3590 }
3591 constant_value = Klass::_lh_neutral_value; // put in a known value
3592 Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset()));
3593 return make_load(nullptr, lhp, TypeInt::INT, T_INT, MemNode::unordered);
3594 }
3595
3596 // We just put in an allocate/initialize with a big raw-memory effect.
3597 // Hook selected additional alias categories on the initialization.
3598 static void hook_memory_on_init(GraphKit& kit, int alias_idx,
3599 MergeMemNode* init_in_merge,
3600 Node* init_out_raw) {
3601 DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());
3602 assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");
3603
3604 Node* prevmem = kit.memory(alias_idx);
3605 init_in_merge->set_memory_at(alias_idx, prevmem);
3606 kit.set_memory(init_out_raw, alias_idx);
3607 }
3608
3609 //---------------------------set_output_for_allocation-------------------------
3610 Node* GraphKit::set_output_for_allocation(AllocateNode* alloc,
3611 const TypeOopPtr* oop_type,
3612 bool deoptimize_on_exception) {
3613 int rawidx = Compile::AliasIdxRaw;
3614 alloc->set_req( TypeFunc::FramePtr, frameptr() );
3615 add_safepoint_edges(alloc);
3616 Node* allocx = _gvn.transform(alloc);
3617 set_control( _gvn.transform(new ProjNode(allocx, TypeFunc::Control) ) );
3618 // create memory projection for i_o
3619 set_memory ( _gvn.transform( new ProjNode(allocx, TypeFunc::Memory, true) ), rawidx );
3620 make_slow_call_ex(allocx, env()->Throwable_klass(), true, deoptimize_on_exception);
3621
3622 // create a memory projection as for the normal control path
3623 Node* malloc = _gvn.transform(new ProjNode(allocx, TypeFunc::Memory));
3624 set_memory(malloc, rawidx);
3625
3626 // a normal slow-call doesn't change i_o, but an allocation does
3627 // we create a separate i_o projection for the normal control path
3628 set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) );
3629 Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) );
3630
3631 // put in an initialization barrier
3632 InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,
3633 rawoop)->as_Initialize();
3634 assert(alloc->initialization() == init, "2-way macro link must work");
3635 assert(init ->allocation() == alloc, "2-way macro link must work");
3636 {
3637 // Extract memory strands which may participate in the new object's
3638 // initialization, and source them from the new InitializeNode.
3639 // This will allow us to observe initializations when they occur,
3640 // and link them properly (as a group) to the InitializeNode.
3641 assert(init->in(InitializeNode::Memory) == malloc, "");
3642 MergeMemNode* minit_in = MergeMemNode::make(malloc);
3643 init->set_req(InitializeNode::Memory, minit_in);
3644 record_for_igvn(minit_in); // fold it up later, if possible
3645 Node* minit_out = memory(rawidx);
3646 assert(minit_out->is_Proj() && minit_out->in(0) == init, "");
3647 int mark_idx = C->get_alias_index(oop_type->add_offset(oopDesc::mark_offset_in_bytes()));
3648 // Add an edge in the MergeMem for the header fields so an access to one of those has correct memory state.
3649 // Use one NarrowMemProjNode per slice to properly record the adr type of each slice. The Initialize node will have
3650 // multiple projections as a result.
3651 set_memory(_gvn.transform(new NarrowMemProjNode(init, C->get_adr_type(mark_idx))), mark_idx);
3652 int klass_idx = C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes()));
3653 set_memory(_gvn.transform(new NarrowMemProjNode(init, C->get_adr_type(klass_idx))), klass_idx);
3654 if (oop_type->isa_aryptr()) {
3655 const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);
3656 int elemidx = C->get_alias_index(telemref);
3657 hook_memory_on_init(*this, elemidx, minit_in, _gvn.transform(new NarrowMemProjNode(init, C->get_adr_type(elemidx))));
3658 } else if (oop_type->isa_instptr()) {
3659 ciInstanceKlass* ik = oop_type->is_instptr()->instance_klass();
3660 for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {
3661 ciField* field = ik->nonstatic_field_at(i);
3662 if (field->offset_in_bytes() >= TrackedInitializationLimit * HeapWordSize)
3663 continue; // do not bother to track really large numbers of fields
3664 // Find (or create) the alias category for this field:
3665 int fieldidx = C->alias_type(field)->index();
3666 hook_memory_on_init(*this, fieldidx, minit_in, _gvn.transform(new NarrowMemProjNode(init, C->get_adr_type(fieldidx))));
3667 }
3668 }
3669 }
3670
3671 // Cast raw oop to the real thing...
3672 Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type);
3673 javaoop = _gvn.transform(javaoop);
3674 C->set_recent_alloc(control(), javaoop);
3675 assert(just_allocated_object(control()) == javaoop, "just allocated");
3676
3677 #ifdef ASSERT
3689 assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");
3690 }
3691 }
3692 #endif //ASSERT
3693
3694 return javaoop;
3695 }
3696
3697 //---------------------------new_instance--------------------------------------
3698 // This routine takes a klass_node which may be constant (for a static type)
3699 // or may be non-constant (for reflective code). It will work equally well
3700 // for either, and the graph will fold nicely if the optimizer later reduces
3701 // the type to a constant.
3702 // The optional arguments are for specialized use by intrinsics:
3703 // - If 'extra_slow_test' if not null is an extra condition for the slow-path.
3704 // - If 'return_size_val', report the total object size to the caller.
3705 // - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
3706 Node* GraphKit::new_instance(Node* klass_node,
3707 Node* extra_slow_test,
3708 Node* *return_size_val,
3709 bool deoptimize_on_exception) {
3710 // Compute size in doublewords
3711 // The size is always an integral number of doublewords, represented
3712 // as a positive bytewise size stored in the klass's layout_helper.
3713 // The layout_helper also encodes (in a low bit) the need for a slow path.
3714 jint layout_con = Klass::_lh_neutral_value;
3715 Node* layout_val = get_layout_helper(klass_node, layout_con);
3716 int layout_is_con = (layout_val == nullptr);
3717
3718 if (extra_slow_test == nullptr) extra_slow_test = intcon(0);
3719 // Generate the initial go-slow test. It's either ALWAYS (return a
3720 // Node for 1) or NEVER (return a null) or perhaps (in the reflective
3721 // case) a computed value derived from the layout_helper.
3722 Node* initial_slow_test = nullptr;
3723 if (layout_is_con) {
3724 assert(!StressReflectiveCode, "stress mode does not use these paths");
3725 bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);
3726 initial_slow_test = must_go_slow ? intcon(1) : extra_slow_test;
3727 } else { // reflective case
3728 // This reflective path is used by Unsafe.allocateInstance.
3729 // (It may be stress-tested by specifying StressReflectiveCode.)
3730 // Basically, we want to get into the VM is there's an illegal argument.
3731 Node* bit = intcon(Klass::_lh_instance_slow_path_bit);
3732 initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) );
3733 if (extra_slow_test != intcon(0)) {
3734 initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) );
3735 }
3736 // (Macro-expander will further convert this to a Bool, if necessary.)
3747
3748 // Clear the low bits to extract layout_helper_size_in_bytes:
3749 assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
3750 Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));
3751 size = _gvn.transform( new AndXNode(size, mask) );
3752 }
3753 if (return_size_val != nullptr) {
3754 (*return_size_val) = size;
3755 }
3756
3757 // This is a precise notnull oop of the klass.
3758 // (Actually, it need not be precise if this is a reflective allocation.)
3759 // It's what we cast the result to.
3760 const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();
3761 if (!tklass) tklass = TypeInstKlassPtr::OBJECT;
3762 const TypeOopPtr* oop_type = tklass->as_instance_type();
3763
3764 // Now generate allocation code
3765
3766 // The entire memory state is needed for slow path of the allocation
3767 // since GC and deoptimization can happened.
3768 Node *mem = reset_memory();
3769 set_all_memory(mem); // Create new memory state
3770
3771 AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP),
3772 control(), mem, i_o(),
3773 size, klass_node,
3774 initial_slow_test);
3775
3776 return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);
3777 }
3778
3779 //-------------------------------new_array-------------------------------------
3780 // helper for both newarray and anewarray
3781 // The 'length' parameter is (obviously) the length of the array.
3782 // The optional arguments are for specialized use by intrinsics:
3783 // - If 'return_size_val', report the non-padded array size (sum of header size
3784 // and array body) to the caller.
3785 // - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
3786 Node* GraphKit::new_array(Node* klass_node, // array klass (maybe variable)
3787 Node* length, // number of array elements
3788 int nargs, // number of arguments to push back for uncommon trap
3789 Node* *return_size_val,
3790 bool deoptimize_on_exception) {
3791 jint layout_con = Klass::_lh_neutral_value;
3792 Node* layout_val = get_layout_helper(klass_node, layout_con);
3793 int layout_is_con = (layout_val == nullptr);
3794
3795 if (!layout_is_con && !StressReflectiveCode &&
3796 !too_many_traps(Deoptimization::Reason_class_check)) {
3797 // This is a reflective array creation site.
3798 // Optimistically assume that it is a subtype of Object[],
3799 // so that we can fold up all the address arithmetic.
3800 layout_con = Klass::array_layout_helper(T_OBJECT);
3801 Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) );
3802 Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) );
3803 { BuildCutout unless(this, bol_lh, PROB_MAX);
3804 inc_sp(nargs);
3805 uncommon_trap(Deoptimization::Reason_class_check,
3806 Deoptimization::Action_maybe_recompile);
3807 }
3808 layout_val = nullptr;
3809 layout_is_con = true;
3810 }
3811
3812 // Generate the initial go-slow test. Make sure we do not overflow
3813 // if length is huge (near 2Gig) or negative! We do not need
3814 // exact double-words here, just a close approximation of needed
3815 // double-words. We can't add any offset or rounding bits, lest we
3816 // take a size -1 of bytes and make it positive. Use an unsigned
3817 // compare, so negative sizes look hugely positive.
3818 int fast_size_limit = FastAllocateSizeLimit;
3819 if (layout_is_con) {
3820 assert(!StressReflectiveCode, "stress mode does not use these paths");
3821 // Increase the size limit if we have exact knowledge of array type.
3822 int log2_esize = Klass::layout_helper_log2_element_size(layout_con);
3823 assert(fast_size_limit == 0 || count_leading_zeros(fast_size_limit) > static_cast<unsigned>(LogBytesPerLong - log2_esize),
3824 "fast_size_limit (%d) overflow when shifted left by %d", fast_size_limit, LogBytesPerLong - log2_esize);
3825 fast_size_limit <<= (LogBytesPerLong - log2_esize);
3826 }
3827
3828 Node* initial_slow_cmp = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) );
3829 Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) );
3830
3831 // --- Size Computation ---
3832 // array_size = round_to_heap(array_header + (length << elem_shift));
3833 // where round_to_heap(x) == align_to(x, MinObjAlignmentInBytes)
3834 // and align_to(x, y) == ((x + y-1) & ~(y-1))
3835 // The rounding mask is strength-reduced, if possible.
3836 int round_mask = MinObjAlignmentInBytes - 1;
3837 Node* header_size = nullptr;
3838 // (T_BYTE has the weakest alignment and size restrictions...)
3839 if (layout_is_con) {
3840 int hsize = Klass::layout_helper_header_size(layout_con);
3841 int eshift = Klass::layout_helper_log2_element_size(layout_con);
3842 if ((round_mask & ~right_n_bits(eshift)) == 0)
3843 round_mask = 0; // strength-reduce it if it goes away completely
3844 assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
3845 int header_size_min = arrayOopDesc::base_offset_in_bytes(T_BYTE);
3846 assert(header_size_min <= hsize, "generic minimum is smallest");
3847 header_size = intcon(hsize);
3848 } else {
3849 Node* hss = intcon(Klass::_lh_header_size_shift);
3850 Node* hsm = intcon(Klass::_lh_header_size_mask);
3851 header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3852 header_size = _gvn.transform(new AndINode(header_size, hsm));
3853 }
3854
3855 Node* elem_shift = nullptr;
3856 if (layout_is_con) {
3857 int eshift = Klass::layout_helper_log2_element_size(layout_con);
3858 if (eshift != 0)
3859 elem_shift = intcon(eshift);
3860 } else {
3861 // There is no need to mask or shift this value.
3862 // The semantics of LShiftINode include an implicit mask to 0x1F.
3863 assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
3864 elem_shift = layout_val;
3913 }
3914 Node* non_rounded_size = _gvn.transform(new AddXNode(headerx, abody));
3915
3916 if (return_size_val != nullptr) {
3917 // This is the size
3918 (*return_size_val) = non_rounded_size;
3919 }
3920
3921 Node* size = non_rounded_size;
3922 if (round_mask != 0) {
3923 Node* mask1 = MakeConX(round_mask);
3924 size = _gvn.transform(new AddXNode(size, mask1));
3925 Node* mask2 = MakeConX(~round_mask);
3926 size = _gvn.transform(new AndXNode(size, mask2));
3927 }
3928 // else if round_mask == 0, the size computation is self-rounding
3929
3930 // Now generate allocation code
3931
3932 // The entire memory state is needed for slow path of the allocation
3933 // since GC and deoptimization can happened.
3934 Node *mem = reset_memory();
3935 set_all_memory(mem); // Create new memory state
3936
3937 if (initial_slow_test->is_Bool()) {
3938 // Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.
3939 initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);
3940 }
3941
3942 const TypeOopPtr* ary_type = _gvn.type(klass_node)->is_klassptr()->as_instance_type();
3943 Node* valid_length_test = _gvn.intcon(1);
3944 if (ary_type->isa_aryptr()) {
3945 BasicType bt = ary_type->isa_aryptr()->elem()->array_element_basic_type();
3946 jint max = TypeAryPtr::max_array_length(bt);
3947 Node* valid_length_cmp = _gvn.transform(new CmpUNode(length, intcon(max)));
3948 valid_length_test = _gvn.transform(new BoolNode(valid_length_cmp, BoolTest::le));
3949 }
3950
3951 // Create the AllocateArrayNode and its result projections
3952 AllocateArrayNode* alloc
3953 = new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),
3954 control(), mem, i_o(),
3955 size, klass_node,
3956 initial_slow_test,
3957 length, valid_length_test);
3958
3959 // Cast to correct type. Note that the klass_node may be constant or not,
3960 // and in the latter case the actual array type will be inexact also.
3961 // (This happens via a non-constant argument to inline_native_newArray.)
3962 // In any case, the value of klass_node provides the desired array type.
3963 const TypeInt* length_type = _gvn.find_int_type(length);
3964 if (ary_type->isa_aryptr() && length_type != nullptr) {
3965 // Try to get a better type than POS for the size
3966 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
3967 }
3968
3969 Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);
3970
3971 array_ideal_length(alloc, ary_type, true);
3972 return javaoop;
3973 }
3974
3975 // The following "Ideal_foo" functions are placed here because they recognize
3976 // the graph shapes created by the functions immediately above.
3977
3978 //---------------------------Ideal_allocation----------------------------------
4073 void GraphKit::add_parse_predicates(int nargs) {
4074 if (ShortRunningLongLoop) {
4075 // Will narrow the limit down with a cast node. Predicates added later may depend on the cast so should be last when
4076 // walking up from the loop.
4077 add_parse_predicate(Deoptimization::Reason_short_running_long_loop, nargs);
4078 }
4079 if (UseLoopPredicate) {
4080 add_parse_predicate(Deoptimization::Reason_predicate, nargs);
4081 if (UseProfiledLoopPredicate) {
4082 add_parse_predicate(Deoptimization::Reason_profile_predicate, nargs);
4083 }
4084 }
4085 if (UseAutoVectorizationPredicate) {
4086 add_parse_predicate(Deoptimization::Reason_auto_vectorization_check, nargs);
4087 }
4088 // Loop Limit Check Predicate should be near the loop.
4089 add_parse_predicate(Deoptimization::Reason_loop_limit_check, nargs);
4090 }
4091
4092 void GraphKit::sync_kit(IdealKit& ideal) {
4093 set_all_memory(ideal.merged_memory());
4094 set_i_o(ideal.i_o());
4095 set_control(ideal.ctrl());
4096 }
4097
4098 void GraphKit::final_sync(IdealKit& ideal) {
4099 // Final sync IdealKit and graphKit.
4100 sync_kit(ideal);
4101 }
4102
4103 Node* GraphKit::load_String_length(Node* str, bool set_ctrl) {
4104 Node* len = load_array_length(load_String_value(str, set_ctrl));
4105 Node* coder = load_String_coder(str, set_ctrl);
4106 // Divide length by 2 if coder is UTF16
4107 return _gvn.transform(new RShiftINode(len, coder));
4108 }
4109
4110 Node* GraphKit::load_String_value(Node* str, bool set_ctrl) {
4111 int value_offset = java_lang_String::value_offset();
4112 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4113 false, nullptr, 0);
4114 const TypePtr* value_field_type = string_type->add_offset(value_offset);
4115 const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull,
4116 TypeAry::make(TypeInt::BYTE, TypeInt::POS),
4117 ciTypeArrayKlass::make(T_BYTE), true, 0);
4118 Node* p = basic_plus_adr(str, str, value_offset);
4119 Node* load = access_load_at(str, p, value_field_type, value_type, T_OBJECT,
4120 IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4121 return load;
4122 }
4123
4124 Node* GraphKit::load_String_coder(Node* str, bool set_ctrl) {
4125 if (!CompactStrings) {
4126 return intcon(java_lang_String::CODER_UTF16);
4127 }
4128 int coder_offset = java_lang_String::coder_offset();
4129 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4130 false, nullptr, 0);
4131 const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4132
4133 Node* p = basic_plus_adr(str, str, coder_offset);
4134 Node* load = access_load_at(str, p, coder_field_type, TypeInt::BYTE, T_BYTE,
4135 IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4136 return load;
4137 }
4138
4139 void GraphKit::store_String_value(Node* str, Node* value) {
4140 int value_offset = java_lang_String::value_offset();
4141 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4142 false, nullptr, 0);
4143 const TypePtr* value_field_type = string_type->add_offset(value_offset);
4144
4145 access_store_at(str, basic_plus_adr(str, value_offset), value_field_type,
4146 value, TypeAryPtr::BYTES, T_OBJECT, IN_HEAP | MO_UNORDERED);
4147 }
4148
4149 void GraphKit::store_String_coder(Node* str, Node* value) {
4150 int coder_offset = java_lang_String::coder_offset();
4151 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4152 false, nullptr, 0);
4153 const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4154
4155 access_store_at(str, basic_plus_adr(str, coder_offset), coder_field_type,
4156 value, TypeInt::BYTE, T_BYTE, IN_HEAP | MO_UNORDERED);
4157 }
4158
4159 // Capture src and dst memory state with a MergeMemNode
4160 Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) {
4161 if (src_type == dst_type) {
4162 // Types are equal, we don't need a MergeMemNode
4163 return memory(src_type);
4164 }
4165 MergeMemNode* merge = MergeMemNode::make(map()->memory());
4166 record_for_igvn(merge); // fold it up later, if possible
4167 int src_idx = C->get_alias_index(src_type);
4168 int dst_idx = C->get_alias_index(dst_type);
4169 merge->set_memory_at(src_idx, memory(src_idx));
4170 merge->set_memory_at(dst_idx, memory(dst_idx));
4171 return merge;
4172 }
4245 i_char->init_req(2, AddI(i_char, intcon(2)));
4246
4247 set_control(IfFalse(iff));
4248 set_memory(st, TypeAryPtr::BYTES);
4249 }
4250
4251 Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) {
4252 if (!field->is_constant()) {
4253 return nullptr; // Field not marked as constant.
4254 }
4255 ciInstance* holder = nullptr;
4256 if (!field->is_static()) {
4257 ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop();
4258 if (const_oop != nullptr && const_oop->is_instance()) {
4259 holder = const_oop->as_instance();
4260 }
4261 }
4262 const Type* con_type = Type::make_constant_from_field(field, holder, field->layout_type(),
4263 /*is_unsigned_load=*/false);
4264 if (con_type != nullptr) {
4265 return makecon(con_type);
4266 }
4267 return nullptr;
4268 }
4269
4270 Node* GraphKit::maybe_narrow_object_type(Node* obj, ciKlass* type) {
4271 const TypeOopPtr* obj_type = obj->bottom_type()->isa_oopptr();
4272 const TypeOopPtr* sig_type = TypeOopPtr::make_from_klass(type);
4273 if (obj_type != nullptr && sig_type->is_loaded() && !obj_type->higher_equal(sig_type)) {
4274 const Type* narrow_obj_type = obj_type->filter_speculative(sig_type); // keep speculative part
4275 Node* casted_obj = gvn().transform(new CheckCastPPNode(control(), obj, narrow_obj_type));
4276 return casted_obj;
4277 }
4278 return obj;
4279 }
|
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "asm/register.hpp"
26 #include "ci/ciFlatArrayKlass.hpp"
27 #include "ci/ciInlineKlass.hpp"
28 #include "ci/ciMethod.hpp"
29 #include "ci/ciObjArray.hpp"
30 #include "ci/ciUtilities.hpp"
31 #include "classfile/javaClasses.hpp"
32 #include "compiler/compileLog.hpp"
33 #include "gc/shared/barrierSet.hpp"
34 #include "gc/shared/c2/barrierSetC2.hpp"
35 #include "interpreter/interpreter.hpp"
36 #include "memory/resourceArea.hpp"
37 #include "oops/flatArrayKlass.hpp"
38 #include "opto/addnode.hpp"
39 #include "opto/castnode.hpp"
40 #include "opto/convertnode.hpp"
41 #include "opto/graphKit.hpp"
42 #include "opto/idealKit.hpp"
43 #include "opto/inlinetypenode.hpp"
44 #include "opto/intrinsicnode.hpp"
45 #include "opto/locknode.hpp"
46 #include "opto/machnode.hpp"
47 #include "opto/multnode.hpp"
48 #include "opto/narrowptrnode.hpp"
49 #include "opto/opaquenode.hpp"
50 #include "opto/parse.hpp"
51 #include "opto/rootnode.hpp"
52 #include "opto/runtime.hpp"
53 #include "opto/subtypenode.hpp"
54 #include "runtime/arguments.hpp"
55 #include "runtime/deoptimization.hpp"
56 #include "runtime/sharedRuntime.hpp"
57 #include "runtime/stubRoutines.hpp"
58 #include "utilities/bitMap.inline.hpp"
59 #include "utilities/growableArray.hpp"
60 #include "utilities/powerOfTwo.hpp"
61
62 //----------------------------GraphKit-----------------------------------------
63 // Main utility constructor.
64 GraphKit::GraphKit(JVMState* jvms, PhaseGVN* gvn)
65 : Phase(Phase::Parser),
66 _env(C->env()),
67 _gvn((gvn != nullptr) ? *gvn : *C->initial_gvn()),
68 _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
69 {
70 assert(gvn == nullptr || !gvn->is_IterGVN() || gvn->is_IterGVN()->delay_transform(), "delay transform should be enabled");
71 _exceptions = jvms->map()->next_exception();
72 if (_exceptions != nullptr) jvms->map()->set_next_exception(nullptr);
73 set_jvms(jvms);
74 #ifdef ASSERT
75 if (_gvn.is_IterGVN() != nullptr) {
76 assert(_gvn.is_IterGVN()->delay_transform(), "Transformation must be delayed if IterGVN is used");
77 // Save the initial size of _for_igvn worklist for verification (see ~GraphKit)
78 _worklist_size = _gvn.C->igvn_worklist()->size();
79 }
80 #endif
81 }
82
83 // Private constructor for parser.
84 GraphKit::GraphKit()
85 : Phase(Phase::Parser),
86 _env(C->env()),
87 _gvn(*C->initial_gvn()),
88 _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
89 {
90 _exceptions = nullptr;
91 set_map(nullptr);
92 DEBUG_ONLY(_sp = -99);
93 DEBUG_ONLY(set_bci(-99));
94 }
95
96
97
98 //---------------------------clean_stack---------------------------------------
99 // Clear away rubbish from the stack area of the JVM state.
100 // This destroys any arguments that may be waiting on the stack.
345 }
346 static inline void add_one_req(Node* dstphi, Node* src) {
347 assert(is_hidden_merge(dstphi), "must be a special merge node");
348 assert(!is_hidden_merge(src), "must not be a special merge node");
349 dstphi->add_req(src);
350 }
351
352 //-----------------------combine_exception_states------------------------------
353 // This helper function combines exception states by building phis on a
354 // specially marked state-merging region. These regions and phis are
355 // untransformed, and can build up gradually. The region is marked by
356 // having a control input of its exception map, rather than null. Such
357 // regions do not appear except in this function, and in use_exception_state.
358 void GraphKit::combine_exception_states(SafePointNode* ex_map, SafePointNode* phi_map) {
359 if (failing_internal()) {
360 return; // dying anyway...
361 }
362 JVMState* ex_jvms = ex_map->_jvms;
363 assert(ex_jvms->same_calls_as(phi_map->_jvms), "consistent call chains");
364 assert(ex_jvms->stkoff() == phi_map->_jvms->stkoff(), "matching locals");
365 // TODO 8325632 Re-enable
366 // assert(ex_jvms->sp() == phi_map->_jvms->sp(), "matching stack sizes");
367 assert(ex_jvms->monoff() == phi_map->_jvms->monoff(), "matching JVMS");
368 assert(ex_jvms->scloff() == phi_map->_jvms->scloff(), "matching scalar replaced objects");
369 assert(ex_map->req() == phi_map->req(), "matching maps");
370 uint tos = ex_jvms->stkoff() + ex_jvms->sp();
371 Node* hidden_merge_mark = root();
372 Node* region = phi_map->control();
373 MergeMemNode* phi_mem = phi_map->merged_memory();
374 MergeMemNode* ex_mem = ex_map->merged_memory();
375 if (region->in(0) != hidden_merge_mark) {
376 // The control input is not (yet) a specially-marked region in phi_map.
377 // Make it so, and build some phis.
378 region = new RegionNode(2);
379 _gvn.set_type(region, Type::CONTROL);
380 region->set_req(0, hidden_merge_mark); // marks an internal ex-state
381 region->init_req(1, phi_map->control());
382 phi_map->set_control(region);
383 Node* io_phi = PhiNode::make(region, phi_map->i_o(), Type::ABIO);
384 record_for_igvn(io_phi);
385 _gvn.set_type(io_phi, Type::ABIO);
386 phi_map->set_i_o(io_phi);
874 if (PrintMiscellaneous && (Verbose || WizardMode)) {
875 tty->print_cr("Zombie local %d: ", local);
876 jvms->dump();
877 }
878 return false;
879 }
880 }
881 }
882 return true;
883 }
884
885 #endif //ASSERT
886
887 // Helper function for enforcing certain bytecodes to reexecute if deoptimization happens.
888 static bool should_reexecute_implied_by_bytecode(JVMState *jvms, bool is_anewarray) {
889 ciMethod* cur_method = jvms->method();
890 int cur_bci = jvms->bci();
891 if (cur_method != nullptr && cur_bci != InvocationEntryBci) {
892 Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci);
893 return Interpreter::bytecode_should_reexecute(code) ||
894 (is_anewarray && (code == Bytecodes::_multianewarray));
895 // Reexecute _multianewarray bytecode which was replaced with
896 // sequence of [a]newarray. See Parse::do_multianewarray().
897 //
898 // Note: interpreter should not have it set since this optimization
899 // is limited by dimensions and guarded by flag so in some cases
900 // multianewarray() runtime calls will be generated and
901 // the bytecode should not be reexecutes (stack will not be reset).
902 } else {
903 return false;
904 }
905 }
906
907 // Helper function for adding JVMState and debug information to node
908 void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) {
909 // Add the safepoint edges to the call (or other safepoint).
910
911 // Make sure dead locals are set to top. This
912 // should help register allocation time and cut down on the size
913 // of the deoptimization information.
914 assert(dead_locals_are_killed(), "garbage in debug info before safepoint");
942
943 if (env()->should_retain_local_variables()) {
944 // At any safepoint, this method can get breakpointed, which would
945 // then require an immediate deoptimization.
946 can_prune_locals = false; // do not prune locals
947 stack_slots_not_pruned = 0;
948 }
949
950 // do not scribble on the input jvms
951 JVMState* out_jvms = youngest_jvms->clone_deep(C);
952 call->set_jvms(out_jvms); // Start jvms list for call node
953
954 // For a known set of bytecodes, the interpreter should reexecute them if
955 // deoptimization happens. We set the reexecute state for them here
956 if (out_jvms->is_reexecute_undefined() && //don't change if already specified
957 should_reexecute_implied_by_bytecode(out_jvms, call->is_AllocateArray())) {
958 #ifdef ASSERT
959 int inputs = 0, not_used; // initialized by GraphKit::compute_stack_effects()
960 assert(method() == youngest_jvms->method(), "sanity");
961 assert(compute_stack_effects(inputs, not_used), "unknown bytecode: %s", Bytecodes::name(java_bc()));
962 // TODO 8371125
963 // assert(out_jvms->sp() >= (uint)inputs, "not enough operands for reexecution");
964 #endif // ASSERT
965 out_jvms->set_should_reexecute(true); //NOTE: youngest_jvms not changed
966 }
967
968 // Presize the call:
969 DEBUG_ONLY(uint non_debug_edges = call->req());
970 call->add_req_batch(top(), youngest_jvms->debug_depth());
971 assert(call->req() == non_debug_edges + youngest_jvms->debug_depth(), "");
972
973 // Set up edges so that the call looks like this:
974 // Call [state:] ctl io mem fptr retadr
975 // [parms:] parm0 ... parmN
976 // [root:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN
977 // [...mid:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN [...]
978 // [young:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN
979 // Note that caller debug info precedes callee debug info.
980
981 // Fill pointer walks backwards from "young:" to "root:" in the diagram above:
982 uint debug_ptr = call->req();
983
984 // Loop over the map input edges associated with jvms, add them
985 // to the call node, & reset all offsets to match call node array.
986
987 JVMState* callee_jvms = nullptr;
988 for (JVMState* in_jvms = youngest_jvms; in_jvms != nullptr; ) {
989 uint debug_end = debug_ptr;
990 uint debug_start = debug_ptr - in_jvms->debug_size();
991 debug_ptr = debug_start; // back up the ptr
992
993 uint p = debug_start; // walks forward in [debug_start, debug_end)
994 uint j, k, l;
995 SafePointNode* in_map = in_jvms->map();
996 out_jvms->set_map(call);
997
998 if (can_prune_locals) {
999 assert(in_jvms->method() == out_jvms->method(), "sanity");
1000 // If the current throw can reach an exception handler in this JVMS,
1001 // then we must keep everything live that can reach that handler.
1002 // As a quick and dirty approximation, we look for any handlers at all.
1003 if (in_jvms->method()->has_exception_handlers()) {
1004 can_prune_locals = false;
1005 }
1006 }
1007
1008 // Add the Locals
1009 k = in_jvms->locoff();
1010 l = in_jvms->loc_size();
1011 out_jvms->set_locoff(p);
1012 if (!can_prune_locals) {
1013 for (j = 0; j < l; j++) {
1014 call->set_req(p++, in_map->in(k + j));
1015 }
1016 } else {
1017 p += l; // already set to top above by add_req_batch
1018 }
1019
1020 // Add the Expression Stack
1021 k = in_jvms->stkoff();
1022 l = in_jvms->sp();
1023 out_jvms->set_stkoff(p);
1024 if (!can_prune_locals) {
1025 for (j = 0; j < l; j++) {
1026 call->set_req(p++, in_map->in(k + j));
1027 }
1028 } else if (can_prune_locals && stack_slots_not_pruned != 0) {
1029 // Divide stack into {S0,...,S1}, where S0 is set to top.
1030 uint s1 = stack_slots_not_pruned;
1031 stack_slots_not_pruned = 0; // for next iteration
1032 if (s1 > l) s1 = l;
1033 uint s0 = l - s1;
1034 p += s0; // skip the tops preinstalled by add_req_batch
1035 for (j = s0; j < l; j++)
1036 call->set_req(p++, in_map->in(k+j));
1037 } else {
1038 p += l; // already set to top above by add_req_batch
1039 }
1040
1041 // Add the Monitors
1042 k = in_jvms->monoff();
1043 l = in_jvms->mon_size();
1044 out_jvms->set_monoff(p);
1045 for (j = 0; j < l; j++)
1046 call->set_req(p++, in_map->in(k+j));
1047
1048 // Copy any scalar object fields.
1049 k = in_jvms->scloff();
1050 l = in_jvms->scl_size();
1051 out_jvms->set_scloff(p);
1052 for (j = 0; j < l; j++)
1053 call->set_req(p++, in_map->in(k+j));
1054
1055 // Finish the new jvms.
1056 out_jvms->set_endoff(p);
1057
1058 assert(out_jvms->endoff() == debug_end, "fill ptr must match");
1059 assert(out_jvms->depth() == in_jvms->depth(), "depth must match");
1060 assert(out_jvms->loc_size() == in_jvms->loc_size(), "size must match");
1061 assert(out_jvms->mon_size() == in_jvms->mon_size(), "size must match");
1062 assert(out_jvms->scl_size() == in_jvms->scl_size(), "size must match");
1063 assert(out_jvms->debug_size() == in_jvms->debug_size(), "size must match");
1064
1065 // Update the two tail pointers in parallel.
1066 callee_jvms = out_jvms;
1067 out_jvms = out_jvms->caller();
1068 in_jvms = in_jvms->caller();
1069 }
1070
1071 assert(debug_ptr == non_debug_edges, "debug info must fit exactly");
1072
1073 // Test the correctness of JVMState::debug_xxx accessors:
1074 assert(call->jvms()->debug_start() == non_debug_edges, "");
1075 assert(call->jvms()->debug_end() == call->req(), "");
1076 assert(call->jvms()->debug_depth() == call->req() - non_debug_edges, "");
1077 }
1078
1079 bool GraphKit::compute_stack_effects(int& inputs, int& depth) {
1080 Bytecodes::Code code = java_bc();
1081 if (code == Bytecodes::_wide) {
1082 code = method()->java_code_at_bci(bci() + 1);
1083 }
1084
1085 if (code != Bytecodes::_illegal) {
1086 depth = Bytecodes::depth(code); // checkcast=0, athrow=-1
1222 Node* conv = _gvn.transform( new ConvI2LNode(offset));
1223 Node* mask = _gvn.transform(ConLNode::make((julong) max_juint));
1224 return _gvn.transform( new AndLNode(conv, mask) );
1225 }
1226
1227 Node* GraphKit::ConvL2I(Node* offset) {
1228 // short-circuit a common case
1229 jlong offset_con = find_long_con(offset, (jlong)Type::OffsetBot);
1230 if (offset_con != (jlong)Type::OffsetBot) {
1231 return intcon((int) offset_con);
1232 }
1233 return _gvn.transform( new ConvL2INode(offset));
1234 }
1235
1236 //-------------------------load_object_klass-----------------------------------
1237 Node* GraphKit::load_object_klass(Node* obj) {
1238 // Special-case a fresh allocation to avoid building nodes:
1239 Node* akls = AllocateNode::Ideal_klass(obj, &_gvn);
1240 if (akls != nullptr) return akls;
1241 Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
1242 return _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), k_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
1243 }
1244
1245 //-------------------------load_array_length-----------------------------------
1246 Node* GraphKit::load_array_length(Node* array) {
1247 // Special-case a fresh allocation to avoid building nodes:
1248 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(array);
1249 Node *alen;
1250 if (alloc == nullptr) {
1251 Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes());
1252 alen = _gvn.transform( new LoadRangeNode(nullptr, immutable_memory(), r_adr, TypeInt::POS));
1253 } else {
1254 alen = array_ideal_length(alloc, _gvn.type(array)->is_oopptr(), false);
1255 }
1256 return alen;
1257 }
1258
1259 Node* GraphKit::array_ideal_length(AllocateArrayNode* alloc,
1260 const TypeOopPtr* oop_type,
1261 bool replace_length_in_map) {
1262 Node* length = alloc->Ideal_length();
1271 replace_in_map(length, ccast);
1272 }
1273 return ccast;
1274 }
1275 }
1276 return length;
1277 }
1278
1279 //------------------------------do_null_check----------------------------------
1280 // Helper function to do a null pointer check. Returned value is
1281 // the incoming address with null casted away. You are allowed to use the
1282 // not-null value only if you are control dependent on the test.
1283 #ifndef PRODUCT
1284 extern uint explicit_null_checks_inserted,
1285 explicit_null_checks_elided;
1286 #endif
1287 Node* GraphKit::null_check_common(Node* value, BasicType type,
1288 // optional arguments for variations:
1289 bool assert_null,
1290 Node* *null_control,
1291 bool speculative,
1292 bool null_marker_check) {
1293 assert(!assert_null || null_control == nullptr, "not both at once");
1294 if (stopped()) return top();
1295 NOT_PRODUCT(explicit_null_checks_inserted++);
1296
1297 if (value->is_InlineType()) {
1298 // Null checking a scalarized but nullable inline type. Check the null marker
1299 // input instead of the oop input to avoid keeping buffer allocations alive.
1300 InlineTypeNode* vtptr = value->as_InlineType();
1301 while (vtptr->get_oop()->is_InlineType()) {
1302 vtptr = vtptr->get_oop()->as_InlineType();
1303 }
1304 null_check_common(vtptr->get_null_marker(), T_INT, assert_null, null_control, speculative, true);
1305 if (stopped()) {
1306 return top();
1307 }
1308 if (assert_null) {
1309 // TODO 8284443 Scalarize here (this currently leads to compilation bailouts)
1310 // vtptr = InlineTypeNode::make_null(_gvn, vtptr->type()->inline_klass());
1311 // replace_in_map(value, vtptr);
1312 // return vtptr;
1313 replace_in_map(value, null());
1314 return null();
1315 }
1316 bool do_replace_in_map = (null_control == nullptr || (*null_control) == top());
1317 return cast_not_null(value, do_replace_in_map);
1318 }
1319
1320 // Construct null check
1321 Node *chk = nullptr;
1322 switch(type) {
1323 case T_LONG : chk = new CmpLNode(value, _gvn.zerocon(T_LONG)); break;
1324 case T_INT : chk = new CmpINode(value, _gvn.intcon(0)); break;
1325 case T_ARRAY : // fall through
1326 type = T_OBJECT; // simplify further tests
1327 case T_OBJECT : {
1328 const Type *t = _gvn.type( value );
1329
1330 const TypeOopPtr* tp = t->isa_oopptr();
1331 if (tp != nullptr && !tp->is_loaded()
1332 // Only for do_null_check, not any of its siblings:
1333 && !assert_null && null_control == nullptr) {
1334 // Usually, any field access or invocation on an unloaded oop type
1335 // will simply fail to link, since the statically linked class is
1336 // likely also to be unloaded. However, in -Xcomp mode, sometimes
1337 // the static class is loaded but the sharper oop type is not.
1338 // Rather than checking for this obscure case in lots of places,
1339 // we simply observe that a null check on an unloaded class
1403 }
1404 Node *oldcontrol = control();
1405 set_control(cfg);
1406 Node *res = cast_not_null(value);
1407 set_control(oldcontrol);
1408 NOT_PRODUCT(explicit_null_checks_elided++);
1409 return res;
1410 }
1411 cfg = IfNode::up_one_dom(cfg, /*linear_only=*/ true);
1412 if (cfg == nullptr) break; // Quit at region nodes
1413 depth++;
1414 }
1415 }
1416
1417 //-----------
1418 // Branch to failure if null
1419 float ok_prob = PROB_MAX; // a priori estimate: nulls never happen
1420 Deoptimization::DeoptReason reason;
1421 if (assert_null) {
1422 reason = Deoptimization::reason_null_assert(speculative);
1423 } else if (type == T_OBJECT || null_marker_check) {
1424 reason = Deoptimization::reason_null_check(speculative);
1425 } else {
1426 reason = Deoptimization::Reason_div0_check;
1427 }
1428 // %%% Since Reason_unhandled is not recorded on a per-bytecode basis,
1429 // ciMethodData::has_trap_at will return a conservative -1 if any
1430 // must-be-null assertion has failed. This could cause performance
1431 // problems for a method after its first do_null_assert failure.
1432 // Consider using 'Reason_class_check' instead?
1433
1434 // To cause an implicit null check, we set the not-null probability
1435 // to the maximum (PROB_MAX). For an explicit check the probability
1436 // is set to a smaller value.
1437 if (null_control != nullptr || too_many_traps(reason)) {
1438 // probability is less likely
1439 ok_prob = PROB_LIKELY_MAG(3);
1440 } else if (!assert_null &&
1441 (ImplicitNullCheckThreshold > 0) &&
1442 method() != nullptr &&
1443 (method()->method_data()->trap_count(reason)
1477 }
1478
1479 if (assert_null) {
1480 // Cast obj to null on this path.
1481 replace_in_map(value, zerocon(type));
1482 return zerocon(type);
1483 }
1484
1485 // Cast obj to not-null on this path, if there is no null_control.
1486 // (If there is a null_control, a non-null value may come back to haunt us.)
1487 if (type == T_OBJECT) {
1488 Node* cast = cast_not_null(value, false);
1489 if (null_control == nullptr || (*null_control) == top())
1490 replace_in_map(value, cast);
1491 value = cast;
1492 }
1493
1494 return value;
1495 }
1496
1497 //------------------------------cast_not_null----------------------------------
1498 // Cast obj to not-null on this path
1499 Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) {
1500 if (obj->is_InlineType()) {
1501 Node* vt = obj->isa_InlineType()->clone_if_required(&gvn(), map(), do_replace_in_map);
1502 vt->as_InlineType()->set_null_marker(_gvn);
1503 vt = _gvn.transform(vt);
1504 if (do_replace_in_map) {
1505 replace_in_map(obj, vt);
1506 }
1507 return vt;
1508 }
1509 const Type *t = _gvn.type(obj);
1510 const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL);
1511 // Object is already not-null?
1512 if( t == t_not_null ) return obj;
1513
1514 Node* cast = new CastPPNode(control(), obj,t_not_null);
1515 cast = _gvn.transform( cast );
1516
1517 // Scan for instances of 'obj' in the current JVM mapping.
1518 // These instances are known to be not-null after the test.
1519 if (do_replace_in_map)
1520 replace_in_map(obj, cast);
1521
1522 return cast; // Return casted value
1523 }
1524
1525 Node* GraphKit::cast_to_non_larval(Node* obj) {
1526 const Type* obj_type = gvn().type(obj);
1527 if (obj->is_InlineType() || !obj_type->is_inlinetypeptr()) {
1528 return obj;
1529 }
1530
1531 Node* new_obj = InlineTypeNode::make_from_oop(this, obj, obj_type->inline_klass());
1532 replace_in_map(obj, new_obj);
1533 return new_obj;
1534 }
1535
1536 // Sometimes in intrinsics, we implicitly know an object is not null
1537 // (there's no actual null check) so we can cast it to not null. In
1538 // the course of optimizations, the input to the cast can become null.
1539 // In that case that data path will die and we need the control path
1540 // to become dead as well to keep the graph consistent. So we have to
1541 // add a check for null for which one branch can't be taken. It uses
1542 // an OpaqueNotNull node that will cause the check to be removed after loop
1543 // opts so the test goes away and the compiled code doesn't execute a
1544 // useless check.
1545 Node* GraphKit::must_be_not_null(Node* value, bool do_replace_in_map) {
1546 if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(value))) {
1547 return value;
1548 }
1549 Node* chk = _gvn.transform(new CmpPNode(value, null()));
1550 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
1551 Node* opaq = _gvn.transform(new OpaqueNotNullNode(C, tst));
1552 IfNode* iff = new IfNode(control(), opaq, PROB_MAX, COUNT_UNKNOWN);
1553 _gvn.set_type(iff, iff->Value(&_gvn));
1554 if (!tst->is_Con()) {
1555 record_for_igvn(iff);
1628 // These are layered on top of the factory methods in LoadNode and StoreNode,
1629 // and integrate with the parser's memory state and _gvn engine.
1630 //
1631
1632 // factory methods in "int adr_idx"
1633 Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,
1634 MemNode::MemOrd mo,
1635 LoadNode::ControlDependency control_dependency,
1636 bool require_atomic_access,
1637 bool unaligned,
1638 bool mismatched,
1639 bool unsafe,
1640 uint8_t barrier_data) {
1641 int adr_idx = C->get_alias_index(_gvn.type(adr)->isa_ptr());
1642 assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );
1643 const TypePtr* adr_type = nullptr; // debug-mode-only argument
1644 DEBUG_ONLY(adr_type = C->get_adr_type(adr_idx));
1645 Node* mem = memory(adr_idx);
1646 Node* ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, require_atomic_access, unaligned, mismatched, unsafe, barrier_data);
1647 ld = _gvn.transform(ld);
1648
1649 if (((bt == T_OBJECT) && C->do_escape_analysis()) || C->eliminate_boxing()) {
1650 // Improve graph before escape analysis and boxing elimination.
1651 record_for_igvn(ld);
1652 if (ld->is_DecodeN()) {
1653 // Also record the actual load (LoadN) in case ld is DecodeN. In some
1654 // rare corner cases, ld->in(1) can be something other than LoadN (e.g.,
1655 // a Phi). Recording such cases is still perfectly sound, but may be
1656 // unnecessary and result in some minor IGVN overhead.
1657 record_for_igvn(ld->in(1));
1658 }
1659 }
1660 return ld;
1661 }
1662
1663 Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,
1664 MemNode::MemOrd mo,
1665 bool require_atomic_access,
1666 bool unaligned,
1667 bool mismatched,
1668 bool unsafe,
1682 if (unsafe) {
1683 st->as_Store()->set_unsafe_access();
1684 }
1685 st->as_Store()->set_barrier_data(barrier_data);
1686 st = _gvn.transform(st);
1687 set_memory(st, adr_idx);
1688 // Back-to-back stores can only remove intermediate store with DU info
1689 // so push on worklist for optimizer.
1690 if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))
1691 record_for_igvn(st);
1692
1693 return st;
1694 }
1695
1696 Node* GraphKit::access_store_at(Node* obj,
1697 Node* adr,
1698 const TypePtr* adr_type,
1699 Node* val,
1700 const Type* val_type,
1701 BasicType bt,
1702 DecoratorSet decorators,
1703 bool safe_for_replace,
1704 const InlineTypeNode* vt) {
1705 // Transformation of a value which could be null pointer (CastPP #null)
1706 // could be delayed during Parse (for example, in adjust_map_after_if()).
1707 // Execute transformation here to avoid barrier generation in such case.
1708 if (_gvn.type(val) == TypePtr::NULL_PTR) {
1709 val = _gvn.makecon(TypePtr::NULL_PTR);
1710 }
1711
1712 if (stopped()) {
1713 return top(); // Dead path ?
1714 }
1715
1716 assert(val != nullptr, "not dead path");
1717 if (val->is_InlineType()) {
1718 // Store to non-flat field. Buffer the inline type and make sure
1719 // the store is re-executed if the allocation triggers deoptimization.
1720 PreserveReexecuteState preexecs(this);
1721 jvms()->set_should_reexecute(true);
1722 val = val->as_InlineType()->buffer(this, safe_for_replace);
1723 }
1724
1725 C2AccessValuePtr addr(adr, adr_type);
1726 C2AccessValue value(val, val_type);
1727 C2ParseAccess access(this, decorators | C2_WRITE_ACCESS, bt, obj, addr, nullptr, vt);
1728 if (access.is_raw()) {
1729 return _barrier_set->BarrierSetC2::store_at(access, value);
1730 } else {
1731 return _barrier_set->store_at(access, value);
1732 }
1733 }
1734
1735 Node* GraphKit::access_load_at(Node* obj, // containing obj
1736 Node* adr, // actual address to store val at
1737 const TypePtr* adr_type,
1738 const Type* val_type,
1739 BasicType bt,
1740 DecoratorSet decorators,
1741 Node* ctl) {
1742 if (stopped()) {
1743 return top(); // Dead path ?
1744 }
1745
1746 C2AccessValuePtr addr(adr, adr_type);
1747 C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, obj, addr, ctl);
1748 if (access.is_raw()) {
1749 return _barrier_set->BarrierSetC2::load_at(access, val_type);
1750 } else {
1751 return _barrier_set->load_at(access, val_type);
1752 }
1753 }
1754
1755 Node* GraphKit::access_load(Node* adr, // actual address to load val at
1756 const Type* val_type,
1757 BasicType bt,
1758 DecoratorSet decorators) {
1759 if (stopped()) {
1760 return top(); // Dead path ?
1761 }
1762
1763 C2AccessValuePtr addr(adr, adr->bottom_type()->is_ptr());
1764 C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, nullptr, addr);
1765 if (access.is_raw()) {
1766 return _barrier_set->BarrierSetC2::load_at(access, val_type);
1767 } else {
1832 Node* new_val,
1833 const Type* value_type,
1834 BasicType bt,
1835 DecoratorSet decorators) {
1836 C2AccessValuePtr addr(adr, adr_type);
1837 C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, bt, obj, addr, alias_idx);
1838 if (access.is_raw()) {
1839 return _barrier_set->BarrierSetC2::atomic_add_at(access, new_val, value_type);
1840 } else {
1841 return _barrier_set->atomic_add_at(access, new_val, value_type);
1842 }
1843 }
1844
1845 void GraphKit::access_clone(Node* src, Node* dst, Node* size, bool is_array) {
1846 return _barrier_set->clone(this, src, dst, size, is_array);
1847 }
1848
1849 //-------------------------array_element_address-------------------------
1850 Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,
1851 const TypeInt* sizetype, Node* ctrl) {
1852 const TypeAryPtr* arytype = _gvn.type(ary)->is_aryptr();
1853 uint shift;
1854 uint header;
1855 if (arytype->is_flat() && arytype->klass_is_exact()) {
1856 // We can only determine the flat array layout statically if the klass is exact. Otherwise, we could have different
1857 // value classes at runtime with a potentially different layout. The caller needs to fall back to call
1858 // load/store_unknown_inline_Type() at runtime. We could return a sentinel node for the non-exact case but that
1859 // might mess with other GVN transformations in between. Thus, we just continue in the else branch normally, even
1860 // though we don't need the address node in this case and throw it away again.
1861 shift = arytype->flat_log_elem_size();
1862 header = arrayOopDesc::base_offset_in_bytes(T_FLAT_ELEMENT);
1863 } else {
1864 shift = exact_log2(type2aelembytes(elembt));
1865 header = arrayOopDesc::base_offset_in_bytes(elembt);
1866 }
1867
1868 // short-circuit a common case (saves lots of confusing waste motion)
1869 jint idx_con = find_int_con(idx, -1);
1870 if (idx_con >= 0) {
1871 intptr_t offset = header + ((intptr_t)idx_con << shift);
1872 return basic_plus_adr(ary, offset);
1873 }
1874
1875 // must be correct type for alignment purposes
1876 Node* base = basic_plus_adr(ary, header);
1877 idx = Compile::conv_I2X_index(&_gvn, idx, sizetype, ctrl);
1878 Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) );
1879 return basic_plus_adr(ary, base, scale);
1880 }
1881
1882 Node* GraphKit::cast_to_flat_array(Node* array, ciInlineKlass* elem_vk) {
1883 assert(elem_vk->maybe_flat_in_array(), "no flat array for %s", elem_vk->name()->as_utf8());
1884 if (!elem_vk->has_atomic_layout() && !elem_vk->has_nullable_atomic_layout()) {
1885 return cast_to_flat_array_exact(array, elem_vk, true, false);
1886 } else if (!elem_vk->has_nullable_atomic_layout() && !elem_vk->has_non_atomic_layout()) {
1887 return cast_to_flat_array_exact(array, elem_vk, true, true);
1888 } else if (!elem_vk->has_atomic_layout() && !elem_vk->has_non_atomic_layout()) {
1889 return cast_to_flat_array_exact(array, elem_vk, false, true);
1890 }
1891
1892 bool is_null_free = false;
1893 if (!elem_vk->has_nullable_atomic_layout()) {
1894 // Element does not have a nullable flat layout, cannot be nullable
1895 is_null_free = true;
1896 }
1897
1898 ciArrayKlass* array_klass = ciObjArrayKlass::make(elem_vk, false);
1899 const TypeAryPtr* arytype = TypeOopPtr::make_from_klass(array_klass)->isa_aryptr();
1900 arytype = arytype->cast_to_flat(true)->cast_to_null_free(is_null_free);
1901 return _gvn.transform(new CheckCastPPNode(control(), array, arytype, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
1902 }
1903
1904 Node* GraphKit::cast_to_flat_array_exact(Node* array, ciInlineKlass* elem_vk, bool is_null_free, bool is_atomic) {
1905 assert(is_null_free || is_atomic, "nullable arrays must be atomic");
1906 ciArrayKlass* array_klass = ciObjArrayKlass::make(elem_vk, true, is_null_free, is_atomic);
1907 const TypeAryPtr* arytype = TypeOopPtr::make_from_klass(array_klass)->isa_aryptr();
1908 assert(arytype->klass_is_exact(), "inconsistency");
1909 assert(arytype->is_flat(), "inconsistency");
1910 assert(arytype->is_null_free() == is_null_free, "inconsistency");
1911 assert(arytype->is_not_null_free() == !is_null_free, "inconsistency");
1912 return _gvn.transform(new CheckCastPPNode(control(), array, arytype, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
1913 }
1914
1915 //-------------------------load_array_element-------------------------
1916 Node* GraphKit::load_array_element(Node* ary, Node* idx, const TypeAryPtr* arytype, bool set_ctrl) {
1917 const Type* elemtype = arytype->elem();
1918 BasicType elembt = elemtype->array_element_basic_type();
1919 Node* adr = array_element_address(ary, idx, elembt, arytype->size());
1920 if (elembt == T_NARROWOOP) {
1921 elembt = T_OBJECT; // To satisfy switch in LoadNode::make()
1922 }
1923 Node* ld = access_load_at(ary, adr, arytype, elemtype, elembt,
1924 IN_HEAP | IS_ARRAY | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0));
1925 return ld;
1926 }
1927
1928 //-------------------------set_arguments_for_java_call-------------------------
1929 // Arguments (pre-popped from the stack) are taken from the JVMS.
1930 void GraphKit::set_arguments_for_java_call(CallJavaNode* call, bool is_late_inline) {
1931 PreserveReexecuteState preexecs(this);
1932 if (Arguments::is_valhalla_enabled()) {
1933 // Make sure the call is "re-executed", if buffering of inline type arguments triggers deoptimization.
1934 // At this point, the call hasn't been executed yet, so we will only ever execute the call once.
1935 jvms()->set_should_reexecute(true);
1936 int arg_size = method()->get_declared_signature_at_bci(bci())->arg_size_for_bc(java_bc());
1937 inc_sp(arg_size);
1938 }
1939 // Add the call arguments
1940 const TypeTuple* domain = call->tf()->domain_sig();
1941 uint nargs = domain->cnt();
1942 int arg_num = 0;
1943 for (uint i = TypeFunc::Parms, idx = TypeFunc::Parms; i < nargs; i++) {
1944 Node* arg = argument(i-TypeFunc::Parms);
1945 const Type* t = domain->field_at(i);
1946 // TODO 8284443 A static call to a mismatched method should still be scalarized
1947 if (t->is_inlinetypeptr() && !call->method()->get_Method()->mismatch() && call->method()->is_scalarized_arg(arg_num)) {
1948 // We don't pass inline type arguments by reference but instead pass each field of the inline type
1949 if (!arg->is_InlineType()) {
1950 assert(_gvn.type(arg)->is_zero_type() && !t->inline_klass()->is_null_free(), "Unexpected argument type");
1951 arg = InlineTypeNode::make_from_oop(this, arg, t->inline_klass());
1952 }
1953 InlineTypeNode* vt = arg->as_InlineType();
1954 vt->pass_fields(this, call, idx, true, !t->maybe_null());
1955 // If an inline type argument is passed as fields, attach the Method* to the call site
1956 // to be able to access the extended signature later via attached_method_before_pc().
1957 // For example, see CompiledMethod::preserve_callee_argument_oops().
1958 call->set_override_symbolic_info(true);
1959 // Register an calling convention dependency on the callee method to make sure that this method is deoptimized and
1960 // re-compiled with a non-scalarized calling convention if the callee method is later marked as mismatched.
1961 C->dependencies()->assert_mismatch_calling_convention(call->method());
1962 arg_num++;
1963 continue;
1964 } else if (arg->is_InlineType()) {
1965 // Pass inline type argument via oop to callee
1966 arg = arg->as_InlineType()->buffer(this, true);
1967 }
1968 if (t != Type::HALF) {
1969 arg_num++;
1970 }
1971 call->init_req(idx++, arg);
1972 }
1973 }
1974
1975 //---------------------------set_edges_for_java_call---------------------------
1976 // Connect a newly created call into the current JVMS.
1977 // A return value node (if any) is returned from set_edges_for_java_call.
1978 void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) {
1979
1980 // Add the predefined inputs:
1981 call->init_req( TypeFunc::Control, control() );
1982 call->init_req( TypeFunc::I_O , i_o() );
1983 call->init_req( TypeFunc::Memory , reset_memory() );
1984 call->init_req( TypeFunc::FramePtr, frameptr() );
1985 call->init_req( TypeFunc::ReturnAdr, top() );
1986
1987 add_safepoint_edges(call, must_throw);
1988
1989 Node* xcall = _gvn.transform(call);
1990
1991 if (xcall == top()) {
1992 set_control(top());
1993 return;
1994 }
1995 assert(xcall == call, "call identity is stable");
1996
1997 // Re-use the current map to produce the result.
1998
1999 set_control(_gvn.transform(new ProjNode(call, TypeFunc::Control)));
2000 set_i_o( _gvn.transform(new ProjNode(call, TypeFunc::I_O , separate_io_proj)));
2001 set_all_memory_call(xcall, separate_io_proj);
2002
2003 //return xcall; // no need, caller already has it
2004 }
2005
2006 Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj, bool deoptimize) {
2007 if (stopped()) return top(); // maybe the call folded up?
2008
2009 // Note: Since any out-of-line call can produce an exception,
2010 // we always insert an I_O projection from the call into the result.
2011
2012 make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj, deoptimize);
2013
2014 if (separate_io_proj) {
2015 // The caller requested separate projections be used by the fall
2016 // through and exceptional paths, so replace the projections for
2017 // the fall through path.
2018 set_i_o(_gvn.transform( new ProjNode(call, TypeFunc::I_O) ));
2019 set_all_memory(_gvn.transform( new ProjNode(call, TypeFunc::Memory) ));
2020 }
2021
2022 // Capture the return value, if any.
2023 Node* ret;
2024 if (call->method() == nullptr || call->method()->return_type()->basic_type() == T_VOID) {
2025 ret = top();
2026 } else if (call->tf()->returns_inline_type_as_fields()) {
2027 // Return of multiple values (inline type fields): we create a
2028 // InlineType node, each field is a projection from the call.
2029 ciInlineKlass* vk = call->method()->return_type()->as_inline_klass();
2030 uint base_input = TypeFunc::Parms;
2031 ret = InlineTypeNode::make_from_multi(this, call, vk, base_input, false, false);
2032 } else {
2033 ret = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
2034 ciType* t = call->method()->return_type();
2035 if (!t->is_loaded() && InlineTypeReturnedAsFields) {
2036 // The return type is unloaded but the callee might later be C2 compiled and then return
2037 // in scalarized form when the return type is loaded. Handle this similar to what we do in
2038 // PhaseMacroExpand::expand_mh_intrinsic_return by calling into the runtime to buffer.
2039 // It's a bit unfortunate because we will deopt anyway but the interpreter needs an oop.
2040 IdealKit ideal(this);
2041 IdealVariable res(ideal);
2042 ideal.declarations_done();
2043 // Change return type of call to scalarized return
2044 const TypeFunc* tf = call->_tf;
2045 const TypeTuple* domain = OptoRuntime::store_inline_type_fields_Type()->domain_cc();
2046 const TypeFunc* new_tf = TypeFunc::make(tf->domain_sig(), tf->domain_cc(), tf->range_sig(), domain);
2047 call->_tf = new_tf;
2048 _gvn.set_type(call, call->Value(&_gvn));
2049 _gvn.set_type(ret, ret->Value(&_gvn));
2050 // Don't add store to buffer call if we are strength reducing
2051 if (!C->strength_reduction()) {
2052 ideal.if_then(ret, BoolTest::eq, ideal.makecon(TypePtr::NULL_PTR)); {
2053 // Return value is null
2054 ideal.set(res, makecon(TypePtr::NULL_PTR));
2055 } ideal.else_(); {
2056 // Return value is non-null
2057 sync_kit(ideal);
2058
2059 Node* store_to_buf_call = make_runtime_call(RC_NO_LEAF | RC_NO_IO,
2060 OptoRuntime::store_inline_type_fields_Type(),
2061 StubRoutines::store_inline_type_fields_to_buf(),
2062 nullptr, TypePtr::BOTTOM, ret);
2063
2064 // We don't know how many values are returned. This assumes the
2065 // worst case, that all available registers are used.
2066 for (uint i = TypeFunc::Parms+1; i < domain->cnt(); i++) {
2067 if (domain->field_at(i) == Type::HALF) {
2068 store_to_buf_call->init_req(i, top());
2069 continue;
2070 }
2071 Node* proj =_gvn.transform(new ProjNode(call, i));
2072 store_to_buf_call->init_req(i, proj);
2073 }
2074 make_slow_call_ex(store_to_buf_call, env()->Throwable_klass(), false);
2075
2076 Node* buf = _gvn.transform(new ProjNode(store_to_buf_call, TypeFunc::Parms));
2077 const Type* buf_type = TypeOopPtr::make_from_klass(t->as_klass())->join_speculative(TypePtr::NOTNULL);
2078 buf = _gvn.transform(new CheckCastPPNode(control(), buf, buf_type));
2079
2080 ideal.set(res, buf);
2081 ideal.sync_kit(this);
2082 } ideal.end_if();
2083 } else {
2084 for (uint i = TypeFunc::Parms+1; i < domain->cnt(); i++) {
2085 Node* proj =_gvn.transform(new ProjNode(call, i));
2086 }
2087 ideal.set(res, ret);
2088 }
2089 sync_kit(ideal);
2090 ret = _gvn.transform(ideal.value(res));
2091 }
2092 if (t->is_klass()) {
2093 const Type* type = TypeOopPtr::make_from_klass(t->as_klass());
2094 if (type->is_inlinetypeptr()) {
2095 ret = InlineTypeNode::make_from_oop(this, ret, type->inline_klass());
2096 }
2097 }
2098 }
2099
2100 return ret;
2101 }
2102
2103 //--------------------set_predefined_input_for_runtime_call--------------------
2104 // Reading and setting the memory state is way conservative here.
2105 // The real problem is that I am not doing real Type analysis on memory,
2106 // so I cannot distinguish card mark stores from other stores. Across a GC
2107 // point the Store Barrier and the card mark memory has to agree. I cannot
2108 // have a card mark store and its barrier split across the GC point from
2109 // either above or below. Here I get that to happen by reading ALL of memory.
2110 // A better answer would be to separate out card marks from other memory.
2111 // For now, return the input memory state, so that it can be reused
2112 // after the call, if this call has restricted memory effects.
2113 Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) {
2114 // Set fixed predefined input arguments
2115 call->init_req(TypeFunc::Control, control());
2116 call->init_req(TypeFunc::I_O, top()); // does no i/o
2117 call->init_req(TypeFunc::ReturnAdr, top());
2118 if (call->is_CallLeafPure()) {
2119 call->init_req(TypeFunc::Memory, top());
2181 if (use->is_MergeMem()) {
2182 wl.push(use);
2183 }
2184 }
2185 }
2186
2187 // Replace the call with the current state of the kit.
2188 void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes, bool do_asserts) {
2189 JVMState* ejvms = nullptr;
2190 if (has_exceptions()) {
2191 ejvms = transfer_exceptions_into_jvms();
2192 }
2193
2194 ReplacedNodes replaced_nodes = map()->replaced_nodes();
2195 ReplacedNodes replaced_nodes_exception;
2196 Node* ex_ctl = top();
2197
2198 SafePointNode* final_state = stop();
2199
2200 // Find all the needed outputs of this call
2201 CallProjections* callprojs = call->extract_projections(true, do_asserts);
2202
2203 Unique_Node_List wl;
2204 Node* init_mem = call->in(TypeFunc::Memory);
2205 Node* final_mem = final_state->in(TypeFunc::Memory);
2206 Node* final_ctl = final_state->in(TypeFunc::Control);
2207 Node* final_io = final_state->in(TypeFunc::I_O);
2208
2209 // Replace all the old call edges with the edges from the inlining result
2210 if (callprojs->fallthrough_catchproj != nullptr) {
2211 C->gvn_replace_by(callprojs->fallthrough_catchproj, final_ctl);
2212 }
2213 if (callprojs->fallthrough_memproj != nullptr) {
2214 if (final_mem->is_MergeMem()) {
2215 // Parser's exits MergeMem was not transformed but may be optimized
2216 final_mem = _gvn.transform(final_mem);
2217 }
2218 C->gvn_replace_by(callprojs->fallthrough_memproj, final_mem);
2219 add_mergemem_users_to_worklist(wl, final_mem);
2220 }
2221 if (callprojs->fallthrough_ioproj != nullptr) {
2222 C->gvn_replace_by(callprojs->fallthrough_ioproj, final_io);
2223 }
2224
2225 // Replace the result with the new result if it exists and is used
2226 if (callprojs->resproj[0] != nullptr && result != nullptr) {
2227 // If the inlined code is dead, the result projections for an inline type returned as
2228 // fields have not been replaced. They will go away once the call is replaced by TOP below.
2229 assert(callprojs->nb_resproj == 1 || (call->tf()->returns_inline_type_as_fields() && stopped()) ||
2230 (C->strength_reduction() && InlineTypeReturnedAsFields && !call->as_CallJava()->method()->return_type()->is_loaded()),
2231 "unexpected number of results");
2232 // If we are doing strength reduction and the return type is not loaded we
2233 // need to rewire all projections since store_inline_type_fields_to_buf is already present
2234 if (C->strength_reduction() && InlineTypeReturnedAsFields && !call->as_CallJava()->method()->return_type()->is_loaded()) {
2235 const TypeTuple* domain = OptoRuntime::store_inline_type_fields_Type()->domain_cc();
2236 for (uint i = TypeFunc::Parms; i < domain->cnt(); i++) {
2237 C->gvn_replace_by(callprojs->resproj[0], final_state->in(i));
2238 }
2239 } else {
2240 C->gvn_replace_by(callprojs->resproj[0], result);
2241 }
2242 }
2243
2244 if (ejvms == nullptr) {
2245 // No exception edges to simply kill off those paths
2246 if (callprojs->catchall_catchproj != nullptr) {
2247 C->gvn_replace_by(callprojs->catchall_catchproj, C->top());
2248 }
2249 if (callprojs->catchall_memproj != nullptr) {
2250 C->gvn_replace_by(callprojs->catchall_memproj, C->top());
2251 }
2252 if (callprojs->catchall_ioproj != nullptr) {
2253 C->gvn_replace_by(callprojs->catchall_ioproj, C->top());
2254 }
2255 // Replace the old exception object with top
2256 if (callprojs->exobj != nullptr) {
2257 C->gvn_replace_by(callprojs->exobj, C->top());
2258 }
2259 } else {
2260 GraphKit ekit(ejvms);
2261
2262 // Load my combined exception state into the kit, with all phis transformed:
2263 SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();
2264 replaced_nodes_exception = ex_map->replaced_nodes();
2265
2266 Node* ex_oop = ekit.use_exception_state(ex_map);
2267
2268 if (callprojs->catchall_catchproj != nullptr) {
2269 C->gvn_replace_by(callprojs->catchall_catchproj, ekit.control());
2270 ex_ctl = ekit.control();
2271 }
2272 if (callprojs->catchall_memproj != nullptr) {
2273 Node* ex_mem = ekit.reset_memory();
2274 C->gvn_replace_by(callprojs->catchall_memproj, ex_mem);
2275 add_mergemem_users_to_worklist(wl, ex_mem);
2276 }
2277 if (callprojs->catchall_ioproj != nullptr) {
2278 C->gvn_replace_by(callprojs->catchall_ioproj, ekit.i_o());
2279 }
2280
2281 // Replace the old exception object with the newly created one
2282 if (callprojs->exobj != nullptr) {
2283 C->gvn_replace_by(callprojs->exobj, ex_oop);
2284 }
2285 }
2286
2287 // Disconnect the call from the graph
2288 call->disconnect_inputs(C);
2289 C->gvn_replace_by(call, C->top());
2290
2291 // Clean up any MergeMems that feed other MergeMems since the
2292 // optimizer doesn't like that.
2293 while (wl.size() > 0) {
2294 _gvn.transform(wl.pop());
2295 }
2296
2297 if (callprojs->fallthrough_catchproj != nullptr && !final_ctl->is_top() && do_replaced_nodes) {
2298 replaced_nodes.apply(C, final_ctl);
2299 }
2300 if (!ex_ctl->is_top() && do_replaced_nodes) {
2301 replaced_nodes_exception.apply(C, ex_ctl);
2302 }
2303 }
2304
2305
2306 //------------------------------increment_counter------------------------------
2307 // for statistics: increment a VM counter by 1
2308
2309 void GraphKit::increment_counter(address counter_addr) {
2310 Node* adr1 = makecon(TypeRawPtr::make(counter_addr));
2311 increment_counter(adr1);
2312 }
2313
2314 void GraphKit::increment_counter(Node* counter_addr) {
2315 Node* ctrl = control();
2316 Node* cnt = make_load(ctrl, counter_addr, TypeLong::LONG, T_LONG, MemNode::unordered);
2317 Node* incr = _gvn.transform(new AddLNode(cnt, _gvn.longcon(1)));
2477 *
2478 * @param n node that the type applies to
2479 * @param exact_kls type from profiling
2480 * @param maybe_null did profiling see null?
2481 *
2482 * @return node with improved type
2483 */
2484 Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, ProfilePtrKind ptr_kind) {
2485 const Type* current_type = _gvn.type(n);
2486 assert(UseTypeSpeculation, "type speculation must be on");
2487
2488 const TypePtr* speculative = current_type->speculative();
2489
2490 // Should the klass from the profile be recorded in the speculative type?
2491 if (current_type->would_improve_type(exact_kls, jvms()->depth())) {
2492 const TypeKlassPtr* tklass = TypeKlassPtr::make(exact_kls, Type::trust_interfaces);
2493 const TypeOopPtr* xtype = tklass->as_instance_type();
2494 assert(xtype->klass_is_exact(), "Should be exact");
2495 // Any reason to believe n is not null (from this profiling or a previous one)?
2496 assert(ptr_kind != ProfileAlwaysNull, "impossible here");
2497 const TypePtr* ptr = (ptr_kind != ProfileNeverNull && current_type->speculative_maybe_null()) ? TypePtr::BOTTOM : TypePtr::NOTNULL;
2498 // record the new speculative type's depth
2499 speculative = xtype->cast_to_ptr_type(ptr->ptr())->is_ptr();
2500 speculative = speculative->with_inline_depth(jvms()->depth());
2501 } else if (current_type->would_improve_ptr(ptr_kind)) {
2502 // Profiling report that null was never seen so we can change the
2503 // speculative type to non null ptr.
2504 if (ptr_kind == ProfileAlwaysNull) {
2505 speculative = TypePtr::NULL_PTR;
2506 } else {
2507 assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement");
2508 const TypePtr* ptr = TypePtr::NOTNULL;
2509 if (speculative != nullptr) {
2510 speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr();
2511 } else {
2512 speculative = ptr;
2513 }
2514 }
2515 }
2516
2517 if (speculative != current_type->speculative()) {
2518 // Build a type with a speculative type (what we think we know
2519 // about the type but will need a guard when we use it)
2520 const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::Offset::bottom, TypeOopPtr::InstanceBot, speculative);
2521 // We're changing the type, we need a new CheckCast node to carry
2522 // the new type. The new type depends on the control: what
2523 // profiling tells us is only valid from here as far as we can
2524 // tell.
2525 Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));
2526 cast = _gvn.transform(cast);
2527 replace_in_map(n, cast);
2528 n = cast;
2529 }
2530
2531 return n;
2532 }
2533
2534 /**
2535 * Record profiling data from receiver profiling at an invoke with the
2536 * type system so that it can propagate it (speculation)
2537 *
2538 * @param n receiver node
2539 *
2540 * @return node with improved type
2541 */
2542 Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {
2543 if (!UseTypeSpeculation) {
2544 return n;
2545 }
2546 ciKlass* exact_kls = profile_has_unique_klass();
2547 ProfilePtrKind ptr_kind = ProfileMaybeNull;
2548 if ((java_bc() == Bytecodes::_checkcast ||
2549 java_bc() == Bytecodes::_instanceof ||
2550 java_bc() == Bytecodes::_aastore) &&
2551 method()->method_data()->is_mature()) {
2552 ciProfileData* data = method()->method_data()->bci_to_data(bci());
2553 if (data != nullptr) {
2554 if (java_bc() == Bytecodes::_aastore) {
2555 ciKlass* array_type = nullptr;
2556 ciKlass* element_type = nullptr;
2557 ProfilePtrKind element_ptr = ProfileMaybeNull;
2558 bool flat_array = true;
2559 bool null_free_array = true;
2560 method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array);
2561 exact_kls = element_type;
2562 ptr_kind = element_ptr;
2563 } else {
2564 if (!data->as_BitData()->null_seen()) {
2565 ptr_kind = ProfileNeverNull;
2566 } else {
2567 if (TypeProfileCasts) {
2568 assert(data->is_ReceiverTypeData(), "bad profile data type");
2569 ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
2570 uint i = 0;
2571 for (; i < call->row_limit(); i++) {
2572 ciKlass* receiver = call->receiver(i);
2573 if (receiver != nullptr) {
2574 break;
2575 }
2576 }
2577 ptr_kind = (i == call->row_limit()) ? ProfileAlwaysNull : ProfileMaybeNull;
2578 }
2579 }
2580 }
2581 }
2582 }
2583 return record_profile_for_speculation(n, exact_kls, ptr_kind);
2584 }
2585
2586 /**
2587 * Record profiling data from argument profiling at an invoke with the
2588 * type system so that it can propagate it (speculation)
2589 *
2590 * @param dest_method target method for the call
2591 * @param bc what invoke bytecode is this?
2592 */
2593 void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {
2594 if (!UseTypeSpeculation) {
2595 return;
2596 }
2597 const TypeFunc* tf = TypeFunc::make(dest_method);
2598 int nargs = tf->domain_sig()->cnt() - TypeFunc::Parms;
2599 int skip = Bytecodes::has_receiver(bc) ? 1 : 0;
2600 for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {
2601 const Type *targ = tf->domain_sig()->field_at(j + TypeFunc::Parms);
2602 if (is_reference_type(targ->basic_type())) {
2603 ProfilePtrKind ptr_kind = ProfileMaybeNull;
2604 ciKlass* better_type = nullptr;
2605 if (method()->argument_profiled_type(bci(), i, better_type, ptr_kind)) {
2606 record_profile_for_speculation(argument(j), better_type, ptr_kind);
2607 }
2608 i++;
2609 }
2610 }
2611 }
2612
2613 /**
2614 * Record profiling data from parameter profiling at an invoke with
2615 * the type system so that it can propagate it (speculation)
2616 */
2617 void GraphKit::record_profiled_parameters_for_speculation() {
2618 if (!UseTypeSpeculation) {
2619 return;
2620 }
2621 for (int i = 0, j = 0; i < method()->arg_size() ; i++) {
2741 // The first null ends the list.
2742 Node* parm0, Node* parm1,
2743 Node* parm2, Node* parm3,
2744 Node* parm4, Node* parm5,
2745 Node* parm6, Node* parm7) {
2746 assert(call_addr != nullptr, "must not call null targets");
2747
2748 // Slow-path call
2749 bool is_leaf = !(flags & RC_NO_LEAF);
2750 bool has_io = (!is_leaf && !(flags & RC_NO_IO));
2751 if (call_name == nullptr) {
2752 assert(!is_leaf, "must supply name for leaf");
2753 call_name = OptoRuntime::stub_name(call_addr);
2754 }
2755 CallNode* call;
2756 if (!is_leaf) {
2757 call = new CallStaticJavaNode(call_type, call_addr, call_name, adr_type);
2758 } else if (flags & RC_NO_FP) {
2759 call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
2760 } else if (flags & RC_VECTOR){
2761 uint num_bits = call_type->range_sig()->field_at(TypeFunc::Parms)->is_vect()->length_in_bytes() * BitsPerByte;
2762 call = new CallLeafVectorNode(call_type, call_addr, call_name, adr_type, num_bits);
2763 } else if (flags & RC_PURE) {
2764 assert(adr_type == nullptr, "pure call does not touch memory");
2765 call = new CallLeafPureNode(call_type, call_addr, call_name);
2766 } else {
2767 call = new CallLeafNode(call_type, call_addr, call_name, adr_type);
2768 }
2769
2770 // The following is similar to set_edges_for_java_call,
2771 // except that the memory effects of the call are restricted to AliasIdxRaw.
2772
2773 // Slow path call has no side-effects, uses few values
2774 bool wide_in = !(flags & RC_NARROW_MEM);
2775 bool wide_out = (C->get_alias_index(adr_type) == Compile::AliasIdxBot);
2776
2777 Node* prev_mem = nullptr;
2778 if (wide_in) {
2779 prev_mem = set_predefined_input_for_runtime_call(call);
2780 } else {
2781 assert(!wide_out, "narrow in => narrow out");
2782 Node* narrow_mem = memory(adr_type);
2783 prev_mem = set_predefined_input_for_runtime_call(call, narrow_mem);
2784 }
2785
2786 // Hook each parm in order. Stop looking at the first null.
2787 if (parm0 != nullptr) { call->init_req(TypeFunc::Parms+0, parm0);
2788 if (parm1 != nullptr) { call->init_req(TypeFunc::Parms+1, parm1);
2789 if (parm2 != nullptr) { call->init_req(TypeFunc::Parms+2, parm2);
2790 if (parm3 != nullptr) { call->init_req(TypeFunc::Parms+3, parm3);
2791 if (parm4 != nullptr) { call->init_req(TypeFunc::Parms+4, parm4);
2792 if (parm5 != nullptr) { call->init_req(TypeFunc::Parms+5, parm5);
2793 if (parm6 != nullptr) { call->init_req(TypeFunc::Parms+6, parm6);
2794 if (parm7 != nullptr) { call->init_req(TypeFunc::Parms+7, parm7);
2795 /* close each nested if ===> */ } } } } } } } }
2796 assert(call->in(call->req()-1) != nullptr || (call->req()-1) > (TypeFunc::Parms+7), "must initialize all parms");
2797
2798 if (!is_leaf) {
2799 // Non-leaves can block and take safepoints:
2800 add_safepoint_edges(call, ((flags & RC_MUST_THROW) != 0));
2801 }
2802 // Non-leaves can throw exceptions:
2803 if (has_io) {
2804 call->set_req(TypeFunc::I_O, i_o());
2805 }
2806
2807 if (flags & RC_UNCOMMON) {
2808 // Set the count to a tiny probability. Cf. Estimate_Block_Frequency.
2809 // (An "if" probability corresponds roughly to an unconditional count.
2810 // Sort of.)
2811 call->set_cnt(PROB_UNLIKELY_MAG(4));
2812 }
2813
2814 Node* c = _gvn.transform(call);
2815 assert(c == call, "cannot disappear");
2816
2824
2825 if (has_io) {
2826 set_i_o(_gvn.transform(new ProjNode(call, TypeFunc::I_O)));
2827 }
2828 return call;
2829
2830 }
2831
2832 // i2b
2833 Node* GraphKit::sign_extend_byte(Node* in) {
2834 Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(24)));
2835 return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(24)));
2836 }
2837
2838 // i2s
2839 Node* GraphKit::sign_extend_short(Node* in) {
2840 Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(16)));
2841 return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(16)));
2842 }
2843
2844
2845 //------------------------------merge_memory-----------------------------------
2846 // Merge memory from one path into the current memory state.
2847 void GraphKit::merge_memory(Node* new_mem, Node* region, int new_path) {
2848 for (MergeMemStream mms(merged_memory(), new_mem->as_MergeMem()); mms.next_non_empty2(); ) {
2849 Node* old_slice = mms.force_memory();
2850 Node* new_slice = mms.memory2();
2851 if (old_slice != new_slice) {
2852 PhiNode* phi;
2853 if (old_slice->is_Phi() && old_slice->as_Phi()->region() == region) {
2854 if (mms.is_empty()) {
2855 // clone base memory Phi's inputs for this memory slice
2856 assert(old_slice == mms.base_memory(), "sanity");
2857 phi = PhiNode::make(region, nullptr, Type::MEMORY, mms.adr_type(C));
2858 _gvn.set_type(phi, Type::MEMORY);
2859 for (uint i = 1; i < phi->req(); i++) {
2860 phi->init_req(i, old_slice->in(i));
2861 }
2862 } else {
2863 phi = old_slice->as_Phi(); // Phi was generated already
2864 }
2921 gvn.transform(iff);
2922 if (!bol->is_Con()) gvn.record_for_igvn(iff);
2923 return iff;
2924 }
2925
2926 //-------------------------------gen_subtype_check-----------------------------
2927 // Generate a subtyping check. Takes as input the subtype and supertype.
2928 // Returns 2 values: sets the default control() to the true path and returns
2929 // the false path. Only reads invariant memory; sets no (visible) memory.
2930 // The PartialSubtypeCheckNode sets the hidden 1-word cache in the encoding
2931 // but that's not exposed to the optimizer. This call also doesn't take in an
2932 // Object; if you wish to check an Object you need to load the Object's class
2933 // prior to coming here.
2934 Node* Phase::gen_subtype_check(Node* subklass, Node* superklass, Node** ctrl, Node* mem, PhaseGVN& gvn,
2935 ciMethod* method, int bci) {
2936 Compile* C = gvn.C;
2937 if ((*ctrl)->is_top()) {
2938 return C->top();
2939 }
2940
2941 const TypeKlassPtr* klass_ptr_type = gvn.type(superklass)->is_klassptr();
2942 // For a direct pointer comparison, we need the refined array klass pointer
2943 Node* vm_superklass = superklass;
2944 if (klass_ptr_type->isa_aryklassptr() && klass_ptr_type->klass_is_exact()) {
2945 assert(!klass_ptr_type->is_aryklassptr()->is_refined_type(), "Unexpected refined array klass pointer");
2946 vm_superklass = gvn.makecon(klass_ptr_type->is_aryklassptr()->cast_to_refined_array_klass_ptr());
2947 }
2948
2949 // Fast check for identical types, perhaps identical constants.
2950 // The types can even be identical non-constants, in cases
2951 // involving Array.newInstance, Object.clone, etc.
2952 if (subklass == superklass)
2953 return C->top(); // false path is dead; no test needed.
2954
2955 if (gvn.type(superklass)->singleton()) {
2956 const TypeKlassPtr* superk = gvn.type(superklass)->is_klassptr();
2957 const TypeKlassPtr* subk = gvn.type(subklass)->is_klassptr();
2958
2959 // In the common case of an exact superklass, try to fold up the
2960 // test before generating code. You may ask, why not just generate
2961 // the code and then let it fold up? The answer is that the generated
2962 // code will necessarily include null checks, which do not always
2963 // completely fold away. If they are also needless, then they turn
2964 // into a performance loss. Example:
2965 // Foo[] fa = blah(); Foo x = fa[0]; fa[1] = x;
2966 // Here, the type of 'fa' is often exact, so the store check
2967 // of fa[1]=x will fold up, without testing the nullness of x.
2968 //
2969 // At macro expansion, we would have already folded the SubTypeCheckNode
2970 // being expanded here because we always perform the static sub type
2971 // check in SubTypeCheckNode::sub() regardless of whether
2972 // StressReflectiveCode is set or not. We can therefore skip this
2973 // static check when StressReflectiveCode is on.
2974 switch (C->static_subtype_check(superk, subk)) {
2975 case Compile::SSC_always_false:
2976 {
2977 Node* always_fail = *ctrl;
2978 *ctrl = gvn.C->top();
2979 return always_fail;
2980 }
2981 case Compile::SSC_always_true:
2982 return C->top();
2983 case Compile::SSC_easy_test:
2984 {
2985 // Just do a direct pointer compare and be done.
2986 IfNode* iff = gen_subtype_check_compare(*ctrl, subklass, vm_superklass, BoolTest::eq, PROB_STATIC_FREQUENT, gvn, T_ADDRESS);
2987 *ctrl = gvn.transform(new IfTrueNode(iff));
2988 return gvn.transform(new IfFalseNode(iff));
2989 }
2990 case Compile::SSC_full_test:
2991 break;
2992 default:
2993 ShouldNotReachHere();
2994 }
2995 }
2996
2997 // %%% Possible further optimization: Even if the superklass is not exact,
2998 // if the subklass is the unique subtype of the superklass, the check
2999 // will always succeed. We could leave a dependency behind to ensure this.
3000
3001 // First load the super-klass's check-offset
3002 Node *p1 = gvn.transform(new AddPNode(superklass, superklass, gvn.MakeConX(in_bytes(Klass::super_check_offset_offset()))));
3003 Node* m = C->immutable_memory();
3004 Node *chk_off = gvn.transform(new LoadINode(nullptr, m, p1, gvn.type(p1)->is_ptr(), TypeInt::INT, MemNode::unordered));
3005 int cacheoff_con = in_bytes(Klass::secondary_super_cache_offset());
3006 const TypeInt* chk_off_t = chk_off->Value(&gvn)->isa_int();
3044 gvn.record_for_igvn(r_ok_subtype);
3045
3046 // If we might perform an expensive check, first try to take advantage of profile data that was attached to the
3047 // SubTypeCheck node
3048 if (might_be_cache && method != nullptr && VM_Version::profile_all_receivers_at_type_check()) {
3049 ciCallProfile profile = method->call_profile_at_bci(bci);
3050 float total_prob = 0;
3051 for (int i = 0; profile.has_receiver(i); ++i) {
3052 float prob = profile.receiver_prob(i);
3053 total_prob += prob;
3054 }
3055 if (total_prob * 100. >= TypeProfileSubTypeCheckCommonThreshold) {
3056 const TypeKlassPtr* superk = gvn.type(superklass)->is_klassptr();
3057 for (int i = 0; profile.has_receiver(i); ++i) {
3058 ciKlass* klass = profile.receiver(i);
3059 const TypeKlassPtr* klass_t = TypeKlassPtr::make(klass);
3060 Compile::SubTypeCheckResult result = C->static_subtype_check(superk, klass_t);
3061 if (result != Compile::SSC_always_true && result != Compile::SSC_always_false) {
3062 continue;
3063 }
3064 if (klass_t->isa_aryklassptr()) {
3065 // For a direct pointer comparison, we need the refined array klass pointer
3066 klass_t = klass_t->is_aryklassptr()->cast_to_refined_array_klass_ptr();
3067 }
3068 float prob = profile.receiver_prob(i);
3069 ConNode* klass_node = gvn.makecon(klass_t);
3070 IfNode* iff = gen_subtype_check_compare(*ctrl, subklass, klass_node, BoolTest::eq, prob, gvn, T_ADDRESS);
3071 Node* iftrue = gvn.transform(new IfTrueNode(iff));
3072
3073 if (result == Compile::SSC_always_true) {
3074 r_ok_subtype->add_req(iftrue);
3075 } else {
3076 assert(result == Compile::SSC_always_false, "");
3077 r_not_subtype->add_req(iftrue);
3078 }
3079 *ctrl = gvn.transform(new IfFalseNode(iff));
3080 }
3081 }
3082 }
3083
3084 // See if we get an immediate positive hit. Happens roughly 83% of the
3085 // time. Test to see if the value loaded just previously from the subklass
3086 // is exactly the superklass.
3087 IfNode *iff1 = gen_subtype_check_compare(*ctrl, superklass, nkls, BoolTest::eq, PROB_LIKELY(0.83f), gvn, T_ADDRESS);
3101 igvn->remove_globally_dead_node(r_not_subtype);
3102 }
3103 return not_subtype_ctrl;
3104 }
3105
3106 r_ok_subtype->init_req(1, iftrue1);
3107
3108 // Check for immediate negative hit. Happens roughly 11% of the time (which
3109 // is roughly 63% of the remaining cases). Test to see if the loaded
3110 // check-offset points into the subklass display list or the 1-element
3111 // cache. If it points to the display (and NOT the cache) and the display
3112 // missed then it's not a subtype.
3113 Node *cacheoff = gvn.intcon(cacheoff_con);
3114 IfNode *iff2 = gen_subtype_check_compare(*ctrl, chk_off, cacheoff, BoolTest::ne, PROB_LIKELY(0.63f), gvn, T_INT);
3115 r_not_subtype->init_req(1, gvn.transform(new IfTrueNode (iff2)));
3116 *ctrl = gvn.transform(new IfFalseNode(iff2));
3117
3118 // Check for self. Very rare to get here, but it is taken 1/3 the time.
3119 // No performance impact (too rare) but allows sharing of secondary arrays
3120 // which has some footprint reduction.
3121 IfNode *iff3 = gen_subtype_check_compare(*ctrl, subklass, vm_superklass, BoolTest::eq, PROB_LIKELY(0.36f), gvn, T_ADDRESS);
3122 r_ok_subtype->init_req(2, gvn.transform(new IfTrueNode(iff3)));
3123 *ctrl = gvn.transform(new IfFalseNode(iff3));
3124
3125 // -- Roads not taken here: --
3126 // We could also have chosen to perform the self-check at the beginning
3127 // of this code sequence, as the assembler does. This would not pay off
3128 // the same way, since the optimizer, unlike the assembler, can perform
3129 // static type analysis to fold away many successful self-checks.
3130 // Non-foldable self checks work better here in second position, because
3131 // the initial primary superclass check subsumes a self-check for most
3132 // types. An exception would be a secondary type like array-of-interface,
3133 // which does not appear in its own primary supertype display.
3134 // Finally, we could have chosen to move the self-check into the
3135 // PartialSubtypeCheckNode, and from there out-of-line in a platform
3136 // dependent manner. But it is worthwhile to have the check here,
3137 // where it can be perhaps be optimized. The cost in code space is
3138 // small (register compare, branch).
3139
3140 // Now do a linear scan of the secondary super-klass array. Again, no real
3141 // performance impact (too rare) but it's gotta be done.
3142 // Since the code is rarely used, there is no penalty for moving it
3143 // out of line, and it can only improve I-cache density.
3144 // The decision to inline or out-of-line this final check is platform
3145 // dependent, and is found in the AD file definition of PartialSubtypeCheck.
3146 Node* psc = gvn.transform(
3147 new PartialSubtypeCheckNode(*ctrl, subklass, superklass));
3148
3149 IfNode *iff4 = gen_subtype_check_compare(*ctrl, psc, gvn.zerocon(T_OBJECT), BoolTest::ne, PROB_FAIR, gvn, T_ADDRESS);
3150 r_not_subtype->init_req(2, gvn.transform(new IfTrueNode (iff4)));
3151 r_ok_subtype ->init_req(3, gvn.transform(new IfFalseNode(iff4)));
3152
3153 // Return false path; set default control to true path.
3154 *ctrl = gvn.transform(r_ok_subtype);
3155 return gvn.transform(r_not_subtype);
3156 }
3157
3158 Node* GraphKit::gen_subtype_check(Node* obj_or_subklass, Node* superklass) {
3159 const Type* sub_t = _gvn.type(obj_or_subklass);
3160 if (sub_t->make_oopptr() != nullptr && sub_t->make_oopptr()->is_inlinetypeptr()) {
3161 sub_t = TypeKlassPtr::make(sub_t->inline_klass());
3162 obj_or_subklass = makecon(sub_t);
3163 }
3164 bool expand_subtype_check = C->post_loop_opts_phase(); // macro node expansion is over
3165 if (expand_subtype_check) {
3166 MergeMemNode* mem = merged_memory();
3167 Node* ctrl = control();
3168 Node* subklass = obj_or_subklass;
3169 if (!sub_t->isa_klassptr()) {
3170 subklass = load_object_klass(obj_or_subklass);
3171 }
3172
3173 Node* n = Phase::gen_subtype_check(subklass, superklass, &ctrl, mem, _gvn, method(), bci());
3174 set_control(ctrl);
3175 return n;
3176 }
3177
3178 Node* check = _gvn.transform(new SubTypeCheckNode(C, obj_or_subklass, superklass, method(), bci()));
3179 Node* bol = _gvn.transform(new BoolNode(check, BoolTest::eq));
3180 IfNode* iff = create_and_xform_if(control(), bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
3181 set_control(_gvn.transform(new IfTrueNode(iff)));
3182 return _gvn.transform(new IfFalseNode(iff));
3183 }
3184
3185 // Profile-driven exact type check:
3186 Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,
3187 float prob, Node* *casted_receiver) {
3188 assert(!klass->is_interface(), "no exact type check on interfaces");
3189 Node* fail = top();
3190 const Type* rec_t = _gvn.type(receiver);
3191 if (rec_t->is_inlinetypeptr()) {
3192 if (klass->equals(rec_t->inline_klass())) {
3193 (*casted_receiver) = receiver; // Always passes
3194 } else {
3195 (*casted_receiver) = top(); // Always fails
3196 fail = control();
3197 set_control(top());
3198 }
3199 return fail;
3200 }
3201 const TypeKlassPtr* tklass = TypeKlassPtr::make(klass, Type::trust_interfaces);
3202 if (tklass->isa_aryklassptr()) {
3203 // For a direct pointer comparison, we need the refined array klass pointer
3204 tklass = tklass->is_aryklassptr()->cast_to_refined_array_klass_ptr();
3205 }
3206 Node* recv_klass = load_object_klass(receiver);
3207 fail = type_check(recv_klass, tklass, prob);
3208
3209 if (!stopped()) {
3210 const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
3211 const TypeOopPtr* recv_xtype = tklass->as_instance_type();
3212 assert(recv_xtype->klass_is_exact(), "");
3213
3214 if (!receiver_type->higher_equal(recv_xtype)) { // ignore redundant casts
3215 // Subsume downstream occurrences of receiver with a cast to
3216 // recv_xtype, since now we know what the type will be.
3217 Node* cast = new CheckCastPPNode(control(), receiver, recv_xtype);
3218 Node* res = _gvn.transform(cast);
3219 if (recv_xtype->is_inlinetypeptr()) {
3220 assert(!gvn().type(res)->maybe_null(), "receiver should never be null");
3221 res = InlineTypeNode::make_from_oop(this, res, recv_xtype->inline_klass());
3222 }
3223 (*casted_receiver) = res;
3224 assert(!(*casted_receiver)->is_top(), "that path should be unreachable");
3225 // (User must make the replace_in_map call.)
3226 }
3227 }
3228
3229 return fail;
3230 }
3231
3232 Node* GraphKit::type_check(Node* recv_klass, const TypeKlassPtr* tklass,
3233 float prob) {
3234 Node* want_klass = makecon(tklass);
3235 Node* cmp = _gvn.transform(new CmpPNode(recv_klass, want_klass));
3236 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
3237 IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);
3238 set_control(_gvn.transform(new IfTrueNode (iff)));
3239 Node* fail = _gvn.transform(new IfFalseNode(iff));
3240 return fail;
3241 }
3242
3243 //------------------------------subtype_check_receiver-------------------------
3244 Node* GraphKit::subtype_check_receiver(Node* receiver, ciKlass* klass,
3245 Node** casted_receiver) {
3246 const TypeKlassPtr* tklass = TypeKlassPtr::make(klass, Type::trust_interfaces)->try_improve();
3247 Node* want_klass = makecon(tklass);
3248
3249 Node* slow_ctl = gen_subtype_check(receiver, want_klass);
3250
3251 // Ignore interface type information until interface types are properly tracked.
3252 if (!stopped() && !klass->is_interface()) {
3253 const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
3254 const TypeOopPtr* recv_type = tklass->cast_to_exactness(false)->is_klassptr()->as_instance_type();
3255 if (receiver_type != nullptr && !receiver_type->higher_equal(recv_type)) { // ignore redundant casts
3256 Node* cast = _gvn.transform(new CheckCastPPNode(control(), receiver, recv_type));
3257 if (recv_type->is_inlinetypeptr()) {
3258 cast = InlineTypeNode::make_from_oop(this, cast, recv_type->inline_klass());
3259 }
3260 (*casted_receiver) = cast;
3261 }
3262 }
3263
3264 return slow_ctl;
3265 }
3266
3267 //------------------------------seems_never_null-------------------------------
3268 // Use null_seen information if it is available from the profile.
3269 // If we see an unexpected null at a type check we record it and force a
3270 // recompile; the offending check will be recompiled to handle nulls.
3271 // If we see several offending BCIs, then all checks in the
3272 // method will be recompiled.
3273 bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) {
3274 speculating = !_gvn.type(obj)->speculative_maybe_null();
3275 Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating);
3276 if (UncommonNullCast // Cutout for this technique
3277 && obj != null() // And not the -Xcomp stupid case?
3278 && !too_many_traps(reason)
3279 ) {
3280 if (speculating) {
3349
3350 //------------------------maybe_cast_profiled_receiver-------------------------
3351 // If the profile has seen exactly one type, narrow to exactly that type.
3352 // Subsequent type checks will always fold up.
3353 Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,
3354 const TypeKlassPtr* require_klass,
3355 ciKlass* spec_klass,
3356 bool safe_for_replace) {
3357 if (!UseTypeProfile || !TypeProfileCasts) return nullptr;
3358
3359 Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != nullptr);
3360
3361 // Make sure we haven't already deoptimized from this tactic.
3362 if (too_many_traps_or_recompiles(reason))
3363 return nullptr;
3364
3365 // (No, this isn't a call, but it's enough like a virtual call
3366 // to use the same ciMethod accessor to get the profile info...)
3367 // If we have a speculative type use it instead of profiling (which
3368 // may not help us)
3369 ciKlass* exact_kls = spec_klass;
3370 if (exact_kls == nullptr) {
3371 if (java_bc() == Bytecodes::_aastore) {
3372 ciKlass* array_type = nullptr;
3373 ciKlass* element_type = nullptr;
3374 ProfilePtrKind element_ptr = ProfileMaybeNull;
3375 bool flat_array = true;
3376 bool null_free_array = true;
3377 method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array);
3378 exact_kls = element_type;
3379 } else {
3380 exact_kls = profile_has_unique_klass();
3381 }
3382 }
3383 if (exact_kls != nullptr) {// no cast failures here
3384 if (require_klass == nullptr ||
3385 C->static_subtype_check(require_klass, TypeKlassPtr::make(exact_kls, Type::trust_interfaces)) == Compile::SSC_always_true) {
3386 // If we narrow the type to match what the type profile sees or
3387 // the speculative type, we can then remove the rest of the
3388 // cast.
3389 // This is a win, even if the exact_kls is very specific,
3390 // because downstream operations, such as method calls,
3391 // will often benefit from the sharper type.
3392 Node* exact_obj = not_null_obj; // will get updated in place...
3393 Node* slow_ctl = type_check_receiver(exact_obj, exact_kls, 1.0,
3394 &exact_obj);
3395 { PreserveJVMState pjvms(this);
3396 set_control(slow_ctl);
3397 uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
3398 }
3399 if (safe_for_replace) {
3400 replace_in_map(not_null_obj, exact_obj);
3401 }
3402 return exact_obj;
3492 // If not_null_obj is dead, only null-path is taken
3493 if (stopped()) { // Doing instance-of on a null?
3494 set_control(null_ctl);
3495 return intcon(0);
3496 }
3497 region->init_req(_null_path, null_ctl);
3498 phi ->init_req(_null_path, intcon(0)); // Set null path value
3499 if (null_ctl == top()) {
3500 // Do this eagerly, so that pattern matches like is_diamond_phi
3501 // will work even during parsing.
3502 assert(_null_path == PATH_LIMIT-1, "delete last");
3503 region->del_req(_null_path);
3504 phi ->del_req(_null_path);
3505 }
3506
3507 // Do we know the type check always succeed?
3508 bool known_statically = false;
3509 if (_gvn.type(superklass)->singleton()) {
3510 const TypeKlassPtr* superk = _gvn.type(superklass)->is_klassptr();
3511 const TypeKlassPtr* subk = _gvn.type(obj)->is_oopptr()->as_klass_type();
3512 if (subk != nullptr && subk->is_loaded()) {
3513 int static_res = C->static_subtype_check(superk, subk);
3514 known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false);
3515 }
3516 }
3517
3518 if (!known_statically) {
3519 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3520 // We may not have profiling here or it may not help us. If we
3521 // have a speculative type use it to perform an exact cast.
3522 ciKlass* spec_obj_type = obj_type->speculative_type();
3523 if (spec_obj_type != nullptr || (ProfileDynamicTypes && data != nullptr)) {
3524 Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, nullptr, spec_obj_type, safe_for_replace);
3525 if (stopped()) { // Profile disagrees with this path.
3526 set_control(null_ctl); // Null is the only remaining possibility.
3527 return intcon(0);
3528 }
3529 if (cast_obj != nullptr) {
3530 not_null_obj = cast_obj;
3531 }
3532 }
3548 record_for_igvn(region);
3549
3550 // If we know the type check always succeeds then we don't use the
3551 // profiling data at this bytecode. Don't lose it, feed it to the
3552 // type system as a speculative type.
3553 if (safe_for_replace) {
3554 Node* casted_obj = record_profiled_receiver_for_speculation(obj);
3555 replace_in_map(obj, casted_obj);
3556 }
3557
3558 return _gvn.transform(phi);
3559 }
3560
3561 //-------------------------------gen_checkcast---------------------------------
3562 // Generate a checkcast idiom. Used by both the checkcast bytecode and the
3563 // array store bytecode. Stack must be as-if BEFORE doing the bytecode so the
3564 // uncommon-trap paths work. Adjust stack after this call.
3565 // If failure_control is supplied and not null, it is filled in with
3566 // the control edge for the cast failure. Otherwise, an appropriate
3567 // uncommon trap or exception is thrown.
3568 Node* GraphKit::gen_checkcast(Node* obj, Node* superklass, Node* *failure_control, bool null_free, bool maybe_larval) {
3569 kill_dead_locals(); // Benefit all the uncommon traps
3570 const TypeKlassPtr* klass_ptr_type = _gvn.type(superklass)->is_klassptr();
3571 const Type* obj_type = _gvn.type(obj);
3572 if (obj_type->is_inlinetypeptr() && !obj_type->maybe_null() && klass_ptr_type->klass_is_exact() && obj_type->inline_klass() == klass_ptr_type->exact_klass(true)) {
3573 // Special case: larval inline objects must not be scalarized. They are also generally not
3574 // allowed to participate in most operations except as the first operand of putfield, or as an
3575 // argument to a constructor invocation with it being a receiver, Unsafe::putXXX with it being
3576 // the first argument, or Unsafe::finishPrivateBuffer. This allows us to aggressively scalarize
3577 // value objects in all other places. This special case comes from the limitation of the Java
3578 // language, Unsafe::makePrivateBuffer returns an Object that is checkcast-ed to the concrete
3579 // value type. We must do this first because C->static_subtype_check may do nothing when
3580 // StressReflectiveCode is set.
3581 return obj;
3582 }
3583
3584 // Else it must be a non-larval object
3585 obj = cast_to_non_larval(obj);
3586
3587 const TypeKlassPtr* improved_klass_ptr_type = klass_ptr_type->try_improve();
3588 const TypeOopPtr* toop = improved_klass_ptr_type->cast_to_exactness(false)->as_instance_type();
3589 bool safe_for_replace = (failure_control == nullptr);
3590 assert(!null_free || toop->can_be_inline_type(), "must be an inline type pointer");
3591
3592 // Fast cutout: Check the case that the cast is vacuously true.
3593 // This detects the common cases where the test will short-circuit
3594 // away completely. We do this before we perform the null check,
3595 // because if the test is going to turn into zero code, we don't
3596 // want a residual null check left around. (Causes a slowdown,
3597 // for example, in some objArray manipulations, such as a[i]=a[j].)
3598 if (improved_klass_ptr_type->singleton()) {
3599 const TypeKlassPtr* kptr = nullptr;
3600 if (obj_type->isa_oop_ptr()) {
3601 kptr = obj_type->is_oopptr()->as_klass_type();
3602 } else if (obj->is_InlineType()) {
3603 ciInlineKlass* vk = obj_type->inline_klass();
3604 kptr = TypeInstKlassPtr::make(TypePtr::NotNull, vk, Type::Offset(0));
3605 }
3606
3607 if (kptr != nullptr) {
3608 switch (C->static_subtype_check(improved_klass_ptr_type, kptr)) {
3609 case Compile::SSC_always_true:
3610 // If we know the type check always succeed then we don't use
3611 // the profiling data at this bytecode. Don't lose it, feed it
3612 // to the type system as a speculative type.
3613 obj = record_profiled_receiver_for_speculation(obj);
3614 if (null_free) {
3615 assert(safe_for_replace, "must be");
3616 obj = null_check(obj);
3617 }
3618 assert(stopped() || !toop->is_inlinetypeptr() || obj->is_InlineType(), "should have been scalarized");
3619 return obj;
3620 case Compile::SSC_always_false:
3621 if (null_free) {
3622 assert(safe_for_replace, "must be");
3623 obj = null_check(obj);
3624 }
3625 // It needs a null check because a null will *pass* the cast check.
3626 if (obj_type->isa_oopptr() != nullptr && !obj_type->is_oopptr()->maybe_null()) {
3627 bool is_aastore = (java_bc() == Bytecodes::_aastore);
3628 Deoptimization::DeoptReason reason = is_aastore ?
3629 Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3630 builtin_throw(reason);
3631 return top();
3632 } else if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
3633 return null_assert(obj);
3634 }
3635 break; // Fall through to full check
3636 default:
3637 break;
3638 }
3639 }
3640 }
3641
3642 ciProfileData* data = nullptr;
3643 if (failure_control == nullptr) { // use MDO in regular case only
3644 assert(java_bc() == Bytecodes::_aastore ||
3645 java_bc() == Bytecodes::_checkcast,
3646 "interpreter profiles type checks only for these BCs");
3647 if (method()->method_data()->is_mature()) {
3648 data = method()->method_data()->bci_to_data(bci());
3649 }
3650 }
3651
3652 // Make the merge point
3653 enum { _obj_path = 1, _null_path, PATH_LIMIT };
3654 RegionNode* region = new RegionNode(PATH_LIMIT);
3655 Node* phi = new PhiNode(region, toop);
3656 _gvn.set_type(region, Type::CONTROL);
3657 _gvn.set_type(phi, toop);
3658
3659 C->set_has_split_ifs(true); // Has chance for split-if optimization
3660
3661 // Use null-cast information if it is available
3662 bool speculative_not_null = false;
3663 bool never_see_null = ((failure_control == nullptr) // regular case only
3664 && seems_never_null(obj, data, speculative_not_null));
3665
3666 if (obj->is_InlineType()) {
3667 // Re-execute if buffering during triggers deoptimization
3668 PreserveReexecuteState preexecs(this);
3669 jvms()->set_should_reexecute(true);
3670 obj = obj->as_InlineType()->buffer(this, safe_for_replace);
3671 }
3672
3673 // Null check; get casted pointer; set region slot 3
3674 Node* null_ctl = top();
3675 Node* not_null_obj = nullptr;
3676 if (null_free) {
3677 assert(safe_for_replace, "must be");
3678 not_null_obj = null_check(obj);
3679 } else {
3680 not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3681 }
3682
3683 // If not_null_obj is dead, only null-path is taken
3684 if (stopped()) { // Doing instance-of on a null?
3685 set_control(null_ctl);
3686 if (toop->is_inlinetypeptr()) {
3687 return InlineTypeNode::make_null(_gvn, toop->inline_klass());
3688 }
3689 return null();
3690 }
3691 region->init_req(_null_path, null_ctl);
3692 phi ->init_req(_null_path, null()); // Set null path value
3693 if (null_ctl == top()) {
3694 // Do this eagerly, so that pattern matches like is_diamond_phi
3695 // will work even during parsing.
3696 assert(_null_path == PATH_LIMIT-1, "delete last");
3697 region->del_req(_null_path);
3698 phi ->del_req(_null_path);
3699 }
3700
3701 Node* cast_obj = nullptr;
3702 if (improved_klass_ptr_type->klass_is_exact()) {
3703 // The following optimization tries to statically cast the speculative type of the object
3704 // (for example obtained during profiling) to the type of the superklass and then do a
3705 // dynamic check that the type of the object is what we expect. To work correctly
3706 // for checkcast and aastore the type of superklass should be exact.
3707 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3708 // We may not have profiling here or it may not help us. If we have
3709 // a speculative type use it to perform an exact cast.
3710 ciKlass* spec_obj_type = obj_type->speculative_type();
3711 if (spec_obj_type != nullptr || data != nullptr) {
3712 cast_obj = maybe_cast_profiled_receiver(not_null_obj, improved_klass_ptr_type, spec_obj_type, safe_for_replace);
3713 if (cast_obj != nullptr) {
3714 if (failure_control != nullptr) // failure is now impossible
3715 (*failure_control) = top();
3716 // adjust the type of the phi to the exact klass:
3717 phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
3718 }
3719 }
3720 }
3721
3722 if (cast_obj == nullptr) {
3723 // Generate the subtype check
3724 Node* improved_superklass = superklass;
3725 if (improved_klass_ptr_type != klass_ptr_type && improved_klass_ptr_type->singleton()) {
3726 // Only improve the super class for constants which allows subsequent sub type checks to possibly be commoned up.
3727 // The other non-constant cases cannot be improved with a cast node here since they could be folded to top.
3728 // Additionally, the benefit would only be minor in non-constant cases.
3729 improved_superklass = makecon(improved_klass_ptr_type);
3730 }
3731 Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, improved_superklass);
3732 // Plug in success path into the merge
3733 cast_obj = _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop));
3734 // Failure path ends in uncommon trap (or may be dead - failure impossible)
3735 if (failure_control == nullptr) {
3736 if (not_subtype_ctrl != top()) { // If failure is possible
3737 PreserveJVMState pjvms(this);
3738 set_control(not_subtype_ctrl);
3739 bool is_aastore = (java_bc() == Bytecodes::_aastore);
3740 Deoptimization::DeoptReason reason = is_aastore ?
3741 Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3742 builtin_throw(reason);
3743 }
3744 } else {
3745 (*failure_control) = not_subtype_ctrl;
3746 }
3747 }
3748
3749 region->init_req(_obj_path, control());
3750 phi ->init_req(_obj_path, cast_obj);
3751
3752 // A merge of null or Casted-NotNull obj
3753 Node* res = _gvn.transform(phi);
3754
3755 // Note I do NOT always 'replace_in_map(obj,result)' here.
3756 // if( tk->klass()->can_be_primary_super() )
3757 // This means that if I successfully store an Object into an array-of-String
3758 // I 'forget' that the Object is really now known to be a String. I have to
3759 // do this because we don't have true union types for interfaces - if I store
3760 // a Baz into an array-of-Interface and then tell the optimizer it's an
3761 // Interface, I forget that it's also a Baz and cannot do Baz-like field
3762 // references to it. FIX THIS WHEN UNION TYPES APPEAR!
3763 // replace_in_map( obj, res );
3764
3765 // Return final merged results
3766 set_control( _gvn.transform(region) );
3767 record_for_igvn(region);
3768
3769 bool not_inline = !toop->can_be_inline_type();
3770 bool not_flat_in_array = !UseArrayFlattening || not_inline || (toop->is_inlinetypeptr() && !toop->inline_klass()->maybe_flat_in_array());
3771 if (Arguments::is_valhalla_enabled() && (not_inline || not_flat_in_array)) {
3772 // Check if obj has been loaded from an array
3773 obj = obj->isa_DecodeN() ? obj->in(1) : obj;
3774 Node* array = nullptr;
3775 if (obj->isa_Load()) {
3776 Node* address = obj->in(MemNode::Address);
3777 if (address->isa_AddP()) {
3778 array = address->as_AddP()->in(AddPNode::Base);
3779 }
3780 } else if (obj->is_Phi()) {
3781 Node* region = obj->in(0);
3782 // TODO make this more robust (see JDK-8231346)
3783 if (region->req() == 3 && region->in(2) != nullptr && region->in(2)->in(0) != nullptr) {
3784 IfNode* iff = region->in(2)->in(0)->isa_If();
3785 if (iff != nullptr) {
3786 iff->is_flat_array_check(&_gvn, &array);
3787 }
3788 }
3789 }
3790 if (array != nullptr) {
3791 const TypeAryPtr* ary_t = _gvn.type(array)->isa_aryptr();
3792 if (ary_t != nullptr) {
3793 if (!ary_t->is_not_null_free() && !ary_t->is_null_free() && not_inline) {
3794 // Casting array element to a non-inline-type, mark array as not null-free.
3795 Node* cast = _gvn.transform(new CheckCastPPNode(control(), array, ary_t->cast_to_not_null_free()));
3796 replace_in_map(array, cast);
3797 array = cast;
3798 }
3799 if (!ary_t->is_not_flat() && !ary_t->is_flat() && not_flat_in_array) {
3800 // Casting array element to a non-flat-in-array type, mark array as not flat.
3801 Node* cast = _gvn.transform(new CheckCastPPNode(control(), array, ary_t->cast_to_not_flat()));
3802 replace_in_map(array, cast);
3803 array = cast;
3804 }
3805 }
3806 }
3807 }
3808
3809 if (!stopped() && !res->is_InlineType()) {
3810 res = record_profiled_receiver_for_speculation(res);
3811 if (toop->is_inlinetypeptr() && !maybe_larval) {
3812 Node* vt = InlineTypeNode::make_from_oop(this, res, toop->inline_klass());
3813 res = vt;
3814 if (safe_for_replace) {
3815 replace_in_map(obj, vt);
3816 replace_in_map(not_null_obj, vt);
3817 replace_in_map(res, vt);
3818 }
3819 }
3820 }
3821 return res;
3822 }
3823
3824 Node* GraphKit::mark_word_test(Node* obj, uintptr_t mask_val, bool eq, bool check_lock) {
3825 // Load markword
3826 Node* mark_adr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
3827 Node* mark = make_load(nullptr, mark_adr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
3828 if (check_lock && !UseCompactObjectHeaders) {
3829 // COH: Locking does not override the markword with a tagged pointer. We can directly read from the markword.
3830 // Check if obj is locked
3831 Node* locked_bit = MakeConX(markWord::unlocked_value);
3832 locked_bit = _gvn.transform(new AndXNode(locked_bit, mark));
3833 Node* cmp = _gvn.transform(new CmpXNode(locked_bit, MakeConX(0)));
3834 Node* is_unlocked = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
3835 IfNode* iff = new IfNode(control(), is_unlocked, PROB_MAX, COUNT_UNKNOWN);
3836 _gvn.transform(iff);
3837 Node* locked_region = new RegionNode(3);
3838 Node* mark_phi = new PhiNode(locked_region, TypeX_X);
3839
3840 // Unlocked: Use bits from mark word
3841 locked_region->init_req(1, _gvn.transform(new IfTrueNode(iff)));
3842 mark_phi->init_req(1, mark);
3843
3844 // Locked: Load prototype header from klass
3845 set_control(_gvn.transform(new IfFalseNode(iff)));
3846 // Make loads control dependent to make sure they are only executed if array is locked
3847 Node* klass_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
3848 Node* klass = _gvn.transform(LoadKlassNode::make(_gvn, C->immutable_memory(), klass_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
3849 Node* proto_adr = basic_plus_adr(klass, in_bytes(Klass::prototype_header_offset()));
3850 Node* proto = _gvn.transform(LoadNode::make(_gvn, control(), C->immutable_memory(), proto_adr, proto_adr->bottom_type()->is_ptr(), TypeX_X, TypeX_X->basic_type(), MemNode::unordered));
3851
3852 locked_region->init_req(2, control());
3853 mark_phi->init_req(2, proto);
3854 set_control(_gvn.transform(locked_region));
3855 record_for_igvn(locked_region);
3856
3857 mark = mark_phi;
3858 }
3859
3860 // Now check if mark word bits are set
3861 Node* mask = MakeConX(mask_val);
3862 Node* masked = _gvn.transform(new AndXNode(_gvn.transform(mark), mask));
3863 record_for_igvn(masked); // Give it a chance to be optimized out by IGVN
3864 Node* cmp = _gvn.transform(new CmpXNode(masked, mask));
3865 return _gvn.transform(new BoolNode(cmp, eq ? BoolTest::eq : BoolTest::ne));
3866 }
3867
3868 Node* GraphKit::inline_type_test(Node* obj, bool is_inline) {
3869 return mark_word_test(obj, markWord::inline_type_pattern, is_inline, /* check_lock = */ false);
3870 }
3871
3872 Node* GraphKit::flat_array_test(Node* array_or_klass, bool flat) {
3873 // We can't use immutable memory here because the mark word is mutable.
3874 // PhaseIdealLoop::move_flat_array_check_out_of_loop will make sure the
3875 // check is moved out of loops (mainly to enable loop unswitching).
3876 Node* cmp = _gvn.transform(new FlatArrayCheckNode(C, memory(Compile::AliasIdxRaw), array_or_klass));
3877 record_for_igvn(cmp); // Give it a chance to be optimized out by IGVN
3878 return _gvn.transform(new BoolNode(cmp, flat ? BoolTest::eq : BoolTest::ne));
3879 }
3880
3881 Node* GraphKit::null_free_array_test(Node* array, bool null_free) {
3882 return mark_word_test(array, markWord::null_free_array_bit_in_place, null_free);
3883 }
3884
3885 Node* GraphKit::null_free_atomic_array_test(Node* array, ciInlineKlass* vk) {
3886 assert(vk->has_atomic_layout() || vk->has_non_atomic_layout(), "Can't be null-free and flat");
3887
3888 // TODO 8350865 Add a stress flag to always access atomic if layout exists?
3889 if (!vk->has_non_atomic_layout()) {
3890 return intcon(1); // Always atomic
3891 } else if (!vk->has_atomic_layout()) {
3892 return intcon(0); // Never atomic
3893 }
3894
3895 Node* array_klass = load_object_klass(array);
3896 int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3897 Node* layout_kind_addr = basic_plus_adr(array_klass, array_klass, layout_kind_offset);
3898 Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::INT, T_INT, MemNode::unordered);
3899 Node* cmp = _gvn.transform(new CmpINode(layout_kind, intcon((int)LayoutKind::NULL_FREE_ATOMIC_FLAT)));
3900 return _gvn.transform(new BoolNode(cmp, BoolTest::eq));
3901 }
3902
3903 // Deoptimize if 'ary' is a null-free inline type array and 'val' is null
3904 Node* GraphKit::inline_array_null_guard(Node* ary, Node* val, int nargs, bool safe_for_replace) {
3905 RegionNode* region = new RegionNode(3);
3906 Node* null_ctl = top();
3907 null_check_oop(val, &null_ctl);
3908 if (null_ctl != top()) {
3909 PreserveJVMState pjvms(this);
3910 set_control(null_ctl);
3911 {
3912 // Deoptimize if null-free array
3913 BuildCutout unless(this, null_free_array_test(ary, /* null_free = */ false), PROB_MAX);
3914 inc_sp(nargs);
3915 uncommon_trap(Deoptimization::Reason_null_check,
3916 Deoptimization::Action_none);
3917 }
3918 region->init_req(1, control());
3919 }
3920 region->init_req(2, control());
3921 set_control(_gvn.transform(region));
3922 record_for_igvn(region);
3923 if (_gvn.type(val) == TypePtr::NULL_PTR) {
3924 // Since we were just successfully storing null, the array can't be null free.
3925 const TypeAryPtr* ary_t = _gvn.type(ary)->is_aryptr();
3926 ary_t = ary_t->cast_to_not_null_free();
3927 Node* cast = _gvn.transform(new CheckCastPPNode(control(), ary, ary_t));
3928 if (safe_for_replace) {
3929 replace_in_map(ary, cast);
3930 }
3931 ary = cast;
3932 }
3933 return ary;
3934 }
3935
3936 //------------------------------next_monitor-----------------------------------
3937 // What number should be given to the next monitor?
3938 int GraphKit::next_monitor() {
3939 int current = jvms()->monitor_depth()* C->sync_stack_slots();
3940 int next = current + C->sync_stack_slots();
3941 // Keep the toplevel high water mark current:
3942 if (C->fixed_slots() < next) C->set_fixed_slots(next);
3943 return current;
3944 }
3945
3946 //------------------------------insert_mem_bar---------------------------------
3947 // Memory barrier to avoid floating things around
3948 // The membar serves as a pinch point between both control and all memory slices.
3949 Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {
3950 MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
3951 mb->init_req(TypeFunc::Control, control());
3952 mb->init_req(TypeFunc::Memory, reset_memory());
3953 Node* membar = _gvn.transform(mb);
4047 lock->create_lock_counter(map()->jvms());
4048 increment_counter(lock->counter()->addr());
4049 }
4050 #endif
4051
4052 return flock;
4053 }
4054
4055
4056 //------------------------------shared_unlock----------------------------------
4057 // Emit unlocking code.
4058 void GraphKit::shared_unlock(Node* box, Node* obj) {
4059 // bci is either a monitorenter bc or InvocationEntryBci
4060 // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
4061 assert(SynchronizationEntryBCI == InvocationEntryBci, "");
4062
4063 if (stopped()) { // Dead monitor?
4064 map()->pop_monitor(); // Kill monitor from debug info
4065 return;
4066 }
4067 assert(!obj->is_InlineType(), "should not unlock on inline type");
4068
4069 // Memory barrier to avoid floating things down past the locked region
4070 insert_mem_bar(Op_MemBarReleaseLock);
4071
4072 const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();
4073 UnlockNode *unlock = new UnlockNode(C, tf);
4074 #ifdef ASSERT
4075 unlock->set_dbg_jvms(sync_jvms());
4076 #endif
4077 uint raw_idx = Compile::AliasIdxRaw;
4078 unlock->init_req( TypeFunc::Control, control() );
4079 unlock->init_req( TypeFunc::Memory , memory(raw_idx) );
4080 unlock->init_req( TypeFunc::I_O , top() ) ; // does no i/o
4081 unlock->init_req( TypeFunc::FramePtr, frameptr() );
4082 unlock->init_req( TypeFunc::ReturnAdr, top() );
4083
4084 unlock->init_req(TypeFunc::Parms + 0, obj);
4085 unlock->init_req(TypeFunc::Parms + 1, box);
4086 unlock = _gvn.transform(unlock)->as_Unlock();
4087
4088 Node* mem = reset_memory();
4089
4090 // unlock has no side-effects, sets few values
4091 set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);
4092
4093 // Kill monitor from debug info
4094 map()->pop_monitor( );
4095 }
4096
4097 //-------------------------------get_layout_helper-----------------------------
4098 // If the given klass is a constant or known to be an array,
4099 // fetch the constant layout helper value into constant_value
4100 // and return null. Otherwise, load the non-constant
4101 // layout helper value, and return the node which represents it.
4102 // This two-faced routine is useful because allocation sites
4103 // almost always feature constant types.
4104 Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {
4105 const TypeKlassPtr* klass_t = _gvn.type(klass_node)->isa_klassptr();
4106 if (!StressReflectiveCode && klass_t != nullptr) {
4107 bool xklass = klass_t->klass_is_exact();
4108 bool can_be_flat = false;
4109 const TypeAryPtr* ary_type = klass_t->as_instance_type()->isa_aryptr();
4110 if (UseArrayFlattening && !xklass && ary_type != nullptr && !ary_type->is_null_free()) {
4111 // Don't constant fold if the runtime type might be a flat array but the static type is not.
4112 const TypeOopPtr* elem = ary_type->elem()->make_oopptr();
4113 can_be_flat = ary_type->can_be_inline_array() && (!elem->is_inlinetypeptr() || elem->inline_klass()->maybe_flat_in_array());
4114 }
4115 if (!can_be_flat && (xklass || (klass_t->isa_aryklassptr() && klass_t->is_aryklassptr()->elem() != Type::BOTTOM))) {
4116 jint lhelper;
4117 if (klass_t->is_flat()) {
4118 lhelper = ary_type->flat_layout_helper();
4119 } else if (klass_t->isa_aryklassptr()) {
4120 BasicType elem = ary_type->elem()->array_element_basic_type();
4121 if (is_reference_type(elem, true)) {
4122 elem = T_OBJECT;
4123 }
4124 lhelper = Klass::array_layout_helper(elem);
4125 } else {
4126 lhelper = klass_t->is_instklassptr()->exact_klass()->layout_helper();
4127 }
4128 if (lhelper != Klass::_lh_neutral_value) {
4129 constant_value = lhelper;
4130 return (Node*) nullptr;
4131 }
4132 }
4133 }
4134 constant_value = Klass::_lh_neutral_value; // put in a known value
4135 Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset()));
4136 return make_load(nullptr, lhp, TypeInt::INT, T_INT, MemNode::unordered);
4137 }
4138
4139 // We just put in an allocate/initialize with a big raw-memory effect.
4140 // Hook selected additional alias categories on the initialization.
4141 static void hook_memory_on_init(GraphKit& kit, int alias_idx,
4142 MergeMemNode* init_in_merge,
4143 Node* init_out_raw) {
4144 DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());
4145 assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");
4146
4147 Node* prevmem = kit.memory(alias_idx);
4148 init_in_merge->set_memory_at(alias_idx, prevmem);
4149 if (init_out_raw != nullptr) {
4150 kit.set_memory(init_out_raw, alias_idx);
4151 }
4152 }
4153
4154 //---------------------------set_output_for_allocation-------------------------
4155 Node* GraphKit::set_output_for_allocation(AllocateNode* alloc,
4156 const TypeOopPtr* oop_type,
4157 bool deoptimize_on_exception) {
4158 int rawidx = Compile::AliasIdxRaw;
4159 alloc->set_req( TypeFunc::FramePtr, frameptr() );
4160 add_safepoint_edges(alloc);
4161 Node* allocx = _gvn.transform(alloc);
4162 set_control( _gvn.transform(new ProjNode(allocx, TypeFunc::Control) ) );
4163 // create memory projection for i_o
4164 set_memory ( _gvn.transform( new ProjNode(allocx, TypeFunc::Memory, true) ), rawidx );
4165 make_slow_call_ex(allocx, env()->Throwable_klass(), true, deoptimize_on_exception);
4166
4167 // create a memory projection as for the normal control path
4168 Node* malloc = _gvn.transform(new ProjNode(allocx, TypeFunc::Memory));
4169 set_memory(malloc, rawidx);
4170
4171 // a normal slow-call doesn't change i_o, but an allocation does
4172 // we create a separate i_o projection for the normal control path
4173 set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) );
4174 Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) );
4175
4176 // put in an initialization barrier
4177 InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,
4178 rawoop)->as_Initialize();
4179 assert(alloc->initialization() == init, "2-way macro link must work");
4180 assert(init ->allocation() == alloc, "2-way macro link must work");
4181 {
4182 // Extract memory strands which may participate in the new object's
4183 // initialization, and source them from the new InitializeNode.
4184 // This will allow us to observe initializations when they occur,
4185 // and link them properly (as a group) to the InitializeNode.
4186 assert(init->in(InitializeNode::Memory) == malloc, "");
4187 MergeMemNode* minit_in = MergeMemNode::make(malloc);
4188 init->set_req(InitializeNode::Memory, minit_in);
4189 record_for_igvn(minit_in); // fold it up later, if possible
4190 _gvn.set_type(minit_in, Type::MEMORY);
4191 Node* minit_out = memory(rawidx);
4192 assert(minit_out->is_Proj() && minit_out->in(0) == init, "");
4193 int mark_idx = C->get_alias_index(oop_type->add_offset(oopDesc::mark_offset_in_bytes()));
4194 // Add an edge in the MergeMem for the header fields so an access to one of those has correct memory state.
4195 // Use one NarrowMemProjNode per slice to properly record the adr type of each slice. The Initialize node will have
4196 // multiple projections as a result.
4197 set_memory(_gvn.transform(new NarrowMemProjNode(init, C->get_adr_type(mark_idx))), mark_idx);
4198 int klass_idx = C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes()));
4199 set_memory(_gvn.transform(new NarrowMemProjNode(init, C->get_adr_type(klass_idx))), klass_idx);
4200 if (oop_type->isa_aryptr()) {
4201 // Initially all flat array accesses share a single slice
4202 // but that changes after parsing. Prepare the memory graph so
4203 // it can optimize flat array accesses properly once they
4204 // don't share a single slice.
4205 assert(C->flat_accesses_share_alias(), "should be set at parse time");
4206 const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);
4207 int elemidx = C->get_alias_index(telemref);
4208 const TypePtr* alias_adr_type = C->get_adr_type(elemidx);
4209 if (alias_adr_type->is_flat()) {
4210 C->set_flat_accesses();
4211 }
4212 hook_memory_on_init(*this, elemidx, minit_in, _gvn.transform(new NarrowMemProjNode(init, alias_adr_type)));
4213 } else if (oop_type->isa_instptr()) {
4214 ciInstanceKlass* ik = oop_type->is_instptr()->instance_klass();
4215 for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {
4216 ciField* field = ik->nonstatic_field_at(i);
4217 if (field->offset_in_bytes() >= TrackedInitializationLimit * HeapWordSize)
4218 continue; // do not bother to track really large numbers of fields
4219 // Find (or create) the alias category for this field:
4220 int fieldidx = C->alias_type(field)->index();
4221 hook_memory_on_init(*this, fieldidx, minit_in, _gvn.transform(new NarrowMemProjNode(init, C->get_adr_type(fieldidx))));
4222 }
4223 }
4224 }
4225
4226 // Cast raw oop to the real thing...
4227 Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type);
4228 javaoop = _gvn.transform(javaoop);
4229 C->set_recent_alloc(control(), javaoop);
4230 assert(just_allocated_object(control()) == javaoop, "just allocated");
4231
4232 #ifdef ASSERT
4244 assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");
4245 }
4246 }
4247 #endif //ASSERT
4248
4249 return javaoop;
4250 }
4251
4252 //---------------------------new_instance--------------------------------------
4253 // This routine takes a klass_node which may be constant (for a static type)
4254 // or may be non-constant (for reflective code). It will work equally well
4255 // for either, and the graph will fold nicely if the optimizer later reduces
4256 // the type to a constant.
4257 // The optional arguments are for specialized use by intrinsics:
4258 // - If 'extra_slow_test' if not null is an extra condition for the slow-path.
4259 // - If 'return_size_val', report the total object size to the caller.
4260 // - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
4261 Node* GraphKit::new_instance(Node* klass_node,
4262 Node* extra_slow_test,
4263 Node* *return_size_val,
4264 bool deoptimize_on_exception,
4265 InlineTypeNode* inline_type_node) {
4266 // Compute size in doublewords
4267 // The size is always an integral number of doublewords, represented
4268 // as a positive bytewise size stored in the klass's layout_helper.
4269 // The layout_helper also encodes (in a low bit) the need for a slow path.
4270 jint layout_con = Klass::_lh_neutral_value;
4271 Node* layout_val = get_layout_helper(klass_node, layout_con);
4272 bool layout_is_con = (layout_val == nullptr);
4273
4274 if (extra_slow_test == nullptr) extra_slow_test = intcon(0);
4275 // Generate the initial go-slow test. It's either ALWAYS (return a
4276 // Node for 1) or NEVER (return a null) or perhaps (in the reflective
4277 // case) a computed value derived from the layout_helper.
4278 Node* initial_slow_test = nullptr;
4279 if (layout_is_con) {
4280 assert(!StressReflectiveCode, "stress mode does not use these paths");
4281 bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);
4282 initial_slow_test = must_go_slow ? intcon(1) : extra_slow_test;
4283 } else { // reflective case
4284 // This reflective path is used by Unsafe.allocateInstance.
4285 // (It may be stress-tested by specifying StressReflectiveCode.)
4286 // Basically, we want to get into the VM is there's an illegal argument.
4287 Node* bit = intcon(Klass::_lh_instance_slow_path_bit);
4288 initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) );
4289 if (extra_slow_test != intcon(0)) {
4290 initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) );
4291 }
4292 // (Macro-expander will further convert this to a Bool, if necessary.)
4303
4304 // Clear the low bits to extract layout_helper_size_in_bytes:
4305 assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
4306 Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));
4307 size = _gvn.transform( new AndXNode(size, mask) );
4308 }
4309 if (return_size_val != nullptr) {
4310 (*return_size_val) = size;
4311 }
4312
4313 // This is a precise notnull oop of the klass.
4314 // (Actually, it need not be precise if this is a reflective allocation.)
4315 // It's what we cast the result to.
4316 const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();
4317 if (!tklass) tklass = TypeInstKlassPtr::OBJECT;
4318 const TypeOopPtr* oop_type = tklass->as_instance_type();
4319
4320 // Now generate allocation code
4321
4322 // The entire memory state is needed for slow path of the allocation
4323 // since GC and deoptimization can happen.
4324 Node *mem = reset_memory();
4325 set_all_memory(mem); // Create new memory state
4326
4327 AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP),
4328 control(), mem, i_o(),
4329 size, klass_node,
4330 initial_slow_test, inline_type_node);
4331
4332 return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);
4333 }
4334
4335 //-------------------------------new_array-------------------------------------
4336 // helper for newarray and anewarray
4337 // The 'length' parameter is (obviously) the length of the array.
4338 // The optional arguments are for specialized use by intrinsics:
4339 // - If 'return_size_val', report the non-padded array size (sum of header size
4340 // and array body) to the caller.
4341 // - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
4342 Node* GraphKit::new_array(Node* klass_node, // array klass (maybe variable)
4343 Node* length, // number of array elements
4344 int nargs, // number of arguments to push back for uncommon trap
4345 Node* *return_size_val,
4346 bool deoptimize_on_exception,
4347 Node* init_val) {
4348 jint layout_con = Klass::_lh_neutral_value;
4349 Node* layout_val = get_layout_helper(klass_node, layout_con);
4350 bool layout_is_con = (layout_val == nullptr);
4351
4352 if (!layout_is_con && !StressReflectiveCode &&
4353 !too_many_traps(Deoptimization::Reason_class_check)) {
4354 // This is a reflective array creation site.
4355 // Optimistically assume that it is a subtype of Object[],
4356 // so that we can fold up all the address arithmetic.
4357 layout_con = Klass::array_layout_helper(T_OBJECT);
4358 Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) );
4359 Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) );
4360 { BuildCutout unless(this, bol_lh, PROB_MAX);
4361 inc_sp(nargs);
4362 uncommon_trap(Deoptimization::Reason_class_check,
4363 Deoptimization::Action_maybe_recompile);
4364 }
4365 layout_val = nullptr;
4366 layout_is_con = true;
4367 }
4368
4369 // Generate the initial go-slow test. Make sure we do not overflow
4370 // if length is huge (near 2Gig) or negative! We do not need
4371 // exact double-words here, just a close approximation of needed
4372 // double-words. We can't add any offset or rounding bits, lest we
4373 // take a size -1 of bytes and make it positive. Use an unsigned
4374 // compare, so negative sizes look hugely positive.
4375 int fast_size_limit = FastAllocateSizeLimit;
4376 if (layout_is_con) {
4377 assert(!StressReflectiveCode, "stress mode does not use these paths");
4378 // Increase the size limit if we have exact knowledge of array type.
4379 int log2_esize = Klass::layout_helper_log2_element_size(layout_con);
4380 fast_size_limit <<= MAX2(LogBytesPerLong - log2_esize, 0);
4381 }
4382
4383 Node* initial_slow_cmp = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) );
4384 Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) );
4385
4386 // --- Size Computation ---
4387 // array_size = round_to_heap(array_header + (length << elem_shift));
4388 // where round_to_heap(x) == align_to(x, MinObjAlignmentInBytes)
4389 // and align_to(x, y) == ((x + y-1) & ~(y-1))
4390 // The rounding mask is strength-reduced, if possible.
4391 int round_mask = MinObjAlignmentInBytes - 1;
4392 Node* header_size = nullptr;
4393 // (T_BYTE has the weakest alignment and size restrictions...)
4394 if (layout_is_con) {
4395 int hsize = Klass::layout_helper_header_size(layout_con);
4396 int eshift = Klass::layout_helper_log2_element_size(layout_con);
4397 bool is_flat_array = Klass::layout_helper_is_flatArray(layout_con);
4398 if ((round_mask & ~right_n_bits(eshift)) == 0)
4399 round_mask = 0; // strength-reduce it if it goes away completely
4400 assert(is_flat_array || (hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
4401 int header_size_min = arrayOopDesc::base_offset_in_bytes(T_BYTE);
4402 assert(header_size_min <= hsize, "generic minimum is smallest");
4403 header_size = intcon(hsize);
4404 } else {
4405 Node* hss = intcon(Klass::_lh_header_size_shift);
4406 Node* hsm = intcon(Klass::_lh_header_size_mask);
4407 header_size = _gvn.transform(new URShiftINode(layout_val, hss));
4408 header_size = _gvn.transform(new AndINode(header_size, hsm));
4409 }
4410
4411 Node* elem_shift = nullptr;
4412 if (layout_is_con) {
4413 int eshift = Klass::layout_helper_log2_element_size(layout_con);
4414 if (eshift != 0)
4415 elem_shift = intcon(eshift);
4416 } else {
4417 // There is no need to mask or shift this value.
4418 // The semantics of LShiftINode include an implicit mask to 0x1F.
4419 assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
4420 elem_shift = layout_val;
4469 }
4470 Node* non_rounded_size = _gvn.transform(new AddXNode(headerx, abody));
4471
4472 if (return_size_val != nullptr) {
4473 // This is the size
4474 (*return_size_val) = non_rounded_size;
4475 }
4476
4477 Node* size = non_rounded_size;
4478 if (round_mask != 0) {
4479 Node* mask1 = MakeConX(round_mask);
4480 size = _gvn.transform(new AddXNode(size, mask1));
4481 Node* mask2 = MakeConX(~round_mask);
4482 size = _gvn.transform(new AndXNode(size, mask2));
4483 }
4484 // else if round_mask == 0, the size computation is self-rounding
4485
4486 // Now generate allocation code
4487
4488 // The entire memory state is needed for slow path of the allocation
4489 // since GC and deoptimization can happen.
4490 Node *mem = reset_memory();
4491 set_all_memory(mem); // Create new memory state
4492
4493 if (initial_slow_test->is_Bool()) {
4494 // Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.
4495 initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);
4496 }
4497
4498 const TypeKlassPtr* ary_klass = _gvn.type(klass_node)->isa_klassptr();
4499 const TypeOopPtr* ary_type = ary_klass->as_instance_type();
4500
4501 Node* raw_init_value = nullptr;
4502 if (init_val != nullptr) {
4503 // TODO 8350865 Fast non-zero init not implemented yet for flat, null-free arrays
4504 if (ary_type->is_flat()) {
4505 initial_slow_test = intcon(1);
4506 }
4507
4508 if (UseCompressedOops) {
4509 // With compressed oops, the 64-bit init value is built from two 32-bit compressed oops
4510 init_val = _gvn.transform(new EncodePNode(init_val, init_val->bottom_type()->make_narrowoop()));
4511 Node* lower = _gvn.transform(new CastP2XNode(control(), init_val));
4512 Node* upper = _gvn.transform(new LShiftLNode(lower, intcon(32)));
4513 raw_init_value = _gvn.transform(new OrLNode(lower, upper));
4514 } else {
4515 raw_init_value = _gvn.transform(new CastP2XNode(control(), init_val));
4516 }
4517 }
4518
4519 Node* valid_length_test = _gvn.intcon(1);
4520 if (ary_type->isa_aryptr()) {
4521 BasicType bt = ary_type->isa_aryptr()->elem()->array_element_basic_type();
4522 jint max = TypeAryPtr::max_array_length(bt);
4523 Node* valid_length_cmp = _gvn.transform(new CmpUNode(length, intcon(max)));
4524 valid_length_test = _gvn.transform(new BoolNode(valid_length_cmp, BoolTest::le));
4525 }
4526
4527 // Create the AllocateArrayNode and its result projections
4528 AllocateArrayNode* alloc
4529 = new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),
4530 control(), mem, i_o(),
4531 size, klass_node,
4532 initial_slow_test,
4533 length, valid_length_test,
4534 init_val, raw_init_value);
4535 // Cast to correct type. Note that the klass_node may be constant or not,
4536 // and in the latter case the actual array type will be inexact also.
4537 // (This happens via a non-constant argument to inline_native_newArray.)
4538 // In any case, the value of klass_node provides the desired array type.
4539 const TypeInt* length_type = _gvn.find_int_type(length);
4540 if (ary_type->isa_aryptr() && length_type != nullptr) {
4541 // Try to get a better type than POS for the size
4542 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
4543 }
4544
4545 Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);
4546
4547 array_ideal_length(alloc, ary_type, true);
4548 return javaoop;
4549 }
4550
4551 // The following "Ideal_foo" functions are placed here because they recognize
4552 // the graph shapes created by the functions immediately above.
4553
4554 //---------------------------Ideal_allocation----------------------------------
4649 void GraphKit::add_parse_predicates(int nargs) {
4650 if (ShortRunningLongLoop) {
4651 // Will narrow the limit down with a cast node. Predicates added later may depend on the cast so should be last when
4652 // walking up from the loop.
4653 add_parse_predicate(Deoptimization::Reason_short_running_long_loop, nargs);
4654 }
4655 if (UseLoopPredicate) {
4656 add_parse_predicate(Deoptimization::Reason_predicate, nargs);
4657 if (UseProfiledLoopPredicate) {
4658 add_parse_predicate(Deoptimization::Reason_profile_predicate, nargs);
4659 }
4660 }
4661 if (UseAutoVectorizationPredicate) {
4662 add_parse_predicate(Deoptimization::Reason_auto_vectorization_check, nargs);
4663 }
4664 // Loop Limit Check Predicate should be near the loop.
4665 add_parse_predicate(Deoptimization::Reason_loop_limit_check, nargs);
4666 }
4667
4668 void GraphKit::sync_kit(IdealKit& ideal) {
4669 reset_memory();
4670 set_all_memory(ideal.merged_memory());
4671 set_i_o(ideal.i_o());
4672 set_control(ideal.ctrl());
4673 }
4674
4675 void GraphKit::final_sync(IdealKit& ideal) {
4676 // Final sync IdealKit and graphKit.
4677 sync_kit(ideal);
4678 }
4679
4680 Node* GraphKit::load_String_length(Node* str, bool set_ctrl) {
4681 Node* len = load_array_length(load_String_value(str, set_ctrl));
4682 Node* coder = load_String_coder(str, set_ctrl);
4683 // Divide length by 2 if coder is UTF16
4684 return _gvn.transform(new RShiftINode(len, coder));
4685 }
4686
4687 Node* GraphKit::load_String_value(Node* str, bool set_ctrl) {
4688 int value_offset = java_lang_String::value_offset();
4689 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4690 false, nullptr, Type::Offset(0));
4691 const TypePtr* value_field_type = string_type->add_offset(value_offset);
4692 const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull,
4693 TypeAry::make(TypeInt::BYTE, TypeInt::POS, false, false, true, true, true),
4694 ciTypeArrayKlass::make(T_BYTE), true, Type::Offset(0));
4695 Node* p = basic_plus_adr(str, str, value_offset);
4696 Node* load = access_load_at(str, p, value_field_type, value_type, T_OBJECT,
4697 IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4698 return load;
4699 }
4700
4701 Node* GraphKit::load_String_coder(Node* str, bool set_ctrl) {
4702 if (!CompactStrings) {
4703 return intcon(java_lang_String::CODER_UTF16);
4704 }
4705 int coder_offset = java_lang_String::coder_offset();
4706 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4707 false, nullptr, Type::Offset(0));
4708 const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4709
4710 Node* p = basic_plus_adr(str, str, coder_offset);
4711 Node* load = access_load_at(str, p, coder_field_type, TypeInt::BYTE, T_BYTE,
4712 IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4713 return load;
4714 }
4715
4716 void GraphKit::store_String_value(Node* str, Node* value) {
4717 int value_offset = java_lang_String::value_offset();
4718 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4719 false, nullptr, Type::Offset(0));
4720 const TypePtr* value_field_type = string_type->add_offset(value_offset);
4721
4722 access_store_at(str, basic_plus_adr(str, value_offset), value_field_type,
4723 value, TypeAryPtr::BYTES, T_OBJECT, IN_HEAP | MO_UNORDERED);
4724 }
4725
4726 void GraphKit::store_String_coder(Node* str, Node* value) {
4727 int coder_offset = java_lang_String::coder_offset();
4728 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4729 false, nullptr, Type::Offset(0));
4730 const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4731
4732 access_store_at(str, basic_plus_adr(str, coder_offset), coder_field_type,
4733 value, TypeInt::BYTE, T_BYTE, IN_HEAP | MO_UNORDERED);
4734 }
4735
4736 // Capture src and dst memory state with a MergeMemNode
4737 Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) {
4738 if (src_type == dst_type) {
4739 // Types are equal, we don't need a MergeMemNode
4740 return memory(src_type);
4741 }
4742 MergeMemNode* merge = MergeMemNode::make(map()->memory());
4743 record_for_igvn(merge); // fold it up later, if possible
4744 int src_idx = C->get_alias_index(src_type);
4745 int dst_idx = C->get_alias_index(dst_type);
4746 merge->set_memory_at(src_idx, memory(src_idx));
4747 merge->set_memory_at(dst_idx, memory(dst_idx));
4748 return merge;
4749 }
4822 i_char->init_req(2, AddI(i_char, intcon(2)));
4823
4824 set_control(IfFalse(iff));
4825 set_memory(st, TypeAryPtr::BYTES);
4826 }
4827
4828 Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) {
4829 if (!field->is_constant()) {
4830 return nullptr; // Field not marked as constant.
4831 }
4832 ciInstance* holder = nullptr;
4833 if (!field->is_static()) {
4834 ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop();
4835 if (const_oop != nullptr && const_oop->is_instance()) {
4836 holder = const_oop->as_instance();
4837 }
4838 }
4839 const Type* con_type = Type::make_constant_from_field(field, holder, field->layout_type(),
4840 /*is_unsigned_load=*/false);
4841 if (con_type != nullptr) {
4842 Node* con = makecon(con_type);
4843 if (field->type()->is_inlinetype()) {
4844 con = InlineTypeNode::make_from_oop(this, con, field->type()->as_inline_klass());
4845 } else if (con_type->is_inlinetypeptr()) {
4846 con = InlineTypeNode::make_from_oop(this, con, con_type->inline_klass());
4847 }
4848 return con;
4849 }
4850 return nullptr;
4851 }
4852
4853 Node* GraphKit::maybe_narrow_object_type(Node* obj, ciKlass* type) {
4854 const Type* obj_type = obj->bottom_type();
4855 const TypeOopPtr* sig_type = TypeOopPtr::make_from_klass(type);
4856 if (obj_type->isa_oopptr() && sig_type->is_loaded() && !obj_type->higher_equal(sig_type)) {
4857 const Type* narrow_obj_type = obj_type->filter_speculative(sig_type); // keep speculative part
4858 Node* casted_obj = gvn().transform(new CheckCastPPNode(control(), obj, narrow_obj_type));
4859 obj = casted_obj;
4860 }
4861 if (sig_type->is_inlinetypeptr()) {
4862 obj = InlineTypeNode::make_from_oop(this, obj, sig_type->inline_klass());
4863 }
4864 return obj;
4865 }
|