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 "precompiled.hpp"
26 #include "ci/ciUtilities.hpp"
27 #include "classfile/javaClasses.hpp"
28 #include "ci/ciObjArray.hpp"
29 #include "asm/register.hpp"
30 #include "compiler/compileLog.hpp"
31 #include "gc/shared/barrierSet.hpp"
32 #include "gc/shared/c2/barrierSetC2.hpp"
33 #include "interpreter/interpreter.hpp"
34 #include "memory/resourceArea.hpp"
35 #include "opto/addnode.hpp"
36 #include "opto/castnode.hpp"
37 #include "opto/convertnode.hpp"
38 #include "opto/graphKit.hpp"
39 #include "opto/idealKit.hpp"
40 #include "opto/intrinsicnode.hpp"
41 #include "opto/locknode.hpp"
42 #include "opto/machnode.hpp"
43 #include "opto/opaquenode.hpp"
44 #include "opto/parse.hpp"
45 #include "opto/rootnode.hpp"
46 #include "opto/runtime.hpp"
47 #include "opto/subtypenode.hpp"
48 #include "runtime/deoptimization.hpp"
49 #include "runtime/sharedRuntime.hpp"
50 #include "utilities/bitMap.inline.hpp"
51 #include "utilities/powerOfTwo.hpp"
52 #include "utilities/growableArray.hpp"
53
54 //----------------------------GraphKit-----------------------------------------
55 // Main utility constructor.
56 GraphKit::GraphKit(JVMState* jvms)
57 : Phase(Phase::Parser),
58 _env(C->env()),
59 _gvn(*C->initial_gvn()),
60 _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
61 {
62 _exceptions = jvms->map()->next_exception();
63 if (_exceptions != nullptr) jvms->map()->set_next_exception(nullptr);
64 set_jvms(jvms);
65 }
66
67 // Private constructor for parser.
68 GraphKit::GraphKit()
69 : Phase(Phase::Parser),
70 _env(C->env()),
71 _gvn(*C->initial_gvn()),
72 _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
73 {
74 _exceptions = nullptr;
75 set_map(nullptr);
76 debug_only(_sp = -99);
77 debug_only(set_bci(-99));
78 }
79
80
81
82 //---------------------------clean_stack---------------------------------------
83 // Clear away rubbish from the stack area of the JVM state.
84 // This destroys any arguments that may be waiting on the stack.
840 if (PrintMiscellaneous && (Verbose || WizardMode)) {
841 tty->print_cr("Zombie local %d: ", local);
842 jvms->dump();
843 }
844 return false;
845 }
846 }
847 }
848 return true;
849 }
850
851 #endif //ASSERT
852
853 // Helper function for enforcing certain bytecodes to reexecute if deoptimization happens.
854 static bool should_reexecute_implied_by_bytecode(JVMState *jvms, bool is_anewarray) {
855 ciMethod* cur_method = jvms->method();
856 int cur_bci = jvms->bci();
857 if (cur_method != nullptr && cur_bci != InvocationEntryBci) {
858 Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci);
859 return Interpreter::bytecode_should_reexecute(code) ||
860 (is_anewarray && code == Bytecodes::_multianewarray);
861 // Reexecute _multianewarray bytecode which was replaced with
862 // sequence of [a]newarray. See Parse::do_multianewarray().
863 //
864 // Note: interpreter should not have it set since this optimization
865 // is limited by dimensions and guarded by flag so in some cases
866 // multianewarray() runtime calls will be generated and
867 // the bytecode should not be reexecutes (stack will not be reset).
868 } else {
869 return false;
870 }
871 }
872
873 // Helper function for adding JVMState and debug information to node
874 void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) {
875 // Add the safepoint edges to the call (or other safepoint).
876
877 // Make sure dead locals are set to top. This
878 // should help register allocation time and cut down on the size
879 // of the deoptimization information.
880 assert(dead_locals_are_killed(), "garbage in debug info before safepoint");
1100 ciSignature* declared_signature = nullptr;
1101 ciMethod* ignored_callee = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
1102 assert(declared_signature != nullptr, "cannot be null");
1103 inputs = declared_signature->arg_size_for_bc(code);
1104 int size = declared_signature->return_type()->size();
1105 depth = size - inputs;
1106 }
1107 break;
1108
1109 case Bytecodes::_multianewarray:
1110 {
1111 ciBytecodeStream iter(method());
1112 iter.reset_to_bci(bci());
1113 iter.next();
1114 inputs = iter.get_dimensions();
1115 assert(rsize() == 1, "");
1116 depth = 1 - inputs;
1117 }
1118 break;
1119
1120 case Bytecodes::_ireturn:
1121 case Bytecodes::_lreturn:
1122 case Bytecodes::_freturn:
1123 case Bytecodes::_dreturn:
1124 case Bytecodes::_areturn:
1125 assert(rsize() == -depth, "");
1126 inputs = -depth;
1127 break;
1128
1129 case Bytecodes::_jsr:
1130 case Bytecodes::_jsr_w:
1131 inputs = 0;
1132 depth = 1; // S.B. depth=1, not zero
1133 break;
1134
1135 default:
1136 // bytecode produces a typed result
1137 inputs = rsize() - depth;
1138 assert(inputs >= 0, "");
1139 break;
1182 Node* conv = _gvn.transform( new ConvI2LNode(offset));
1183 Node* mask = _gvn.transform(ConLNode::make((julong) max_juint));
1184 return _gvn.transform( new AndLNode(conv, mask) );
1185 }
1186
1187 Node* GraphKit::ConvL2I(Node* offset) {
1188 // short-circuit a common case
1189 jlong offset_con = find_long_con(offset, (jlong)Type::OffsetBot);
1190 if (offset_con != (jlong)Type::OffsetBot) {
1191 return intcon((int) offset_con);
1192 }
1193 return _gvn.transform( new ConvL2INode(offset));
1194 }
1195
1196 //-------------------------load_object_klass-----------------------------------
1197 Node* GraphKit::load_object_klass(Node* obj) {
1198 // Special-case a fresh allocation to avoid building nodes:
1199 Node* akls = AllocateNode::Ideal_klass(obj, &_gvn);
1200 if (akls != nullptr) return akls;
1201 Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
1202 return _gvn.transform(LoadKlassNode::make(_gvn, nullptr, immutable_memory(), k_adr, TypeInstPtr::KLASS));
1203 }
1204
1205 //-------------------------load_array_length-----------------------------------
1206 Node* GraphKit::load_array_length(Node* array) {
1207 // Special-case a fresh allocation to avoid building nodes:
1208 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(array, &_gvn);
1209 Node *alen;
1210 if (alloc == nullptr) {
1211 Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes());
1212 alen = _gvn.transform( new LoadRangeNode(0, immutable_memory(), r_adr, TypeInt::POS));
1213 } else {
1214 alen = array_ideal_length(alloc, _gvn.type(array)->is_oopptr(), false);
1215 }
1216 return alen;
1217 }
1218
1219 Node* GraphKit::array_ideal_length(AllocateArrayNode* alloc,
1220 const TypeOopPtr* oop_type,
1221 bool replace_length_in_map) {
1222 Node* length = alloc->Ideal_length();
1231 replace_in_map(length, ccast);
1232 }
1233 return ccast;
1234 }
1235 }
1236 return length;
1237 }
1238
1239 //------------------------------do_null_check----------------------------------
1240 // Helper function to do a null pointer check. Returned value is
1241 // the incoming address with null casted away. You are allowed to use the
1242 // not-null value only if you are control dependent on the test.
1243 #ifndef PRODUCT
1244 extern int explicit_null_checks_inserted,
1245 explicit_null_checks_elided;
1246 #endif
1247 Node* GraphKit::null_check_common(Node* value, BasicType type,
1248 // optional arguments for variations:
1249 bool assert_null,
1250 Node* *null_control,
1251 bool speculative) {
1252 assert(!assert_null || null_control == nullptr, "not both at once");
1253 if (stopped()) return top();
1254 NOT_PRODUCT(explicit_null_checks_inserted++);
1255
1256 // Construct null check
1257 Node *chk = nullptr;
1258 switch(type) {
1259 case T_LONG : chk = new CmpLNode(value, _gvn.zerocon(T_LONG)); break;
1260 case T_INT : chk = new CmpINode(value, _gvn.intcon(0)); break;
1261 case T_ARRAY : // fall through
1262 type = T_OBJECT; // simplify further tests
1263 case T_OBJECT : {
1264 const Type *t = _gvn.type( value );
1265
1266 const TypeOopPtr* tp = t->isa_oopptr();
1267 if (tp != nullptr && !tp->is_loaded()
1268 // Only for do_null_check, not any of its siblings:
1269 && !assert_null && null_control == nullptr) {
1270 // Usually, any field access or invocation on an unloaded oop type
1271 // will simply fail to link, since the statically linked class is
1272 // likely also to be unloaded. However, in -Xcomp mode, sometimes
1273 // the static class is loaded but the sharper oop type is not.
1274 // Rather than checking for this obscure case in lots of places,
1275 // we simply observe that a null check on an unloaded class
1276 // will always be followed by a nonsense operation, so we
1277 // can just issue the uncommon trap here.
1278 // Our access to the unloaded class will only be correct
1279 // after it has been loaded and initialized, which requires
1280 // a trip through the interpreter.
1339 }
1340 Node *oldcontrol = control();
1341 set_control(cfg);
1342 Node *res = cast_not_null(value);
1343 set_control(oldcontrol);
1344 NOT_PRODUCT(explicit_null_checks_elided++);
1345 return res;
1346 }
1347 cfg = IfNode::up_one_dom(cfg, /*linear_only=*/ true);
1348 if (cfg == nullptr) break; // Quit at region nodes
1349 depth++;
1350 }
1351 }
1352
1353 //-----------
1354 // Branch to failure if null
1355 float ok_prob = PROB_MAX; // a priori estimate: nulls never happen
1356 Deoptimization::DeoptReason reason;
1357 if (assert_null) {
1358 reason = Deoptimization::reason_null_assert(speculative);
1359 } else if (type == T_OBJECT) {
1360 reason = Deoptimization::reason_null_check(speculative);
1361 } else {
1362 reason = Deoptimization::Reason_div0_check;
1363 }
1364 // %%% Since Reason_unhandled is not recorded on a per-bytecode basis,
1365 // ciMethodData::has_trap_at will return a conservative -1 if any
1366 // must-be-null assertion has failed. This could cause performance
1367 // problems for a method after its first do_null_assert failure.
1368 // Consider using 'Reason_class_check' instead?
1369
1370 // To cause an implicit null check, we set the not-null probability
1371 // to the maximum (PROB_MAX). For an explicit check the probability
1372 // is set to a smaller value.
1373 if (null_control != nullptr || too_many_traps(reason)) {
1374 // probability is less likely
1375 ok_prob = PROB_LIKELY_MAG(3);
1376 } else if (!assert_null &&
1377 (ImplicitNullCheckThreshold > 0) &&
1378 method() != nullptr &&
1379 (method()->method_data()->trap_count(reason)
1413 }
1414
1415 if (assert_null) {
1416 // Cast obj to null on this path.
1417 replace_in_map(value, zerocon(type));
1418 return zerocon(type);
1419 }
1420
1421 // Cast obj to not-null on this path, if there is no null_control.
1422 // (If there is a null_control, a non-null value may come back to haunt us.)
1423 if (type == T_OBJECT) {
1424 Node* cast = cast_not_null(value, false);
1425 if (null_control == nullptr || (*null_control) == top())
1426 replace_in_map(value, cast);
1427 value = cast;
1428 }
1429
1430 return value;
1431 }
1432
1433
1434 //------------------------------cast_not_null----------------------------------
1435 // Cast obj to not-null on this path
1436 Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) {
1437 const Type *t = _gvn.type(obj);
1438 const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL);
1439 // Object is already not-null?
1440 if( t == t_not_null ) return obj;
1441
1442 Node *cast = new CastPPNode(obj,t_not_null);
1443 cast->init_req(0, control());
1444 cast = _gvn.transform( cast );
1445
1446 // Scan for instances of 'obj' in the current JVM mapping.
1447 // These instances are known to be not-null after the test.
1448 if (do_replace_in_map)
1449 replace_in_map(obj, cast);
1450
1451 return cast; // Return casted value
1452 }
1453
1454 // Sometimes in intrinsics, we implicitly know an object is not null
1455 // (there's no actual null check) so we can cast it to not null. In
1456 // the course of optimizations, the input to the cast can become null.
1543 // These are layered on top of the factory methods in LoadNode and StoreNode,
1544 // and integrate with the parser's memory state and _gvn engine.
1545 //
1546
1547 // factory methods in "int adr_idx"
1548 Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,
1549 int adr_idx,
1550 MemNode::MemOrd mo,
1551 LoadNode::ControlDependency control_dependency,
1552 bool require_atomic_access,
1553 bool unaligned,
1554 bool mismatched,
1555 bool unsafe,
1556 uint8_t barrier_data) {
1557 assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );
1558 const TypePtr* adr_type = nullptr; // debug-mode-only argument
1559 debug_only(adr_type = C->get_adr_type(adr_idx));
1560 Node* mem = memory(adr_idx);
1561 Node* ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, require_atomic_access, unaligned, mismatched, unsafe, barrier_data);
1562 ld = _gvn.transform(ld);
1563 if (((bt == T_OBJECT) && C->do_escape_analysis()) || C->eliminate_boxing()) {
1564 // Improve graph before escape analysis and boxing elimination.
1565 record_for_igvn(ld);
1566 }
1567 return ld;
1568 }
1569
1570 Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,
1571 int adr_idx,
1572 MemNode::MemOrd mo,
1573 bool require_atomic_access,
1574 bool unaligned,
1575 bool mismatched,
1576 bool unsafe,
1577 int barrier_data) {
1578 assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
1579 const TypePtr* adr_type = nullptr;
1580 debug_only(adr_type = C->get_adr_type(adr_idx));
1581 Node *mem = memory(adr_idx);
1582 Node* st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo, require_atomic_access);
1583 if (unaligned) {
1589 if (unsafe) {
1590 st->as_Store()->set_unsafe_access();
1591 }
1592 st->as_Store()->set_barrier_data(barrier_data);
1593 st = _gvn.transform(st);
1594 set_memory(st, adr_idx);
1595 // Back-to-back stores can only remove intermediate store with DU info
1596 // so push on worklist for optimizer.
1597 if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))
1598 record_for_igvn(st);
1599
1600 return st;
1601 }
1602
1603 Node* GraphKit::access_store_at(Node* obj,
1604 Node* adr,
1605 const TypePtr* adr_type,
1606 Node* val,
1607 const Type* val_type,
1608 BasicType bt,
1609 DecoratorSet decorators) {
1610 // Transformation of a value which could be null pointer (CastPP #null)
1611 // could be delayed during Parse (for example, in adjust_map_after_if()).
1612 // Execute transformation here to avoid barrier generation in such case.
1613 if (_gvn.type(val) == TypePtr::NULL_PTR) {
1614 val = _gvn.makecon(TypePtr::NULL_PTR);
1615 }
1616
1617 if (stopped()) {
1618 return top(); // Dead path ?
1619 }
1620
1621 assert(val != nullptr, "not dead path");
1622
1623 C2AccessValuePtr addr(adr, adr_type);
1624 C2AccessValue value(val, val_type);
1625 C2ParseAccess access(this, decorators | C2_WRITE_ACCESS, bt, obj, addr);
1626 if (access.is_raw()) {
1627 return _barrier_set->BarrierSetC2::store_at(access, value);
1628 } else {
1629 return _barrier_set->store_at(access, value);
1630 }
1631 }
1632
1633 Node* GraphKit::access_load_at(Node* obj, // containing obj
1634 Node* adr, // actual address to store val at
1635 const TypePtr* adr_type,
1636 const Type* val_type,
1637 BasicType bt,
1638 DecoratorSet decorators) {
1639 if (stopped()) {
1640 return top(); // Dead path ?
1641 }
1642
1643 C2AccessValuePtr addr(adr, adr_type);
1644 C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, obj, addr);
1645 if (access.is_raw()) {
1646 return _barrier_set->BarrierSetC2::load_at(access, val_type);
1647 } else {
1648 return _barrier_set->load_at(access, val_type);
1649 }
1650 }
1651
1652 Node* GraphKit::access_load(Node* adr, // actual address to load val at
1653 const Type* val_type,
1654 BasicType bt,
1655 DecoratorSet decorators) {
1656 if (stopped()) {
1657 return top(); // Dead path ?
1658 }
1659
1660 C2AccessValuePtr addr(adr, adr->bottom_type()->is_ptr());
1661 C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, nullptr, addr);
1662 if (access.is_raw()) {
1663 return _barrier_set->BarrierSetC2::load_at(access, val_type);
1664 } else {
1729 Node* new_val,
1730 const Type* value_type,
1731 BasicType bt,
1732 DecoratorSet decorators) {
1733 C2AccessValuePtr addr(adr, adr_type);
1734 C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, bt, obj, addr, alias_idx);
1735 if (access.is_raw()) {
1736 return _barrier_set->BarrierSetC2::atomic_add_at(access, new_val, value_type);
1737 } else {
1738 return _barrier_set->atomic_add_at(access, new_val, value_type);
1739 }
1740 }
1741
1742 void GraphKit::access_clone(Node* src, Node* dst, Node* size, bool is_array) {
1743 return _barrier_set->clone(this, src, dst, size, is_array);
1744 }
1745
1746 //-------------------------array_element_address-------------------------
1747 Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,
1748 const TypeInt* sizetype, Node* ctrl) {
1749 uint shift = exact_log2(type2aelembytes(elembt));
1750 uint header = arrayOopDesc::base_offset_in_bytes(elembt);
1751
1752 // short-circuit a common case (saves lots of confusing waste motion)
1753 jint idx_con = find_int_con(idx, -1);
1754 if (idx_con >= 0) {
1755 intptr_t offset = header + ((intptr_t)idx_con << shift);
1756 return basic_plus_adr(ary, offset);
1757 }
1758
1759 // must be correct type for alignment purposes
1760 Node* base = basic_plus_adr(ary, header);
1761 idx = Compile::conv_I2X_index(&_gvn, idx, sizetype, ctrl);
1762 Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) );
1763 return basic_plus_adr(ary, base, scale);
1764 }
1765
1766 //-------------------------load_array_element-------------------------
1767 Node* GraphKit::load_array_element(Node* ary, Node* idx, const TypeAryPtr* arytype, bool set_ctrl) {
1768 const Type* elemtype = arytype->elem();
1769 BasicType elembt = elemtype->array_element_basic_type();
1770 Node* adr = array_element_address(ary, idx, elembt, arytype->size());
1771 if (elembt == T_NARROWOOP) {
1772 elembt = T_OBJECT; // To satisfy switch in LoadNode::make()
1773 }
1774 Node* ld = access_load_at(ary, adr, arytype, elemtype, elembt,
1775 IN_HEAP | IS_ARRAY | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0));
1776 return ld;
1777 }
1778
1779 //-------------------------set_arguments_for_java_call-------------------------
1780 // Arguments (pre-popped from the stack) are taken from the JVMS.
1781 void GraphKit::set_arguments_for_java_call(CallJavaNode* call) {
1782 // Add the call arguments:
1783 uint nargs = call->method()->arg_size();
1784 for (uint i = 0; i < nargs; i++) {
1785 Node* arg = argument(i);
1786 call->init_req(i + TypeFunc::Parms, arg);
1787 }
1788 }
1789
1790 //---------------------------set_edges_for_java_call---------------------------
1791 // Connect a newly created call into the current JVMS.
1792 // A return value node (if any) is returned from set_edges_for_java_call.
1793 void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) {
1794
1795 // Add the predefined inputs:
1796 call->init_req( TypeFunc::Control, control() );
1797 call->init_req( TypeFunc::I_O , i_o() );
1798 call->init_req( TypeFunc::Memory , reset_memory() );
1799 call->init_req( TypeFunc::FramePtr, frameptr() );
1800 call->init_req( TypeFunc::ReturnAdr, top() );
1801
1802 add_safepoint_edges(call, must_throw);
1803
1804 Node* xcall = _gvn.transform(call);
1805
1806 if (xcall == top()) {
1807 set_control(top());
1808 return;
1809 }
1810 assert(xcall == call, "call identity is stable");
1811
1812 // Re-use the current map to produce the result.
1813
1814 set_control(_gvn.transform(new ProjNode(call, TypeFunc::Control)));
1815 set_i_o( _gvn.transform(new ProjNode(call, TypeFunc::I_O , separate_io_proj)));
1816 set_all_memory_call(xcall, separate_io_proj);
1817
1818 //return xcall; // no need, caller already has it
1819 }
1820
1821 Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj, bool deoptimize) {
1822 if (stopped()) return top(); // maybe the call folded up?
1823
1824 // Capture the return value, if any.
1825 Node* ret;
1826 if (call->method() == nullptr ||
1827 call->method()->return_type()->basic_type() == T_VOID)
1828 ret = top();
1829 else ret = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1830
1831 // Note: Since any out-of-line call can produce an exception,
1832 // we always insert an I_O projection from the call into the result.
1833
1834 make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj, deoptimize);
1835
1836 if (separate_io_proj) {
1837 // The caller requested separate projections be used by the fall
1838 // through and exceptional paths, so replace the projections for
1839 // the fall through path.
1840 set_i_o(_gvn.transform( new ProjNode(call, TypeFunc::I_O) ));
1841 set_all_memory(_gvn.transform( new ProjNode(call, TypeFunc::Memory) ));
1842 }
1843 return ret;
1844 }
1845
1846 //--------------------set_predefined_input_for_runtime_call--------------------
1847 // Reading and setting the memory state is way conservative here.
1848 // The real problem is that I am not doing real Type analysis on memory,
1849 // so I cannot distinguish card mark stores from other stores. Across a GC
1850 // point the Store Barrier and the card mark memory has to agree. I cannot
1851 // have a card mark store and its barrier split across the GC point from
1852 // either above or below. Here I get that to happen by reading ALL of memory.
1853 // A better answer would be to separate out card marks from other memory.
1854 // For now, return the input memory state, so that it can be reused
1855 // after the call, if this call has restricted memory effects.
1856 Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) {
1857 // Set fixed predefined input arguments
1858 Node* memory = reset_memory();
1859 Node* m = narrow_mem == nullptr ? memory : narrow_mem;
1860 call->init_req( TypeFunc::Control, control() );
1861 call->init_req( TypeFunc::I_O, top() ); // does no i/o
1862 call->init_req( TypeFunc::Memory, m ); // may gc ptrs
1913 if (use->is_MergeMem()) {
1914 wl.push(use);
1915 }
1916 }
1917 }
1918
1919 // Replace the call with the current state of the kit.
1920 void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes) {
1921 JVMState* ejvms = nullptr;
1922 if (has_exceptions()) {
1923 ejvms = transfer_exceptions_into_jvms();
1924 }
1925
1926 ReplacedNodes replaced_nodes = map()->replaced_nodes();
1927 ReplacedNodes replaced_nodes_exception;
1928 Node* ex_ctl = top();
1929
1930 SafePointNode* final_state = stop();
1931
1932 // Find all the needed outputs of this call
1933 CallProjections callprojs;
1934 call->extract_projections(&callprojs, true);
1935
1936 Unique_Node_List wl;
1937 Node* init_mem = call->in(TypeFunc::Memory);
1938 Node* final_mem = final_state->in(TypeFunc::Memory);
1939 Node* final_ctl = final_state->in(TypeFunc::Control);
1940 Node* final_io = final_state->in(TypeFunc::I_O);
1941
1942 // Replace all the old call edges with the edges from the inlining result
1943 if (callprojs.fallthrough_catchproj != nullptr) {
1944 C->gvn_replace_by(callprojs.fallthrough_catchproj, final_ctl);
1945 }
1946 if (callprojs.fallthrough_memproj != nullptr) {
1947 if (final_mem->is_MergeMem()) {
1948 // Parser's exits MergeMem was not transformed but may be optimized
1949 final_mem = _gvn.transform(final_mem);
1950 }
1951 C->gvn_replace_by(callprojs.fallthrough_memproj, final_mem);
1952 add_mergemem_users_to_worklist(wl, final_mem);
1953 }
1954 if (callprojs.fallthrough_ioproj != nullptr) {
1955 C->gvn_replace_by(callprojs.fallthrough_ioproj, final_io);
1956 }
1957
1958 // Replace the result with the new result if it exists and is used
1959 if (callprojs.resproj != nullptr && result != nullptr) {
1960 C->gvn_replace_by(callprojs.resproj, result);
1961 }
1962
1963 if (ejvms == nullptr) {
1964 // No exception edges to simply kill off those paths
1965 if (callprojs.catchall_catchproj != nullptr) {
1966 C->gvn_replace_by(callprojs.catchall_catchproj, C->top());
1967 }
1968 if (callprojs.catchall_memproj != nullptr) {
1969 C->gvn_replace_by(callprojs.catchall_memproj, C->top());
1970 }
1971 if (callprojs.catchall_ioproj != nullptr) {
1972 C->gvn_replace_by(callprojs.catchall_ioproj, C->top());
1973 }
1974 // Replace the old exception object with top
1975 if (callprojs.exobj != nullptr) {
1976 C->gvn_replace_by(callprojs.exobj, C->top());
1977 }
1978 } else {
1979 GraphKit ekit(ejvms);
1980
1981 // Load my combined exception state into the kit, with all phis transformed:
1982 SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();
1983 replaced_nodes_exception = ex_map->replaced_nodes();
1984
1985 Node* ex_oop = ekit.use_exception_state(ex_map);
1986
1987 if (callprojs.catchall_catchproj != nullptr) {
1988 C->gvn_replace_by(callprojs.catchall_catchproj, ekit.control());
1989 ex_ctl = ekit.control();
1990 }
1991 if (callprojs.catchall_memproj != nullptr) {
1992 Node* ex_mem = ekit.reset_memory();
1993 C->gvn_replace_by(callprojs.catchall_memproj, ex_mem);
1994 add_mergemem_users_to_worklist(wl, ex_mem);
1995 }
1996 if (callprojs.catchall_ioproj != nullptr) {
1997 C->gvn_replace_by(callprojs.catchall_ioproj, ekit.i_o());
1998 }
1999
2000 // Replace the old exception object with the newly created one
2001 if (callprojs.exobj != nullptr) {
2002 C->gvn_replace_by(callprojs.exobj, ex_oop);
2003 }
2004 }
2005
2006 // Disconnect the call from the graph
2007 call->disconnect_inputs(C);
2008 C->gvn_replace_by(call, C->top());
2009
2010 // Clean up any MergeMems that feed other MergeMems since the
2011 // optimizer doesn't like that.
2012 while (wl.size() > 0) {
2013 _gvn.transform(wl.pop());
2014 }
2015
2016 if (callprojs.fallthrough_catchproj != nullptr && !final_ctl->is_top() && do_replaced_nodes) {
2017 replaced_nodes.apply(C, final_ctl);
2018 }
2019 if (!ex_ctl->is_top() && do_replaced_nodes) {
2020 replaced_nodes_exception.apply(C, ex_ctl);
2021 }
2022 }
2023
2024
2025 //------------------------------increment_counter------------------------------
2026 // for statistics: increment a VM counter by 1
2027
2028 void GraphKit::increment_counter(address counter_addr) {
2029 Node* adr1 = makecon(TypeRawPtr::make(counter_addr));
2030 increment_counter(adr1);
2031 }
2032
2033 void GraphKit::increment_counter(Node* counter_addr) {
2034 int adr_type = Compile::AliasIdxRaw;
2035 Node* ctrl = control();
2036 Node* cnt = make_load(ctrl, counter_addr, TypeLong::LONG, T_LONG, adr_type, MemNode::unordered);
2195 *
2196 * @param n node that the type applies to
2197 * @param exact_kls type from profiling
2198 * @param maybe_null did profiling see null?
2199 *
2200 * @return node with improved type
2201 */
2202 Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, ProfilePtrKind ptr_kind) {
2203 const Type* current_type = _gvn.type(n);
2204 assert(UseTypeSpeculation, "type speculation must be on");
2205
2206 const TypePtr* speculative = current_type->speculative();
2207
2208 // Should the klass from the profile be recorded in the speculative type?
2209 if (current_type->would_improve_type(exact_kls, jvms()->depth())) {
2210 const TypeKlassPtr* tklass = TypeKlassPtr::make(exact_kls, Type::trust_interfaces);
2211 const TypeOopPtr* xtype = tklass->as_instance_type();
2212 assert(xtype->klass_is_exact(), "Should be exact");
2213 // Any reason to believe n is not null (from this profiling or a previous one)?
2214 assert(ptr_kind != ProfileAlwaysNull, "impossible here");
2215 const TypePtr* ptr = (ptr_kind == ProfileMaybeNull && current_type->speculative_maybe_null()) ? TypePtr::BOTTOM : TypePtr::NOTNULL;
2216 // record the new speculative type's depth
2217 speculative = xtype->cast_to_ptr_type(ptr->ptr())->is_ptr();
2218 speculative = speculative->with_inline_depth(jvms()->depth());
2219 } else if (current_type->would_improve_ptr(ptr_kind)) {
2220 // Profiling report that null was never seen so we can change the
2221 // speculative type to non null ptr.
2222 if (ptr_kind == ProfileAlwaysNull) {
2223 speculative = TypePtr::NULL_PTR;
2224 } else {
2225 assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement");
2226 const TypePtr* ptr = TypePtr::NOTNULL;
2227 if (speculative != nullptr) {
2228 speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr();
2229 } else {
2230 speculative = ptr;
2231 }
2232 }
2233 }
2234
2235 if (speculative != current_type->speculative()) {
2236 // Build a type with a speculative type (what we think we know
2237 // about the type but will need a guard when we use it)
2238 const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::OffsetBot, TypeOopPtr::InstanceBot, speculative);
2239 // We're changing the type, we need a new CheckCast node to carry
2240 // the new type. The new type depends on the control: what
2241 // profiling tells us is only valid from here as far as we can
2242 // tell.
2243 Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));
2244 cast = _gvn.transform(cast);
2245 replace_in_map(n, cast);
2246 n = cast;
2247 }
2248
2249 return n;
2250 }
2251
2252 /**
2253 * Record profiling data from receiver profiling at an invoke with the
2254 * type system so that it can propagate it (speculation)
2255 *
2256 * @param n receiver node
2257 *
2258 * @return node with improved type
2259 */
2260 Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {
2261 if (!UseTypeSpeculation) {
2262 return n;
2263 }
2264 ciKlass* exact_kls = profile_has_unique_klass();
2265 ProfilePtrKind ptr_kind = ProfileMaybeNull;
2266 if ((java_bc() == Bytecodes::_checkcast ||
2267 java_bc() == Bytecodes::_instanceof ||
2268 java_bc() == Bytecodes::_aastore) &&
2269 method()->method_data()->is_mature()) {
2270 ciProfileData* data = method()->method_data()->bci_to_data(bci());
2271 if (data != nullptr) {
2272 if (!data->as_BitData()->null_seen()) {
2273 ptr_kind = ProfileNeverNull;
2274 } else {
2275 assert(data->is_ReceiverTypeData(), "bad profile data type");
2276 ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
2277 uint i = 0;
2278 for (; i < call->row_limit(); i++) {
2279 ciKlass* receiver = call->receiver(i);
2280 if (receiver != nullptr) {
2281 break;
2282 }
2283 }
2284 ptr_kind = (i == call->row_limit()) ? ProfileAlwaysNull : ProfileMaybeNull;
2285 }
2286 }
2287 }
2288 return record_profile_for_speculation(n, exact_kls, ptr_kind);
2289 }
2290
2291 /**
2292 * Record profiling data from argument profiling at an invoke with the
2293 * type system so that it can propagate it (speculation)
2294 *
2295 * @param dest_method target method for the call
2296 * @param bc what invoke bytecode is this?
2297 */
2298 void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {
2299 if (!UseTypeSpeculation) {
2300 return;
2301 }
2302 const TypeFunc* tf = TypeFunc::make(dest_method);
2303 int nargs = tf->domain()->cnt() - TypeFunc::Parms;
2304 int skip = Bytecodes::has_receiver(bc) ? 1 : 0;
2305 for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {
2306 const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);
2307 if (is_reference_type(targ->basic_type())) {
2308 ProfilePtrKind ptr_kind = ProfileMaybeNull;
2309 ciKlass* better_type = nullptr;
2310 if (method()->argument_profiled_type(bci(), i, better_type, ptr_kind)) {
2311 record_profile_for_speculation(argument(j), better_type, ptr_kind);
2312 }
2313 i++;
2314 }
2315 }
2316 }
2317
2318 /**
2319 * Record profiling data from parameter profiling at an invoke with
2320 * the type system so that it can propagate it (speculation)
2321 */
2322 void GraphKit::record_profiled_parameters_for_speculation() {
2323 if (!UseTypeSpeculation) {
2324 return;
2325 }
2326 for (int i = 0, j = 0; i < method()->arg_size() ; i++) {
2340 * the type system so that it can propagate it (speculation)
2341 */
2342 void GraphKit::record_profiled_return_for_speculation() {
2343 if (!UseTypeSpeculation) {
2344 return;
2345 }
2346 ProfilePtrKind ptr_kind = ProfileMaybeNull;
2347 ciKlass* better_type = nullptr;
2348 if (method()->return_profiled_type(bci(), better_type, ptr_kind)) {
2349 // If profiling reports a single type for the return value,
2350 // feed it to the type system so it can propagate it as a
2351 // speculative type
2352 record_profile_for_speculation(stack(sp()-1), better_type, ptr_kind);
2353 }
2354 }
2355
2356 void GraphKit::round_double_arguments(ciMethod* dest_method) {
2357 if (Matcher::strict_fp_requires_explicit_rounding) {
2358 // (Note: TypeFunc::make has a cache that makes this fast.)
2359 const TypeFunc* tf = TypeFunc::make(dest_method);
2360 int nargs = tf->domain()->cnt() - TypeFunc::Parms;
2361 for (int j = 0; j < nargs; j++) {
2362 const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);
2363 if (targ->basic_type() == T_DOUBLE) {
2364 // If any parameters are doubles, they must be rounded before
2365 // the call, dprecision_rounding does gvn.transform
2366 Node *arg = argument(j);
2367 arg = dprecision_rounding(arg);
2368 set_argument(j, arg);
2369 }
2370 }
2371 }
2372 }
2373
2374 // rounding for strict float precision conformance
2375 Node* GraphKit::precision_rounding(Node* n) {
2376 if (Matcher::strict_fp_requires_explicit_rounding) {
2377 #ifdef IA32
2378 if (UseSSE == 0) {
2379 return _gvn.transform(new RoundFloatNode(0, n));
2380 }
2381 #else
2382 Unimplemented();
2491 // The first null ends the list.
2492 Node* parm0, Node* parm1,
2493 Node* parm2, Node* parm3,
2494 Node* parm4, Node* parm5,
2495 Node* parm6, Node* parm7) {
2496 assert(call_addr != nullptr, "must not call null targets");
2497
2498 // Slow-path call
2499 bool is_leaf = !(flags & RC_NO_LEAF);
2500 bool has_io = (!is_leaf && !(flags & RC_NO_IO));
2501 if (call_name == nullptr) {
2502 assert(!is_leaf, "must supply name for leaf");
2503 call_name = OptoRuntime::stub_name(call_addr);
2504 }
2505 CallNode* call;
2506 if (!is_leaf) {
2507 call = new CallStaticJavaNode(call_type, call_addr, call_name, adr_type);
2508 } else if (flags & RC_NO_FP) {
2509 call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
2510 } else if (flags & RC_VECTOR){
2511 uint num_bits = call_type->range()->field_at(TypeFunc::Parms)->is_vect()->length_in_bytes() * BitsPerByte;
2512 call = new CallLeafVectorNode(call_type, call_addr, call_name, adr_type, num_bits);
2513 } else {
2514 call = new CallLeafNode(call_type, call_addr, call_name, adr_type);
2515 }
2516
2517 // The following is similar to set_edges_for_java_call,
2518 // except that the memory effects of the call are restricted to AliasIdxRaw.
2519
2520 // Slow path call has no side-effects, uses few values
2521 bool wide_in = !(flags & RC_NARROW_MEM);
2522 bool wide_out = (C->get_alias_index(adr_type) == Compile::AliasIdxBot);
2523
2524 Node* prev_mem = nullptr;
2525 if (wide_in) {
2526 prev_mem = set_predefined_input_for_runtime_call(call);
2527 } else {
2528 assert(!wide_out, "narrow in => narrow out");
2529 Node* narrow_mem = memory(adr_type);
2530 prev_mem = set_predefined_input_for_runtime_call(call, narrow_mem);
2531 }
2571
2572 if (has_io) {
2573 set_i_o(_gvn.transform(new ProjNode(call, TypeFunc::I_O)));
2574 }
2575 return call;
2576
2577 }
2578
2579 // i2b
2580 Node* GraphKit::sign_extend_byte(Node* in) {
2581 Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(24)));
2582 return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(24)));
2583 }
2584
2585 // i2s
2586 Node* GraphKit::sign_extend_short(Node* in) {
2587 Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(16)));
2588 return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(16)));
2589 }
2590
2591 //------------------------------merge_memory-----------------------------------
2592 // Merge memory from one path into the current memory state.
2593 void GraphKit::merge_memory(Node* new_mem, Node* region, int new_path) {
2594 for (MergeMemStream mms(merged_memory(), new_mem->as_MergeMem()); mms.next_non_empty2(); ) {
2595 Node* old_slice = mms.force_memory();
2596 Node* new_slice = mms.memory2();
2597 if (old_slice != new_slice) {
2598 PhiNode* phi;
2599 if (old_slice->is_Phi() && old_slice->as_Phi()->region() == region) {
2600 if (mms.is_empty()) {
2601 // clone base memory Phi's inputs for this memory slice
2602 assert(old_slice == mms.base_memory(), "sanity");
2603 phi = PhiNode::make(region, nullptr, Type::MEMORY, mms.adr_type(C));
2604 _gvn.set_type(phi, Type::MEMORY);
2605 for (uint i = 1; i < phi->req(); i++) {
2606 phi->init_req(i, old_slice->in(i));
2607 }
2608 } else {
2609 phi = old_slice->as_Phi(); // Phi was generated already
2610 }
2824
2825 // Now do a linear scan of the secondary super-klass array. Again, no real
2826 // performance impact (too rare) but it's gotta be done.
2827 // Since the code is rarely used, there is no penalty for moving it
2828 // out of line, and it can only improve I-cache density.
2829 // The decision to inline or out-of-line this final check is platform
2830 // dependent, and is found in the AD file definition of PartialSubtypeCheck.
2831 Node* psc = gvn.transform(
2832 new PartialSubtypeCheckNode(*ctrl, subklass, superklass));
2833
2834 IfNode *iff4 = gen_subtype_check_compare(*ctrl, psc, gvn.zerocon(T_OBJECT), BoolTest::ne, PROB_FAIR, gvn, T_ADDRESS);
2835 r_not_subtype->init_req(2, gvn.transform(new IfTrueNode (iff4)));
2836 r_ok_subtype ->init_req(3, gvn.transform(new IfFalseNode(iff4)));
2837
2838 // Return false path; set default control to true path.
2839 *ctrl = gvn.transform(r_ok_subtype);
2840 return gvn.transform(r_not_subtype);
2841 }
2842
2843 Node* GraphKit::gen_subtype_check(Node* obj_or_subklass, Node* superklass) {
2844 bool expand_subtype_check = C->post_loop_opts_phase() || // macro node expansion is over
2845 ExpandSubTypeCheckAtParseTime; // forced expansion
2846 if (expand_subtype_check) {
2847 MergeMemNode* mem = merged_memory();
2848 Node* ctrl = control();
2849 Node* subklass = obj_or_subklass;
2850 if (!_gvn.type(obj_or_subklass)->isa_klassptr()) {
2851 subklass = load_object_klass(obj_or_subklass);
2852 }
2853
2854 Node* n = Phase::gen_subtype_check(subklass, superklass, &ctrl, mem, _gvn);
2855 set_control(ctrl);
2856 return n;
2857 }
2858
2859 Node* check = _gvn.transform(new SubTypeCheckNode(C, obj_or_subklass, superklass));
2860 Node* bol = _gvn.transform(new BoolNode(check, BoolTest::eq));
2861 IfNode* iff = create_and_xform_if(control(), bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
2862 set_control(_gvn.transform(new IfTrueNode(iff)));
2863 return _gvn.transform(new IfFalseNode(iff));
2864 }
2865
2866 // Profile-driven exact type check:
2867 Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,
2868 float prob,
2869 Node* *casted_receiver) {
2870 assert(!klass->is_interface(), "no exact type check on interfaces");
2871
2872 const TypeKlassPtr* tklass = TypeKlassPtr::make(klass, Type::trust_interfaces);
2873 Node* recv_klass = load_object_klass(receiver);
2874 Node* want_klass = makecon(tklass);
2875 Node* cmp = _gvn.transform(new CmpPNode(recv_klass, want_klass));
2876 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
2877 IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);
2878 set_control( _gvn.transform(new IfTrueNode (iff)));
2879 Node* fail = _gvn.transform(new IfFalseNode(iff));
2880
2881 if (!stopped()) {
2882 const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
2883 const TypeOopPtr* recvx_type = tklass->as_instance_type();
2884 assert(recvx_type->klass_is_exact(), "");
2885
2886 if (!receiver_type->higher_equal(recvx_type)) { // ignore redundant casts
2887 // Subsume downstream occurrences of receiver with a cast to
2888 // recv_xtype, since now we know what the type will be.
2889 Node* cast = new CheckCastPPNode(control(), receiver, recvx_type);
2890 (*casted_receiver) = _gvn.transform(cast);
2891 // (User must make the replace_in_map call.)
2892 }
2893 }
2894
2895 return fail;
2896 }
2897
2898 //------------------------------subtype_check_receiver-------------------------
2899 Node* GraphKit::subtype_check_receiver(Node* receiver, ciKlass* klass,
2900 Node** casted_receiver) {
2901 const TypeKlassPtr* tklass = TypeKlassPtr::make(klass, Type::trust_interfaces)->try_improve();
2902 Node* want_klass = makecon(tklass);
2903
2904 Node* slow_ctl = gen_subtype_check(receiver, want_klass);
2905
2906 // Ignore interface type information until interface types are properly tracked.
2907 if (!stopped() && !klass->is_interface()) {
2908 const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
2909 const TypeOopPtr* recv_type = tklass->cast_to_exactness(false)->is_klassptr()->as_instance_type();
2910 if (!receiver_type->higher_equal(recv_type)) { // ignore redundant casts
2911 Node* cast = new CheckCastPPNode(control(), receiver, recv_type);
2912 (*casted_receiver) = _gvn.transform(cast);
2913 }
2914 }
2915
2916 return slow_ctl;
2917 }
2918
2919 //------------------------------seems_never_null-------------------------------
2920 // Use null_seen information if it is available from the profile.
2921 // If we see an unexpected null at a type check we record it and force a
2922 // recompile; the offending check will be recompiled to handle nulls.
2923 // If we see several offending BCIs, then all checks in the
2924 // method will be recompiled.
2925 bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) {
2926 speculating = !_gvn.type(obj)->speculative_maybe_null();
2927 Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating);
2928 if (UncommonNullCast // Cutout for this technique
2929 && obj != null() // And not the -Xcomp stupid case?
2930 && !too_many_traps(reason)
2931 ) {
2932 if (speculating) {
2933 return true;
2934 }
2935 if (data == nullptr)
2936 // Edge case: no mature data. Be optimistic here.
2937 return true;
2938 // If the profile has not seen a null, assume it won't happen.
2939 assert(java_bc() == Bytecodes::_checkcast ||
2940 java_bc() == Bytecodes::_instanceof ||
2941 java_bc() == Bytecodes::_aastore, "MDO must collect null_seen bit here");
2942 return !data->as_BitData()->null_seen();
2943 }
2944 speculating = false;
2945 return false;
2946 }
2947
2948 void GraphKit::guard_klass_being_initialized(Node* klass) {
2949 int init_state_off = in_bytes(InstanceKlass::init_state_offset());
2950 Node* adr = basic_plus_adr(top(), klass, init_state_off);
2951 Node* init_state = LoadNode::make(_gvn, nullptr, immutable_memory(), adr,
2952 adr->bottom_type()->is_ptr(), TypeInt::BYTE,
2953 T_BYTE, MemNode::unordered);
2954 init_state = _gvn.transform(init_state);
2955
2956 Node* being_initialized_state = makecon(TypeInt::make(InstanceKlass::being_initialized));
2957
2958 Node* chk = _gvn.transform(new CmpINode(being_initialized_state, init_state));
2959 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
2960
2961 { BuildCutout unless(this, tst, PROB_MAX);
3001
3002 //------------------------maybe_cast_profiled_receiver-------------------------
3003 // If the profile has seen exactly one type, narrow to exactly that type.
3004 // Subsequent type checks will always fold up.
3005 Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,
3006 const TypeKlassPtr* require_klass,
3007 ciKlass* spec_klass,
3008 bool safe_for_replace) {
3009 if (!UseTypeProfile || !TypeProfileCasts) return nullptr;
3010
3011 Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != nullptr);
3012
3013 // Make sure we haven't already deoptimized from this tactic.
3014 if (too_many_traps_or_recompiles(reason))
3015 return nullptr;
3016
3017 // (No, this isn't a call, but it's enough like a virtual call
3018 // to use the same ciMethod accessor to get the profile info...)
3019 // If we have a speculative type use it instead of profiling (which
3020 // may not help us)
3021 ciKlass* exact_kls = spec_klass == nullptr ? profile_has_unique_klass() : spec_klass;
3022 if (exact_kls != nullptr) {// no cast failures here
3023 if (require_klass == nullptr ||
3024 C->static_subtype_check(require_klass, TypeKlassPtr::make(exact_kls, Type::trust_interfaces)) == Compile::SSC_always_true) {
3025 // If we narrow the type to match what the type profile sees or
3026 // the speculative type, we can then remove the rest of the
3027 // cast.
3028 // This is a win, even if the exact_kls is very specific,
3029 // because downstream operations, such as method calls,
3030 // will often benefit from the sharper type.
3031 Node* exact_obj = not_null_obj; // will get updated in place...
3032 Node* slow_ctl = type_check_receiver(exact_obj, exact_kls, 1.0,
3033 &exact_obj);
3034 { PreserveJVMState pjvms(this);
3035 set_control(slow_ctl);
3036 uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
3037 }
3038 if (safe_for_replace) {
3039 replace_in_map(not_null_obj, exact_obj);
3040 }
3041 return exact_obj;
3131 // If not_null_obj is dead, only null-path is taken
3132 if (stopped()) { // Doing instance-of on a null?
3133 set_control(null_ctl);
3134 return intcon(0);
3135 }
3136 region->init_req(_null_path, null_ctl);
3137 phi ->init_req(_null_path, intcon(0)); // Set null path value
3138 if (null_ctl == top()) {
3139 // Do this eagerly, so that pattern matches like is_diamond_phi
3140 // will work even during parsing.
3141 assert(_null_path == PATH_LIMIT-1, "delete last");
3142 region->del_req(_null_path);
3143 phi ->del_req(_null_path);
3144 }
3145
3146 // Do we know the type check always succeed?
3147 bool known_statically = false;
3148 if (_gvn.type(superklass)->singleton()) {
3149 const TypeKlassPtr* superk = _gvn.type(superklass)->is_klassptr();
3150 const TypeKlassPtr* subk = _gvn.type(obj)->is_oopptr()->as_klass_type();
3151 if (subk->is_loaded()) {
3152 int static_res = C->static_subtype_check(superk, subk);
3153 known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false);
3154 }
3155 }
3156
3157 if (!known_statically) {
3158 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3159 // We may not have profiling here or it may not help us. If we
3160 // have a speculative type use it to perform an exact cast.
3161 ciKlass* spec_obj_type = obj_type->speculative_type();
3162 if (spec_obj_type != nullptr || (ProfileDynamicTypes && data != nullptr)) {
3163 Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, nullptr, spec_obj_type, safe_for_replace);
3164 if (stopped()) { // Profile disagrees with this path.
3165 set_control(null_ctl); // Null is the only remaining possibility.
3166 return intcon(0);
3167 }
3168 if (cast_obj != nullptr) {
3169 not_null_obj = cast_obj;
3170 }
3171 }
3187 record_for_igvn(region);
3188
3189 // If we know the type check always succeeds then we don't use the
3190 // profiling data at this bytecode. Don't lose it, feed it to the
3191 // type system as a speculative type.
3192 if (safe_for_replace) {
3193 Node* casted_obj = record_profiled_receiver_for_speculation(obj);
3194 replace_in_map(obj, casted_obj);
3195 }
3196
3197 return _gvn.transform(phi);
3198 }
3199
3200 //-------------------------------gen_checkcast---------------------------------
3201 // Generate a checkcast idiom. Used by both the checkcast bytecode and the
3202 // array store bytecode. Stack must be as-if BEFORE doing the bytecode so the
3203 // uncommon-trap paths work. Adjust stack after this call.
3204 // If failure_control is supplied and not null, it is filled in with
3205 // the control edge for the cast failure. Otherwise, an appropriate
3206 // uncommon trap or exception is thrown.
3207 Node* GraphKit::gen_checkcast(Node *obj, Node* superklass,
3208 Node* *failure_control) {
3209 kill_dead_locals(); // Benefit all the uncommon traps
3210 const TypeKlassPtr *tk = _gvn.type(superklass)->is_klassptr()->try_improve();
3211 const TypeOopPtr *toop = tk->cast_to_exactness(false)->as_instance_type();
3212
3213 // Fast cutout: Check the case that the cast is vacuously true.
3214 // This detects the common cases where the test will short-circuit
3215 // away completely. We do this before we perform the null check,
3216 // because if the test is going to turn into zero code, we don't
3217 // want a residual null check left around. (Causes a slowdown,
3218 // for example, in some objArray manipulations, such as a[i]=a[j].)
3219 if (tk->singleton()) {
3220 const TypeOopPtr* objtp = _gvn.type(obj)->isa_oopptr();
3221 if (objtp != nullptr) {
3222 switch (C->static_subtype_check(tk, objtp->as_klass_type())) {
3223 case Compile::SSC_always_true:
3224 // If we know the type check always succeed then we don't use
3225 // the profiling data at this bytecode. Don't lose it, feed it
3226 // to the type system as a speculative type.
3227 return record_profiled_receiver_for_speculation(obj);
3228 case Compile::SSC_always_false:
3229 // It needs a null check because a null will *pass* the cast check.
3230 // A non-null value will always produce an exception.
3231 if (!objtp->maybe_null()) {
3232 bool is_aastore = (java_bc() == Bytecodes::_aastore);
3233 Deoptimization::DeoptReason reason = is_aastore ?
3234 Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3235 builtin_throw(reason);
3236 return top();
3237 } else if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
3238 return null_assert(obj);
3239 }
3240 break; // Fall through to full check
3241 default:
3242 break;
3243 }
3244 }
3245 }
3246
3247 ciProfileData* data = nullptr;
3248 bool safe_for_replace = false;
3249 if (failure_control == nullptr) { // use MDO in regular case only
3250 assert(java_bc() == Bytecodes::_aastore ||
3251 java_bc() == Bytecodes::_checkcast,
3252 "interpreter profiles type checks only for these BCs");
3253 data = method()->method_data()->bci_to_data(bci());
3254 safe_for_replace = true;
3255 }
3256
3257 // Make the merge point
3258 enum { _obj_path = 1, _null_path, PATH_LIMIT };
3259 RegionNode* region = new RegionNode(PATH_LIMIT);
3260 Node* phi = new PhiNode(region, toop);
3261 C->set_has_split_ifs(true); // Has chance for split-if optimization
3262
3263 // Use null-cast information if it is available
3264 bool speculative_not_null = false;
3265 bool never_see_null = ((failure_control == nullptr) // regular case only
3266 && seems_never_null(obj, data, speculative_not_null));
3267
3268 // Null check; get casted pointer; set region slot 3
3269 Node* null_ctl = top();
3270 Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3271
3272 // If not_null_obj is dead, only null-path is taken
3273 if (stopped()) { // Doing instance-of on a null?
3274 set_control(null_ctl);
3275 return null();
3276 }
3277 region->init_req(_null_path, null_ctl);
3278 phi ->init_req(_null_path, null()); // Set null path value
3279 if (null_ctl == top()) {
3280 // Do this eagerly, so that pattern matches like is_diamond_phi
3281 // will work even during parsing.
3282 assert(_null_path == PATH_LIMIT-1, "delete last");
3283 region->del_req(_null_path);
3284 phi ->del_req(_null_path);
3285 }
3286
3287 Node* cast_obj = nullptr;
3288 if (tk->klass_is_exact()) {
3289 // The following optimization tries to statically cast the speculative type of the object
3290 // (for example obtained during profiling) to the type of the superklass and then do a
3291 // dynamic check that the type of the object is what we expect. To work correctly
3292 // for checkcast and aastore the type of superklass should be exact.
3293 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3294 // We may not have profiling here or it may not help us. If we have
3295 // a speculative type use it to perform an exact cast.
3296 ciKlass* spec_obj_type = obj_type->speculative_type();
3297 if (spec_obj_type != nullptr || data != nullptr) {
3298 cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk, spec_obj_type, safe_for_replace);
3299 if (cast_obj != nullptr) {
3300 if (failure_control != nullptr) // failure is now impossible
3301 (*failure_control) = top();
3302 // adjust the type of the phi to the exact klass:
3303 phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
3304 }
3305 }
3306 }
3307
3308 if (cast_obj == nullptr) {
3309 // Generate the subtype check
3310 Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass );
3311
3312 // Plug in success path into the merge
3313 cast_obj = _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop));
3314 // Failure path ends in uncommon trap (or may be dead - failure impossible)
3315 if (failure_control == nullptr) {
3316 if (not_subtype_ctrl != top()) { // If failure is possible
3317 PreserveJVMState pjvms(this);
3318 set_control(not_subtype_ctrl);
3319 bool is_aastore = (java_bc() == Bytecodes::_aastore);
3320 Deoptimization::DeoptReason reason = is_aastore ?
3321 Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3322 builtin_throw(reason);
3323 }
3324 } else {
3325 (*failure_control) = not_subtype_ctrl;
3326 }
3327 }
3328
3329 region->init_req(_obj_path, control());
3330 phi ->init_req(_obj_path, cast_obj);
3331
3332 // A merge of null or Casted-NotNull obj
3333 Node* res = _gvn.transform(phi);
3334
3335 // Note I do NOT always 'replace_in_map(obj,result)' here.
3336 // if( tk->klass()->can_be_primary_super() )
3337 // This means that if I successfully store an Object into an array-of-String
3338 // I 'forget' that the Object is really now known to be a String. I have to
3339 // do this because we don't have true union types for interfaces - if I store
3340 // a Baz into an array-of-Interface and then tell the optimizer it's an
3341 // Interface, I forget that it's also a Baz and cannot do Baz-like field
3342 // references to it. FIX THIS WHEN UNION TYPES APPEAR!
3343 // replace_in_map( obj, res );
3344
3345 // Return final merged results
3346 set_control( _gvn.transform(region) );
3347 record_for_igvn(region);
3348
3349 return record_profiled_receiver_for_speculation(res);
3350 }
3351
3352 //------------------------------next_monitor-----------------------------------
3353 // What number should be given to the next monitor?
3354 int GraphKit::next_monitor() {
3355 int current = jvms()->monitor_depth()* C->sync_stack_slots();
3356 int next = current + C->sync_stack_slots();
3357 // Keep the toplevel high water mark current:
3358 if (C->fixed_slots() < next) C->set_fixed_slots(next);
3359 return current;
3360 }
3361
3362 //------------------------------insert_mem_bar---------------------------------
3363 // Memory barrier to avoid floating things around
3364 // The membar serves as a pinch point between both control and all memory slices.
3365 Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {
3366 MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
3367 mb->init_req(TypeFunc::Control, control());
3368 mb->init_req(TypeFunc::Memory, reset_memory());
3369 Node* membar = _gvn.transform(mb);
3397 }
3398 Node* membar = _gvn.transform(mb);
3399 set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3400 if (alias_idx == Compile::AliasIdxBot) {
3401 merged_memory()->set_base_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)));
3402 } else {
3403 set_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)),alias_idx);
3404 }
3405 return membar;
3406 }
3407
3408 //------------------------------shared_lock------------------------------------
3409 // Emit locking code.
3410 FastLockNode* GraphKit::shared_lock(Node* obj) {
3411 // bci is either a monitorenter bc or InvocationEntryBci
3412 // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3413 assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3414
3415 if( !GenerateSynchronizationCode )
3416 return nullptr; // Not locking things?
3417 if (stopped()) // Dead monitor?
3418 return nullptr;
3419
3420 assert(dead_locals_are_killed(), "should kill locals before sync. point");
3421
3422 // Box the stack location
3423 Node* box = _gvn.transform(new BoxLockNode(next_monitor()));
3424 Node* mem = reset_memory();
3425
3426 FastLockNode * flock = _gvn.transform(new FastLockNode(0, obj, box) )->as_FastLock();
3427
3428 // Create the rtm counters for this fast lock if needed.
3429 flock->create_rtm_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3430
3431 // Add monitor to debug info for the slow path. If we block inside the
3432 // slow path and de-opt, we need the monitor hanging around
3433 map()->push_monitor( flock );
3434
3435 const TypeFunc *tf = LockNode::lock_type();
3436 LockNode *lock = new LockNode(C, tf);
3465 }
3466 #endif
3467
3468 return flock;
3469 }
3470
3471
3472 //------------------------------shared_unlock----------------------------------
3473 // Emit unlocking code.
3474 void GraphKit::shared_unlock(Node* box, Node* obj) {
3475 // bci is either a monitorenter bc or InvocationEntryBci
3476 // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3477 assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3478
3479 if( !GenerateSynchronizationCode )
3480 return;
3481 if (stopped()) { // Dead monitor?
3482 map()->pop_monitor(); // Kill monitor from debug info
3483 return;
3484 }
3485
3486 // Memory barrier to avoid floating things down past the locked region
3487 insert_mem_bar(Op_MemBarReleaseLock);
3488
3489 const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();
3490 UnlockNode *unlock = new UnlockNode(C, tf);
3491 #ifdef ASSERT
3492 unlock->set_dbg_jvms(sync_jvms());
3493 #endif
3494 uint raw_idx = Compile::AliasIdxRaw;
3495 unlock->init_req( TypeFunc::Control, control() );
3496 unlock->init_req( TypeFunc::Memory , memory(raw_idx) );
3497 unlock->init_req( TypeFunc::I_O , top() ) ; // does no i/o
3498 unlock->init_req( TypeFunc::FramePtr, frameptr() );
3499 unlock->init_req( TypeFunc::ReturnAdr, top() );
3500
3501 unlock->init_req(TypeFunc::Parms + 0, obj);
3502 unlock->init_req(TypeFunc::Parms + 1, box);
3503 unlock = _gvn.transform(unlock)->as_Unlock();
3504
3505 Node* mem = reset_memory();
3506
3507 // unlock has no side-effects, sets few values
3508 set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);
3509
3510 // Kill monitor from debug info
3511 map()->pop_monitor( );
3512 }
3513
3514 //-------------------------------get_layout_helper-----------------------------
3515 // If the given klass is a constant or known to be an array,
3516 // fetch the constant layout helper value into constant_value
3517 // and return null. Otherwise, load the non-constant
3518 // layout helper value, and return the node which represents it.
3519 // This two-faced routine is useful because allocation sites
3520 // almost always feature constant types.
3521 Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {
3522 const TypeKlassPtr* inst_klass = _gvn.type(klass_node)->isa_klassptr();
3523 if (!StressReflectiveCode && inst_klass != nullptr) {
3524 bool xklass = inst_klass->klass_is_exact();
3525 if (xklass || inst_klass->isa_aryklassptr()) {
3526 jint lhelper;
3527 if (inst_klass->isa_aryklassptr()) {
3528 BasicType elem = inst_klass->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type();
3529 if (is_reference_type(elem, true)) {
3530 elem = T_OBJECT;
3531 }
3532 lhelper = Klass::array_layout_helper(elem);
3533 } else {
3534 lhelper = inst_klass->is_instklassptr()->exact_klass()->layout_helper();
3535 }
3536 if (lhelper != Klass::_lh_neutral_value) {
3537 constant_value = lhelper;
3538 return (Node*) nullptr;
3539 }
3540 }
3541 }
3542 constant_value = Klass::_lh_neutral_value; // put in a known value
3543 Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset()));
3544 return make_load(nullptr, lhp, TypeInt::INT, T_INT, MemNode::unordered);
3545 }
3546
3547 // We just put in an allocate/initialize with a big raw-memory effect.
3548 // Hook selected additional alias categories on the initialization.
3549 static void hook_memory_on_init(GraphKit& kit, int alias_idx,
3550 MergeMemNode* init_in_merge,
3551 Node* init_out_raw) {
3552 DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());
3553 assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");
3554
3555 Node* prevmem = kit.memory(alias_idx);
3556 init_in_merge->set_memory_at(alias_idx, prevmem);
3557 kit.set_memory(init_out_raw, alias_idx);
3558 }
3559
3560 //---------------------------set_output_for_allocation-------------------------
3561 Node* GraphKit::set_output_for_allocation(AllocateNode* alloc,
3562 const TypeOopPtr* oop_type,
3563 bool deoptimize_on_exception) {
3564 int rawidx = Compile::AliasIdxRaw;
3565 alloc->set_req( TypeFunc::FramePtr, frameptr() );
3566 add_safepoint_edges(alloc);
3567 Node* allocx = _gvn.transform(alloc);
3568 set_control( _gvn.transform(new ProjNode(allocx, TypeFunc::Control) ) );
3569 // create memory projection for i_o
3570 set_memory ( _gvn.transform( new ProjNode(allocx, TypeFunc::Memory, true) ), rawidx );
3571 make_slow_call_ex(allocx, env()->Throwable_klass(), true, deoptimize_on_exception);
3572
3573 // create a memory projection as for the normal control path
3574 Node* malloc = _gvn.transform(new ProjNode(allocx, TypeFunc::Memory));
3575 set_memory(malloc, rawidx);
3576
3577 // a normal slow-call doesn't change i_o, but an allocation does
3578 // we create a separate i_o projection for the normal control path
3579 set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) );
3580 Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) );
3581
3582 // put in an initialization barrier
3583 InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,
3584 rawoop)->as_Initialize();
3585 assert(alloc->initialization() == init, "2-way macro link must work");
3586 assert(init ->allocation() == alloc, "2-way macro link must work");
3587 {
3588 // Extract memory strands which may participate in the new object's
3589 // initialization, and source them from the new InitializeNode.
3590 // This will allow us to observe initializations when they occur,
3591 // and link them properly (as a group) to the InitializeNode.
3592 assert(init->in(InitializeNode::Memory) == malloc, "");
3593 MergeMemNode* minit_in = MergeMemNode::make(malloc);
3594 init->set_req(InitializeNode::Memory, minit_in);
3595 record_for_igvn(minit_in); // fold it up later, if possible
3596 Node* minit_out = memory(rawidx);
3597 assert(minit_out->is_Proj() && minit_out->in(0) == init, "");
3598 // Add an edge in the MergeMem for the header fields so an access
3599 // to one of those has correct memory state
3600 set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::mark_offset_in_bytes())));
3601 set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes())));
3602 if (oop_type->isa_aryptr()) {
3603 const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);
3604 int elemidx = C->get_alias_index(telemref);
3605 hook_memory_on_init(*this, elemidx, minit_in, minit_out);
3606 } else if (oop_type->isa_instptr()) {
3607 ciInstanceKlass* ik = oop_type->is_instptr()->instance_klass();
3608 for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {
3609 ciField* field = ik->nonstatic_field_at(i);
3610 if (field->offset_in_bytes() >= TrackedInitializationLimit * HeapWordSize)
3611 continue; // do not bother to track really large numbers of fields
3612 // Find (or create) the alias category for this field:
3613 int fieldidx = C->alias_type(field)->index();
3614 hook_memory_on_init(*this, fieldidx, minit_in, minit_out);
3615 }
3616 }
3617 }
3618
3619 // Cast raw oop to the real thing...
3620 Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type);
3621 javaoop = _gvn.transform(javaoop);
3622 C->set_recent_alloc(control(), javaoop);
3623 assert(just_allocated_object(control()) == javaoop, "just allocated");
3624
3625 #ifdef ASSERT
3626 { // Verify that the AllocateNode::Ideal_allocation recognizers work:
3637 assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");
3638 }
3639 }
3640 #endif //ASSERT
3641
3642 return javaoop;
3643 }
3644
3645 //---------------------------new_instance--------------------------------------
3646 // This routine takes a klass_node which may be constant (for a static type)
3647 // or may be non-constant (for reflective code). It will work equally well
3648 // for either, and the graph will fold nicely if the optimizer later reduces
3649 // the type to a constant.
3650 // The optional arguments are for specialized use by intrinsics:
3651 // - If 'extra_slow_test' if not null is an extra condition for the slow-path.
3652 // - If 'return_size_val', report the total object size to the caller.
3653 // - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
3654 Node* GraphKit::new_instance(Node* klass_node,
3655 Node* extra_slow_test,
3656 Node* *return_size_val,
3657 bool deoptimize_on_exception) {
3658 // Compute size in doublewords
3659 // The size is always an integral number of doublewords, represented
3660 // as a positive bytewise size stored in the klass's layout_helper.
3661 // The layout_helper also encodes (in a low bit) the need for a slow path.
3662 jint layout_con = Klass::_lh_neutral_value;
3663 Node* layout_val = get_layout_helper(klass_node, layout_con);
3664 int layout_is_con = (layout_val == nullptr);
3665
3666 if (extra_slow_test == nullptr) extra_slow_test = intcon(0);
3667 // Generate the initial go-slow test. It's either ALWAYS (return a
3668 // Node for 1) or NEVER (return a null) or perhaps (in the reflective
3669 // case) a computed value derived from the layout_helper.
3670 Node* initial_slow_test = nullptr;
3671 if (layout_is_con) {
3672 assert(!StressReflectiveCode, "stress mode does not use these paths");
3673 bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);
3674 initial_slow_test = must_go_slow ? intcon(1) : extra_slow_test;
3675 } else { // reflective case
3676 // This reflective path is used by Unsafe.allocateInstance.
3677 // (It may be stress-tested by specifying StressReflectiveCode.)
3678 // Basically, we want to get into the VM is there's an illegal argument.
3679 Node* bit = intcon(Klass::_lh_instance_slow_path_bit);
3680 initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) );
3681 if (extra_slow_test != intcon(0)) {
3682 initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) );
3683 }
3684 // (Macro-expander will further convert this to a Bool, if necessary.)
3695
3696 // Clear the low bits to extract layout_helper_size_in_bytes:
3697 assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
3698 Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));
3699 size = _gvn.transform( new AndXNode(size, mask) );
3700 }
3701 if (return_size_val != nullptr) {
3702 (*return_size_val) = size;
3703 }
3704
3705 // This is a precise notnull oop of the klass.
3706 // (Actually, it need not be precise if this is a reflective allocation.)
3707 // It's what we cast the result to.
3708 const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();
3709 if (!tklass) tklass = TypeInstKlassPtr::OBJECT;
3710 const TypeOopPtr* oop_type = tklass->as_instance_type();
3711
3712 // Now generate allocation code
3713
3714 // The entire memory state is needed for slow path of the allocation
3715 // since GC and deoptimization can happened.
3716 Node *mem = reset_memory();
3717 set_all_memory(mem); // Create new memory state
3718
3719 AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP),
3720 control(), mem, i_o(),
3721 size, klass_node,
3722 initial_slow_test);
3723
3724 return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);
3725 }
3726
3727 //-------------------------------new_array-------------------------------------
3728 // helper for both newarray and anewarray
3729 // The 'length' parameter is (obviously) the length of the array.
3730 // See comments on new_instance for the meaning of the other arguments.
3731 Node* GraphKit::new_array(Node* klass_node, // array klass (maybe variable)
3732 Node* length, // number of array elements
3733 int nargs, // number of arguments to push back for uncommon trap
3734 Node* *return_size_val,
3735 bool deoptimize_on_exception) {
3736 jint layout_con = Klass::_lh_neutral_value;
3737 Node* layout_val = get_layout_helper(klass_node, layout_con);
3738 int layout_is_con = (layout_val == nullptr);
3739
3740 if (!layout_is_con && !StressReflectiveCode &&
3741 !too_many_traps(Deoptimization::Reason_class_check)) {
3742 // This is a reflective array creation site.
3743 // Optimistically assume that it is a subtype of Object[],
3744 // so that we can fold up all the address arithmetic.
3745 layout_con = Klass::array_layout_helper(T_OBJECT);
3746 Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) );
3747 Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) );
3748 { BuildCutout unless(this, bol_lh, PROB_MAX);
3749 inc_sp(nargs);
3750 uncommon_trap(Deoptimization::Reason_class_check,
3751 Deoptimization::Action_maybe_recompile);
3752 }
3753 layout_val = nullptr;
3754 layout_is_con = true;
3755 }
3756
3757 // Generate the initial go-slow test. Make sure we do not overflow
3758 // if length is huge (near 2Gig) or negative! We do not need
3759 // exact double-words here, just a close approximation of needed
3760 // double-words. We can't add any offset or rounding bits, lest we
3761 // take a size -1 of bytes and make it positive. Use an unsigned
3762 // compare, so negative sizes look hugely positive.
3763 int fast_size_limit = FastAllocateSizeLimit;
3764 if (layout_is_con) {
3765 assert(!StressReflectiveCode, "stress mode does not use these paths");
3766 // Increase the size limit if we have exact knowledge of array type.
3767 int log2_esize = Klass::layout_helper_log2_element_size(layout_con);
3768 fast_size_limit <<= (LogBytesPerLong - log2_esize);
3769 }
3770
3771 Node* initial_slow_cmp = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) );
3772 Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) );
3773
3774 // --- Size Computation ---
3775 // array_size = round_to_heap(array_header + (length << elem_shift));
3776 // where round_to_heap(x) == align_to(x, MinObjAlignmentInBytes)
3777 // and align_to(x, y) == ((x + y-1) & ~(y-1))
3778 // The rounding mask is strength-reduced, if possible.
3779 int round_mask = MinObjAlignmentInBytes - 1;
3780 Node* header_size = nullptr;
3781 int header_size_min = arrayOopDesc::base_offset_in_bytes(T_BYTE);
3782 // (T_BYTE has the weakest alignment and size restrictions...)
3783 if (layout_is_con) {
3784 int hsize = Klass::layout_helper_header_size(layout_con);
3785 int eshift = Klass::layout_helper_log2_element_size(layout_con);
3786 BasicType etype = Klass::layout_helper_element_type(layout_con);
3787 if ((round_mask & ~right_n_bits(eshift)) == 0)
3788 round_mask = 0; // strength-reduce it if it goes away completely
3789 assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
3790 assert(header_size_min <= hsize, "generic minimum is smallest");
3791 header_size_min = hsize;
3792 header_size = intcon(hsize + round_mask);
3793 } else {
3794 Node* hss = intcon(Klass::_lh_header_size_shift);
3795 Node* hsm = intcon(Klass::_lh_header_size_mask);
3796 Node* hsize = _gvn.transform( new URShiftINode(layout_val, hss) );
3797 hsize = _gvn.transform( new AndINode(hsize, hsm) );
3798 Node* mask = intcon(round_mask);
3799 header_size = _gvn.transform( new AddINode(hsize, mask) );
3800 }
3801
3802 Node* elem_shift = nullptr;
3803 if (layout_is_con) {
3804 int eshift = Klass::layout_helper_log2_element_size(layout_con);
3805 if (eshift != 0)
3806 elem_shift = intcon(eshift);
3807 } else {
3808 // There is no need to mask or shift this value.
3809 // The semantics of LShiftINode include an implicit mask to 0x1F.
3853 // places, one where the length is sharply limited, and the other
3854 // after a successful allocation.
3855 Node* abody = lengthx;
3856 if (elem_shift != nullptr)
3857 abody = _gvn.transform( new LShiftXNode(lengthx, elem_shift) );
3858 Node* size = _gvn.transform( new AddXNode(headerx, abody) );
3859 if (round_mask != 0) {
3860 Node* mask = MakeConX(~round_mask);
3861 size = _gvn.transform( new AndXNode(size, mask) );
3862 }
3863 // else if round_mask == 0, the size computation is self-rounding
3864
3865 if (return_size_val != nullptr) {
3866 // This is the size
3867 (*return_size_val) = size;
3868 }
3869
3870 // Now generate allocation code
3871
3872 // The entire memory state is needed for slow path of the allocation
3873 // since GC and deoptimization can happened.
3874 Node *mem = reset_memory();
3875 set_all_memory(mem); // Create new memory state
3876
3877 if (initial_slow_test->is_Bool()) {
3878 // Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.
3879 initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);
3880 }
3881
3882 const TypeOopPtr* ary_type = _gvn.type(klass_node)->is_klassptr()->as_instance_type();
3883 Node* valid_length_test = _gvn.intcon(1);
3884 if (ary_type->isa_aryptr()) {
3885 BasicType bt = ary_type->isa_aryptr()->elem()->array_element_basic_type();
3886 jint max = TypeAryPtr::max_array_length(bt);
3887 Node* valid_length_cmp = _gvn.transform(new CmpUNode(length, intcon(max)));
3888 valid_length_test = _gvn.transform(new BoolNode(valid_length_cmp, BoolTest::le));
3889 }
3890
3891 // Create the AllocateArrayNode and its result projections
3892 AllocateArrayNode* alloc
3893 = new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),
3894 control(), mem, i_o(),
3895 size, klass_node,
3896 initial_slow_test,
3897 length, valid_length_test);
3898
3899 // Cast to correct type. Note that the klass_node may be constant or not,
3900 // and in the latter case the actual array type will be inexact also.
3901 // (This happens via a non-constant argument to inline_native_newArray.)
3902 // In any case, the value of klass_node provides the desired array type.
3903 const TypeInt* length_type = _gvn.find_int_type(length);
3904 if (ary_type->isa_aryptr() && length_type != nullptr) {
3905 // Try to get a better type than POS for the size
3906 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
3907 }
3908
3909 Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);
3910
3911 array_ideal_length(alloc, ary_type, true);
3912 return javaoop;
3913 }
3914
3915 // The following "Ideal_foo" functions are placed here because they recognize
3916 // the graph shapes created by the functions immediately above.
3917
3918 //---------------------------Ideal_allocation----------------------------------
4028 set_all_memory(ideal.merged_memory());
4029 set_i_o(ideal.i_o());
4030 set_control(ideal.ctrl());
4031 }
4032
4033 void GraphKit::final_sync(IdealKit& ideal) {
4034 // Final sync IdealKit and graphKit.
4035 sync_kit(ideal);
4036 }
4037
4038 Node* GraphKit::load_String_length(Node* str, bool set_ctrl) {
4039 Node* len = load_array_length(load_String_value(str, set_ctrl));
4040 Node* coder = load_String_coder(str, set_ctrl);
4041 // Divide length by 2 if coder is UTF16
4042 return _gvn.transform(new RShiftINode(len, coder));
4043 }
4044
4045 Node* GraphKit::load_String_value(Node* str, bool set_ctrl) {
4046 int value_offset = java_lang_String::value_offset();
4047 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4048 false, nullptr, 0);
4049 const TypePtr* value_field_type = string_type->add_offset(value_offset);
4050 const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull,
4051 TypeAry::make(TypeInt::BYTE, TypeInt::POS),
4052 ciTypeArrayKlass::make(T_BYTE), true, 0);
4053 Node* p = basic_plus_adr(str, str, value_offset);
4054 Node* load = access_load_at(str, p, value_field_type, value_type, T_OBJECT,
4055 IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4056 return load;
4057 }
4058
4059 Node* GraphKit::load_String_coder(Node* str, bool set_ctrl) {
4060 if (!CompactStrings) {
4061 return intcon(java_lang_String::CODER_UTF16);
4062 }
4063 int coder_offset = java_lang_String::coder_offset();
4064 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4065 false, nullptr, 0);
4066 const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4067
4068 Node* p = basic_plus_adr(str, str, coder_offset);
4069 Node* load = access_load_at(str, p, coder_field_type, TypeInt::BYTE, T_BYTE,
4070 IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4071 return load;
4072 }
4073
4074 void GraphKit::store_String_value(Node* str, Node* value) {
4075 int value_offset = java_lang_String::value_offset();
4076 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4077 false, nullptr, 0);
4078 const TypePtr* value_field_type = string_type->add_offset(value_offset);
4079
4080 access_store_at(str, basic_plus_adr(str, value_offset), value_field_type,
4081 value, TypeAryPtr::BYTES, T_OBJECT, IN_HEAP | MO_UNORDERED);
4082 }
4083
4084 void GraphKit::store_String_coder(Node* str, Node* value) {
4085 int coder_offset = java_lang_String::coder_offset();
4086 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4087 false, nullptr, 0);
4088 const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4089
4090 access_store_at(str, basic_plus_adr(str, coder_offset), coder_field_type,
4091 value, TypeInt::BYTE, T_BYTE, IN_HEAP | MO_UNORDERED);
4092 }
4093
4094 // Capture src and dst memory state with a MergeMemNode
4095 Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) {
4096 if (src_type == dst_type) {
4097 // Types are equal, we don't need a MergeMemNode
4098 return memory(src_type);
4099 }
4100 MergeMemNode* merge = MergeMemNode::make(map()->memory());
4101 record_for_igvn(merge); // fold it up later, if possible
4102 int src_idx = C->get_alias_index(src_type);
4103 int dst_idx = C->get_alias_index(dst_type);
4104 merge->set_memory_at(src_idx, memory(src_idx));
4105 merge->set_memory_at(dst_idx, memory(dst_idx));
4106 return merge;
4107 }
4180 i_char->init_req(2, AddI(i_char, intcon(2)));
4181
4182 set_control(IfFalse(iff));
4183 set_memory(st, TypeAryPtr::BYTES);
4184 }
4185
4186 Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) {
4187 if (!field->is_constant()) {
4188 return nullptr; // Field not marked as constant.
4189 }
4190 ciInstance* holder = nullptr;
4191 if (!field->is_static()) {
4192 ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop();
4193 if (const_oop != nullptr && const_oop->is_instance()) {
4194 holder = const_oop->as_instance();
4195 }
4196 }
4197 const Type* con_type = Type::make_constant_from_field(field, holder, field->layout_type(),
4198 /*is_unsigned_load=*/false);
4199 if (con_type != nullptr) {
4200 return makecon(con_type);
4201 }
4202 return nullptr;
4203 }
|
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 "precompiled.hpp"
26 #include "ci/ciFlatArrayKlass.hpp"
27 #include "ci/ciInlineKlass.hpp"
28 #include "ci/ciUtilities.hpp"
29 #include "classfile/javaClasses.hpp"
30 #include "ci/ciObjArray.hpp"
31 #include "asm/register.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 "opto/addnode.hpp"
38 #include "opto/castnode.hpp"
39 #include "opto/convertnode.hpp"
40 #include "opto/graphKit.hpp"
41 #include "opto/idealKit.hpp"
42 #include "opto/inlinetypenode.hpp"
43 #include "opto/intrinsicnode.hpp"
44 #include "opto/locknode.hpp"
45 #include "opto/machnode.hpp"
46 #include "opto/narrowptrnode.hpp"
47 #include "opto/opaquenode.hpp"
48 #include "opto/parse.hpp"
49 #include "opto/rootnode.hpp"
50 #include "opto/runtime.hpp"
51 #include "opto/subtypenode.hpp"
52 #include "runtime/deoptimization.hpp"
53 #include "runtime/sharedRuntime.hpp"
54 #include "utilities/bitMap.inline.hpp"
55 #include "utilities/powerOfTwo.hpp"
56 #include "utilities/growableArray.hpp"
57
58 //----------------------------GraphKit-----------------------------------------
59 // Main utility constructor.
60 GraphKit::GraphKit(JVMState* jvms, PhaseGVN* gvn)
61 : Phase(Phase::Parser),
62 _env(C->env()),
63 _gvn((gvn != nullptr) ? *gvn : *C->initial_gvn()),
64 _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
65 {
66 assert(gvn == nullptr || !gvn->is_IterGVN() || gvn->is_IterGVN()->delay_transform(), "delay transform should be enabled");
67 _exceptions = jvms->map()->next_exception();
68 if (_exceptions != nullptr) jvms->map()->set_next_exception(nullptr);
69 set_jvms(jvms);
70 #ifdef ASSERT
71 if (_gvn.is_IterGVN() != nullptr) {
72 assert(_gvn.is_IterGVN()->delay_transform(), "Transformation must be delayed if IterGVN is used");
73 // Save the initial size of _for_igvn worklist for verification (see ~GraphKit)
74 _worklist_size = _gvn.C->for_igvn()->size();
75 }
76 #endif
77 }
78
79 // Private constructor for parser.
80 GraphKit::GraphKit()
81 : Phase(Phase::Parser),
82 _env(C->env()),
83 _gvn(*C->initial_gvn()),
84 _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
85 {
86 _exceptions = nullptr;
87 set_map(nullptr);
88 debug_only(_sp = -99);
89 debug_only(set_bci(-99));
90 }
91
92
93
94 //---------------------------clean_stack---------------------------------------
95 // Clear away rubbish from the stack area of the JVM state.
96 // This destroys any arguments that may be waiting on the stack.
852 if (PrintMiscellaneous && (Verbose || WizardMode)) {
853 tty->print_cr("Zombie local %d: ", local);
854 jvms->dump();
855 }
856 return false;
857 }
858 }
859 }
860 return true;
861 }
862
863 #endif //ASSERT
864
865 // Helper function for enforcing certain bytecodes to reexecute if deoptimization happens.
866 static bool should_reexecute_implied_by_bytecode(JVMState *jvms, bool is_anewarray) {
867 ciMethod* cur_method = jvms->method();
868 int cur_bci = jvms->bci();
869 if (cur_method != nullptr && cur_bci != InvocationEntryBci) {
870 Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci);
871 return Interpreter::bytecode_should_reexecute(code) ||
872 (is_anewarray && (code == Bytecodes::_multianewarray));
873 // Reexecute _multianewarray bytecode which was replaced with
874 // sequence of [a]newarray. See Parse::do_multianewarray().
875 //
876 // Note: interpreter should not have it set since this optimization
877 // is limited by dimensions and guarded by flag so in some cases
878 // multianewarray() runtime calls will be generated and
879 // the bytecode should not be reexecutes (stack will not be reset).
880 } else {
881 return false;
882 }
883 }
884
885 // Helper function for adding JVMState and debug information to node
886 void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) {
887 // Add the safepoint edges to the call (or other safepoint).
888
889 // Make sure dead locals are set to top. This
890 // should help register allocation time and cut down on the size
891 // of the deoptimization information.
892 assert(dead_locals_are_killed(), "garbage in debug info before safepoint");
1112 ciSignature* declared_signature = nullptr;
1113 ciMethod* ignored_callee = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
1114 assert(declared_signature != nullptr, "cannot be null");
1115 inputs = declared_signature->arg_size_for_bc(code);
1116 int size = declared_signature->return_type()->size();
1117 depth = size - inputs;
1118 }
1119 break;
1120
1121 case Bytecodes::_multianewarray:
1122 {
1123 ciBytecodeStream iter(method());
1124 iter.reset_to_bci(bci());
1125 iter.next();
1126 inputs = iter.get_dimensions();
1127 assert(rsize() == 1, "");
1128 depth = 1 - inputs;
1129 }
1130 break;
1131
1132 case Bytecodes::_withfield: {
1133 bool ignored_will_link;
1134 ciField* field = method()->get_field_at_bci(bci(), ignored_will_link);
1135 int size = field->type()->size();
1136 inputs = size+1;
1137 depth = rsize() - inputs;
1138 break;
1139 }
1140
1141 case Bytecodes::_ireturn:
1142 case Bytecodes::_lreturn:
1143 case Bytecodes::_freturn:
1144 case Bytecodes::_dreturn:
1145 case Bytecodes::_areturn:
1146 assert(rsize() == -depth, "");
1147 inputs = -depth;
1148 break;
1149
1150 case Bytecodes::_jsr:
1151 case Bytecodes::_jsr_w:
1152 inputs = 0;
1153 depth = 1; // S.B. depth=1, not zero
1154 break;
1155
1156 default:
1157 // bytecode produces a typed result
1158 inputs = rsize() - depth;
1159 assert(inputs >= 0, "");
1160 break;
1203 Node* conv = _gvn.transform( new ConvI2LNode(offset));
1204 Node* mask = _gvn.transform(ConLNode::make((julong) max_juint));
1205 return _gvn.transform( new AndLNode(conv, mask) );
1206 }
1207
1208 Node* GraphKit::ConvL2I(Node* offset) {
1209 // short-circuit a common case
1210 jlong offset_con = find_long_con(offset, (jlong)Type::OffsetBot);
1211 if (offset_con != (jlong)Type::OffsetBot) {
1212 return intcon((int) offset_con);
1213 }
1214 return _gvn.transform( new ConvL2INode(offset));
1215 }
1216
1217 //-------------------------load_object_klass-----------------------------------
1218 Node* GraphKit::load_object_klass(Node* obj) {
1219 // Special-case a fresh allocation to avoid building nodes:
1220 Node* akls = AllocateNode::Ideal_klass(obj, &_gvn);
1221 if (akls != nullptr) return akls;
1222 Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
1223 return _gvn.transform(LoadKlassNode::make(_gvn, nullptr, immutable_memory(), k_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
1224 }
1225
1226 //-------------------------load_array_length-----------------------------------
1227 Node* GraphKit::load_array_length(Node* array) {
1228 // Special-case a fresh allocation to avoid building nodes:
1229 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(array, &_gvn);
1230 Node *alen;
1231 if (alloc == nullptr) {
1232 Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes());
1233 alen = _gvn.transform( new LoadRangeNode(0, immutable_memory(), r_adr, TypeInt::POS));
1234 } else {
1235 alen = array_ideal_length(alloc, _gvn.type(array)->is_oopptr(), false);
1236 }
1237 return alen;
1238 }
1239
1240 Node* GraphKit::array_ideal_length(AllocateArrayNode* alloc,
1241 const TypeOopPtr* oop_type,
1242 bool replace_length_in_map) {
1243 Node* length = alloc->Ideal_length();
1252 replace_in_map(length, ccast);
1253 }
1254 return ccast;
1255 }
1256 }
1257 return length;
1258 }
1259
1260 //------------------------------do_null_check----------------------------------
1261 // Helper function to do a null pointer check. Returned value is
1262 // the incoming address with null casted away. You are allowed to use the
1263 // not-null value only if you are control dependent on the test.
1264 #ifndef PRODUCT
1265 extern int explicit_null_checks_inserted,
1266 explicit_null_checks_elided;
1267 #endif
1268 Node* GraphKit::null_check_common(Node* value, BasicType type,
1269 // optional arguments for variations:
1270 bool assert_null,
1271 Node* *null_control,
1272 bool speculative,
1273 bool is_init_check) {
1274 assert(!assert_null || null_control == nullptr, "not both at once");
1275 if (stopped()) return top();
1276 NOT_PRODUCT(explicit_null_checks_inserted++);
1277
1278 if (value->is_InlineType()) {
1279 // Null checking a scalarized but nullable inline type. Check the IsInit
1280 // input instead of the oop input to avoid keeping buffer allocations alive.
1281 InlineTypeNode* vtptr = value->as_InlineType();
1282 while (vtptr->get_oop()->is_InlineType()) {
1283 vtptr = vtptr->get_oop()->as_InlineType();
1284 }
1285 null_check_common(vtptr->get_is_init(), T_INT, assert_null, null_control, speculative, true);
1286 if (stopped()) {
1287 return top();
1288 }
1289 if (assert_null) {
1290 // TODO 8284443 Scalarize here (this currently leads to compilation bailouts)
1291 // vtptr = InlineTypeNode::make_null(_gvn, vtptr->type()->inline_klass());
1292 // replace_in_map(value, vtptr);
1293 // return vtptr;
1294 return null();
1295 }
1296 bool do_replace_in_map = (null_control == nullptr || (*null_control) == top());
1297 return cast_not_null(value, do_replace_in_map);
1298 }
1299
1300 // Construct null check
1301 Node *chk = nullptr;
1302 switch(type) {
1303 case T_LONG : chk = new CmpLNode(value, _gvn.zerocon(T_LONG)); break;
1304 case T_INT : chk = new CmpINode(value, _gvn.intcon(0)); break;
1305 case T_PRIMITIVE_OBJECT : // fall through
1306 case T_ARRAY : // fall through
1307 type = T_OBJECT; // simplify further tests
1308 case T_OBJECT : {
1309 const Type *t = _gvn.type( value );
1310
1311 const TypeOopPtr* tp = t->isa_oopptr();
1312 if (tp != nullptr && !tp->is_loaded()
1313 // Only for do_null_check, not any of its siblings:
1314 && !assert_null && null_control == nullptr) {
1315 // Usually, any field access or invocation on an unloaded oop type
1316 // will simply fail to link, since the statically linked class is
1317 // likely also to be unloaded. However, in -Xcomp mode, sometimes
1318 // the static class is loaded but the sharper oop type is not.
1319 // Rather than checking for this obscure case in lots of places,
1320 // we simply observe that a null check on an unloaded class
1321 // will always be followed by a nonsense operation, so we
1322 // can just issue the uncommon trap here.
1323 // Our access to the unloaded class will only be correct
1324 // after it has been loaded and initialized, which requires
1325 // a trip through the interpreter.
1384 }
1385 Node *oldcontrol = control();
1386 set_control(cfg);
1387 Node *res = cast_not_null(value);
1388 set_control(oldcontrol);
1389 NOT_PRODUCT(explicit_null_checks_elided++);
1390 return res;
1391 }
1392 cfg = IfNode::up_one_dom(cfg, /*linear_only=*/ true);
1393 if (cfg == nullptr) break; // Quit at region nodes
1394 depth++;
1395 }
1396 }
1397
1398 //-----------
1399 // Branch to failure if null
1400 float ok_prob = PROB_MAX; // a priori estimate: nulls never happen
1401 Deoptimization::DeoptReason reason;
1402 if (assert_null) {
1403 reason = Deoptimization::reason_null_assert(speculative);
1404 } else if (type == T_OBJECT || is_init_check) {
1405 reason = Deoptimization::reason_null_check(speculative);
1406 } else {
1407 reason = Deoptimization::Reason_div0_check;
1408 }
1409 // %%% Since Reason_unhandled is not recorded on a per-bytecode basis,
1410 // ciMethodData::has_trap_at will return a conservative -1 if any
1411 // must-be-null assertion has failed. This could cause performance
1412 // problems for a method after its first do_null_assert failure.
1413 // Consider using 'Reason_class_check' instead?
1414
1415 // To cause an implicit null check, we set the not-null probability
1416 // to the maximum (PROB_MAX). For an explicit check the probability
1417 // is set to a smaller value.
1418 if (null_control != nullptr || too_many_traps(reason)) {
1419 // probability is less likely
1420 ok_prob = PROB_LIKELY_MAG(3);
1421 } else if (!assert_null &&
1422 (ImplicitNullCheckThreshold > 0) &&
1423 method() != nullptr &&
1424 (method()->method_data()->trap_count(reason)
1458 }
1459
1460 if (assert_null) {
1461 // Cast obj to null on this path.
1462 replace_in_map(value, zerocon(type));
1463 return zerocon(type);
1464 }
1465
1466 // Cast obj to not-null on this path, if there is no null_control.
1467 // (If there is a null_control, a non-null value may come back to haunt us.)
1468 if (type == T_OBJECT) {
1469 Node* cast = cast_not_null(value, false);
1470 if (null_control == nullptr || (*null_control) == top())
1471 replace_in_map(value, cast);
1472 value = cast;
1473 }
1474
1475 return value;
1476 }
1477
1478 //------------------------------cast_not_null----------------------------------
1479 // Cast obj to not-null on this path
1480 Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) {
1481 if (obj->is_InlineType()) {
1482 Node* vt = obj->clone();
1483 vt->as_InlineType()->set_is_init(_gvn);
1484 vt = _gvn.transform(vt);
1485 if (do_replace_in_map) {
1486 replace_in_map(obj, vt);
1487 }
1488 return vt;
1489 }
1490 const Type *t = _gvn.type(obj);
1491 const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL);
1492 // Object is already not-null?
1493 if( t == t_not_null ) return obj;
1494
1495 Node *cast = new CastPPNode(obj,t_not_null);
1496 cast->init_req(0, control());
1497 cast = _gvn.transform( cast );
1498
1499 // Scan for instances of 'obj' in the current JVM mapping.
1500 // These instances are known to be not-null after the test.
1501 if (do_replace_in_map)
1502 replace_in_map(obj, cast);
1503
1504 return cast; // Return casted value
1505 }
1506
1507 // Sometimes in intrinsics, we implicitly know an object is not null
1508 // (there's no actual null check) so we can cast it to not null. In
1509 // the course of optimizations, the input to the cast can become null.
1596 // These are layered on top of the factory methods in LoadNode and StoreNode,
1597 // and integrate with the parser's memory state and _gvn engine.
1598 //
1599
1600 // factory methods in "int adr_idx"
1601 Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,
1602 int adr_idx,
1603 MemNode::MemOrd mo,
1604 LoadNode::ControlDependency control_dependency,
1605 bool require_atomic_access,
1606 bool unaligned,
1607 bool mismatched,
1608 bool unsafe,
1609 uint8_t barrier_data) {
1610 assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );
1611 const TypePtr* adr_type = nullptr; // debug-mode-only argument
1612 debug_only(adr_type = C->get_adr_type(adr_idx));
1613 Node* mem = memory(adr_idx);
1614 Node* ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, require_atomic_access, unaligned, mismatched, unsafe, barrier_data);
1615 ld = _gvn.transform(ld);
1616
1617 if (((bt == T_OBJECT || bt == T_PRIMITIVE_OBJECT) && C->do_escape_analysis()) || C->eliminate_boxing()) {
1618 // Improve graph before escape analysis and boxing elimination.
1619 record_for_igvn(ld);
1620 }
1621 return ld;
1622 }
1623
1624 Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,
1625 int adr_idx,
1626 MemNode::MemOrd mo,
1627 bool require_atomic_access,
1628 bool unaligned,
1629 bool mismatched,
1630 bool unsafe,
1631 int barrier_data) {
1632 assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
1633 const TypePtr* adr_type = nullptr;
1634 debug_only(adr_type = C->get_adr_type(adr_idx));
1635 Node *mem = memory(adr_idx);
1636 Node* st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo, require_atomic_access);
1637 if (unaligned) {
1643 if (unsafe) {
1644 st->as_Store()->set_unsafe_access();
1645 }
1646 st->as_Store()->set_barrier_data(barrier_data);
1647 st = _gvn.transform(st);
1648 set_memory(st, adr_idx);
1649 // Back-to-back stores can only remove intermediate store with DU info
1650 // so push on worklist for optimizer.
1651 if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))
1652 record_for_igvn(st);
1653
1654 return st;
1655 }
1656
1657 Node* GraphKit::access_store_at(Node* obj,
1658 Node* adr,
1659 const TypePtr* adr_type,
1660 Node* val,
1661 const Type* val_type,
1662 BasicType bt,
1663 DecoratorSet decorators,
1664 bool safe_for_replace) {
1665 // Transformation of a value which could be null pointer (CastPP #null)
1666 // could be delayed during Parse (for example, in adjust_map_after_if()).
1667 // Execute transformation here to avoid barrier generation in such case.
1668 if (_gvn.type(val) == TypePtr::NULL_PTR) {
1669 val = _gvn.makecon(TypePtr::NULL_PTR);
1670 }
1671
1672 if (stopped()) {
1673 return top(); // Dead path ?
1674 }
1675
1676 assert(val != nullptr, "not dead path");
1677 if (val->is_InlineType()) {
1678 // Store to non-flattened field. Buffer the inline type and make sure
1679 // the store is re-executed if the allocation triggers deoptimization.
1680 PreserveReexecuteState preexecs(this);
1681 jvms()->set_should_reexecute(true);
1682 val = val->as_InlineType()->buffer(this, safe_for_replace);
1683 }
1684
1685 C2AccessValuePtr addr(adr, adr_type);
1686 C2AccessValue value(val, val_type);
1687 C2ParseAccess access(this, decorators | C2_WRITE_ACCESS, bt, obj, addr);
1688 if (access.is_raw()) {
1689 return _barrier_set->BarrierSetC2::store_at(access, value);
1690 } else {
1691 return _barrier_set->store_at(access, value);
1692 }
1693 }
1694
1695 Node* GraphKit::access_load_at(Node* obj, // containing obj
1696 Node* adr, // actual address to store val at
1697 const TypePtr* adr_type,
1698 const Type* val_type,
1699 BasicType bt,
1700 DecoratorSet decorators,
1701 Node* ctl) {
1702 if (stopped()) {
1703 return top(); // Dead path ?
1704 }
1705
1706 C2AccessValuePtr addr(adr, adr_type);
1707 C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, obj, addr, ctl);
1708 if (access.is_raw()) {
1709 return _barrier_set->BarrierSetC2::load_at(access, val_type);
1710 } else {
1711 return _barrier_set->load_at(access, val_type);
1712 }
1713 }
1714
1715 Node* GraphKit::access_load(Node* adr, // actual address to load val at
1716 const Type* val_type,
1717 BasicType bt,
1718 DecoratorSet decorators) {
1719 if (stopped()) {
1720 return top(); // Dead path ?
1721 }
1722
1723 C2AccessValuePtr addr(adr, adr->bottom_type()->is_ptr());
1724 C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, nullptr, addr);
1725 if (access.is_raw()) {
1726 return _barrier_set->BarrierSetC2::load_at(access, val_type);
1727 } else {
1792 Node* new_val,
1793 const Type* value_type,
1794 BasicType bt,
1795 DecoratorSet decorators) {
1796 C2AccessValuePtr addr(adr, adr_type);
1797 C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, bt, obj, addr, alias_idx);
1798 if (access.is_raw()) {
1799 return _barrier_set->BarrierSetC2::atomic_add_at(access, new_val, value_type);
1800 } else {
1801 return _barrier_set->atomic_add_at(access, new_val, value_type);
1802 }
1803 }
1804
1805 void GraphKit::access_clone(Node* src, Node* dst, Node* size, bool is_array) {
1806 return _barrier_set->clone(this, src, dst, size, is_array);
1807 }
1808
1809 //-------------------------array_element_address-------------------------
1810 Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,
1811 const TypeInt* sizetype, Node* ctrl) {
1812 const TypeAryPtr* arytype = _gvn.type(ary)->is_aryptr();
1813 uint shift = arytype->is_flat() ? arytype->flat_log_elem_size() : exact_log2(type2aelembytes(elembt));
1814 uint header = arrayOopDesc::base_offset_in_bytes(elembt);
1815
1816 // short-circuit a common case (saves lots of confusing waste motion)
1817 jint idx_con = find_int_con(idx, -1);
1818 if (idx_con >= 0) {
1819 intptr_t offset = header + ((intptr_t)idx_con << shift);
1820 return basic_plus_adr(ary, offset);
1821 }
1822
1823 // must be correct type for alignment purposes
1824 Node* base = basic_plus_adr(ary, header);
1825 idx = Compile::conv_I2X_index(&_gvn, idx, sizetype, ctrl);
1826 Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) );
1827 return basic_plus_adr(ary, base, scale);
1828 }
1829
1830 //-------------------------load_array_element-------------------------
1831 Node* GraphKit::load_array_element(Node* ary, Node* idx, const TypeAryPtr* arytype, bool set_ctrl) {
1832 const Type* elemtype = arytype->elem();
1833 BasicType elembt = elemtype->array_element_basic_type();
1834 assert(elembt != T_PRIMITIVE_OBJECT, "inline types are not supported by this method");
1835 Node* adr = array_element_address(ary, idx, elembt, arytype->size());
1836 if (elembt == T_NARROWOOP) {
1837 elembt = T_OBJECT; // To satisfy switch in LoadNode::make()
1838 }
1839 Node* ld = access_load_at(ary, adr, arytype, elemtype, elembt,
1840 IN_HEAP | IS_ARRAY | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0));
1841 return ld;
1842 }
1843
1844 //-------------------------set_arguments_for_java_call-------------------------
1845 // Arguments (pre-popped from the stack) are taken from the JVMS.
1846 void GraphKit::set_arguments_for_java_call(CallJavaNode* call, bool is_late_inline) {
1847 PreserveReexecuteState preexecs(this);
1848 if (EnableValhalla) {
1849 // Make sure the call is "re-executed", if buffering of inline type arguments triggers deoptimization.
1850 // At this point, the call hasn't been executed yet, so we will only ever execute the call once.
1851 jvms()->set_should_reexecute(true);
1852 int arg_size = method()->get_declared_signature_at_bci(bci())->arg_size_for_bc(java_bc());
1853 inc_sp(arg_size);
1854 }
1855 // Add the call arguments
1856 const TypeTuple* domain = call->tf()->domain_sig();
1857 uint nargs = domain->cnt();
1858 int arg_num = 0;
1859 for (uint i = TypeFunc::Parms, idx = TypeFunc::Parms; i < nargs; i++) {
1860 Node* arg = argument(i-TypeFunc::Parms);
1861 const Type* t = domain->field_at(i);
1862 // TODO 8284443 A static call to a mismatched method should still be scalarized
1863 if (t->is_inlinetypeptr() && !call->method()->get_Method()->mismatch() && call->method()->is_scalarized_arg(arg_num)) {
1864 // We don't pass inline type arguments by reference but instead pass each field of the inline type
1865 if (!arg->is_InlineType()) {
1866 assert(_gvn.type(arg)->is_zero_type() && !t->inline_klass()->is_null_free(), "Unexpected argument type");
1867 arg = InlineTypeNode::make_from_oop(this, arg, t->inline_klass(), t->inline_klass()->is_null_free());
1868 }
1869 InlineTypeNode* vt = arg->as_InlineType();
1870 vt->pass_fields(this, call, idx, true, !t->maybe_null());
1871 // If an inline type argument is passed as fields, attach the Method* to the call site
1872 // to be able to access the extended signature later via attached_method_before_pc().
1873 // For example, see CompiledMethod::preserve_callee_argument_oops().
1874 call->set_override_symbolic_info(true);
1875 // Register an evol dependency on the callee method to make sure that this method is deoptimized and
1876 // re-compiled with a non-scalarized calling convention if the callee method is later marked as mismatched.
1877 C->dependencies()->assert_evol_method(call->method());
1878 arg_num++;
1879 continue;
1880 } else if (arg->is_InlineType()) {
1881 // Pass inline type argument via oop to callee
1882 arg = arg->as_InlineType()->buffer(this);
1883 if (!is_late_inline) {
1884 arg = arg->as_InlineType()->get_oop();
1885 }
1886 }
1887 if (t != Type::HALF) {
1888 arg_num++;
1889 }
1890 call->init_req(idx++, arg);
1891 }
1892 }
1893
1894 //---------------------------set_edges_for_java_call---------------------------
1895 // Connect a newly created call into the current JVMS.
1896 // A return value node (if any) is returned from set_edges_for_java_call.
1897 void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) {
1898
1899 // Add the predefined inputs:
1900 call->init_req( TypeFunc::Control, control() );
1901 call->init_req( TypeFunc::I_O , i_o() );
1902 call->init_req( TypeFunc::Memory , reset_memory() );
1903 call->init_req( TypeFunc::FramePtr, frameptr() );
1904 call->init_req( TypeFunc::ReturnAdr, top() );
1905
1906 add_safepoint_edges(call, must_throw);
1907
1908 Node* xcall = _gvn.transform(call);
1909
1910 if (xcall == top()) {
1911 set_control(top());
1912 return;
1913 }
1914 assert(xcall == call, "call identity is stable");
1915
1916 // Re-use the current map to produce the result.
1917
1918 set_control(_gvn.transform(new ProjNode(call, TypeFunc::Control)));
1919 set_i_o( _gvn.transform(new ProjNode(call, TypeFunc::I_O , separate_io_proj)));
1920 set_all_memory_call(xcall, separate_io_proj);
1921
1922 //return xcall; // no need, caller already has it
1923 }
1924
1925 Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj, bool deoptimize) {
1926 if (stopped()) return top(); // maybe the call folded up?
1927
1928 // Note: Since any out-of-line call can produce an exception,
1929 // we always insert an I_O projection from the call into the result.
1930
1931 make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj, deoptimize);
1932
1933 if (separate_io_proj) {
1934 // The caller requested separate projections be used by the fall
1935 // through and exceptional paths, so replace the projections for
1936 // the fall through path.
1937 set_i_o(_gvn.transform( new ProjNode(call, TypeFunc::I_O) ));
1938 set_all_memory(_gvn.transform( new ProjNode(call, TypeFunc::Memory) ));
1939 }
1940
1941 // Capture the return value, if any.
1942 Node* ret;
1943 if (call->method() == nullptr || call->method()->return_type()->basic_type() == T_VOID) {
1944 ret = top();
1945 } else if (call->tf()->returns_inline_type_as_fields()) {
1946 // Return of multiple values (inline type fields): we create a
1947 // InlineType node, each field is a projection from the call.
1948 ciInlineKlass* vk = call->method()->return_type()->as_inline_klass();
1949 uint base_input = TypeFunc::Parms;
1950 ret = InlineTypeNode::make_from_multi(this, call, vk, base_input, false, call->method()->signature()->returns_null_free_inline_type());
1951 } else {
1952 ret = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1953 if (call->method()->return_type()->is_inlinetype()) {
1954 ret = InlineTypeNode::make_from_oop(this, ret, call->method()->return_type()->as_inline_klass(), call->method()->signature()->returns_null_free_inline_type());
1955 }
1956 }
1957
1958 return ret;
1959 }
1960
1961 //--------------------set_predefined_input_for_runtime_call--------------------
1962 // Reading and setting the memory state is way conservative here.
1963 // The real problem is that I am not doing real Type analysis on memory,
1964 // so I cannot distinguish card mark stores from other stores. Across a GC
1965 // point the Store Barrier and the card mark memory has to agree. I cannot
1966 // have a card mark store and its barrier split across the GC point from
1967 // either above or below. Here I get that to happen by reading ALL of memory.
1968 // A better answer would be to separate out card marks from other memory.
1969 // For now, return the input memory state, so that it can be reused
1970 // after the call, if this call has restricted memory effects.
1971 Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) {
1972 // Set fixed predefined input arguments
1973 Node* memory = reset_memory();
1974 Node* m = narrow_mem == nullptr ? memory : narrow_mem;
1975 call->init_req( TypeFunc::Control, control() );
1976 call->init_req( TypeFunc::I_O, top() ); // does no i/o
1977 call->init_req( TypeFunc::Memory, m ); // may gc ptrs
2028 if (use->is_MergeMem()) {
2029 wl.push(use);
2030 }
2031 }
2032 }
2033
2034 // Replace the call with the current state of the kit.
2035 void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes) {
2036 JVMState* ejvms = nullptr;
2037 if (has_exceptions()) {
2038 ejvms = transfer_exceptions_into_jvms();
2039 }
2040
2041 ReplacedNodes replaced_nodes = map()->replaced_nodes();
2042 ReplacedNodes replaced_nodes_exception;
2043 Node* ex_ctl = top();
2044
2045 SafePointNode* final_state = stop();
2046
2047 // Find all the needed outputs of this call
2048 CallProjections* callprojs = call->extract_projections(true);
2049
2050 Unique_Node_List wl;
2051 Node* init_mem = call->in(TypeFunc::Memory);
2052 Node* final_mem = final_state->in(TypeFunc::Memory);
2053 Node* final_ctl = final_state->in(TypeFunc::Control);
2054 Node* final_io = final_state->in(TypeFunc::I_O);
2055
2056 // Replace all the old call edges with the edges from the inlining result
2057 if (callprojs->fallthrough_catchproj != nullptr) {
2058 C->gvn_replace_by(callprojs->fallthrough_catchproj, final_ctl);
2059 }
2060 if (callprojs->fallthrough_memproj != nullptr) {
2061 if (final_mem->is_MergeMem()) {
2062 // Parser's exits MergeMem was not transformed but may be optimized
2063 final_mem = _gvn.transform(final_mem);
2064 }
2065 C->gvn_replace_by(callprojs->fallthrough_memproj, final_mem);
2066 add_mergemem_users_to_worklist(wl, final_mem);
2067 }
2068 if (callprojs->fallthrough_ioproj != nullptr) {
2069 C->gvn_replace_by(callprojs->fallthrough_ioproj, final_io);
2070 }
2071
2072 // Replace the result with the new result if it exists and is used
2073 if (callprojs->resproj[0] != nullptr && result != nullptr) {
2074 // If the inlined code is dead, the result projections for an inline type returned as
2075 // fields have not been replaced. They will go away once the call is replaced by TOP below.
2076 assert(callprojs->nb_resproj == 1 || (call->tf()->returns_inline_type_as_fields() && stopped()),
2077 "unexpected number of results");
2078 C->gvn_replace_by(callprojs->resproj[0], result);
2079 }
2080
2081 if (ejvms == nullptr) {
2082 // No exception edges to simply kill off those paths
2083 if (callprojs->catchall_catchproj != nullptr) {
2084 C->gvn_replace_by(callprojs->catchall_catchproj, C->top());
2085 }
2086 if (callprojs->catchall_memproj != nullptr) {
2087 C->gvn_replace_by(callprojs->catchall_memproj, C->top());
2088 }
2089 if (callprojs->catchall_ioproj != nullptr) {
2090 C->gvn_replace_by(callprojs->catchall_ioproj, C->top());
2091 }
2092 // Replace the old exception object with top
2093 if (callprojs->exobj != nullptr) {
2094 C->gvn_replace_by(callprojs->exobj, C->top());
2095 }
2096 } else {
2097 GraphKit ekit(ejvms);
2098
2099 // Load my combined exception state into the kit, with all phis transformed:
2100 SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();
2101 replaced_nodes_exception = ex_map->replaced_nodes();
2102
2103 Node* ex_oop = ekit.use_exception_state(ex_map);
2104
2105 if (callprojs->catchall_catchproj != nullptr) {
2106 C->gvn_replace_by(callprojs->catchall_catchproj, ekit.control());
2107 ex_ctl = ekit.control();
2108 }
2109 if (callprojs->catchall_memproj != nullptr) {
2110 Node* ex_mem = ekit.reset_memory();
2111 C->gvn_replace_by(callprojs->catchall_memproj, ex_mem);
2112 add_mergemem_users_to_worklist(wl, ex_mem);
2113 }
2114 if (callprojs->catchall_ioproj != nullptr) {
2115 C->gvn_replace_by(callprojs->catchall_ioproj, ekit.i_o());
2116 }
2117
2118 // Replace the old exception object with the newly created one
2119 if (callprojs->exobj != nullptr) {
2120 C->gvn_replace_by(callprojs->exobj, ex_oop);
2121 }
2122 }
2123
2124 // Disconnect the call from the graph
2125 call->disconnect_inputs(C);
2126 C->gvn_replace_by(call, C->top());
2127
2128 // Clean up any MergeMems that feed other MergeMems since the
2129 // optimizer doesn't like that.
2130 while (wl.size() > 0) {
2131 _gvn.transform(wl.pop());
2132 }
2133
2134 if (callprojs->fallthrough_catchproj != nullptr && !final_ctl->is_top() && do_replaced_nodes) {
2135 replaced_nodes.apply(C, final_ctl);
2136 }
2137 if (!ex_ctl->is_top() && do_replaced_nodes) {
2138 replaced_nodes_exception.apply(C, ex_ctl);
2139 }
2140 }
2141
2142
2143 //------------------------------increment_counter------------------------------
2144 // for statistics: increment a VM counter by 1
2145
2146 void GraphKit::increment_counter(address counter_addr) {
2147 Node* adr1 = makecon(TypeRawPtr::make(counter_addr));
2148 increment_counter(adr1);
2149 }
2150
2151 void GraphKit::increment_counter(Node* counter_addr) {
2152 int adr_type = Compile::AliasIdxRaw;
2153 Node* ctrl = control();
2154 Node* cnt = make_load(ctrl, counter_addr, TypeLong::LONG, T_LONG, adr_type, MemNode::unordered);
2313 *
2314 * @param n node that the type applies to
2315 * @param exact_kls type from profiling
2316 * @param maybe_null did profiling see null?
2317 *
2318 * @return node with improved type
2319 */
2320 Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, ProfilePtrKind ptr_kind) {
2321 const Type* current_type = _gvn.type(n);
2322 assert(UseTypeSpeculation, "type speculation must be on");
2323
2324 const TypePtr* speculative = current_type->speculative();
2325
2326 // Should the klass from the profile be recorded in the speculative type?
2327 if (current_type->would_improve_type(exact_kls, jvms()->depth())) {
2328 const TypeKlassPtr* tklass = TypeKlassPtr::make(exact_kls, Type::trust_interfaces);
2329 const TypeOopPtr* xtype = tklass->as_instance_type();
2330 assert(xtype->klass_is_exact(), "Should be exact");
2331 // Any reason to believe n is not null (from this profiling or a previous one)?
2332 assert(ptr_kind != ProfileAlwaysNull, "impossible here");
2333 const TypePtr* ptr = (ptr_kind != ProfileNeverNull && current_type->speculative_maybe_null()) ? TypePtr::BOTTOM : TypePtr::NOTNULL;
2334 // record the new speculative type's depth
2335 speculative = xtype->cast_to_ptr_type(ptr->ptr())->is_ptr();
2336 speculative = speculative->with_inline_depth(jvms()->depth());
2337 } else if (current_type->would_improve_ptr(ptr_kind)) {
2338 // Profiling report that null was never seen so we can change the
2339 // speculative type to non null ptr.
2340 if (ptr_kind == ProfileAlwaysNull) {
2341 speculative = TypePtr::NULL_PTR;
2342 } else {
2343 assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement");
2344 const TypePtr* ptr = TypePtr::NOTNULL;
2345 if (speculative != nullptr) {
2346 speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr();
2347 } else {
2348 speculative = ptr;
2349 }
2350 }
2351 }
2352
2353 if (speculative != current_type->speculative()) {
2354 // Build a type with a speculative type (what we think we know
2355 // about the type but will need a guard when we use it)
2356 const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::Offset::bottom, TypeOopPtr::InstanceBot, speculative);
2357 // We're changing the type, we need a new CheckCast node to carry
2358 // the new type. The new type depends on the control: what
2359 // profiling tells us is only valid from here as far as we can
2360 // tell.
2361 Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));
2362 cast = _gvn.transform(cast);
2363 replace_in_map(n, cast);
2364 n = cast;
2365 }
2366
2367 return n;
2368 }
2369
2370 /**
2371 * Record profiling data from receiver profiling at an invoke with the
2372 * type system so that it can propagate it (speculation)
2373 *
2374 * @param n receiver node
2375 *
2376 * @return node with improved type
2377 */
2378 Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {
2379 if (!UseTypeSpeculation) {
2380 return n;
2381 }
2382 ciKlass* exact_kls = profile_has_unique_klass();
2383 ProfilePtrKind ptr_kind = ProfileMaybeNull;
2384 if ((java_bc() == Bytecodes::_checkcast ||
2385 java_bc() == Bytecodes::_instanceof ||
2386 java_bc() == Bytecodes::_aastore) &&
2387 method()->method_data()->is_mature()) {
2388 ciProfileData* data = method()->method_data()->bci_to_data(bci());
2389 if (data != nullptr) {
2390 if (java_bc() == Bytecodes::_aastore) {
2391 ciKlass* array_type = nullptr;
2392 ciKlass* element_type = nullptr;
2393 ProfilePtrKind element_ptr = ProfileMaybeNull;
2394 bool flat_array = true;
2395 bool null_free_array = true;
2396 method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array);
2397 exact_kls = element_type;
2398 ptr_kind = element_ptr;
2399 } else {
2400 if (!data->as_BitData()->null_seen()) {
2401 ptr_kind = ProfileNeverNull;
2402 } else {
2403 assert(data->is_ReceiverTypeData(), "bad profile data type");
2404 ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
2405 uint i = 0;
2406 for (; i < call->row_limit(); i++) {
2407 ciKlass* receiver = call->receiver(i);
2408 if (receiver != nullptr) {
2409 break;
2410 }
2411 }
2412 ptr_kind = (i == call->row_limit()) ? ProfileAlwaysNull : ProfileMaybeNull;
2413 }
2414 }
2415 }
2416 }
2417 return record_profile_for_speculation(n, exact_kls, ptr_kind);
2418 }
2419
2420 /**
2421 * Record profiling data from argument profiling at an invoke with the
2422 * type system so that it can propagate it (speculation)
2423 *
2424 * @param dest_method target method for the call
2425 * @param bc what invoke bytecode is this?
2426 */
2427 void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {
2428 if (!UseTypeSpeculation) {
2429 return;
2430 }
2431 const TypeFunc* tf = TypeFunc::make(dest_method);
2432 int nargs = tf->domain_sig()->cnt() - TypeFunc::Parms;
2433 int skip = Bytecodes::has_receiver(bc) ? 1 : 0;
2434 for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {
2435 const Type *targ = tf->domain_sig()->field_at(j + TypeFunc::Parms);
2436 if (is_reference_type(targ->basic_type())) {
2437 ProfilePtrKind ptr_kind = ProfileMaybeNull;
2438 ciKlass* better_type = nullptr;
2439 if (method()->argument_profiled_type(bci(), i, better_type, ptr_kind)) {
2440 record_profile_for_speculation(argument(j), better_type, ptr_kind);
2441 }
2442 i++;
2443 }
2444 }
2445 }
2446
2447 /**
2448 * Record profiling data from parameter profiling at an invoke with
2449 * the type system so that it can propagate it (speculation)
2450 */
2451 void GraphKit::record_profiled_parameters_for_speculation() {
2452 if (!UseTypeSpeculation) {
2453 return;
2454 }
2455 for (int i = 0, j = 0; i < method()->arg_size() ; i++) {
2469 * the type system so that it can propagate it (speculation)
2470 */
2471 void GraphKit::record_profiled_return_for_speculation() {
2472 if (!UseTypeSpeculation) {
2473 return;
2474 }
2475 ProfilePtrKind ptr_kind = ProfileMaybeNull;
2476 ciKlass* better_type = nullptr;
2477 if (method()->return_profiled_type(bci(), better_type, ptr_kind)) {
2478 // If profiling reports a single type for the return value,
2479 // feed it to the type system so it can propagate it as a
2480 // speculative type
2481 record_profile_for_speculation(stack(sp()-1), better_type, ptr_kind);
2482 }
2483 }
2484
2485 void GraphKit::round_double_arguments(ciMethod* dest_method) {
2486 if (Matcher::strict_fp_requires_explicit_rounding) {
2487 // (Note: TypeFunc::make has a cache that makes this fast.)
2488 const TypeFunc* tf = TypeFunc::make(dest_method);
2489 int nargs = tf->domain_sig()->cnt() - TypeFunc::Parms;
2490 for (int j = 0; j < nargs; j++) {
2491 const Type *targ = tf->domain_sig()->field_at(j + TypeFunc::Parms);
2492 if (targ->basic_type() == T_DOUBLE) {
2493 // If any parameters are doubles, they must be rounded before
2494 // the call, dprecision_rounding does gvn.transform
2495 Node *arg = argument(j);
2496 arg = dprecision_rounding(arg);
2497 set_argument(j, arg);
2498 }
2499 }
2500 }
2501 }
2502
2503 // rounding for strict float precision conformance
2504 Node* GraphKit::precision_rounding(Node* n) {
2505 if (Matcher::strict_fp_requires_explicit_rounding) {
2506 #ifdef IA32
2507 if (UseSSE == 0) {
2508 return _gvn.transform(new RoundFloatNode(0, n));
2509 }
2510 #else
2511 Unimplemented();
2620 // The first null ends the list.
2621 Node* parm0, Node* parm1,
2622 Node* parm2, Node* parm3,
2623 Node* parm4, Node* parm5,
2624 Node* parm6, Node* parm7) {
2625 assert(call_addr != nullptr, "must not call null targets");
2626
2627 // Slow-path call
2628 bool is_leaf = !(flags & RC_NO_LEAF);
2629 bool has_io = (!is_leaf && !(flags & RC_NO_IO));
2630 if (call_name == nullptr) {
2631 assert(!is_leaf, "must supply name for leaf");
2632 call_name = OptoRuntime::stub_name(call_addr);
2633 }
2634 CallNode* call;
2635 if (!is_leaf) {
2636 call = new CallStaticJavaNode(call_type, call_addr, call_name, adr_type);
2637 } else if (flags & RC_NO_FP) {
2638 call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
2639 } else if (flags & RC_VECTOR){
2640 uint num_bits = call_type->range_sig()->field_at(TypeFunc::Parms)->is_vect()->length_in_bytes() * BitsPerByte;
2641 call = new CallLeafVectorNode(call_type, call_addr, call_name, adr_type, num_bits);
2642 } else {
2643 call = new CallLeafNode(call_type, call_addr, call_name, adr_type);
2644 }
2645
2646 // The following is similar to set_edges_for_java_call,
2647 // except that the memory effects of the call are restricted to AliasIdxRaw.
2648
2649 // Slow path call has no side-effects, uses few values
2650 bool wide_in = !(flags & RC_NARROW_MEM);
2651 bool wide_out = (C->get_alias_index(adr_type) == Compile::AliasIdxBot);
2652
2653 Node* prev_mem = nullptr;
2654 if (wide_in) {
2655 prev_mem = set_predefined_input_for_runtime_call(call);
2656 } else {
2657 assert(!wide_out, "narrow in => narrow out");
2658 Node* narrow_mem = memory(adr_type);
2659 prev_mem = set_predefined_input_for_runtime_call(call, narrow_mem);
2660 }
2700
2701 if (has_io) {
2702 set_i_o(_gvn.transform(new ProjNode(call, TypeFunc::I_O)));
2703 }
2704 return call;
2705
2706 }
2707
2708 // i2b
2709 Node* GraphKit::sign_extend_byte(Node* in) {
2710 Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(24)));
2711 return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(24)));
2712 }
2713
2714 // i2s
2715 Node* GraphKit::sign_extend_short(Node* in) {
2716 Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(16)));
2717 return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(16)));
2718 }
2719
2720
2721 //------------------------------merge_memory-----------------------------------
2722 // Merge memory from one path into the current memory state.
2723 void GraphKit::merge_memory(Node* new_mem, Node* region, int new_path) {
2724 for (MergeMemStream mms(merged_memory(), new_mem->as_MergeMem()); mms.next_non_empty2(); ) {
2725 Node* old_slice = mms.force_memory();
2726 Node* new_slice = mms.memory2();
2727 if (old_slice != new_slice) {
2728 PhiNode* phi;
2729 if (old_slice->is_Phi() && old_slice->as_Phi()->region() == region) {
2730 if (mms.is_empty()) {
2731 // clone base memory Phi's inputs for this memory slice
2732 assert(old_slice == mms.base_memory(), "sanity");
2733 phi = PhiNode::make(region, nullptr, Type::MEMORY, mms.adr_type(C));
2734 _gvn.set_type(phi, Type::MEMORY);
2735 for (uint i = 1; i < phi->req(); i++) {
2736 phi->init_req(i, old_slice->in(i));
2737 }
2738 } else {
2739 phi = old_slice->as_Phi(); // Phi was generated already
2740 }
2954
2955 // Now do a linear scan of the secondary super-klass array. Again, no real
2956 // performance impact (too rare) but it's gotta be done.
2957 // Since the code is rarely used, there is no penalty for moving it
2958 // out of line, and it can only improve I-cache density.
2959 // The decision to inline or out-of-line this final check is platform
2960 // dependent, and is found in the AD file definition of PartialSubtypeCheck.
2961 Node* psc = gvn.transform(
2962 new PartialSubtypeCheckNode(*ctrl, subklass, superklass));
2963
2964 IfNode *iff4 = gen_subtype_check_compare(*ctrl, psc, gvn.zerocon(T_OBJECT), BoolTest::ne, PROB_FAIR, gvn, T_ADDRESS);
2965 r_not_subtype->init_req(2, gvn.transform(new IfTrueNode (iff4)));
2966 r_ok_subtype ->init_req(3, gvn.transform(new IfFalseNode(iff4)));
2967
2968 // Return false path; set default control to true path.
2969 *ctrl = gvn.transform(r_ok_subtype);
2970 return gvn.transform(r_not_subtype);
2971 }
2972
2973 Node* GraphKit::gen_subtype_check(Node* obj_or_subklass, Node* superklass) {
2974 const Type* sub_t = _gvn.type(obj_or_subklass);
2975 if (sub_t->make_oopptr() != nullptr && sub_t->make_oopptr()->is_inlinetypeptr()) {
2976 sub_t = TypeKlassPtr::make(sub_t->inline_klass());
2977 obj_or_subklass = makecon(sub_t);
2978 }
2979 bool expand_subtype_check = C->post_loop_opts_phase() || // macro node expansion is over
2980 ExpandSubTypeCheckAtParseTime; // forced expansion
2981 if (expand_subtype_check) {
2982 MergeMemNode* mem = merged_memory();
2983 Node* ctrl = control();
2984 Node* subklass = obj_or_subklass;
2985 if (!sub_t->isa_klassptr()) {
2986 subklass = load_object_klass(obj_or_subklass);
2987 }
2988 Node* n = Phase::gen_subtype_check(subklass, superklass, &ctrl, mem, _gvn);
2989 set_control(ctrl);
2990 return n;
2991 }
2992
2993 Node* check = _gvn.transform(new SubTypeCheckNode(C, obj_or_subklass, superklass));
2994 Node* bol = _gvn.transform(new BoolNode(check, BoolTest::eq));
2995 IfNode* iff = create_and_xform_if(control(), bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
2996 set_control(_gvn.transform(new IfTrueNode(iff)));
2997 return _gvn.transform(new IfFalseNode(iff));
2998 }
2999
3000 // Profile-driven exact type check:
3001 Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,
3002 float prob, Node* *casted_receiver) {
3003 assert(!klass->is_interface(), "no exact type check on interfaces");
3004 Node* fail = top();
3005 const Type* rec_t = _gvn.type(receiver);
3006 if (rec_t->is_inlinetypeptr()) {
3007 if (klass->equals(rec_t->inline_klass())) {
3008 (*casted_receiver) = receiver; // Always passes
3009 } else {
3010 (*casted_receiver) = top(); // Always fails
3011 fail = control();
3012 set_control(top());
3013 }
3014 return fail;
3015 }
3016 const TypeKlassPtr* tklass = TypeKlassPtr::make(klass, Type::trust_interfaces);
3017 Node* recv_klass = load_object_klass(receiver);
3018 fail = type_check(recv_klass, tklass, prob);
3019
3020 if (!stopped()) {
3021 const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
3022 const TypeOopPtr* recv_xtype = tklass->as_instance_type();
3023 assert(recv_xtype->klass_is_exact(), "");
3024
3025 if (!receiver_type->higher_equal(recv_xtype)) { // ignore redundant casts
3026 // Subsume downstream occurrences of receiver with a cast to
3027 // recv_xtype, since now we know what the type will be.
3028 Node* cast = new CheckCastPPNode(control(), receiver, recv_xtype);
3029 Node* res = _gvn.transform(cast);
3030 if (recv_xtype->is_inlinetypeptr()) {
3031 assert(!gvn().type(res)->maybe_null(), "receiver should never be null");
3032 res = InlineTypeNode::make_from_oop(this, res, recv_xtype->inline_klass());
3033 }
3034 (*casted_receiver) = res;
3035 // (User must make the replace_in_map call.)
3036 }
3037 }
3038
3039 return fail;
3040 }
3041
3042 Node* GraphKit::type_check(Node* recv_klass, const TypeKlassPtr* tklass,
3043 float prob) {
3044 Node* want_klass = makecon(tklass);
3045 Node* cmp = _gvn.transform(new CmpPNode(recv_klass, want_klass));
3046 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
3047 IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);
3048 set_control(_gvn.transform(new IfTrueNode (iff)));
3049 Node* fail = _gvn.transform(new IfFalseNode(iff));
3050 return fail;
3051 }
3052
3053 //------------------------------subtype_check_receiver-------------------------
3054 Node* GraphKit::subtype_check_receiver(Node* receiver, ciKlass* klass,
3055 Node** casted_receiver) {
3056 const TypeKlassPtr* tklass = TypeKlassPtr::make(klass, Type::trust_interfaces)->try_improve();
3057 Node* want_klass = makecon(tklass);
3058
3059 Node* slow_ctl = gen_subtype_check(receiver, want_klass);
3060
3061 // Ignore interface type information until interface types are properly tracked.
3062 if (!stopped() && !klass->is_interface()) {
3063 const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
3064 const TypeOopPtr* recv_type = tklass->cast_to_exactness(false)->is_klassptr()->as_instance_type();
3065 if (receiver_type != nullptr && !receiver_type->higher_equal(recv_type)) { // ignore redundant casts
3066 Node* cast = _gvn.transform(new CheckCastPPNode(control(), receiver, recv_type));
3067 if (recv_type->is_inlinetypeptr()) {
3068 cast = InlineTypeNode::make_from_oop(this, cast, recv_type->inline_klass());
3069 }
3070 (*casted_receiver) = cast;
3071 }
3072 }
3073
3074 return slow_ctl;
3075 }
3076
3077 //------------------------------seems_never_null-------------------------------
3078 // Use null_seen information if it is available from the profile.
3079 // If we see an unexpected null at a type check we record it and force a
3080 // recompile; the offending check will be recompiled to handle nulls.
3081 // If we see several offending BCIs, then all checks in the
3082 // method will be recompiled.
3083 bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) {
3084 speculating = !_gvn.type(obj)->speculative_maybe_null();
3085 Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating);
3086 if (UncommonNullCast // Cutout for this technique
3087 && obj != null() // And not the -Xcomp stupid case?
3088 && !too_many_traps(reason)
3089 ) {
3090 if (speculating) {
3091 return true;
3092 }
3093 if (data == nullptr)
3094 // Edge case: no mature data. Be optimistic here.
3095 return true;
3096 // If the profile has not seen a null, assume it won't happen.
3097 assert(java_bc() == Bytecodes::_checkcast ||
3098 java_bc() == Bytecodes::_instanceof ||
3099 java_bc() == Bytecodes::_aastore, "MDO must collect null_seen bit here");
3100 if (java_bc() == Bytecodes::_aastore) {
3101 return ((ciArrayLoadStoreData*)data->as_ArrayLoadStoreData())->element()->ptr_kind() == ProfileNeverNull;
3102 }
3103 return !data->as_BitData()->null_seen();
3104 }
3105 speculating = false;
3106 return false;
3107 }
3108
3109 void GraphKit::guard_klass_being_initialized(Node* klass) {
3110 int init_state_off = in_bytes(InstanceKlass::init_state_offset());
3111 Node* adr = basic_plus_adr(top(), klass, init_state_off);
3112 Node* init_state = LoadNode::make(_gvn, nullptr, immutable_memory(), adr,
3113 adr->bottom_type()->is_ptr(), TypeInt::BYTE,
3114 T_BYTE, MemNode::unordered);
3115 init_state = _gvn.transform(init_state);
3116
3117 Node* being_initialized_state = makecon(TypeInt::make(InstanceKlass::being_initialized));
3118
3119 Node* chk = _gvn.transform(new CmpINode(being_initialized_state, init_state));
3120 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3121
3122 { BuildCutout unless(this, tst, PROB_MAX);
3162
3163 //------------------------maybe_cast_profiled_receiver-------------------------
3164 // If the profile has seen exactly one type, narrow to exactly that type.
3165 // Subsequent type checks will always fold up.
3166 Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,
3167 const TypeKlassPtr* require_klass,
3168 ciKlass* spec_klass,
3169 bool safe_for_replace) {
3170 if (!UseTypeProfile || !TypeProfileCasts) return nullptr;
3171
3172 Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != nullptr);
3173
3174 // Make sure we haven't already deoptimized from this tactic.
3175 if (too_many_traps_or_recompiles(reason))
3176 return nullptr;
3177
3178 // (No, this isn't a call, but it's enough like a virtual call
3179 // to use the same ciMethod accessor to get the profile info...)
3180 // If we have a speculative type use it instead of profiling (which
3181 // may not help us)
3182 ciKlass* exact_kls = spec_klass;
3183 if (exact_kls == nullptr) {
3184 if (java_bc() == Bytecodes::_aastore) {
3185 ciKlass* array_type = nullptr;
3186 ciKlass* element_type = nullptr;
3187 ProfilePtrKind element_ptr = ProfileMaybeNull;
3188 bool flat_array = true;
3189 bool null_free_array = true;
3190 method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array);
3191 exact_kls = element_type;
3192 } else {
3193 exact_kls = profile_has_unique_klass();
3194 }
3195 }
3196 if (exact_kls != nullptr) {// no cast failures here
3197 if (require_klass == nullptr ||
3198 C->static_subtype_check(require_klass, TypeKlassPtr::make(exact_kls, Type::trust_interfaces)) == Compile::SSC_always_true) {
3199 // If we narrow the type to match what the type profile sees or
3200 // the speculative type, we can then remove the rest of the
3201 // cast.
3202 // This is a win, even if the exact_kls is very specific,
3203 // because downstream operations, such as method calls,
3204 // will often benefit from the sharper type.
3205 Node* exact_obj = not_null_obj; // will get updated in place...
3206 Node* slow_ctl = type_check_receiver(exact_obj, exact_kls, 1.0,
3207 &exact_obj);
3208 { PreserveJVMState pjvms(this);
3209 set_control(slow_ctl);
3210 uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
3211 }
3212 if (safe_for_replace) {
3213 replace_in_map(not_null_obj, exact_obj);
3214 }
3215 return exact_obj;
3305 // If not_null_obj is dead, only null-path is taken
3306 if (stopped()) { // Doing instance-of on a null?
3307 set_control(null_ctl);
3308 return intcon(0);
3309 }
3310 region->init_req(_null_path, null_ctl);
3311 phi ->init_req(_null_path, intcon(0)); // Set null path value
3312 if (null_ctl == top()) {
3313 // Do this eagerly, so that pattern matches like is_diamond_phi
3314 // will work even during parsing.
3315 assert(_null_path == PATH_LIMIT-1, "delete last");
3316 region->del_req(_null_path);
3317 phi ->del_req(_null_path);
3318 }
3319
3320 // Do we know the type check always succeed?
3321 bool known_statically = false;
3322 if (_gvn.type(superklass)->singleton()) {
3323 const TypeKlassPtr* superk = _gvn.type(superklass)->is_klassptr();
3324 const TypeKlassPtr* subk = _gvn.type(obj)->is_oopptr()->as_klass_type();
3325 if (subk != nullptr && subk->is_loaded()) {
3326 int static_res = C->static_subtype_check(superk, subk);
3327 known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false);
3328 }
3329 }
3330
3331 if (!known_statically) {
3332 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3333 // We may not have profiling here or it may not help us. If we
3334 // have a speculative type use it to perform an exact cast.
3335 ciKlass* spec_obj_type = obj_type->speculative_type();
3336 if (spec_obj_type != nullptr || (ProfileDynamicTypes && data != nullptr)) {
3337 Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, nullptr, spec_obj_type, safe_for_replace);
3338 if (stopped()) { // Profile disagrees with this path.
3339 set_control(null_ctl); // Null is the only remaining possibility.
3340 return intcon(0);
3341 }
3342 if (cast_obj != nullptr) {
3343 not_null_obj = cast_obj;
3344 }
3345 }
3361 record_for_igvn(region);
3362
3363 // If we know the type check always succeeds then we don't use the
3364 // profiling data at this bytecode. Don't lose it, feed it to the
3365 // type system as a speculative type.
3366 if (safe_for_replace) {
3367 Node* casted_obj = record_profiled_receiver_for_speculation(obj);
3368 replace_in_map(obj, casted_obj);
3369 }
3370
3371 return _gvn.transform(phi);
3372 }
3373
3374 //-------------------------------gen_checkcast---------------------------------
3375 // Generate a checkcast idiom. Used by both the checkcast bytecode and the
3376 // array store bytecode. Stack must be as-if BEFORE doing the bytecode so the
3377 // uncommon-trap paths work. Adjust stack after this call.
3378 // If failure_control is supplied and not null, it is filled in with
3379 // the control edge for the cast failure. Otherwise, an appropriate
3380 // uncommon trap or exception is thrown.
3381 Node* GraphKit::gen_checkcast(Node *obj, Node* superklass, Node* *failure_control, bool null_free) {
3382 kill_dead_locals(); // Benefit all the uncommon traps
3383 const TypeKlassPtr *tk = _gvn.type(superklass)->is_klassptr()->try_improve();
3384 const TypeOopPtr *toop = tk->cast_to_exactness(false)->as_instance_type();
3385 bool safe_for_replace = (failure_control == nullptr);
3386 assert(!null_free || toop->is_inlinetypeptr(), "must be an inline type pointer");
3387
3388 // Fast cutout: Check the case that the cast is vacuously true.
3389 // This detects the common cases where the test will short-circuit
3390 // away completely. We do this before we perform the null check,
3391 // because if the test is going to turn into zero code, we don't
3392 // want a residual null check left around. (Causes a slowdown,
3393 // for example, in some objArray manipulations, such as a[i]=a[j].)
3394 if (tk->singleton()) {
3395 const TypeKlassPtr* kptr = nullptr;
3396 const Type* t = _gvn.type(obj);
3397 if (t->isa_oop_ptr()) {
3398 kptr = t->is_oopptr()->as_klass_type();
3399 } else if (obj->is_InlineType()) {
3400 ciInlineKlass* vk = t->inline_klass();
3401 kptr = TypeInstKlassPtr::make(TypePtr::NotNull, vk, Type::Offset(0));
3402 }
3403 if (kptr != nullptr) {
3404 switch (C->static_subtype_check(tk, kptr)) {
3405 case Compile::SSC_always_true:
3406 // If we know the type check always succeed then we don't use
3407 // the profiling data at this bytecode. Don't lose it, feed it
3408 // to the type system as a speculative type.
3409 obj = record_profiled_receiver_for_speculation(obj);
3410 if (null_free) {
3411 assert(safe_for_replace, "must be");
3412 obj = null_check(obj);
3413 }
3414 assert(stopped() || !toop->is_inlinetypeptr() || obj->is_InlineType(), "should have been scalarized");
3415 return obj;
3416 case Compile::SSC_always_false:
3417 if (null_free) {
3418 assert(safe_for_replace, "must be");
3419 obj = null_check(obj);
3420 }
3421 // It needs a null check because a null will *pass* the cast check.
3422 if (t->isa_oopptr() != nullptr && !t->is_oopptr()->maybe_null()) {
3423 bool is_aastore = (java_bc() == Bytecodes::_aastore);
3424 Deoptimization::DeoptReason reason = is_aastore ?
3425 Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3426 builtin_throw(reason);
3427 return top();
3428 } else if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
3429 return null_assert(obj);
3430 }
3431 break; // Fall through to full check
3432 default:
3433 break;
3434 }
3435 }
3436 }
3437
3438 ciProfileData* data = nullptr;
3439 if (failure_control == nullptr) { // use MDO in regular case only
3440 assert(java_bc() == Bytecodes::_aastore ||
3441 java_bc() == Bytecodes::_checkcast,
3442 "interpreter profiles type checks only for these BCs");
3443 if (method()->method_data()->is_mature()) {
3444 data = method()->method_data()->bci_to_data(bci());
3445 }
3446 }
3447
3448 // Make the merge point
3449 enum { _obj_path = 1, _null_path, PATH_LIMIT };
3450 RegionNode* region = new RegionNode(PATH_LIMIT);
3451 Node* phi = new PhiNode(region, toop);
3452 _gvn.set_type(region, Type::CONTROL);
3453 _gvn.set_type(phi, toop);
3454
3455 C->set_has_split_ifs(true); // Has chance for split-if optimization
3456
3457 // Use null-cast information if it is available
3458 bool speculative_not_null = false;
3459 bool never_see_null = ((failure_control == nullptr) // regular case only
3460 && seems_never_null(obj, data, speculative_not_null));
3461
3462 if (obj->is_InlineType()) {
3463 // Re-execute if buffering during triggers deoptimization
3464 PreserveReexecuteState preexecs(this);
3465 jvms()->set_should_reexecute(true);
3466 obj = obj->as_InlineType()->buffer(this, safe_for_replace);
3467 }
3468
3469 // Null check; get casted pointer; set region slot 3
3470 Node* null_ctl = top();
3471 Node* not_null_obj = nullptr;
3472 if (null_free) {
3473 assert(safe_for_replace, "must be");
3474 not_null_obj = null_check(obj);
3475 } else {
3476 not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3477 }
3478
3479 // If not_null_obj is dead, only null-path is taken
3480 if (stopped()) { // Doing instance-of on a null?
3481 set_control(null_ctl);
3482 if (toop->is_inlinetypeptr()) {
3483 return InlineTypeNode::make_null(_gvn, toop->inline_klass());
3484 }
3485 return null();
3486 }
3487 region->init_req(_null_path, null_ctl);
3488 phi ->init_req(_null_path, null()); // Set null path value
3489 if (null_ctl == top()) {
3490 // Do this eagerly, so that pattern matches like is_diamond_phi
3491 // will work even during parsing.
3492 assert(_null_path == PATH_LIMIT-1, "delete last");
3493 region->del_req(_null_path);
3494 phi ->del_req(_null_path);
3495 }
3496
3497 Node* cast_obj = nullptr;
3498 if (tk->klass_is_exact()) {
3499 // The following optimization tries to statically cast the speculative type of the object
3500 // (for example obtained during profiling) to the type of the superklass and then do a
3501 // dynamic check that the type of the object is what we expect. To work correctly
3502 // for checkcast and aastore the type of superklass should be exact.
3503 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3504 // We may not have profiling here or it may not help us. If we have
3505 // a speculative type use it to perform an exact cast.
3506 ciKlass* spec_obj_type = obj_type->speculative_type();
3507 if (spec_obj_type != nullptr || data != nullptr) {
3508 cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk, spec_obj_type, safe_for_replace);
3509 if (cast_obj != nullptr) {
3510 if (failure_control != nullptr) // failure is now impossible
3511 (*failure_control) = top();
3512 // adjust the type of the phi to the exact klass:
3513 phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
3514 }
3515 }
3516 }
3517
3518 if (cast_obj == nullptr) {
3519 // Generate the subtype check
3520 Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass);
3521
3522 // Plug in success path into the merge
3523 cast_obj = _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop));
3524 // Failure path ends in uncommon trap (or may be dead - failure impossible)
3525 if (failure_control == nullptr) {
3526 if (not_subtype_ctrl != top()) { // If failure is possible
3527 PreserveJVMState pjvms(this);
3528 set_control(not_subtype_ctrl);
3529 Node* obj_klass = nullptr;
3530 if (not_null_obj->is_InlineType()) {
3531 obj_klass = makecon(TypeKlassPtr::make(_gvn.type(not_null_obj)->inline_klass()));
3532 } else {
3533 obj_klass = load_object_klass(not_null_obj);
3534 }
3535 bool is_aastore = (java_bc() == Bytecodes::_aastore);
3536 Deoptimization::DeoptReason reason = is_aastore ?
3537 Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3538 builtin_throw(reason);
3539 }
3540 } else {
3541 (*failure_control) = not_subtype_ctrl;
3542 }
3543 }
3544
3545 region->init_req(_obj_path, control());
3546 phi ->init_req(_obj_path, cast_obj);
3547
3548 // A merge of null or Casted-NotNull obj
3549 Node* res = _gvn.transform(phi);
3550
3551 // Note I do NOT always 'replace_in_map(obj,result)' here.
3552 // if( tk->klass()->can_be_primary_super() )
3553 // This means that if I successfully store an Object into an array-of-String
3554 // I 'forget' that the Object is really now known to be a String. I have to
3555 // do this because we don't have true union types for interfaces - if I store
3556 // a Baz into an array-of-Interface and then tell the optimizer it's an
3557 // Interface, I forget that it's also a Baz and cannot do Baz-like field
3558 // references to it. FIX THIS WHEN UNION TYPES APPEAR!
3559 // replace_in_map( obj, res );
3560
3561 // Return final merged results
3562 set_control( _gvn.transform(region) );
3563 record_for_igvn(region);
3564
3565 bool not_inline = !toop->can_be_inline_type();
3566 bool not_flattened = !UseFlatArray || not_inline || (toop->is_inlinetypeptr() && !toop->inline_klass()->flatten_array());
3567 if (EnableValhalla && not_flattened) {
3568 // Check if obj has been loaded from an array
3569 obj = obj->isa_DecodeN() ? obj->in(1) : obj;
3570 Node* array = nullptr;
3571 if (obj->isa_Load()) {
3572 Node* address = obj->in(MemNode::Address);
3573 if (address->isa_AddP()) {
3574 array = address->as_AddP()->in(AddPNode::Base);
3575 }
3576 } else if (obj->is_Phi()) {
3577 Node* region = obj->in(0);
3578 // TODO make this more robust (see JDK-8231346)
3579 if (region->req() == 3 && region->in(2) != nullptr && region->in(2)->in(0) != nullptr) {
3580 IfNode* iff = region->in(2)->in(0)->isa_If();
3581 if (iff != nullptr) {
3582 iff->is_flat_array_check(&_gvn, &array);
3583 }
3584 }
3585 }
3586 if (array != nullptr) {
3587 const TypeAryPtr* ary_t = _gvn.type(array)->isa_aryptr();
3588 if (ary_t != nullptr) {
3589 if (!ary_t->is_not_null_free() && not_inline) {
3590 // Casting array element to a non-inline-type, mark array as not null-free.
3591 Node* cast = _gvn.transform(new CheckCastPPNode(control(), array, ary_t->cast_to_not_null_free()));
3592 replace_in_map(array, cast);
3593 } else if (!ary_t->is_not_flat()) {
3594 // Casting array element to a non-flattened type, mark array as not flat.
3595 Node* cast = _gvn.transform(new CheckCastPPNode(control(), array, ary_t->cast_to_not_flat()));
3596 replace_in_map(array, cast);
3597 }
3598 }
3599 }
3600 }
3601
3602 if (!stopped() && !res->is_InlineType()) {
3603 res = record_profiled_receiver_for_speculation(res);
3604 if (toop->is_inlinetypeptr()) {
3605 Node* vt = InlineTypeNode::make_from_oop(this, res, toop->inline_klass(), !gvn().type(res)->maybe_null());
3606 res = vt;
3607 if (safe_for_replace) {
3608 replace_in_map(obj, vt);
3609 replace_in_map(not_null_obj, vt);
3610 replace_in_map(res, vt);
3611 }
3612 }
3613 }
3614 return res;
3615 }
3616
3617 Node* GraphKit::inline_type_test(Node* obj, bool is_inline) {
3618 Node* mark_adr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
3619 Node* mark = make_load(nullptr, mark_adr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
3620 Node* mask = MakeConX(markWord::inline_type_pattern);
3621 Node* masked = _gvn.transform(new AndXNode(mark, mask));
3622 Node* cmp = _gvn.transform(new CmpXNode(masked, mask));
3623 return _gvn.transform(new BoolNode(cmp, is_inline ? BoolTest::eq : BoolTest::ne));
3624 }
3625
3626 Node* GraphKit::is_val_mirror(Node* mirror) {
3627 Node* p = basic_plus_adr(mirror, java_lang_Class::secondary_mirror_offset());
3628 Node* secondary_mirror = access_load_at(mirror, p, _gvn.type(p)->is_ptr(), TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR), T_OBJECT, IN_HEAP);
3629 Node* cmp = _gvn.transform(new CmpPNode(mirror, secondary_mirror));
3630 return _gvn.transform(new BoolNode(cmp, BoolTest::eq));
3631 }
3632
3633 Node* GraphKit::array_lh_test(Node* klass, jint mask, jint val, bool eq) {
3634 Node* lh_adr = basic_plus_adr(klass, in_bytes(Klass::layout_helper_offset()));
3635 // Make sure to use immutable memory here to enable hoisting the check out of loops
3636 Node* lh_val = _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), lh_adr, lh_adr->bottom_type()->is_ptr(), TypeInt::INT, T_INT, MemNode::unordered));
3637 Node* masked = _gvn.transform(new AndINode(lh_val, intcon(mask)));
3638 Node* cmp = _gvn.transform(new CmpINode(masked, intcon(val)));
3639 return _gvn.transform(new BoolNode(cmp, eq ? BoolTest::eq : BoolTest::ne));
3640 }
3641
3642 Node* GraphKit::flat_array_test(Node* array_or_klass, bool flat) {
3643 // We can't use immutable memory here because the mark word is mutable.
3644 // PhaseIdealLoop::move_flat_array_check_out_of_loop will make sure the
3645 // check is moved out of loops (mainly to enable loop unswitching).
3646 Node* mem = UseArrayMarkWordCheck ? memory(Compile::AliasIdxRaw) : immutable_memory();
3647 Node* cmp = _gvn.transform(new FlatArrayCheckNode(C, mem, array_or_klass));
3648 record_for_igvn(cmp); // Give it a chance to be optimized out by IGVN
3649 return _gvn.transform(new BoolNode(cmp, flat ? BoolTest::eq : BoolTest::ne));
3650 }
3651
3652 Node* GraphKit::null_free_array_test(Node* klass, bool null_free) {
3653 return array_lh_test(klass, Klass::_lh_null_free_array_bit_inplace, 0, !null_free);
3654 }
3655
3656 // Deoptimize if 'ary' is a null-free inline type array and 'val' is null
3657 Node* GraphKit::inline_array_null_guard(Node* ary, Node* val, int nargs, bool safe_for_replace) {
3658 RegionNode* region = new RegionNode(3);
3659 Node* null_ctl = top();
3660 null_check_oop(val, &null_ctl);
3661 if (null_ctl != top()) {
3662 PreserveJVMState pjvms(this);
3663 set_control(null_ctl);
3664 {
3665 // Deoptimize if null-free array
3666 BuildCutout unless(this, null_free_array_test(load_object_klass(ary), /* null_free = */ false), PROB_MAX);
3667 inc_sp(nargs);
3668 uncommon_trap(Deoptimization::Reason_null_check,
3669 Deoptimization::Action_none);
3670 }
3671 region->init_req(1, control());
3672 }
3673 region->init_req(2, control());
3674 set_control(_gvn.transform(region));
3675 record_for_igvn(region);
3676 if (_gvn.type(val) == TypePtr::NULL_PTR) {
3677 // Since we were just successfully storing null, the array can't be null free.
3678 const TypeAryPtr* ary_t = _gvn.type(ary)->is_aryptr();
3679 ary_t = ary_t->cast_to_not_null_free();
3680 Node* cast = _gvn.transform(new CheckCastPPNode(control(), ary, ary_t));
3681 if (safe_for_replace) {
3682 replace_in_map(ary, cast);
3683 }
3684 ary = cast;
3685 }
3686 return ary;
3687 }
3688
3689 //------------------------------next_monitor-----------------------------------
3690 // What number should be given to the next monitor?
3691 int GraphKit::next_monitor() {
3692 int current = jvms()->monitor_depth()* C->sync_stack_slots();
3693 int next = current + C->sync_stack_slots();
3694 // Keep the toplevel high water mark current:
3695 if (C->fixed_slots() < next) C->set_fixed_slots(next);
3696 return current;
3697 }
3698
3699 //------------------------------insert_mem_bar---------------------------------
3700 // Memory barrier to avoid floating things around
3701 // The membar serves as a pinch point between both control and all memory slices.
3702 Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {
3703 MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
3704 mb->init_req(TypeFunc::Control, control());
3705 mb->init_req(TypeFunc::Memory, reset_memory());
3706 Node* membar = _gvn.transform(mb);
3734 }
3735 Node* membar = _gvn.transform(mb);
3736 set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3737 if (alias_idx == Compile::AliasIdxBot) {
3738 merged_memory()->set_base_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)));
3739 } else {
3740 set_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)),alias_idx);
3741 }
3742 return membar;
3743 }
3744
3745 //------------------------------shared_lock------------------------------------
3746 // Emit locking code.
3747 FastLockNode* GraphKit::shared_lock(Node* obj) {
3748 // bci is either a monitorenter bc or InvocationEntryBci
3749 // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3750 assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3751
3752 if( !GenerateSynchronizationCode )
3753 return nullptr; // Not locking things?
3754
3755 if (stopped()) // Dead monitor?
3756 return nullptr;
3757
3758 assert(dead_locals_are_killed(), "should kill locals before sync. point");
3759
3760 // Box the stack location
3761 Node* box = _gvn.transform(new BoxLockNode(next_monitor()));
3762 Node* mem = reset_memory();
3763
3764 FastLockNode * flock = _gvn.transform(new FastLockNode(0, obj, box) )->as_FastLock();
3765
3766 // Create the rtm counters for this fast lock if needed.
3767 flock->create_rtm_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3768
3769 // Add monitor to debug info for the slow path. If we block inside the
3770 // slow path and de-opt, we need the monitor hanging around
3771 map()->push_monitor( flock );
3772
3773 const TypeFunc *tf = LockNode::lock_type();
3774 LockNode *lock = new LockNode(C, tf);
3803 }
3804 #endif
3805
3806 return flock;
3807 }
3808
3809
3810 //------------------------------shared_unlock----------------------------------
3811 // Emit unlocking code.
3812 void GraphKit::shared_unlock(Node* box, Node* obj) {
3813 // bci is either a monitorenter bc or InvocationEntryBci
3814 // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3815 assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3816
3817 if( !GenerateSynchronizationCode )
3818 return;
3819 if (stopped()) { // Dead monitor?
3820 map()->pop_monitor(); // Kill monitor from debug info
3821 return;
3822 }
3823 assert(!obj->is_InlineType(), "should not unlock on inline type");
3824
3825 // Memory barrier to avoid floating things down past the locked region
3826 insert_mem_bar(Op_MemBarReleaseLock);
3827
3828 const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();
3829 UnlockNode *unlock = new UnlockNode(C, tf);
3830 #ifdef ASSERT
3831 unlock->set_dbg_jvms(sync_jvms());
3832 #endif
3833 uint raw_idx = Compile::AliasIdxRaw;
3834 unlock->init_req( TypeFunc::Control, control() );
3835 unlock->init_req( TypeFunc::Memory , memory(raw_idx) );
3836 unlock->init_req( TypeFunc::I_O , top() ) ; // does no i/o
3837 unlock->init_req( TypeFunc::FramePtr, frameptr() );
3838 unlock->init_req( TypeFunc::ReturnAdr, top() );
3839
3840 unlock->init_req(TypeFunc::Parms + 0, obj);
3841 unlock->init_req(TypeFunc::Parms + 1, box);
3842 unlock = _gvn.transform(unlock)->as_Unlock();
3843
3844 Node* mem = reset_memory();
3845
3846 // unlock has no side-effects, sets few values
3847 set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);
3848
3849 // Kill monitor from debug info
3850 map()->pop_monitor( );
3851 }
3852
3853 //-------------------------------get_layout_helper-----------------------------
3854 // If the given klass is a constant or known to be an array,
3855 // fetch the constant layout helper value into constant_value
3856 // and return null. Otherwise, load the non-constant
3857 // layout helper value, and return the node which represents it.
3858 // This two-faced routine is useful because allocation sites
3859 // almost always feature constant types.
3860 Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {
3861 const TypeKlassPtr* inst_klass = _gvn.type(klass_node)->isa_klassptr();
3862 if (!StressReflectiveCode && inst_klass != nullptr) {
3863 bool xklass = inst_klass->klass_is_exact();
3864 bool can_be_flattened = false;
3865 const TypeAryPtr* ary_type = inst_klass->as_instance_type()->isa_aryptr();
3866 if (UseFlatArray && !xklass && ary_type != nullptr && !ary_type->is_null_free()) {
3867 // The runtime type of [LMyValue might be [QMyValue due to [QMyValue <: [LMyValue. Don't constant fold.
3868 const TypeOopPtr* elem = ary_type->elem()->make_oopptr();
3869 can_be_flattened = ary_type->can_be_inline_array() && (!elem->is_inlinetypeptr() || elem->inline_klass()->flatten_array());
3870 }
3871 if (!can_be_flattened && (xklass || inst_klass->isa_aryklassptr())) {
3872 jint lhelper;
3873 if (inst_klass->is_flat()) {
3874 lhelper = ary_type->flat_layout_helper();
3875 } else if (inst_klass->isa_aryklassptr()) {
3876 BasicType elem = ary_type->elem()->array_element_basic_type();
3877 if (is_reference_type(elem, true)) {
3878 elem = T_OBJECT;
3879 }
3880 lhelper = Klass::array_layout_helper(elem);
3881 } else {
3882 lhelper = inst_klass->is_instklassptr()->exact_klass()->layout_helper();
3883 }
3884 if (lhelper != Klass::_lh_neutral_value) {
3885 constant_value = lhelper;
3886 return (Node*) nullptr;
3887 }
3888 }
3889 }
3890 constant_value = Klass::_lh_neutral_value; // put in a known value
3891 Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset()));
3892 return make_load(nullptr, lhp, TypeInt::INT, T_INT, MemNode::unordered);
3893 }
3894
3895 // We just put in an allocate/initialize with a big raw-memory effect.
3896 // Hook selected additional alias categories on the initialization.
3897 static void hook_memory_on_init(GraphKit& kit, int alias_idx,
3898 MergeMemNode* init_in_merge,
3899 Node* init_out_raw) {
3900 DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());
3901 assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");
3902
3903 Node* prevmem = kit.memory(alias_idx);
3904 init_in_merge->set_memory_at(alias_idx, prevmem);
3905 if (init_out_raw != nullptr) {
3906 kit.set_memory(init_out_raw, alias_idx);
3907 }
3908 }
3909
3910 //---------------------------set_output_for_allocation-------------------------
3911 Node* GraphKit::set_output_for_allocation(AllocateNode* alloc,
3912 const TypeOopPtr* oop_type,
3913 bool deoptimize_on_exception) {
3914 int rawidx = Compile::AliasIdxRaw;
3915 alloc->set_req( TypeFunc::FramePtr, frameptr() );
3916 add_safepoint_edges(alloc);
3917 Node* allocx = _gvn.transform(alloc);
3918 set_control( _gvn.transform(new ProjNode(allocx, TypeFunc::Control) ) );
3919 // create memory projection for i_o
3920 set_memory ( _gvn.transform( new ProjNode(allocx, TypeFunc::Memory, true) ), rawidx );
3921 make_slow_call_ex(allocx, env()->Throwable_klass(), true, deoptimize_on_exception);
3922
3923 // create a memory projection as for the normal control path
3924 Node* malloc = _gvn.transform(new ProjNode(allocx, TypeFunc::Memory));
3925 set_memory(malloc, rawidx);
3926
3927 // a normal slow-call doesn't change i_o, but an allocation does
3928 // we create a separate i_o projection for the normal control path
3929 set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) );
3930 Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) );
3931
3932 // put in an initialization barrier
3933 InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,
3934 rawoop)->as_Initialize();
3935 assert(alloc->initialization() == init, "2-way macro link must work");
3936 assert(init ->allocation() == alloc, "2-way macro link must work");
3937 {
3938 // Extract memory strands which may participate in the new object's
3939 // initialization, and source them from the new InitializeNode.
3940 // This will allow us to observe initializations when they occur,
3941 // and link them properly (as a group) to the InitializeNode.
3942 assert(init->in(InitializeNode::Memory) == malloc, "");
3943 MergeMemNode* minit_in = MergeMemNode::make(malloc);
3944 init->set_req(InitializeNode::Memory, minit_in);
3945 record_for_igvn(minit_in); // fold it up later, if possible
3946 _gvn.set_type(minit_in, Type::MEMORY);
3947 Node* minit_out = memory(rawidx);
3948 assert(minit_out->is_Proj() && minit_out->in(0) == init, "");
3949 // Add an edge in the MergeMem for the header fields so an access
3950 // to one of those has correct memory state
3951 set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::mark_offset_in_bytes())));
3952 set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes())));
3953 if (oop_type->isa_aryptr()) {
3954 const TypeAryPtr* arytype = oop_type->is_aryptr();
3955 if (arytype->is_flat()) {
3956 // Initially all flattened array accesses share a single slice
3957 // but that changes after parsing. Prepare the memory graph so
3958 // it can optimize flattened array accesses properly once they
3959 // don't share a single slice.
3960 assert(C->flattened_accesses_share_alias(), "should be set at parse time");
3961 C->set_flattened_accesses_share_alias(false);
3962 ciInlineKlass* vk = arytype->elem()->inline_klass();
3963 for (int i = 0, len = vk->nof_nonstatic_fields(); i < len; i++) {
3964 ciField* field = vk->nonstatic_field_at(i);
3965 if (field->offset_in_bytes() >= TrackedInitializationLimit * HeapWordSize)
3966 continue; // do not bother to track really large numbers of fields
3967 int off_in_vt = field->offset_in_bytes() - vk->first_field_offset();
3968 const TypePtr* adr_type = arytype->with_field_offset(off_in_vt)->add_offset(Type::OffsetBot);
3969 int fieldidx = C->get_alias_index(adr_type, true);
3970 // Pass nullptr for init_out. Having per flat array element field memory edges as uses of the Initialize node
3971 // can result in per flat array field Phis to be created which confuses the logic of
3972 // Compile::adjust_flattened_array_access_aliases().
3973 hook_memory_on_init(*this, fieldidx, minit_in, nullptr);
3974 }
3975 C->set_flattened_accesses_share_alias(true);
3976 hook_memory_on_init(*this, C->get_alias_index(TypeAryPtr::INLINES), minit_in, minit_out);
3977 } else {
3978 const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);
3979 int elemidx = C->get_alias_index(telemref);
3980 hook_memory_on_init(*this, elemidx, minit_in, minit_out);
3981 }
3982 } else if (oop_type->isa_instptr()) {
3983 set_memory(minit_out, C->get_alias_index(oop_type)); // mark word
3984 ciInstanceKlass* ik = oop_type->is_instptr()->instance_klass();
3985 for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {
3986 ciField* field = ik->nonstatic_field_at(i);
3987 if (field->offset_in_bytes() >= TrackedInitializationLimit * HeapWordSize)
3988 continue; // do not bother to track really large numbers of fields
3989 // Find (or create) the alias category for this field:
3990 int fieldidx = C->alias_type(field)->index();
3991 hook_memory_on_init(*this, fieldidx, minit_in, minit_out);
3992 }
3993 }
3994 }
3995
3996 // Cast raw oop to the real thing...
3997 Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type);
3998 javaoop = _gvn.transform(javaoop);
3999 C->set_recent_alloc(control(), javaoop);
4000 assert(just_allocated_object(control()) == javaoop, "just allocated");
4001
4002 #ifdef ASSERT
4003 { // Verify that the AllocateNode::Ideal_allocation recognizers work:
4014 assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");
4015 }
4016 }
4017 #endif //ASSERT
4018
4019 return javaoop;
4020 }
4021
4022 //---------------------------new_instance--------------------------------------
4023 // This routine takes a klass_node which may be constant (for a static type)
4024 // or may be non-constant (for reflective code). It will work equally well
4025 // for either, and the graph will fold nicely if the optimizer later reduces
4026 // the type to a constant.
4027 // The optional arguments are for specialized use by intrinsics:
4028 // - If 'extra_slow_test' if not null is an extra condition for the slow-path.
4029 // - If 'return_size_val', report the total object size to the caller.
4030 // - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
4031 Node* GraphKit::new_instance(Node* klass_node,
4032 Node* extra_slow_test,
4033 Node* *return_size_val,
4034 bool deoptimize_on_exception,
4035 InlineTypeNode* inline_type_node) {
4036 // Compute size in doublewords
4037 // The size is always an integral number of doublewords, represented
4038 // as a positive bytewise size stored in the klass's layout_helper.
4039 // The layout_helper also encodes (in a low bit) the need for a slow path.
4040 jint layout_con = Klass::_lh_neutral_value;
4041 Node* layout_val = get_layout_helper(klass_node, layout_con);
4042 bool layout_is_con = (layout_val == nullptr);
4043
4044 if (extra_slow_test == nullptr) extra_slow_test = intcon(0);
4045 // Generate the initial go-slow test. It's either ALWAYS (return a
4046 // Node for 1) or NEVER (return a null) or perhaps (in the reflective
4047 // case) a computed value derived from the layout_helper.
4048 Node* initial_slow_test = nullptr;
4049 if (layout_is_con) {
4050 assert(!StressReflectiveCode, "stress mode does not use these paths");
4051 bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);
4052 initial_slow_test = must_go_slow ? intcon(1) : extra_slow_test;
4053 } else { // reflective case
4054 // This reflective path is used by Unsafe.allocateInstance.
4055 // (It may be stress-tested by specifying StressReflectiveCode.)
4056 // Basically, we want to get into the VM is there's an illegal argument.
4057 Node* bit = intcon(Klass::_lh_instance_slow_path_bit);
4058 initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) );
4059 if (extra_slow_test != intcon(0)) {
4060 initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) );
4061 }
4062 // (Macro-expander will further convert this to a Bool, if necessary.)
4073
4074 // Clear the low bits to extract layout_helper_size_in_bytes:
4075 assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
4076 Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));
4077 size = _gvn.transform( new AndXNode(size, mask) );
4078 }
4079 if (return_size_val != nullptr) {
4080 (*return_size_val) = size;
4081 }
4082
4083 // This is a precise notnull oop of the klass.
4084 // (Actually, it need not be precise if this is a reflective allocation.)
4085 // It's what we cast the result to.
4086 const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();
4087 if (!tklass) tklass = TypeInstKlassPtr::OBJECT;
4088 const TypeOopPtr* oop_type = tklass->as_instance_type();
4089
4090 // Now generate allocation code
4091
4092 // The entire memory state is needed for slow path of the allocation
4093 // since GC and deoptimization can happen.
4094 Node *mem = reset_memory();
4095 set_all_memory(mem); // Create new memory state
4096
4097 AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP),
4098 control(), mem, i_o(),
4099 size, klass_node,
4100 initial_slow_test, inline_type_node);
4101
4102 return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);
4103 }
4104
4105 //-------------------------------new_array-------------------------------------
4106 // helper for newarray and anewarray
4107 // The 'length' parameter is (obviously) the length of the array.
4108 // See comments on new_instance for the meaning of the other arguments.
4109 Node* GraphKit::new_array(Node* klass_node, // array klass (maybe variable)
4110 Node* length, // number of array elements
4111 int nargs, // number of arguments to push back for uncommon trap
4112 Node* *return_size_val,
4113 bool deoptimize_on_exception) {
4114 jint layout_con = Klass::_lh_neutral_value;
4115 Node* layout_val = get_layout_helper(klass_node, layout_con);
4116 bool layout_is_con = (layout_val == nullptr);
4117
4118 if (!layout_is_con && !StressReflectiveCode &&
4119 !too_many_traps(Deoptimization::Reason_class_check)) {
4120 // This is a reflective array creation site.
4121 // Optimistically assume that it is a subtype of Object[],
4122 // so that we can fold up all the address arithmetic.
4123 layout_con = Klass::array_layout_helper(T_OBJECT);
4124 Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) );
4125 Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) );
4126 { BuildCutout unless(this, bol_lh, PROB_MAX);
4127 inc_sp(nargs);
4128 uncommon_trap(Deoptimization::Reason_class_check,
4129 Deoptimization::Action_maybe_recompile);
4130 }
4131 layout_val = nullptr;
4132 layout_is_con = true;
4133 }
4134
4135 // Generate the initial go-slow test. Make sure we do not overflow
4136 // if length is huge (near 2Gig) or negative! We do not need
4137 // exact double-words here, just a close approximation of needed
4138 // double-words. We can't add any offset or rounding bits, lest we
4139 // take a size -1 of bytes and make it positive. Use an unsigned
4140 // compare, so negative sizes look hugely positive.
4141 int fast_size_limit = FastAllocateSizeLimit;
4142 if (layout_is_con) {
4143 assert(!StressReflectiveCode, "stress mode does not use these paths");
4144 // Increase the size limit if we have exact knowledge of array type.
4145 int log2_esize = Klass::layout_helper_log2_element_size(layout_con);
4146 fast_size_limit <<= MAX2(LogBytesPerLong - log2_esize, 0);
4147 }
4148
4149 Node* initial_slow_cmp = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) );
4150 Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) );
4151
4152 // --- Size Computation ---
4153 // array_size = round_to_heap(array_header + (length << elem_shift));
4154 // where round_to_heap(x) == align_to(x, MinObjAlignmentInBytes)
4155 // and align_to(x, y) == ((x + y-1) & ~(y-1))
4156 // The rounding mask is strength-reduced, if possible.
4157 int round_mask = MinObjAlignmentInBytes - 1;
4158 Node* header_size = nullptr;
4159 int header_size_min = arrayOopDesc::base_offset_in_bytes(T_BYTE);
4160 // (T_BYTE has the weakest alignment and size restrictions...)
4161 if (layout_is_con) {
4162 int hsize = Klass::layout_helper_header_size(layout_con);
4163 int eshift = Klass::layout_helper_log2_element_size(layout_con);
4164 bool is_flat_array = Klass::layout_helper_is_flatArray(layout_con);
4165 if ((round_mask & ~right_n_bits(eshift)) == 0)
4166 round_mask = 0; // strength-reduce it if it goes away completely
4167 assert(is_flat_array || (hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
4168 assert(header_size_min <= hsize, "generic minimum is smallest");
4169 header_size_min = hsize;
4170 header_size = intcon(hsize + round_mask);
4171 } else {
4172 Node* hss = intcon(Klass::_lh_header_size_shift);
4173 Node* hsm = intcon(Klass::_lh_header_size_mask);
4174 Node* hsize = _gvn.transform( new URShiftINode(layout_val, hss) );
4175 hsize = _gvn.transform( new AndINode(hsize, hsm) );
4176 Node* mask = intcon(round_mask);
4177 header_size = _gvn.transform( new AddINode(hsize, mask) );
4178 }
4179
4180 Node* elem_shift = nullptr;
4181 if (layout_is_con) {
4182 int eshift = Klass::layout_helper_log2_element_size(layout_con);
4183 if (eshift != 0)
4184 elem_shift = intcon(eshift);
4185 } else {
4186 // There is no need to mask or shift this value.
4187 // The semantics of LShiftINode include an implicit mask to 0x1F.
4231 // places, one where the length is sharply limited, and the other
4232 // after a successful allocation.
4233 Node* abody = lengthx;
4234 if (elem_shift != nullptr)
4235 abody = _gvn.transform( new LShiftXNode(lengthx, elem_shift) );
4236 Node* size = _gvn.transform( new AddXNode(headerx, abody) );
4237 if (round_mask != 0) {
4238 Node* mask = MakeConX(~round_mask);
4239 size = _gvn.transform( new AndXNode(size, mask) );
4240 }
4241 // else if round_mask == 0, the size computation is self-rounding
4242
4243 if (return_size_val != nullptr) {
4244 // This is the size
4245 (*return_size_val) = size;
4246 }
4247
4248 // Now generate allocation code
4249
4250 // The entire memory state is needed for slow path of the allocation
4251 // since GC and deoptimization can happen.
4252 Node *mem = reset_memory();
4253 set_all_memory(mem); // Create new memory state
4254
4255 if (initial_slow_test->is_Bool()) {
4256 // Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.
4257 initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);
4258 }
4259
4260 const TypeKlassPtr* ary_klass = _gvn.type(klass_node)->isa_klassptr();
4261 const TypeOopPtr* ary_type = ary_klass->as_instance_type();
4262 const TypeAryPtr* ary_ptr = ary_type->isa_aryptr();
4263
4264 // Inline type array variants:
4265 // - null-ok: MyValue.ref[] (ciObjArrayKlass "[LMyValue")
4266 // - null-free: MyValue.val[] (ciObjArrayKlass "[QMyValue")
4267 // - null-free, flattened: MyValue.val[] (ciFlatArrayKlass "[QMyValue")
4268 // Check if array is a null-free, non-flattened inline type array
4269 // that needs to be initialized with the default inline type.
4270 Node* default_value = nullptr;
4271 Node* raw_default_value = nullptr;
4272 if (ary_ptr != nullptr && ary_ptr->klass_is_exact()) {
4273 // Array type is known
4274 if (ary_ptr->is_null_free() && !ary_ptr->is_flat()) {
4275 ciInlineKlass* vk = ary_ptr->elem()->inline_klass();
4276 default_value = InlineTypeNode::default_oop(gvn(), vk);
4277 }
4278 } else if (ary_type->can_be_inline_array()) {
4279 // Array type is not known, add runtime checks
4280 assert(!ary_klass->klass_is_exact(), "unexpected exact type");
4281 Node* r = new RegionNode(3);
4282 default_value = new PhiNode(r, TypeInstPtr::BOTTOM);
4283
4284 Node* bol = array_lh_test(klass_node, Klass::_lh_array_tag_flat_value_bit_inplace | Klass::_lh_null_free_array_bit_inplace, Klass::_lh_null_free_array_bit_inplace);
4285 IfNode* iff = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
4286
4287 // Null-free, non-flattened inline type array, initialize with the default value
4288 set_control(_gvn.transform(new IfTrueNode(iff)));
4289 Node* p = basic_plus_adr(klass_node, in_bytes(ArrayKlass::element_klass_offset()));
4290 Node* eklass = _gvn.transform(LoadKlassNode::make(_gvn, control(), immutable_memory(), p, TypeInstPtr::KLASS));
4291 Node* adr_fixed_block_addr = basic_plus_adr(eklass, in_bytes(InstanceKlass::adr_inlineklass_fixed_block_offset()));
4292 Node* adr_fixed_block = make_load(control(), adr_fixed_block_addr, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4293 Node* default_value_offset_addr = basic_plus_adr(adr_fixed_block, in_bytes(InlineKlass::default_value_offset_offset()));
4294 Node* default_value_offset = make_load(control(), default_value_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
4295 Node* elem_mirror = load_mirror_from_klass(eklass);
4296 Node* default_value_addr = basic_plus_adr(elem_mirror, ConvI2X(default_value_offset));
4297 Node* val = access_load_at(elem_mirror, default_value_addr, TypeInstPtr::MIRROR, TypeInstPtr::NOTNULL, T_OBJECT, IN_HEAP);
4298 r->init_req(1, control());
4299 default_value->init_req(1, val);
4300
4301 // Otherwise initialize with all zero
4302 r->init_req(2, _gvn.transform(new IfFalseNode(iff)));
4303 default_value->init_req(2, null());
4304
4305 set_control(_gvn.transform(r));
4306 default_value = _gvn.transform(default_value);
4307 }
4308 if (default_value != nullptr) {
4309 if (UseCompressedOops) {
4310 // With compressed oops, the 64-bit init value is built from two 32-bit compressed oops
4311 default_value = _gvn.transform(new EncodePNode(default_value, default_value->bottom_type()->make_narrowoop()));
4312 Node* lower = _gvn.transform(new CastP2XNode(control(), default_value));
4313 Node* upper = _gvn.transform(new LShiftLNode(lower, intcon(32)));
4314 raw_default_value = _gvn.transform(new OrLNode(lower, upper));
4315 } else {
4316 raw_default_value = _gvn.transform(new CastP2XNode(control(), default_value));
4317 }
4318 }
4319
4320 Node* valid_length_test = _gvn.intcon(1);
4321 if (ary_type->isa_aryptr()) {
4322 BasicType bt = ary_type->isa_aryptr()->elem()->array_element_basic_type();
4323 jint max = TypeAryPtr::max_array_length(bt);
4324 Node* valid_length_cmp = _gvn.transform(new CmpUNode(length, intcon(max)));
4325 valid_length_test = _gvn.transform(new BoolNode(valid_length_cmp, BoolTest::le));
4326 }
4327
4328 // Create the AllocateArrayNode and its result projections
4329 AllocateArrayNode* alloc
4330 = new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),
4331 control(), mem, i_o(),
4332 size, klass_node,
4333 initial_slow_test,
4334 length, valid_length_test,
4335 default_value, raw_default_value);
4336 // Cast to correct type. Note that the klass_node may be constant or not,
4337 // and in the latter case the actual array type will be inexact also.
4338 // (This happens via a non-constant argument to inline_native_newArray.)
4339 // In any case, the value of klass_node provides the desired array type.
4340 const TypeInt* length_type = _gvn.find_int_type(length);
4341 if (ary_type->isa_aryptr() && length_type != nullptr) {
4342 // Try to get a better type than POS for the size
4343 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
4344 }
4345
4346 Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);
4347
4348 array_ideal_length(alloc, ary_type, true);
4349 return javaoop;
4350 }
4351
4352 // The following "Ideal_foo" functions are placed here because they recognize
4353 // the graph shapes created by the functions immediately above.
4354
4355 //---------------------------Ideal_allocation----------------------------------
4465 set_all_memory(ideal.merged_memory());
4466 set_i_o(ideal.i_o());
4467 set_control(ideal.ctrl());
4468 }
4469
4470 void GraphKit::final_sync(IdealKit& ideal) {
4471 // Final sync IdealKit and graphKit.
4472 sync_kit(ideal);
4473 }
4474
4475 Node* GraphKit::load_String_length(Node* str, bool set_ctrl) {
4476 Node* len = load_array_length(load_String_value(str, set_ctrl));
4477 Node* coder = load_String_coder(str, set_ctrl);
4478 // Divide length by 2 if coder is UTF16
4479 return _gvn.transform(new RShiftINode(len, coder));
4480 }
4481
4482 Node* GraphKit::load_String_value(Node* str, bool set_ctrl) {
4483 int value_offset = java_lang_String::value_offset();
4484 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4485 false, nullptr, Type::Offset(0));
4486 const TypePtr* value_field_type = string_type->add_offset(value_offset);
4487 const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull,
4488 TypeAry::make(TypeInt::BYTE, TypeInt::POS, false, false, true, true),
4489 ciTypeArrayKlass::make(T_BYTE), true, Type::Offset(0));
4490 Node* p = basic_plus_adr(str, str, value_offset);
4491 Node* load = access_load_at(str, p, value_field_type, value_type, T_OBJECT,
4492 IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4493 return load;
4494 }
4495
4496 Node* GraphKit::load_String_coder(Node* str, bool set_ctrl) {
4497 if (!CompactStrings) {
4498 return intcon(java_lang_String::CODER_UTF16);
4499 }
4500 int coder_offset = java_lang_String::coder_offset();
4501 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4502 false, nullptr, Type::Offset(0));
4503 const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4504
4505 Node* p = basic_plus_adr(str, str, coder_offset);
4506 Node* load = access_load_at(str, p, coder_field_type, TypeInt::BYTE, T_BYTE,
4507 IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4508 return load;
4509 }
4510
4511 void GraphKit::store_String_value(Node* str, Node* value) {
4512 int value_offset = java_lang_String::value_offset();
4513 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4514 false, nullptr, Type::Offset(0));
4515 const TypePtr* value_field_type = string_type->add_offset(value_offset);
4516
4517 access_store_at(str, basic_plus_adr(str, value_offset), value_field_type,
4518 value, TypeAryPtr::BYTES, T_OBJECT, IN_HEAP | MO_UNORDERED);
4519 }
4520
4521 void GraphKit::store_String_coder(Node* str, Node* value) {
4522 int coder_offset = java_lang_String::coder_offset();
4523 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4524 false, nullptr, Type::Offset(0));
4525 const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4526
4527 access_store_at(str, basic_plus_adr(str, coder_offset), coder_field_type,
4528 value, TypeInt::BYTE, T_BYTE, IN_HEAP | MO_UNORDERED);
4529 }
4530
4531 // Capture src and dst memory state with a MergeMemNode
4532 Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) {
4533 if (src_type == dst_type) {
4534 // Types are equal, we don't need a MergeMemNode
4535 return memory(src_type);
4536 }
4537 MergeMemNode* merge = MergeMemNode::make(map()->memory());
4538 record_for_igvn(merge); // fold it up later, if possible
4539 int src_idx = C->get_alias_index(src_type);
4540 int dst_idx = C->get_alias_index(dst_type);
4541 merge->set_memory_at(src_idx, memory(src_idx));
4542 merge->set_memory_at(dst_idx, memory(dst_idx));
4543 return merge;
4544 }
4617 i_char->init_req(2, AddI(i_char, intcon(2)));
4618
4619 set_control(IfFalse(iff));
4620 set_memory(st, TypeAryPtr::BYTES);
4621 }
4622
4623 Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) {
4624 if (!field->is_constant()) {
4625 return nullptr; // Field not marked as constant.
4626 }
4627 ciInstance* holder = nullptr;
4628 if (!field->is_static()) {
4629 ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop();
4630 if (const_oop != nullptr && const_oop->is_instance()) {
4631 holder = const_oop->as_instance();
4632 }
4633 }
4634 const Type* con_type = Type::make_constant_from_field(field, holder, field->layout_type(),
4635 /*is_unsigned_load=*/false);
4636 if (con_type != nullptr) {
4637 Node* con = makecon(con_type);
4638 if (field->type()->is_inlinetype()) {
4639 con = InlineTypeNode::make_from_oop(this, con, field->type()->as_inline_klass(), field->is_null_free());
4640 } else if (con_type->is_inlinetypeptr()) {
4641 con = InlineTypeNode::make_from_oop(this, con, con_type->inline_klass(), field->is_null_free());
4642 }
4643 return con;
4644 }
4645 return nullptr;
4646 }
4647
4648 //---------------------------load_mirror_from_klass----------------------------
4649 // Given a klass oop, load its java mirror (a java.lang.Class oop).
4650 Node* GraphKit::load_mirror_from_klass(Node* klass) {
4651 Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
4652 Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4653 // mirror = ((OopHandle)mirror)->resolve();
4654 return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4655 }
|