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