< prev index next >

src/hotspot/share/opto/graphKit.cpp

Print this page

   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 != NULL)  jvms->map()->set_next_exception(NULL);
  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 = NULL;
  75   set_map(NULL);
  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.

 817         if (PrintMiscellaneous && (Verbose || WizardMode)) {
 818           tty->print_cr("Zombie local %d: ", local);
 819           jvms->dump();
 820         }
 821         return false;
 822       }
 823     }
 824   }
 825   return true;
 826 }
 827 
 828 #endif //ASSERT
 829 
 830 // Helper function for enforcing certain bytecodes to reexecute if deoptimization happens.
 831 static bool should_reexecute_implied_by_bytecode(JVMState *jvms, bool is_anewarray) {
 832   ciMethod* cur_method = jvms->method();
 833   int       cur_bci   = jvms->bci();
 834   if (cur_method != NULL && cur_bci != InvocationEntryBci) {
 835     Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci);
 836     return Interpreter::bytecode_should_reexecute(code) ||
 837            (is_anewarray && code == Bytecodes::_multianewarray);
 838     // Reexecute _multianewarray bytecode which was replaced with
 839     // sequence of [a]newarray. See Parse::do_multianewarray().
 840     //
 841     // Note: interpreter should not have it set since this optimization
 842     // is limited by dimensions and guarded by flag so in some cases
 843     // multianewarray() runtime calls will be generated and
 844     // the bytecode should not be reexecutes (stack will not be reset).
 845   } else {
 846     return false;
 847   }
 848 }
 849 
 850 // Helper function for adding JVMState and debug information to node
 851 void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) {
 852   // Add the safepoint edges to the call (or other safepoint).
 853 
 854   // Make sure dead locals are set to top.  This
 855   // should help register allocation time and cut down on the size
 856   // of the deoptimization information.
 857   assert(dead_locals_are_killed(), "garbage in debug info before safepoint");

1077       ciSignature* declared_signature = NULL;
1078       ciMethod* ignored_callee = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
1079       assert(declared_signature != NULL, "cannot be null");
1080       inputs   = declared_signature->arg_size_for_bc(code);
1081       int size = declared_signature->return_type()->size();
1082       depth = size - inputs;
1083     }
1084     break;
1085 
1086   case Bytecodes::_multianewarray:
1087     {
1088       ciBytecodeStream iter(method());
1089       iter.reset_to_bci(bci());
1090       iter.next();
1091       inputs = iter.get_dimensions();
1092       assert(rsize == 1, "");
1093       depth = rsize - inputs;
1094     }
1095     break;
1096 









1097   case Bytecodes::_ireturn:
1098   case Bytecodes::_lreturn:
1099   case Bytecodes::_freturn:
1100   case Bytecodes::_dreturn:
1101   case Bytecodes::_areturn:
1102     assert(rsize == -depth, "");
1103     inputs = rsize;
1104     break;
1105 
1106   case Bytecodes::_jsr:
1107   case Bytecodes::_jsr_w:
1108     inputs = 0;
1109     depth  = 1;                  // S.B. depth=1, not zero
1110     break;
1111 
1112   default:
1113     // bytecode produces a typed result
1114     inputs = rsize - depth;
1115     assert(inputs >= 0, "");
1116     break;

1159   Node* conv = _gvn.transform( new ConvI2LNode(offset));
1160   Node* mask = _gvn.transform(ConLNode::make((julong) max_juint));
1161   return _gvn.transform( new AndLNode(conv, mask) );
1162 }
1163 
1164 Node* GraphKit::ConvL2I(Node* offset) {
1165   // short-circuit a common case
1166   jlong offset_con = find_long_con(offset, (jlong)Type::OffsetBot);
1167   if (offset_con != (jlong)Type::OffsetBot) {
1168     return intcon((int) offset_con);
1169   }
1170   return _gvn.transform( new ConvL2INode(offset));
1171 }
1172 
1173 //-------------------------load_object_klass-----------------------------------
1174 Node* GraphKit::load_object_klass(Node* obj) {
1175   // Special-case a fresh allocation to avoid building nodes:
1176   Node* akls = AllocateNode::Ideal_klass(obj, &_gvn);
1177   if (akls != NULL)  return akls;
1178   Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
1179   return _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), k_adr, TypeInstPtr::KLASS));
1180 }
1181 
1182 //-------------------------load_array_length-----------------------------------
1183 Node* GraphKit::load_array_length(Node* array) {
1184   // Special-case a fresh allocation to avoid building nodes:
1185   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(array, &_gvn);
1186   Node *alen;
1187   if (alloc == NULL) {
1188     Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes());
1189     alen = _gvn.transform( new LoadRangeNode(0, immutable_memory(), r_adr, TypeInt::POS));
1190   } else {
1191     alen = array_ideal_length(alloc, _gvn.type(array)->is_oopptr(), false);
1192   }
1193   return alen;
1194 }
1195 
1196 Node* GraphKit::array_ideal_length(AllocateArrayNode* alloc,
1197                                    const TypeOopPtr* oop_type,
1198                                    bool replace_length_in_map) {
1199   Node* length = alloc->Ideal_length();

1208         replace_in_map(length, ccast);
1209       }
1210       return ccast;
1211     }
1212   }
1213   return length;
1214 }
1215 
1216 //------------------------------do_null_check----------------------------------
1217 // Helper function to do a NULL pointer check.  Returned value is
1218 // the incoming address with NULL casted away.  You are allowed to use the
1219 // not-null value only if you are control dependent on the test.
1220 #ifndef PRODUCT
1221 extern int explicit_null_checks_inserted,
1222            explicit_null_checks_elided;
1223 #endif
1224 Node* GraphKit::null_check_common(Node* value, BasicType type,
1225                                   // optional arguments for variations:
1226                                   bool assert_null,
1227                                   Node* *null_control,
1228                                   bool speculative) {

1229   assert(!assert_null || null_control == NULL, "not both at once");
1230   if (stopped())  return top();
1231   NOT_PRODUCT(explicit_null_checks_inserted++);
1232 






















1233   // Construct NULL check
1234   Node *chk = NULL;
1235   switch(type) {
1236     case T_LONG   : chk = new CmpLNode(value, _gvn.zerocon(T_LONG)); break;
1237     case T_INT    : chk = new CmpINode(value, _gvn.intcon(0)); break;

1238     case T_ARRAY  : // fall through
1239       type = T_OBJECT;  // simplify further tests
1240     case T_OBJECT : {
1241       const Type *t = _gvn.type( value );
1242 
1243       const TypeOopPtr* tp = t->isa_oopptr();
1244       if (tp != NULL && !tp->is_loaded()
1245           // Only for do_null_check, not any of its siblings:
1246           && !assert_null && null_control == NULL) {
1247         // Usually, any field access or invocation on an unloaded oop type
1248         // will simply fail to link, since the statically linked class is
1249         // likely also to be unloaded.  However, in -Xcomp mode, sometimes
1250         // the static class is loaded but the sharper oop type is not.
1251         // Rather than checking for this obscure case in lots of places,
1252         // we simply observe that a null check on an unloaded class
1253         // will always be followed by a nonsense operation, so we
1254         // can just issue the uncommon trap here.
1255         // Our access to the unloaded class will only be correct
1256         // after it has been loaded and initialized, which requires
1257         // a trip through the interpreter.

1316         }
1317         Node *oldcontrol = control();
1318         set_control(cfg);
1319         Node *res = cast_not_null(value);
1320         set_control(oldcontrol);
1321         NOT_PRODUCT(explicit_null_checks_elided++);
1322         return res;
1323       }
1324       cfg = IfNode::up_one_dom(cfg, /*linear_only=*/ true);
1325       if (cfg == NULL)  break;  // Quit at region nodes
1326       depth++;
1327     }
1328   }
1329 
1330   //-----------
1331   // Branch to failure if null
1332   float ok_prob = PROB_MAX;  // a priori estimate:  nulls never happen
1333   Deoptimization::DeoptReason reason;
1334   if (assert_null) {
1335     reason = Deoptimization::reason_null_assert(speculative);
1336   } else if (type == T_OBJECT) {
1337     reason = Deoptimization::reason_null_check(speculative);
1338   } else {
1339     reason = Deoptimization::Reason_div0_check;
1340   }
1341   // %%% Since Reason_unhandled is not recorded on a per-bytecode basis,
1342   // ciMethodData::has_trap_at will return a conservative -1 if any
1343   // must-be-null assertion has failed.  This could cause performance
1344   // problems for a method after its first do_null_assert failure.
1345   // Consider using 'Reason_class_check' instead?
1346 
1347   // To cause an implicit null check, we set the not-null probability
1348   // to the maximum (PROB_MAX).  For an explicit check the probability
1349   // is set to a smaller value.
1350   if (null_control != NULL || too_many_traps(reason)) {
1351     // probability is less likely
1352     ok_prob =  PROB_LIKELY_MAG(3);
1353   } else if (!assert_null &&
1354              (ImplicitNullCheckThreshold > 0) &&
1355              method() != NULL &&
1356              (method()->method_data()->trap_count(reason)

1390   }
1391 
1392   if (assert_null) {
1393     // Cast obj to null on this path.
1394     replace_in_map(value, zerocon(type));
1395     return zerocon(type);
1396   }
1397 
1398   // Cast obj to not-null on this path, if there is no null_control.
1399   // (If there is a null_control, a non-null value may come back to haunt us.)
1400   if (type == T_OBJECT) {
1401     Node* cast = cast_not_null(value, false);
1402     if (null_control == NULL || (*null_control) == top())
1403       replace_in_map(value, cast);
1404     value = cast;
1405   }
1406 
1407   return value;
1408 }
1409 
1410 
1411 //------------------------------cast_not_null----------------------------------
1412 // Cast obj to not-null on this path
1413 Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) {









1414   const Type *t = _gvn.type(obj);
1415   const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL);
1416   // Object is already not-null?
1417   if( t == t_not_null ) return obj;
1418 
1419   Node *cast = new CastPPNode(obj,t_not_null);
1420   cast->init_req(0, control());
1421   cast = _gvn.transform( cast );
1422 
1423   // Scan for instances of 'obj' in the current JVM mapping.
1424   // These instances are known to be not-null after the test.
1425   if (do_replace_in_map)
1426     replace_in_map(obj, cast);
1427 
1428   return cast;                  // Return casted value
1429 }
1430 
1431 // Sometimes in intrinsics, we implicitly know an object is not null
1432 // (there's no actual null check) so we can cast it to not null. In
1433 // the course of optimizations, the input to the cast can become null.

1520 // These are layered on top of the factory methods in LoadNode and StoreNode,
1521 // and integrate with the parser's memory state and _gvn engine.
1522 //
1523 
1524 // factory methods in "int adr_idx"
1525 Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,
1526                           int adr_idx,
1527                           MemNode::MemOrd mo,
1528                           LoadNode::ControlDependency control_dependency,
1529                           bool require_atomic_access,
1530                           bool unaligned,
1531                           bool mismatched,
1532                           bool unsafe,
1533                           uint8_t barrier_data) {
1534   assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );
1535   const TypePtr* adr_type = NULL; // debug-mode-only argument
1536   debug_only(adr_type = C->get_adr_type(adr_idx));
1537   Node* mem = memory(adr_idx);
1538   Node* ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, require_atomic_access, unaligned, mismatched, unsafe, barrier_data);
1539   ld = _gvn.transform(ld);
1540   if (((bt == T_OBJECT) && C->do_escape_analysis()) || C->eliminate_boxing()) {

1541     // Improve graph before escape analysis and boxing elimination.
1542     record_for_igvn(ld);
1543   }
1544   return ld;
1545 }
1546 
1547 Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,
1548                                 int adr_idx,
1549                                 MemNode::MemOrd mo,
1550                                 bool require_atomic_access,
1551                                 bool unaligned,
1552                                 bool mismatched,
1553                                 bool unsafe) {
1554   assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
1555   const TypePtr* adr_type = NULL;
1556   debug_only(adr_type = C->get_adr_type(adr_idx));
1557   Node *mem = memory(adr_idx);
1558   Node* st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo, require_atomic_access);
1559   if (unaligned) {
1560     st->as_Store()->set_unaligned_access();

1564   }
1565   if (unsafe) {
1566     st->as_Store()->set_unsafe_access();
1567   }
1568   st = _gvn.transform(st);
1569   set_memory(st, adr_idx);
1570   // Back-to-back stores can only remove intermediate store with DU info
1571   // so push on worklist for optimizer.
1572   if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))
1573     record_for_igvn(st);
1574 
1575   return st;
1576 }
1577 
1578 Node* GraphKit::access_store_at(Node* obj,
1579                                 Node* adr,
1580                                 const TypePtr* adr_type,
1581                                 Node* val,
1582                                 const Type* val_type,
1583                                 BasicType bt,
1584                                 DecoratorSet decorators) {

1585   // Transformation of a value which could be NULL pointer (CastPP #NULL)
1586   // could be delayed during Parse (for example, in adjust_map_after_if()).
1587   // Execute transformation here to avoid barrier generation in such case.
1588   if (_gvn.type(val) == TypePtr::NULL_PTR) {
1589     val = _gvn.makecon(TypePtr::NULL_PTR);
1590   }
1591 
1592   if (stopped()) {
1593     return top(); // Dead path ?
1594   }
1595 
1596   assert(val != NULL, "not dead path");







1597 
1598   C2AccessValuePtr addr(adr, adr_type);
1599   C2AccessValue value(val, val_type);
1600   C2ParseAccess access(this, decorators | C2_WRITE_ACCESS, bt, obj, addr);
1601   if (access.is_raw()) {
1602     return _barrier_set->BarrierSetC2::store_at(access, value);
1603   } else {
1604     return _barrier_set->store_at(access, value);
1605   }
1606 }
1607 
1608 Node* GraphKit::access_load_at(Node* obj,   // containing obj
1609                                Node* adr,   // actual address to store val at
1610                                const TypePtr* adr_type,
1611                                const Type* val_type,
1612                                BasicType bt,
1613                                DecoratorSet decorators) {

1614   if (stopped()) {
1615     return top(); // Dead path ?
1616   }
1617 
1618   C2AccessValuePtr addr(adr, adr_type);
1619   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, obj, addr);
1620   if (access.is_raw()) {
1621     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1622   } else {
1623     return _barrier_set->load_at(access, val_type);
1624   }
1625 }
1626 
1627 Node* GraphKit::access_load(Node* adr,   // actual address to load val at
1628                             const Type* val_type,
1629                             BasicType bt,
1630                             DecoratorSet decorators) {
1631   if (stopped()) {
1632     return top(); // Dead path ?
1633   }
1634 
1635   C2AccessValuePtr addr(adr, adr->bottom_type()->is_ptr());
1636   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, NULL, addr);
1637   if (access.is_raw()) {
1638     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1639   } else {

1704                                      Node* new_val,
1705                                      const Type* value_type,
1706                                      BasicType bt,
1707                                      DecoratorSet decorators) {
1708   C2AccessValuePtr addr(adr, adr_type);
1709   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, bt, obj, addr, alias_idx);
1710   if (access.is_raw()) {
1711     return _barrier_set->BarrierSetC2::atomic_add_at(access, new_val, value_type);
1712   } else {
1713     return _barrier_set->atomic_add_at(access, new_val, value_type);
1714   }
1715 }
1716 
1717 void GraphKit::access_clone(Node* src, Node* dst, Node* size, bool is_array) {
1718   return _barrier_set->clone(this, src, dst, size, is_array);
1719 }
1720 
1721 //-------------------------array_element_address-------------------------
1722 Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,
1723                                       const TypeInt* sizetype, Node* ctrl) {
1724   uint shift  = exact_log2(type2aelembytes(elembt));

1725   uint header = arrayOopDesc::base_offset_in_bytes(elembt);
1726 
1727   // short-circuit a common case (saves lots of confusing waste motion)
1728   jint idx_con = find_int_con(idx, -1);
1729   if (idx_con >= 0) {
1730     intptr_t offset = header + ((intptr_t)idx_con << shift);
1731     return basic_plus_adr(ary, offset);
1732   }
1733 
1734   // must be correct type for alignment purposes
1735   Node* base  = basic_plus_adr(ary, header);
1736   idx = Compile::conv_I2X_index(&_gvn, idx, sizetype, ctrl);
1737   Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) );
1738   return basic_plus_adr(ary, base, scale);
1739 }
1740 
1741 //-------------------------load_array_element-------------------------
1742 Node* GraphKit::load_array_element(Node* ary, Node* idx, const TypeAryPtr* arytype, bool set_ctrl) {
1743   const Type* elemtype = arytype->elem();
1744   BasicType elembt = elemtype->array_element_basic_type();

1745   Node* adr = array_element_address(ary, idx, elembt, arytype->size());
1746   if (elembt == T_NARROWOOP) {
1747     elembt = T_OBJECT; // To satisfy switch in LoadNode::make()
1748   }
1749   Node* ld = access_load_at(ary, adr, arytype, elemtype, elembt,
1750                             IN_HEAP | IS_ARRAY | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0));
1751   return ld;
1752 }
1753 
1754 //-------------------------set_arguments_for_java_call-------------------------
1755 // Arguments (pre-popped from the stack) are taken from the JVMS.
1756 void GraphKit::set_arguments_for_java_call(CallJavaNode* call) {
1757   // Add the call arguments:
1758   uint nargs = call->method()->arg_size();
1759   for (uint i = 0; i < nargs; i++) {
1760     Node* arg = argument(i);
1761     call->init_req(i + TypeFunc::Parms, arg);



































1762   }
1763 }
1764 
1765 //---------------------------set_edges_for_java_call---------------------------
1766 // Connect a newly created call into the current JVMS.
1767 // A return value node (if any) is returned from set_edges_for_java_call.
1768 void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) {
1769 
1770   // Add the predefined inputs:
1771   call->init_req( TypeFunc::Control, control() );
1772   call->init_req( TypeFunc::I_O    , i_o() );
1773   call->init_req( TypeFunc::Memory , reset_memory() );
1774   call->init_req( TypeFunc::FramePtr, frameptr() );
1775   call->init_req( TypeFunc::ReturnAdr, top() );
1776 
1777   add_safepoint_edges(call, must_throw);
1778 
1779   Node* xcall = _gvn.transform(call);
1780 
1781   if (xcall == top()) {
1782     set_control(top());
1783     return;
1784   }
1785   assert(xcall == call, "call identity is stable");
1786 
1787   // Re-use the current map to produce the result.
1788 
1789   set_control(_gvn.transform(new ProjNode(call, TypeFunc::Control)));
1790   set_i_o(    _gvn.transform(new ProjNode(call, TypeFunc::I_O    , separate_io_proj)));
1791   set_all_memory_call(xcall, separate_io_proj);
1792 
1793   //return xcall;   // no need, caller already has it
1794 }
1795 
1796 Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj, bool deoptimize) {
1797   if (stopped())  return top();  // maybe the call folded up?
1798 
1799   // Capture the return value, if any.
1800   Node* ret;
1801   if (call->method() == NULL ||
1802       call->method()->return_type()->basic_type() == T_VOID)
1803         ret = top();
1804   else  ret = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1805 
1806   // Note:  Since any out-of-line call can produce an exception,
1807   // we always insert an I_O projection from the call into the result.
1808 
1809   make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj, deoptimize);
1810 
1811   if (separate_io_proj) {
1812     // The caller requested separate projections be used by the fall
1813     // through and exceptional paths, so replace the projections for
1814     // the fall through path.
1815     set_i_o(_gvn.transform( new ProjNode(call, TypeFunc::I_O) ));
1816     set_all_memory(_gvn.transform( new ProjNode(call, TypeFunc::Memory) ));
1817   }















1818   return ret;
1819 }
1820 
1821 //--------------------set_predefined_input_for_runtime_call--------------------
1822 // Reading and setting the memory state is way conservative here.
1823 // The real problem is that I am not doing real Type analysis on memory,
1824 // so I cannot distinguish card mark stores from other stores.  Across a GC
1825 // point the Store Barrier and the card mark memory has to agree.  I cannot
1826 // have a card mark store and its barrier split across the GC point from
1827 // either above or below.  Here I get that to happen by reading ALL of memory.
1828 // A better answer would be to separate out card marks from other memory.
1829 // For now, return the input memory state, so that it can be reused
1830 // after the call, if this call has restricted memory effects.
1831 Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) {
1832   // Set fixed predefined input arguments
1833   Node* memory = reset_memory();
1834   Node* m = narrow_mem == NULL ? memory : narrow_mem;
1835   call->init_req( TypeFunc::Control,   control()  );
1836   call->init_req( TypeFunc::I_O,       top()      ); // does no i/o
1837   call->init_req( TypeFunc::Memory,    m          ); // may gc ptrs

1888     if (use->is_MergeMem()) {
1889       wl.push(use);
1890     }
1891   }
1892 }
1893 
1894 // Replace the call with the current state of the kit.
1895 void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes) {
1896   JVMState* ejvms = NULL;
1897   if (has_exceptions()) {
1898     ejvms = transfer_exceptions_into_jvms();
1899   }
1900 
1901   ReplacedNodes replaced_nodes = map()->replaced_nodes();
1902   ReplacedNodes replaced_nodes_exception;
1903   Node* ex_ctl = top();
1904 
1905   SafePointNode* final_state = stop();
1906 
1907   // Find all the needed outputs of this call
1908   CallProjections callprojs;
1909   call->extract_projections(&callprojs, true);
1910 
1911   Unique_Node_List wl;
1912   Node* init_mem = call->in(TypeFunc::Memory);
1913   Node* final_mem = final_state->in(TypeFunc::Memory);
1914   Node* final_ctl = final_state->in(TypeFunc::Control);
1915   Node* final_io = final_state->in(TypeFunc::I_O);
1916 
1917   // Replace all the old call edges with the edges from the inlining result
1918   if (callprojs.fallthrough_catchproj != NULL) {
1919     C->gvn_replace_by(callprojs.fallthrough_catchproj, final_ctl);
1920   }
1921   if (callprojs.fallthrough_memproj != NULL) {
1922     if (final_mem->is_MergeMem()) {
1923       // Parser's exits MergeMem was not transformed but may be optimized
1924       final_mem = _gvn.transform(final_mem);
1925     }
1926     C->gvn_replace_by(callprojs.fallthrough_memproj,   final_mem);
1927     add_mergemem_users_to_worklist(wl, final_mem);
1928   }
1929   if (callprojs.fallthrough_ioproj != NULL) {
1930     C->gvn_replace_by(callprojs.fallthrough_ioproj,    final_io);
1931   }
1932 
1933   // Replace the result with the new result if it exists and is used
1934   if (callprojs.resproj != NULL && result != NULL) {
1935     C->gvn_replace_by(callprojs.resproj, result);




1936   }
1937 
1938   if (ejvms == NULL) {
1939     // No exception edges to simply kill off those paths
1940     if (callprojs.catchall_catchproj != NULL) {
1941       C->gvn_replace_by(callprojs.catchall_catchproj, C->top());
1942     }
1943     if (callprojs.catchall_memproj != NULL) {
1944       C->gvn_replace_by(callprojs.catchall_memproj,   C->top());
1945     }
1946     if (callprojs.catchall_ioproj != NULL) {
1947       C->gvn_replace_by(callprojs.catchall_ioproj,    C->top());
1948     }
1949     // Replace the old exception object with top
1950     if (callprojs.exobj != NULL) {
1951       C->gvn_replace_by(callprojs.exobj, C->top());
1952     }
1953   } else {
1954     GraphKit ekit(ejvms);
1955 
1956     // Load my combined exception state into the kit, with all phis transformed:
1957     SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();
1958     replaced_nodes_exception = ex_map->replaced_nodes();
1959 
1960     Node* ex_oop = ekit.use_exception_state(ex_map);
1961 
1962     if (callprojs.catchall_catchproj != NULL) {
1963       C->gvn_replace_by(callprojs.catchall_catchproj, ekit.control());
1964       ex_ctl = ekit.control();
1965     }
1966     if (callprojs.catchall_memproj != NULL) {
1967       Node* ex_mem = ekit.reset_memory();
1968       C->gvn_replace_by(callprojs.catchall_memproj,   ex_mem);
1969       add_mergemem_users_to_worklist(wl, ex_mem);
1970     }
1971     if (callprojs.catchall_ioproj != NULL) {
1972       C->gvn_replace_by(callprojs.catchall_ioproj,    ekit.i_o());
1973     }
1974 
1975     // Replace the old exception object with the newly created one
1976     if (callprojs.exobj != NULL) {
1977       C->gvn_replace_by(callprojs.exobj, ex_oop);
1978     }
1979   }
1980 
1981   // Disconnect the call from the graph
1982   call->disconnect_inputs(C);
1983   C->gvn_replace_by(call, C->top());
1984 
1985   // Clean up any MergeMems that feed other MergeMems since the
1986   // optimizer doesn't like that.
1987   while (wl.size() > 0) {
1988     _gvn.transform(wl.pop());
1989   }
1990 
1991   if (callprojs.fallthrough_catchproj != NULL && !final_ctl->is_top() && do_replaced_nodes) {
1992     replaced_nodes.apply(C, final_ctl);
1993   }
1994   if (!ex_ctl->is_top() && do_replaced_nodes) {
1995     replaced_nodes_exception.apply(C, ex_ctl);
1996   }
1997 }
1998 
1999 
2000 //------------------------------increment_counter------------------------------
2001 // for statistics: increment a VM counter by 1
2002 
2003 void GraphKit::increment_counter(address counter_addr) {
2004   Node* adr1 = makecon(TypeRawPtr::make(counter_addr));
2005   increment_counter(adr1);
2006 }
2007 
2008 void GraphKit::increment_counter(Node* counter_addr) {
2009   int adr_type = Compile::AliasIdxRaw;
2010   Node* ctrl = control();
2011   Node* cnt  = make_load(ctrl, counter_addr, TypeLong::LONG, T_LONG, adr_type, MemNode::unordered);

2170  *
2171  * @param n          node that the type applies to
2172  * @param exact_kls  type from profiling
2173  * @param maybe_null did profiling see null?
2174  *
2175  * @return           node with improved type
2176  */
2177 Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, ProfilePtrKind ptr_kind) {
2178   const Type* current_type = _gvn.type(n);
2179   assert(UseTypeSpeculation, "type speculation must be on");
2180 
2181   const TypePtr* speculative = current_type->speculative();
2182 
2183   // Should the klass from the profile be recorded in the speculative type?
2184   if (current_type->would_improve_type(exact_kls, jvms()->depth())) {
2185     const TypeKlassPtr* tklass = TypeKlassPtr::make(exact_kls);
2186     const TypeOopPtr* xtype = tklass->as_instance_type();
2187     assert(xtype->klass_is_exact(), "Should be exact");
2188     // Any reason to believe n is not null (from this profiling or a previous one)?
2189     assert(ptr_kind != ProfileAlwaysNull, "impossible here");
2190     const TypePtr* ptr = (ptr_kind == ProfileMaybeNull && current_type->speculative_maybe_null()) ? TypePtr::BOTTOM : TypePtr::NOTNULL;
2191     // record the new speculative type's depth
2192     speculative = xtype->cast_to_ptr_type(ptr->ptr())->is_ptr();
2193     speculative = speculative->with_inline_depth(jvms()->depth());
2194   } else if (current_type->would_improve_ptr(ptr_kind)) {
2195     // Profiling report that null was never seen so we can change the
2196     // speculative type to non null ptr.
2197     if (ptr_kind == ProfileAlwaysNull) {
2198       speculative = TypePtr::NULL_PTR;
2199     } else {
2200       assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement");
2201       const TypePtr* ptr = TypePtr::NOTNULL;
2202       if (speculative != NULL) {
2203         speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr();
2204       } else {
2205         speculative = ptr;
2206       }
2207     }
2208   }
2209 
2210   if (speculative != current_type->speculative()) {
2211     // Build a type with a speculative type (what we think we know
2212     // about the type but will need a guard when we use it)
2213     const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::OffsetBot, TypeOopPtr::InstanceBot, speculative);
2214     // We're changing the type, we need a new CheckCast node to carry
2215     // the new type. The new type depends on the control: what
2216     // profiling tells us is only valid from here as far as we can
2217     // tell.
2218     Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));
2219     cast = _gvn.transform(cast);
2220     replace_in_map(n, cast);
2221     n = cast;
2222   }
2223 
2224   return n;
2225 }
2226 
2227 /**
2228  * Record profiling data from receiver profiling at an invoke with the
2229  * type system so that it can propagate it (speculation)
2230  *
2231  * @param n  receiver node
2232  *
2233  * @return   node with improved type
2234  */
2235 Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {
2236   if (!UseTypeSpeculation) {
2237     return n;
2238   }
2239   ciKlass* exact_kls = profile_has_unique_klass();
2240   ProfilePtrKind ptr_kind = ProfileMaybeNull;
2241   if ((java_bc() == Bytecodes::_checkcast ||
2242        java_bc() == Bytecodes::_instanceof ||
2243        java_bc() == Bytecodes::_aastore) &&
2244       method()->method_data()->is_mature()) {
2245     ciProfileData* data = method()->method_data()->bci_to_data(bci());
2246     if (data != NULL) {
2247       if (!data->as_BitData()->null_seen()) {
2248         ptr_kind = ProfileNeverNull;







2249       } else {
2250         assert(data->is_ReceiverTypeData(), "bad profile data type");
2251         ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
2252         uint i = 0;
2253         for (; i < call->row_limit(); i++) {
2254           ciKlass* receiver = call->receiver(i);
2255           if (receiver != NULL) {
2256             break;




2257           }

2258         }
2259         ptr_kind = (i == call->row_limit()) ? ProfileAlwaysNull : ProfileMaybeNull;
2260       }
2261     }
2262   }
2263   return record_profile_for_speculation(n, exact_kls, ptr_kind);
2264 }
2265 
2266 /**
2267  * Record profiling data from argument profiling at an invoke with the
2268  * type system so that it can propagate it (speculation)
2269  *
2270  * @param dest_method  target method for the call
2271  * @param bc           what invoke bytecode is this?
2272  */
2273 void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {
2274   if (!UseTypeSpeculation) {
2275     return;
2276   }
2277   const TypeFunc* tf    = TypeFunc::make(dest_method);
2278   int             nargs = tf->domain()->cnt() - TypeFunc::Parms;
2279   int skip = Bytecodes::has_receiver(bc) ? 1 : 0;
2280   for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {
2281     const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);
2282     if (is_reference_type(targ->basic_type())) {
2283       ProfilePtrKind ptr_kind = ProfileMaybeNull;
2284       ciKlass* better_type = NULL;
2285       if (method()->argument_profiled_type(bci(), i, better_type, ptr_kind)) {
2286         record_profile_for_speculation(argument(j), better_type, ptr_kind);
2287       }
2288       i++;
2289     }
2290   }
2291 }
2292 
2293 /**
2294  * Record profiling data from parameter profiling at an invoke with
2295  * the type system so that it can propagate it (speculation)
2296  */
2297 void GraphKit::record_profiled_parameters_for_speculation() {
2298   if (!UseTypeSpeculation) {
2299     return;
2300   }
2301   for (int i = 0, j = 0; i < method()->arg_size() ; i++) {

2315  * the type system so that it can propagate it (speculation)
2316  */
2317 void GraphKit::record_profiled_return_for_speculation() {
2318   if (!UseTypeSpeculation) {
2319     return;
2320   }
2321   ProfilePtrKind ptr_kind = ProfileMaybeNull;
2322   ciKlass* better_type = NULL;
2323   if (method()->return_profiled_type(bci(), better_type, ptr_kind)) {
2324     // If profiling reports a single type for the return value,
2325     // feed it to the type system so it can propagate it as a
2326     // speculative type
2327     record_profile_for_speculation(stack(sp()-1), better_type, ptr_kind);
2328   }
2329 }
2330 
2331 void GraphKit::round_double_arguments(ciMethod* dest_method) {
2332   if (Matcher::strict_fp_requires_explicit_rounding) {
2333     // (Note:  TypeFunc::make has a cache that makes this fast.)
2334     const TypeFunc* tf    = TypeFunc::make(dest_method);
2335     int             nargs = tf->domain()->cnt() - TypeFunc::Parms;
2336     for (int j = 0; j < nargs; j++) {
2337       const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);
2338       if (targ->basic_type() == T_DOUBLE) {
2339         // If any parameters are doubles, they must be rounded before
2340         // the call, dprecision_rounding does gvn.transform
2341         Node *arg = argument(j);
2342         arg = dprecision_rounding(arg);
2343         set_argument(j, arg);
2344       }
2345     }
2346   }
2347 }
2348 
2349 // rounding for strict float precision conformance
2350 Node* GraphKit::precision_rounding(Node* n) {
2351   if (Matcher::strict_fp_requires_explicit_rounding) {
2352 #ifdef IA32
2353     if (UseSSE == 0) {
2354       return _gvn.transform(new RoundFloatNode(0, n));
2355     }
2356 #else
2357     Unimplemented();

2466                                   // The first NULL ends the list.
2467                                   Node* parm0, Node* parm1,
2468                                   Node* parm2, Node* parm3,
2469                                   Node* parm4, Node* parm5,
2470                                   Node* parm6, Node* parm7) {
2471   assert(call_addr != NULL, "must not call NULL targets");
2472 
2473   // Slow-path call
2474   bool is_leaf = !(flags & RC_NO_LEAF);
2475   bool has_io  = (!is_leaf && !(flags & RC_NO_IO));
2476   if (call_name == NULL) {
2477     assert(!is_leaf, "must supply name for leaf");
2478     call_name = OptoRuntime::stub_name(call_addr);
2479   }
2480   CallNode* call;
2481   if (!is_leaf) {
2482     call = new CallStaticJavaNode(call_type, call_addr, call_name, adr_type);
2483   } else if (flags & RC_NO_FP) {
2484     call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
2485   } else  if (flags & RC_VECTOR){
2486     uint num_bits = call_type->range()->field_at(TypeFunc::Parms)->is_vect()->length_in_bytes() * BitsPerByte;
2487     call = new CallLeafVectorNode(call_type, call_addr, call_name, adr_type, num_bits);
2488   } else {
2489     call = new CallLeafNode(call_type, call_addr, call_name, adr_type);
2490   }
2491 
2492   // The following is similar to set_edges_for_java_call,
2493   // except that the memory effects of the call are restricted to AliasIdxRaw.
2494 
2495   // Slow path call has no side-effects, uses few values
2496   bool wide_in  = !(flags & RC_NARROW_MEM);
2497   bool wide_out = (C->get_alias_index(adr_type) == Compile::AliasIdxBot);
2498 
2499   Node* prev_mem = NULL;
2500   if (wide_in) {
2501     prev_mem = set_predefined_input_for_runtime_call(call);
2502   } else {
2503     assert(!wide_out, "narrow in => narrow out");
2504     Node* narrow_mem = memory(adr_type);
2505     prev_mem = set_predefined_input_for_runtime_call(call, narrow_mem);
2506   }

2546 
2547   if (has_io) {
2548     set_i_o(_gvn.transform(new ProjNode(call, TypeFunc::I_O)));
2549   }
2550   return call;
2551 
2552 }
2553 
2554 // i2b
2555 Node* GraphKit::sign_extend_byte(Node* in) {
2556   Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(24)));
2557   return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(24)));
2558 }
2559 
2560 // i2s
2561 Node* GraphKit::sign_extend_short(Node* in) {
2562   Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(16)));
2563   return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(16)));
2564 }
2565 

2566 //------------------------------merge_memory-----------------------------------
2567 // Merge memory from one path into the current memory state.
2568 void GraphKit::merge_memory(Node* new_mem, Node* region, int new_path) {
2569   for (MergeMemStream mms(merged_memory(), new_mem->as_MergeMem()); mms.next_non_empty2(); ) {
2570     Node* old_slice = mms.force_memory();
2571     Node* new_slice = mms.memory2();
2572     if (old_slice != new_slice) {
2573       PhiNode* phi;
2574       if (old_slice->is_Phi() && old_slice->as_Phi()->region() == region) {
2575         if (mms.is_empty()) {
2576           // clone base memory Phi's inputs for this memory slice
2577           assert(old_slice == mms.base_memory(), "sanity");
2578           phi = PhiNode::make(region, NULL, Type::MEMORY, mms.adr_type(C));
2579           _gvn.set_type(phi, Type::MEMORY);
2580           for (uint i = 1; i < phi->req(); i++) {
2581             phi->init_req(i, old_slice->in(i));
2582           }
2583         } else {
2584           phi = old_slice->as_Phi(); // Phi was generated already
2585         }

2799 
2800   // Now do a linear scan of the secondary super-klass array.  Again, no real
2801   // performance impact (too rare) but it's gotta be done.
2802   // Since the code is rarely used, there is no penalty for moving it
2803   // out of line, and it can only improve I-cache density.
2804   // The decision to inline or out-of-line this final check is platform
2805   // dependent, and is found in the AD file definition of PartialSubtypeCheck.
2806   Node* psc = gvn.transform(
2807     new PartialSubtypeCheckNode(*ctrl, subklass, superklass));
2808 
2809   IfNode *iff4 = gen_subtype_check_compare(*ctrl, psc, gvn.zerocon(T_OBJECT), BoolTest::ne, PROB_FAIR, gvn, T_ADDRESS);
2810   r_not_subtype->init_req(2, gvn.transform(new IfTrueNode (iff4)));
2811   r_ok_subtype ->init_req(3, gvn.transform(new IfFalseNode(iff4)));
2812 
2813   // Return false path; set default control to true path.
2814   *ctrl = gvn.transform(r_ok_subtype);
2815   return gvn.transform(r_not_subtype);
2816 }
2817 
2818 Node* GraphKit::gen_subtype_check(Node* obj_or_subklass, Node* superklass) {





2819   bool expand_subtype_check = C->post_loop_opts_phase() ||   // macro node expansion is over
2820                               ExpandSubTypeCheckAtParseTime; // forced expansion
2821   if (expand_subtype_check) {
2822     MergeMemNode* mem = merged_memory();
2823     Node* ctrl = control();
2824     Node* subklass = obj_or_subklass;
2825     if (!_gvn.type(obj_or_subklass)->isa_klassptr()) {
2826       subklass = load_object_klass(obj_or_subklass);
2827     }
2828 
2829     Node* n = Phase::gen_subtype_check(subklass, superklass, &ctrl, mem, _gvn);
2830     set_control(ctrl);
2831     return n;
2832   }
2833 
2834   Node* check = _gvn.transform(new SubTypeCheckNode(C, obj_or_subklass, superklass));
2835   Node* bol = _gvn.transform(new BoolNode(check, BoolTest::eq));
2836   IfNode* iff = create_and_xform_if(control(), bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
2837   set_control(_gvn.transform(new IfTrueNode(iff)));
2838   return _gvn.transform(new IfFalseNode(iff));
2839 }
2840 
2841 // Profile-driven exact type check:
2842 Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,
2843                                     float prob,
2844                                     Node* *casted_receiver) {
2845   assert(!klass->is_interface(), "no exact type check on interfaces");
2846 











2847   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
2848   Node* recv_klass = load_object_klass(receiver);
2849   Node* want_klass = makecon(tklass);
2850   Node* cmp = _gvn.transform(new CmpPNode(recv_klass, want_klass));
2851   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
2852   IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);
2853   set_control( _gvn.transform(new IfTrueNode (iff)));
2854   Node* fail = _gvn.transform(new IfFalseNode(iff));
2855 
2856   if (!stopped()) {
2857     const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
2858     const TypeOopPtr* recvx_type = tklass->as_instance_type();
2859     assert(recvx_type->klass_is_exact(), "");
2860 
2861     if (!receiver_type->higher_equal(recvx_type)) { // ignore redundant casts
2862       // Subsume downstream occurrences of receiver with a cast to
2863       // recv_xtype, since now we know what the type will be.
2864       Node* cast = new CheckCastPPNode(control(), receiver, recvx_type);
2865       (*casted_receiver) = _gvn.transform(cast);





2866       // (User must make the replace_in_map call.)
2867     }
2868   }
2869 
2870   return fail;
2871 }
2872 











2873 //------------------------------subtype_check_receiver-------------------------
2874 Node* GraphKit::subtype_check_receiver(Node* receiver, ciKlass* klass,
2875                                        Node** casted_receiver) {
2876   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
2877   Node* want_klass = makecon(tklass);
2878 
2879   Node* slow_ctl = gen_subtype_check(receiver, want_klass);
2880 
2881   // Ignore interface type information until interface types are properly tracked.
2882   if (!stopped() && !klass->is_interface()) {
2883     const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
2884     const TypeOopPtr* recv_type = tklass->cast_to_exactness(false)->is_klassptr()->as_instance_type();
2885     if (!receiver_type->higher_equal(recv_type)) { // ignore redundant casts
2886       Node* cast = new CheckCastPPNode(control(), receiver, recv_type);
2887       (*casted_receiver) = _gvn.transform(cast);



2888     }
2889   }
2890 
2891   return slow_ctl;
2892 }
2893 
2894 //------------------------------seems_never_null-------------------------------
2895 // Use null_seen information if it is available from the profile.
2896 // If we see an unexpected null at a type check we record it and force a
2897 // recompile; the offending check will be recompiled to handle NULLs.
2898 // If we see several offending BCIs, then all checks in the
2899 // method will be recompiled.
2900 bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) {
2901   speculating = !_gvn.type(obj)->speculative_maybe_null();
2902   Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating);
2903   if (UncommonNullCast               // Cutout for this technique
2904       && obj != null()               // And not the -Xcomp stupid case?
2905       && !too_many_traps(reason)
2906       ) {
2907     if (speculating) {
2908       return true;
2909     }
2910     if (data == NULL)
2911       // Edge case:  no mature data.  Be optimistic here.
2912       return true;
2913     // If the profile has not seen a null, assume it won't happen.
2914     assert(java_bc() == Bytecodes::_checkcast ||
2915            java_bc() == Bytecodes::_instanceof ||
2916            java_bc() == Bytecodes::_aastore, "MDO must collect null_seen bit here");



2917     return !data->as_BitData()->null_seen();
2918   }
2919   speculating = false;
2920   return false;
2921 }
2922 
2923 void GraphKit::guard_klass_being_initialized(Node* klass) {
2924   int init_state_off = in_bytes(InstanceKlass::init_state_offset());
2925   Node* adr = basic_plus_adr(top(), klass, init_state_off);
2926   Node* init_state = LoadNode::make(_gvn, NULL, immutable_memory(), adr,
2927                                     adr->bottom_type()->is_ptr(), TypeInt::BYTE,
2928                                     T_BYTE, MemNode::unordered);
2929   init_state = _gvn.transform(init_state);
2930 
2931   Node* being_initialized_state = makecon(TypeInt::make(InstanceKlass::being_initialized));
2932 
2933   Node* chk = _gvn.transform(new CmpINode(being_initialized_state, init_state));
2934   Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
2935 
2936   { BuildCutout unless(this, tst, PROB_MAX);

2976 
2977 //------------------------maybe_cast_profiled_receiver-------------------------
2978 // If the profile has seen exactly one type, narrow to exactly that type.
2979 // Subsequent type checks will always fold up.
2980 Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,
2981                                              const TypeKlassPtr* require_klass,
2982                                              ciKlass* spec_klass,
2983                                              bool safe_for_replace) {
2984   if (!UseTypeProfile || !TypeProfileCasts) return NULL;
2985 
2986   Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != NULL);
2987 
2988   // Make sure we haven't already deoptimized from this tactic.
2989   if (too_many_traps_or_recompiles(reason))
2990     return NULL;
2991 
2992   // (No, this isn't a call, but it's enough like a virtual call
2993   // to use the same ciMethod accessor to get the profile info...)
2994   // If we have a speculative type use it instead of profiling (which
2995   // may not help us)
2996   ciKlass* exact_kls = spec_klass == NULL ? profile_has_unique_klass() : spec_klass;













2997   if (exact_kls != NULL) {// no cast failures here
2998     if (require_klass == NULL ||
2999         C->static_subtype_check(require_klass, TypeKlassPtr::make(exact_kls)) == Compile::SSC_always_true) {
3000       // If we narrow the type to match what the type profile sees or
3001       // the speculative type, we can then remove the rest of the
3002       // cast.
3003       // This is a win, even if the exact_kls is very specific,
3004       // because downstream operations, such as method calls,
3005       // will often benefit from the sharper type.
3006       Node* exact_obj = not_null_obj; // will get updated in place...
3007       Node* slow_ctl  = type_check_receiver(exact_obj, exact_kls, 1.0,
3008                                             &exact_obj);
3009       { PreserveJVMState pjvms(this);
3010         set_control(slow_ctl);
3011         uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
3012       }
3013       if (safe_for_replace) {
3014         replace_in_map(not_null_obj, exact_obj);
3015       }
3016       return exact_obj;

3106   // If not_null_obj is dead, only null-path is taken
3107   if (stopped()) {              // Doing instance-of on a NULL?
3108     set_control(null_ctl);
3109     return intcon(0);
3110   }
3111   region->init_req(_null_path, null_ctl);
3112   phi   ->init_req(_null_path, intcon(0)); // Set null path value
3113   if (null_ctl == top()) {
3114     // Do this eagerly, so that pattern matches like is_diamond_phi
3115     // will work even during parsing.
3116     assert(_null_path == PATH_LIMIT-1, "delete last");
3117     region->del_req(_null_path);
3118     phi   ->del_req(_null_path);
3119   }
3120 
3121   // Do we know the type check always succeed?
3122   bool known_statically = false;
3123   if (_gvn.type(superklass)->singleton()) {
3124     const TypeKlassPtr* superk = _gvn.type(superklass)->is_klassptr();
3125     const TypeKlassPtr* subk = _gvn.type(obj)->is_oopptr()->as_klass_type();
3126     if (subk->is_loaded()) {
3127       int static_res = C->static_subtype_check(superk, subk);
3128       known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false);
3129     }
3130   }
3131 
3132   if (!known_statically) {
3133     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3134     // We may not have profiling here or it may not help us. If we
3135     // have a speculative type use it to perform an exact cast.
3136     ciKlass* spec_obj_type = obj_type->speculative_type();
3137     if (spec_obj_type != NULL || (ProfileDynamicTypes && data != NULL)) {
3138       Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, NULL, spec_obj_type, safe_for_replace);
3139       if (stopped()) {            // Profile disagrees with this path.
3140         set_control(null_ctl);    // Null is the only remaining possibility.
3141         return intcon(0);
3142       }
3143       if (cast_obj != NULL) {
3144         not_null_obj = cast_obj;
3145       }
3146     }

3162   record_for_igvn(region);
3163 
3164   // If we know the type check always succeeds then we don't use the
3165   // profiling data at this bytecode. Don't lose it, feed it to the
3166   // type system as a speculative type.
3167   if (safe_for_replace) {
3168     Node* casted_obj = record_profiled_receiver_for_speculation(obj);
3169     replace_in_map(obj, casted_obj);
3170   }
3171 
3172   return _gvn.transform(phi);
3173 }
3174 
3175 //-------------------------------gen_checkcast---------------------------------
3176 // Generate a checkcast idiom.  Used by both the checkcast bytecode and the
3177 // array store bytecode.  Stack must be as-if BEFORE doing the bytecode so the
3178 // uncommon-trap paths work.  Adjust stack after this call.
3179 // If failure_control is supplied and not null, it is filled in with
3180 // the control edge for the cast failure.  Otherwise, an appropriate
3181 // uncommon trap or exception is thrown.
3182 Node* GraphKit::gen_checkcast(Node *obj, Node* superklass,
3183                               Node* *failure_control) {
3184   kill_dead_locals();           // Benefit all the uncommon traps
3185   const TypeKlassPtr *tk = _gvn.type(superklass)->is_klassptr();
3186   const Type *toop = tk->cast_to_exactness(false)->as_instance_type();


3187 
3188   // Fast cutout:  Check the case that the cast is vacuously true.
3189   // This detects the common cases where the test will short-circuit
3190   // away completely.  We do this before we perform the null check,
3191   // because if the test is going to turn into zero code, we don't
3192   // want a residual null check left around.  (Causes a slowdown,
3193   // for example, in some objArray manipulations, such as a[i]=a[j].)
3194   if (tk->singleton()) {
3195     const TypeOopPtr* objtp = _gvn.type(obj)->isa_oopptr();
3196     if (objtp != NULL) {
3197       switch (C->static_subtype_check(tk, objtp->as_klass_type())) {







3198       case Compile::SSC_always_true:
3199         // If we know the type check always succeed then we don't use
3200         // the profiling data at this bytecode. Don't lose it, feed it
3201         // to the type system as a speculative type.
3202         return record_profiled_receiver_for_speculation(obj);






3203       case Compile::SSC_always_false:




3204         // It needs a null check because a null will *pass* the cast check.
3205         // A non-null value will always produce an exception.
3206         if (!objtp->maybe_null()) {
3207           bool is_aastore = (java_bc() == Bytecodes::_aastore);
3208           Deoptimization::DeoptReason reason = is_aastore ?
3209             Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3210           builtin_throw(reason);
3211           return top();
3212         } else if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
3213           return null_assert(obj);
3214         }
3215         break; // Fall through to full check
3216       default:
3217         break;
3218       }
3219     }
3220   }
3221 
3222   ciProfileData* data = NULL;
3223   bool safe_for_replace = false;
3224   if (failure_control == NULL) {        // use MDO in regular case only
3225     assert(java_bc() == Bytecodes::_aastore ||
3226            java_bc() == Bytecodes::_checkcast,
3227            "interpreter profiles type checks only for these BCs");
3228     data = method()->method_data()->bci_to_data(bci());
3229     safe_for_replace = true;

3230   }
3231 
3232   // Make the merge point
3233   enum { _obj_path = 1, _null_path, PATH_LIMIT };
3234   RegionNode* region = new RegionNode(PATH_LIMIT);
3235   Node*       phi    = new PhiNode(region, toop);



3236   C->set_has_split_ifs(true); // Has chance for split-if optimization
3237 
3238   // Use null-cast information if it is available
3239   bool speculative_not_null = false;
3240   bool never_see_null = ((failure_control == NULL)  // regular case only
3241                          && seems_never_null(obj, data, speculative_not_null));
3242 







3243   // Null check; get casted pointer; set region slot 3
3244   Node* null_ctl = top();
3245   Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);






3246 
3247   // If not_null_obj is dead, only null-path is taken
3248   if (stopped()) {              // Doing instance-of on a NULL?
3249     set_control(null_ctl);



3250     return null();
3251   }
3252   region->init_req(_null_path, null_ctl);
3253   phi   ->init_req(_null_path, null());  // Set null path value
3254   if (null_ctl == top()) {
3255     // Do this eagerly, so that pattern matches like is_diamond_phi
3256     // will work even during parsing.
3257     assert(_null_path == PATH_LIMIT-1, "delete last");
3258     region->del_req(_null_path);
3259     phi   ->del_req(_null_path);
3260   }
3261 
3262   Node* cast_obj = NULL;
3263   if (tk->klass_is_exact()) {
3264     // The following optimization tries to statically cast the speculative type of the object
3265     // (for example obtained during profiling) to the type of the superklass and then do a
3266     // dynamic check that the type of the object is what we expect. To work correctly
3267     // for checkcast and aastore the type of superklass should be exact.
3268     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3269     // We may not have profiling here or it may not help us. If we have
3270     // a speculative type use it to perform an exact cast.
3271     ciKlass* spec_obj_type = obj_type->speculative_type();
3272     if (spec_obj_type != NULL || data != NULL) {
3273       cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk, spec_obj_type, safe_for_replace);
3274       if (cast_obj != NULL) {
3275         if (failure_control != NULL) // failure is now impossible
3276           (*failure_control) = top();
3277         // adjust the type of the phi to the exact klass:
3278         phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
3279       }
3280     }
3281   }
3282 
3283   if (cast_obj == NULL) {
3284     // Generate the subtype check
3285     Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass );
3286 
3287     // Plug in success path into the merge
3288     cast_obj = _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop));
3289     // Failure path ends in uncommon trap (or may be dead - failure impossible)
3290     if (failure_control == NULL) {
3291       if (not_subtype_ctrl != top()) { // If failure is possible
3292         PreserveJVMState pjvms(this);
3293         set_control(not_subtype_ctrl);






3294         bool is_aastore = (java_bc() == Bytecodes::_aastore);
3295         Deoptimization::DeoptReason reason = is_aastore ?
3296           Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3297         builtin_throw(reason);
3298       }
3299     } else {
3300       (*failure_control) = not_subtype_ctrl;
3301     }
3302   }
3303 
3304   region->init_req(_obj_path, control());
3305   phi   ->init_req(_obj_path, cast_obj);
3306 
3307   // A merge of NULL or Casted-NotNull obj
3308   Node* res = _gvn.transform(phi);
3309 
3310   // Note I do NOT always 'replace_in_map(obj,result)' here.
3311   //  if( tk->klass()->can_be_primary_super()  )
3312     // This means that if I successfully store an Object into an array-of-String
3313     // I 'forget' that the Object is really now known to be a String.  I have to
3314     // do this because we don't have true union types for interfaces - if I store
3315     // a Baz into an array-of-Interface and then tell the optimizer it's an
3316     // Interface, I forget that it's also a Baz and cannot do Baz-like field
3317     // references to it.  FIX THIS WHEN UNION TYPES APPEAR!
3318   //  replace_in_map( obj, res );
3319 
3320   // Return final merged results
3321   set_control( _gvn.transform(region) );
3322   record_for_igvn(region);
3323 
3324   return record_profiled_receiver_for_speculation(res);

























































































































3325 }
3326 
3327 //------------------------------next_monitor-----------------------------------
3328 // What number should be given to the next monitor?
3329 int GraphKit::next_monitor() {
3330   int current = jvms()->monitor_depth()* C->sync_stack_slots();
3331   int next = current + C->sync_stack_slots();
3332   // Keep the toplevel high water mark current:
3333   if (C->fixed_slots() < next)  C->set_fixed_slots(next);
3334   return current;
3335 }
3336 
3337 //------------------------------insert_mem_bar---------------------------------
3338 // Memory barrier to avoid floating things around
3339 // The membar serves as a pinch point between both control and all memory slices.
3340 Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {
3341   MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
3342   mb->init_req(TypeFunc::Control, control());
3343   mb->init_req(TypeFunc::Memory,  reset_memory());
3344   Node* membar = _gvn.transform(mb);

3372   }
3373   Node* membar = _gvn.transform(mb);
3374   set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3375   if (alias_idx == Compile::AliasIdxBot) {
3376     merged_memory()->set_base_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)));
3377   } else {
3378     set_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)),alias_idx);
3379   }
3380   return membar;
3381 }
3382 
3383 //------------------------------shared_lock------------------------------------
3384 // Emit locking code.
3385 FastLockNode* GraphKit::shared_lock(Node* obj) {
3386   // bci is either a monitorenter bc or InvocationEntryBci
3387   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3388   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3389 
3390   if( !GenerateSynchronizationCode )
3391     return NULL;                // Not locking things?

3392   if (stopped())                // Dead monitor?
3393     return NULL;
3394 
3395   assert(dead_locals_are_killed(), "should kill locals before sync. point");
3396 
3397   // Box the stack location
3398   Node* box = _gvn.transform(new BoxLockNode(next_monitor()));
3399   Node* mem = reset_memory();
3400 
3401   FastLockNode * flock = _gvn.transform(new FastLockNode(0, obj, box) )->as_FastLock();
3402 
3403   // Create the rtm counters for this fast lock if needed.
3404   flock->create_rtm_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3405 
3406   // Add monitor to debug info for the slow path.  If we block inside the
3407   // slow path and de-opt, we need the monitor hanging around
3408   map()->push_monitor( flock );
3409 
3410   const TypeFunc *tf = LockNode::lock_type();
3411   LockNode *lock = new LockNode(C, tf);

3440   }
3441 #endif
3442 
3443   return flock;
3444 }
3445 
3446 
3447 //------------------------------shared_unlock----------------------------------
3448 // Emit unlocking code.
3449 void GraphKit::shared_unlock(Node* box, Node* obj) {
3450   // bci is either a monitorenter bc or InvocationEntryBci
3451   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3452   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3453 
3454   if( !GenerateSynchronizationCode )
3455     return;
3456   if (stopped()) {               // Dead monitor?
3457     map()->pop_monitor();        // Kill monitor from debug info
3458     return;
3459   }

3460 
3461   // Memory barrier to avoid floating things down past the locked region
3462   insert_mem_bar(Op_MemBarReleaseLock);
3463 
3464   const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();
3465   UnlockNode *unlock = new UnlockNode(C, tf);
3466 #ifdef ASSERT
3467   unlock->set_dbg_jvms(sync_jvms());
3468 #endif
3469   uint raw_idx = Compile::AliasIdxRaw;
3470   unlock->init_req( TypeFunc::Control, control() );
3471   unlock->init_req( TypeFunc::Memory , memory(raw_idx) );
3472   unlock->init_req( TypeFunc::I_O    , top() )     ;   // does no i/o
3473   unlock->init_req( TypeFunc::FramePtr, frameptr() );
3474   unlock->init_req( TypeFunc::ReturnAdr, top() );
3475 
3476   unlock->init_req(TypeFunc::Parms + 0, obj);
3477   unlock->init_req(TypeFunc::Parms + 1, box);
3478   unlock = _gvn.transform(unlock)->as_Unlock();
3479 
3480   Node* mem = reset_memory();
3481 
3482   // unlock has no side-effects, sets few values
3483   set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);
3484 
3485   // Kill monitor from debug info
3486   map()->pop_monitor( );
3487 }
3488 
3489 //-------------------------------get_layout_helper-----------------------------
3490 // If the given klass is a constant or known to be an array,
3491 // fetch the constant layout helper value into constant_value
3492 // and return (Node*)NULL.  Otherwise, load the non-constant
3493 // layout helper value, and return the node which represents it.
3494 // This two-faced routine is useful because allocation sites
3495 // almost always feature constant types.
3496 Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {
3497   const TypeKlassPtr* inst_klass = _gvn.type(klass_node)->isa_klassptr();
3498   if (!StressReflectiveCode && inst_klass != NULL) {
3499     bool    xklass = inst_klass->klass_is_exact();
3500     if (xklass || inst_klass->isa_aryklassptr()) {







3501       jint lhelper;
3502       if (inst_klass->isa_aryklassptr()) {
3503         BasicType elem = inst_klass->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type();


3504         if (is_reference_type(elem, true)) {
3505           elem = T_OBJECT;
3506         }
3507         lhelper = Klass::array_layout_helper(elem);
3508       } else {
3509         lhelper = inst_klass->is_instklassptr()->exact_klass()->layout_helper();
3510       }
3511       if (lhelper != Klass::_lh_neutral_value) {
3512         constant_value = lhelper;
3513         return (Node*) NULL;
3514       }
3515     }
3516   }
3517   constant_value = Klass::_lh_neutral_value;  // put in a known value
3518   Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset()));
3519   return make_load(NULL, lhp, TypeInt::INT, T_INT, MemNode::unordered);
3520 }
3521 
3522 // We just put in an allocate/initialize with a big raw-memory effect.
3523 // Hook selected additional alias categories on the initialization.
3524 static void hook_memory_on_init(GraphKit& kit, int alias_idx,
3525                                 MergeMemNode* init_in_merge,
3526                                 Node* init_out_raw) {
3527   DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());
3528   assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");
3529 
3530   Node* prevmem = kit.memory(alias_idx);
3531   init_in_merge->set_memory_at(alias_idx, prevmem);
3532   kit.set_memory(init_out_raw, alias_idx);


3533 }
3534 
3535 //---------------------------set_output_for_allocation-------------------------
3536 Node* GraphKit::set_output_for_allocation(AllocateNode* alloc,
3537                                           const TypeOopPtr* oop_type,
3538                                           bool deoptimize_on_exception) {
3539   int rawidx = Compile::AliasIdxRaw;
3540   alloc->set_req( TypeFunc::FramePtr, frameptr() );
3541   add_safepoint_edges(alloc);
3542   Node* allocx = _gvn.transform(alloc);
3543   set_control( _gvn.transform(new ProjNode(allocx, TypeFunc::Control) ) );
3544   // create memory projection for i_o
3545   set_memory ( _gvn.transform( new ProjNode(allocx, TypeFunc::Memory, true) ), rawidx );
3546   make_slow_call_ex(allocx, env()->Throwable_klass(), true, deoptimize_on_exception);
3547 
3548   // create a memory projection as for the normal control path
3549   Node* malloc = _gvn.transform(new ProjNode(allocx, TypeFunc::Memory));
3550   set_memory(malloc, rawidx);
3551 
3552   // a normal slow-call doesn't change i_o, but an allocation does
3553   // we create a separate i_o projection for the normal control path
3554   set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) );
3555   Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) );
3556 
3557   // put in an initialization barrier
3558   InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,
3559                                                  rawoop)->as_Initialize();
3560   assert(alloc->initialization() == init,  "2-way macro link must work");
3561   assert(init ->allocation()     == alloc, "2-way macro link must work");
3562   {
3563     // Extract memory strands which may participate in the new object's
3564     // initialization, and source them from the new InitializeNode.
3565     // This will allow us to observe initializations when they occur,
3566     // and link them properly (as a group) to the InitializeNode.
3567     assert(init->in(InitializeNode::Memory) == malloc, "");
3568     MergeMemNode* minit_in = MergeMemNode::make(malloc);
3569     init->set_req(InitializeNode::Memory, minit_in);
3570     record_for_igvn(minit_in); // fold it up later, if possible

3571     Node* minit_out = memory(rawidx);
3572     assert(minit_out->is_Proj() && minit_out->in(0) == init, "");
3573     // Add an edge in the MergeMem for the header fields so an access
3574     // to one of those has correct memory state
3575     set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::mark_offset_in_bytes())));
3576     set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes())));
3577     if (oop_type->isa_aryptr()) {
3578       const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);
3579       int            elemidx  = C->get_alias_index(telemref);
3580       hook_memory_on_init(*this, elemidx, minit_in, minit_out);

























3581     } else if (oop_type->isa_instptr()) {

3582       ciInstanceKlass* ik = oop_type->is_instptr()->instance_klass();
3583       for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {
3584         ciField* field = ik->nonstatic_field_at(i);
3585         if (field->offset() >= TrackedInitializationLimit * HeapWordSize)
3586           continue;  // do not bother to track really large numbers of fields
3587         // Find (or create) the alias category for this field:
3588         int fieldidx = C->alias_type(field)->index();
3589         hook_memory_on_init(*this, fieldidx, minit_in, minit_out);
3590       }
3591     }
3592   }
3593 
3594   // Cast raw oop to the real thing...
3595   Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type);
3596   javaoop = _gvn.transform(javaoop);
3597   C->set_recent_alloc(control(), javaoop);
3598   assert(just_allocated_object(control()) == javaoop, "just allocated");
3599 
3600 #ifdef ASSERT
3601   { // Verify that the AllocateNode::Ideal_allocation recognizers work:

3612       assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");
3613     }
3614   }
3615 #endif //ASSERT
3616 
3617   return javaoop;
3618 }
3619 
3620 //---------------------------new_instance--------------------------------------
3621 // This routine takes a klass_node which may be constant (for a static type)
3622 // or may be non-constant (for reflective code).  It will work equally well
3623 // for either, and the graph will fold nicely if the optimizer later reduces
3624 // the type to a constant.
3625 // The optional arguments are for specialized use by intrinsics:
3626 //  - If 'extra_slow_test' if not null is an extra condition for the slow-path.
3627 //  - If 'return_size_val', report the total object size to the caller.
3628 //  - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
3629 Node* GraphKit::new_instance(Node* klass_node,
3630                              Node* extra_slow_test,
3631                              Node* *return_size_val,
3632                              bool deoptimize_on_exception) {

3633   // Compute size in doublewords
3634   // The size is always an integral number of doublewords, represented
3635   // as a positive bytewise size stored in the klass's layout_helper.
3636   // The layout_helper also encodes (in a low bit) the need for a slow path.
3637   jint  layout_con = Klass::_lh_neutral_value;
3638   Node* layout_val = get_layout_helper(klass_node, layout_con);
3639   int   layout_is_con = (layout_val == NULL);
3640 
3641   if (extra_slow_test == NULL)  extra_slow_test = intcon(0);
3642   // Generate the initial go-slow test.  It's either ALWAYS (return a
3643   // Node for 1) or NEVER (return a NULL) or perhaps (in the reflective
3644   // case) a computed value derived from the layout_helper.
3645   Node* initial_slow_test = NULL;
3646   if (layout_is_con) {
3647     assert(!StressReflectiveCode, "stress mode does not use these paths");
3648     bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);
3649     initial_slow_test = must_go_slow ? intcon(1) : extra_slow_test;
3650   } else {   // reflective case
3651     // This reflective path is used by Unsafe.allocateInstance.
3652     // (It may be stress-tested by specifying StressReflectiveCode.)
3653     // Basically, we want to get into the VM is there's an illegal argument.
3654     Node* bit = intcon(Klass::_lh_instance_slow_path_bit);
3655     initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) );
3656     if (extra_slow_test != intcon(0)) {
3657       initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) );
3658     }
3659     // (Macro-expander will further convert this to a Bool, if necessary.)

3670 
3671     // Clear the low bits to extract layout_helper_size_in_bytes:
3672     assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
3673     Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));
3674     size = _gvn.transform( new AndXNode(size, mask) );
3675   }
3676   if (return_size_val != NULL) {
3677     (*return_size_val) = size;
3678   }
3679 
3680   // This is a precise notnull oop of the klass.
3681   // (Actually, it need not be precise if this is a reflective allocation.)
3682   // It's what we cast the result to.
3683   const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();
3684   if (!tklass)  tklass = TypeInstKlassPtr::OBJECT;
3685   const TypeOopPtr* oop_type = tklass->as_instance_type();
3686 
3687   // Now generate allocation code
3688 
3689   // The entire memory state is needed for slow path of the allocation
3690   // since GC and deoptimization can happened.
3691   Node *mem = reset_memory();
3692   set_all_memory(mem); // Create new memory state
3693 
3694   AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP),
3695                                          control(), mem, i_o(),
3696                                          size, klass_node,
3697                                          initial_slow_test);
3698 
3699   return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);
3700 }
3701 
3702 //-------------------------------new_array-------------------------------------
3703 // helper for both newarray and anewarray
3704 // The 'length' parameter is (obviously) the length of the array.
3705 // See comments on new_instance for the meaning of the other arguments.
3706 Node* GraphKit::new_array(Node* klass_node,     // array klass (maybe variable)
3707                           Node* length,         // number of array elements
3708                           int   nargs,          // number of arguments to push back for uncommon trap
3709                           Node* *return_size_val,
3710                           bool deoptimize_on_exception) {
3711   jint  layout_con = Klass::_lh_neutral_value;
3712   Node* layout_val = get_layout_helper(klass_node, layout_con);
3713   int   layout_is_con = (layout_val == NULL);
3714 
3715   if (!layout_is_con && !StressReflectiveCode &&
3716       !too_many_traps(Deoptimization::Reason_class_check)) {
3717     // This is a reflective array creation site.
3718     // Optimistically assume that it is a subtype of Object[],
3719     // so that we can fold up all the address arithmetic.
3720     layout_con = Klass::array_layout_helper(T_OBJECT);
3721     Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) );
3722     Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) );
3723     { BuildCutout unless(this, bol_lh, PROB_MAX);
3724       inc_sp(nargs);
3725       uncommon_trap(Deoptimization::Reason_class_check,
3726                     Deoptimization::Action_maybe_recompile);
3727     }
3728     layout_val = NULL;
3729     layout_is_con = true;
3730   }
3731 
3732   // Generate the initial go-slow test.  Make sure we do not overflow
3733   // if length is huge (near 2Gig) or negative!  We do not need
3734   // exact double-words here, just a close approximation of needed
3735   // double-words.  We can't add any offset or rounding bits, lest we
3736   // take a size -1 of bytes and make it positive.  Use an unsigned
3737   // compare, so negative sizes look hugely positive.
3738   int fast_size_limit = FastAllocateSizeLimit;
3739   if (layout_is_con) {
3740     assert(!StressReflectiveCode, "stress mode does not use these paths");
3741     // Increase the size limit if we have exact knowledge of array type.
3742     int log2_esize = Klass::layout_helper_log2_element_size(layout_con);
3743     fast_size_limit <<= (LogBytesPerLong - log2_esize);
3744   }
3745 
3746   Node* initial_slow_cmp  = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) );
3747   Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) );
3748 
3749   // --- Size Computation ---
3750   // array_size = round_to_heap(array_header + (length << elem_shift));
3751   // where round_to_heap(x) == align_to(x, MinObjAlignmentInBytes)
3752   // and align_to(x, y) == ((x + y-1) & ~(y-1))
3753   // The rounding mask is strength-reduced, if possible.
3754   int round_mask = MinObjAlignmentInBytes - 1;
3755   Node* header_size = NULL;
3756   int   header_size_min  = arrayOopDesc::base_offset_in_bytes(T_BYTE);
3757   // (T_BYTE has the weakest alignment and size restrictions...)
3758   if (layout_is_con) {
3759     int       hsize  = Klass::layout_helper_header_size(layout_con);
3760     int       eshift = Klass::layout_helper_log2_element_size(layout_con);
3761     BasicType etype  = Klass::layout_helper_element_type(layout_con);
3762     if ((round_mask & ~right_n_bits(eshift)) == 0)
3763       round_mask = 0;  // strength-reduce it if it goes away completely
3764     assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
3765     assert(header_size_min <= hsize, "generic minimum is smallest");
3766     header_size_min = hsize;
3767     header_size = intcon(hsize + round_mask);
3768   } else {
3769     Node* hss   = intcon(Klass::_lh_header_size_shift);
3770     Node* hsm   = intcon(Klass::_lh_header_size_mask);
3771     Node* hsize = _gvn.transform( new URShiftINode(layout_val, hss) );
3772     hsize       = _gvn.transform( new AndINode(hsize, hsm) );
3773     Node* mask  = intcon(round_mask);
3774     header_size = _gvn.transform( new AddINode(hsize, mask) );
3775   }
3776 
3777   Node* elem_shift = NULL;
3778   if (layout_is_con) {
3779     int eshift = Klass::layout_helper_log2_element_size(layout_con);
3780     if (eshift != 0)
3781       elem_shift = intcon(eshift);
3782   } else {
3783     // There is no need to mask or shift this value.
3784     // The semantics of LShiftINode include an implicit mask to 0x1F.

3828   // places, one where the length is sharply limited, and the other
3829   // after a successful allocation.
3830   Node* abody = lengthx;
3831   if (elem_shift != NULL)
3832     abody     = _gvn.transform( new LShiftXNode(lengthx, elem_shift) );
3833   Node* size  = _gvn.transform( new AddXNode(headerx, abody) );
3834   if (round_mask != 0) {
3835     Node* mask = MakeConX(~round_mask);
3836     size       = _gvn.transform( new AndXNode(size, mask) );
3837   }
3838   // else if round_mask == 0, the size computation is self-rounding
3839 
3840   if (return_size_val != NULL) {
3841     // This is the size
3842     (*return_size_val) = size;
3843   }
3844 
3845   // Now generate allocation code
3846 
3847   // The entire memory state is needed for slow path of the allocation
3848   // since GC and deoptimization can happened.
3849   Node *mem = reset_memory();
3850   set_all_memory(mem); // Create new memory state
3851 
3852   if (initial_slow_test->is_Bool()) {
3853     // Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.
3854     initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);
3855   }
3856 
3857   const TypeOopPtr* ary_type = _gvn.type(klass_node)->is_klassptr()->as_instance_type();



























































3858   Node* valid_length_test = _gvn.intcon(1);
3859   if (ary_type->isa_aryptr()) {
3860     BasicType bt = ary_type->isa_aryptr()->elem()->array_element_basic_type();
3861     jint max = TypeAryPtr::max_array_length(bt);
3862     Node* valid_length_cmp  = _gvn.transform(new CmpUNode(length, intcon(max)));
3863     valid_length_test = _gvn.transform(new BoolNode(valid_length_cmp, BoolTest::le));
3864   }
3865 
3866   // Create the AllocateArrayNode and its result projections
3867   AllocateArrayNode* alloc
3868     = new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),
3869                             control(), mem, i_o(),
3870                             size, klass_node,
3871                             initial_slow_test,
3872                             length, valid_length_test);
3873 
3874   // Cast to correct type.  Note that the klass_node may be constant or not,
3875   // and in the latter case the actual array type will be inexact also.
3876   // (This happens via a non-constant argument to inline_native_newArray.)
3877   // In any case, the value of klass_node provides the desired array type.
3878   const TypeInt* length_type = _gvn.find_int_type(length);
3879   if (ary_type->isa_aryptr() && length_type != NULL) {
3880     // Try to get a better type than POS for the size
3881     ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
3882   }
3883 
3884   Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);
3885 
3886   array_ideal_length(alloc, ary_type, true);
3887   return javaoop;
3888 }
3889 
3890 // The following "Ideal_foo" functions are placed here because they recognize
3891 // the graph shapes created by the functions immediately above.
3892 
3893 //---------------------------Ideal_allocation----------------------------------

4007   set_all_memory(ideal.merged_memory());
4008   set_i_o(ideal.i_o());
4009   set_control(ideal.ctrl());
4010 }
4011 
4012 void GraphKit::final_sync(IdealKit& ideal) {
4013   // Final sync IdealKit and graphKit.
4014   sync_kit(ideal);
4015 }
4016 
4017 Node* GraphKit::load_String_length(Node* str, bool set_ctrl) {
4018   Node* len = load_array_length(load_String_value(str, set_ctrl));
4019   Node* coder = load_String_coder(str, set_ctrl);
4020   // Divide length by 2 if coder is UTF16
4021   return _gvn.transform(new RShiftINode(len, coder));
4022 }
4023 
4024 Node* GraphKit::load_String_value(Node* str, bool set_ctrl) {
4025   int value_offset = java_lang_String::value_offset();
4026   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4027                                                      false, NULL, 0);
4028   const TypePtr* value_field_type = string_type->add_offset(value_offset);
4029   const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull,
4030                                                   TypeAry::make(TypeInt::BYTE, TypeInt::POS),
4031                                                   ciTypeArrayKlass::make(T_BYTE), true, 0);
4032   Node* p = basic_plus_adr(str, str, value_offset);
4033   Node* load = access_load_at(str, p, value_field_type, value_type, T_OBJECT,
4034                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4035   return load;
4036 }
4037 
4038 Node* GraphKit::load_String_coder(Node* str, bool set_ctrl) {
4039   if (!CompactStrings) {
4040     return intcon(java_lang_String::CODER_UTF16);
4041   }
4042   int coder_offset = java_lang_String::coder_offset();
4043   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4044                                                      false, NULL, 0);
4045   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4046 
4047   Node* p = basic_plus_adr(str, str, coder_offset);
4048   Node* load = access_load_at(str, p, coder_field_type, TypeInt::BYTE, T_BYTE,
4049                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4050   return load;
4051 }
4052 
4053 void GraphKit::store_String_value(Node* str, Node* value) {
4054   int value_offset = java_lang_String::value_offset();
4055   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4056                                                      false, NULL, 0);
4057   const TypePtr* value_field_type = string_type->add_offset(value_offset);
4058 
4059   access_store_at(str,  basic_plus_adr(str, value_offset), value_field_type,
4060                   value, TypeAryPtr::BYTES, T_OBJECT, IN_HEAP | MO_UNORDERED);
4061 }
4062 
4063 void GraphKit::store_String_coder(Node* str, Node* value) {
4064   int coder_offset = java_lang_String::coder_offset();
4065   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4066                                                      false, NULL, 0);
4067   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4068 
4069   access_store_at(str, basic_plus_adr(str, coder_offset), coder_field_type,
4070                   value, TypeInt::BYTE, T_BYTE, IN_HEAP | MO_UNORDERED);
4071 }
4072 
4073 // Capture src and dst memory state with a MergeMemNode
4074 Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) {
4075   if (src_type == dst_type) {
4076     // Types are equal, we don't need a MergeMemNode
4077     return memory(src_type);
4078   }
4079   MergeMemNode* merge = MergeMemNode::make(map()->memory());
4080   record_for_igvn(merge); // fold it up later, if possible
4081   int src_idx = C->get_alias_index(src_type);
4082   int dst_idx = C->get_alias_index(dst_type);
4083   merge->set_memory_at(src_idx, memory(src_idx));
4084   merge->set_memory_at(dst_idx, memory(dst_idx));
4085   return merge;
4086 }

4159   i_char->init_req(2, AddI(i_char, intcon(2)));
4160 
4161   set_control(IfFalse(iff));
4162   set_memory(st, TypeAryPtr::BYTES);
4163 }
4164 
4165 Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) {
4166   if (!field->is_constant()) {
4167     return NULL; // Field not marked as constant.
4168   }
4169   ciInstance* holder = NULL;
4170   if (!field->is_static()) {
4171     ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop();
4172     if (const_oop != NULL && const_oop->is_instance()) {
4173       holder = const_oop->as_instance();
4174     }
4175   }
4176   const Type* con_type = Type::make_constant_from_field(field, holder, field->layout_type(),
4177                                                         /*is_unsigned_load=*/false);
4178   if (con_type != NULL) {
4179     return makecon(con_type);






4180   }
4181   return NULL;
4182 }










   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 != NULL) ? *gvn : *C->initial_gvn()),
  64     _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
  65 {
  66   assert(gvn == NULL || !gvn->is_IterGVN() || gvn->is_IterGVN()->delay_transform(), "delay transform should be enabled");
  67   _exceptions = jvms->map()->next_exception();
  68   if (_exceptions != NULL)  jvms->map()->set_next_exception(NULL);
  69   set_jvms(jvms);
  70 #ifdef ASSERT
  71   if (_gvn.is_IterGVN() != NULL) {
  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 = NULL;
  87   set_map(NULL);
  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.

 829         if (PrintMiscellaneous && (Verbose || WizardMode)) {
 830           tty->print_cr("Zombie local %d: ", local);
 831           jvms->dump();
 832         }
 833         return false;
 834       }
 835     }
 836   }
 837   return true;
 838 }
 839 
 840 #endif //ASSERT
 841 
 842 // Helper function for enforcing certain bytecodes to reexecute if deoptimization happens.
 843 static bool should_reexecute_implied_by_bytecode(JVMState *jvms, bool is_anewarray) {
 844   ciMethod* cur_method = jvms->method();
 845   int       cur_bci   = jvms->bci();
 846   if (cur_method != NULL && cur_bci != InvocationEntryBci) {
 847     Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci);
 848     return Interpreter::bytecode_should_reexecute(code) ||
 849            (is_anewarray && (code == Bytecodes::_multianewarray));
 850     // Reexecute _multianewarray bytecode which was replaced with
 851     // sequence of [a]newarray. See Parse::do_multianewarray().
 852     //
 853     // Note: interpreter should not have it set since this optimization
 854     // is limited by dimensions and guarded by flag so in some cases
 855     // multianewarray() runtime calls will be generated and
 856     // the bytecode should not be reexecutes (stack will not be reset).
 857   } else {
 858     return false;
 859   }
 860 }
 861 
 862 // Helper function for adding JVMState and debug information to node
 863 void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) {
 864   // Add the safepoint edges to the call (or other safepoint).
 865 
 866   // Make sure dead locals are set to top.  This
 867   // should help register allocation time and cut down on the size
 868   // of the deoptimization information.
 869   assert(dead_locals_are_killed(), "garbage in debug info before safepoint");

1089       ciSignature* declared_signature = NULL;
1090       ciMethod* ignored_callee = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
1091       assert(declared_signature != NULL, "cannot be null");
1092       inputs   = declared_signature->arg_size_for_bc(code);
1093       int size = declared_signature->return_type()->size();
1094       depth = size - inputs;
1095     }
1096     break;
1097 
1098   case Bytecodes::_multianewarray:
1099     {
1100       ciBytecodeStream iter(method());
1101       iter.reset_to_bci(bci());
1102       iter.next();
1103       inputs = iter.get_dimensions();
1104       assert(rsize == 1, "");
1105       depth = rsize - inputs;
1106     }
1107     break;
1108 
1109   case Bytecodes::_withfield: {
1110     bool ignored_will_link;
1111     ciField* field = method()->get_field_at_bci(bci(), ignored_will_link);
1112     int      size  = field->type()->size();
1113     inputs = size+1;
1114     depth = rsize - inputs;
1115     break;
1116   }
1117 
1118   case Bytecodes::_ireturn:
1119   case Bytecodes::_lreturn:
1120   case Bytecodes::_freturn:
1121   case Bytecodes::_dreturn:
1122   case Bytecodes::_areturn:
1123     assert(rsize == -depth, "");
1124     inputs = rsize;
1125     break;
1126 
1127   case Bytecodes::_jsr:
1128   case Bytecodes::_jsr_w:
1129     inputs = 0;
1130     depth  = 1;                  // S.B. depth=1, not zero
1131     break;
1132 
1133   default:
1134     // bytecode produces a typed result
1135     inputs = rsize - depth;
1136     assert(inputs >= 0, "");
1137     break;

1180   Node* conv = _gvn.transform( new ConvI2LNode(offset));
1181   Node* mask = _gvn.transform(ConLNode::make((julong) max_juint));
1182   return _gvn.transform( new AndLNode(conv, mask) );
1183 }
1184 
1185 Node* GraphKit::ConvL2I(Node* offset) {
1186   // short-circuit a common case
1187   jlong offset_con = find_long_con(offset, (jlong)Type::OffsetBot);
1188   if (offset_con != (jlong)Type::OffsetBot) {
1189     return intcon((int) offset_con);
1190   }
1191   return _gvn.transform( new ConvL2INode(offset));
1192 }
1193 
1194 //-------------------------load_object_klass-----------------------------------
1195 Node* GraphKit::load_object_klass(Node* obj) {
1196   // Special-case a fresh allocation to avoid building nodes:
1197   Node* akls = AllocateNode::Ideal_klass(obj, &_gvn);
1198   if (akls != NULL)  return akls;
1199   Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
1200   return _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), k_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
1201 }
1202 
1203 //-------------------------load_array_length-----------------------------------
1204 Node* GraphKit::load_array_length(Node* array) {
1205   // Special-case a fresh allocation to avoid building nodes:
1206   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(array, &_gvn);
1207   Node *alen;
1208   if (alloc == NULL) {
1209     Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes());
1210     alen = _gvn.transform( new LoadRangeNode(0, immutable_memory(), r_adr, TypeInt::POS));
1211   } else {
1212     alen = array_ideal_length(alloc, _gvn.type(array)->is_oopptr(), false);
1213   }
1214   return alen;
1215 }
1216 
1217 Node* GraphKit::array_ideal_length(AllocateArrayNode* alloc,
1218                                    const TypeOopPtr* oop_type,
1219                                    bool replace_length_in_map) {
1220   Node* length = alloc->Ideal_length();

1229         replace_in_map(length, ccast);
1230       }
1231       return ccast;
1232     }
1233   }
1234   return length;
1235 }
1236 
1237 //------------------------------do_null_check----------------------------------
1238 // Helper function to do a NULL pointer check.  Returned value is
1239 // the incoming address with NULL casted away.  You are allowed to use the
1240 // not-null value only if you are control dependent on the test.
1241 #ifndef PRODUCT
1242 extern int explicit_null_checks_inserted,
1243            explicit_null_checks_elided;
1244 #endif
1245 Node* GraphKit::null_check_common(Node* value, BasicType type,
1246                                   // optional arguments for variations:
1247                                   bool assert_null,
1248                                   Node* *null_control,
1249                                   bool speculative,
1250                                   bool is_init_check) {
1251   assert(!assert_null || null_control == NULL, "not both at once");
1252   if (stopped())  return top();
1253   NOT_PRODUCT(explicit_null_checks_inserted++);
1254 
1255   if (value->is_InlineType()) {
1256     // Null checking a scalarized but nullable inline type. Check the IsInit
1257     // input instead of the oop input to avoid keeping buffer allocations alive.
1258     InlineTypeNode* vtptr = value->as_InlineType();
1259     while (vtptr->get_oop()->is_InlineType()) {
1260       vtptr = vtptr->get_oop()->as_InlineType();
1261     }
1262     null_check_common(vtptr->get_is_init(), T_INT, assert_null, null_control, speculative, true);
1263     if (stopped()) {
1264       return top();
1265     }
1266     if (assert_null) {
1267       // TODO 8284443 Scalarize here (this currently leads to compilation bailouts)
1268       // vtptr = InlineTypeNode::make_null(_gvn, vtptr->type()->inline_klass());
1269       // replace_in_map(value, vtptr);
1270       // return vtptr;
1271       return null();
1272     }
1273     bool do_replace_in_map = (null_control == NULL || (*null_control) == top());
1274     return cast_not_null(value, do_replace_in_map);
1275   }
1276 
1277   // Construct NULL check
1278   Node *chk = NULL;
1279   switch(type) {
1280     case T_LONG   : chk = new CmpLNode(value, _gvn.zerocon(T_LONG)); break;
1281     case T_INT    : chk = new CmpINode(value, _gvn.intcon(0)); break;
1282     case T_PRIMITIVE_OBJECT : // fall through
1283     case T_ARRAY  : // fall through
1284       type = T_OBJECT;  // simplify further tests
1285     case T_OBJECT : {
1286       const Type *t = _gvn.type( value );
1287 
1288       const TypeOopPtr* tp = t->isa_oopptr();
1289       if (tp != NULL && !tp->is_loaded()
1290           // Only for do_null_check, not any of its siblings:
1291           && !assert_null && null_control == NULL) {
1292         // Usually, any field access or invocation on an unloaded oop type
1293         // will simply fail to link, since the statically linked class is
1294         // likely also to be unloaded.  However, in -Xcomp mode, sometimes
1295         // the static class is loaded but the sharper oop type is not.
1296         // Rather than checking for this obscure case in lots of places,
1297         // we simply observe that a null check on an unloaded class
1298         // will always be followed by a nonsense operation, so we
1299         // can just issue the uncommon trap here.
1300         // Our access to the unloaded class will only be correct
1301         // after it has been loaded and initialized, which requires
1302         // a trip through the interpreter.

1361         }
1362         Node *oldcontrol = control();
1363         set_control(cfg);
1364         Node *res = cast_not_null(value);
1365         set_control(oldcontrol);
1366         NOT_PRODUCT(explicit_null_checks_elided++);
1367         return res;
1368       }
1369       cfg = IfNode::up_one_dom(cfg, /*linear_only=*/ true);
1370       if (cfg == NULL)  break;  // Quit at region nodes
1371       depth++;
1372     }
1373   }
1374 
1375   //-----------
1376   // Branch to failure if null
1377   float ok_prob = PROB_MAX;  // a priori estimate:  nulls never happen
1378   Deoptimization::DeoptReason reason;
1379   if (assert_null) {
1380     reason = Deoptimization::reason_null_assert(speculative);
1381   } else if (type == T_OBJECT || is_init_check) {
1382     reason = Deoptimization::reason_null_check(speculative);
1383   } else {
1384     reason = Deoptimization::Reason_div0_check;
1385   }
1386   // %%% Since Reason_unhandled is not recorded on a per-bytecode basis,
1387   // ciMethodData::has_trap_at will return a conservative -1 if any
1388   // must-be-null assertion has failed.  This could cause performance
1389   // problems for a method after its first do_null_assert failure.
1390   // Consider using 'Reason_class_check' instead?
1391 
1392   // To cause an implicit null check, we set the not-null probability
1393   // to the maximum (PROB_MAX).  For an explicit check the probability
1394   // is set to a smaller value.
1395   if (null_control != NULL || too_many_traps(reason)) {
1396     // probability is less likely
1397     ok_prob =  PROB_LIKELY_MAG(3);
1398   } else if (!assert_null &&
1399              (ImplicitNullCheckThreshold > 0) &&
1400              method() != NULL &&
1401              (method()->method_data()->trap_count(reason)

1435   }
1436 
1437   if (assert_null) {
1438     // Cast obj to null on this path.
1439     replace_in_map(value, zerocon(type));
1440     return zerocon(type);
1441   }
1442 
1443   // Cast obj to not-null on this path, if there is no null_control.
1444   // (If there is a null_control, a non-null value may come back to haunt us.)
1445   if (type == T_OBJECT) {
1446     Node* cast = cast_not_null(value, false);
1447     if (null_control == NULL || (*null_control) == top())
1448       replace_in_map(value, cast);
1449     value = cast;
1450   }
1451 
1452   return value;
1453 }
1454 

1455 //------------------------------cast_not_null----------------------------------
1456 // Cast obj to not-null on this path
1457 Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) {
1458   if (obj->is_InlineType()) {
1459     Node* vt = obj->clone();
1460     vt->as_InlineType()->set_is_init(_gvn);
1461     vt = _gvn.transform(vt);
1462     if (do_replace_in_map) {
1463       replace_in_map(obj, vt);
1464     }
1465     return vt;
1466   }
1467   const Type *t = _gvn.type(obj);
1468   const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL);
1469   // Object is already not-null?
1470   if( t == t_not_null ) return obj;
1471 
1472   Node *cast = new CastPPNode(obj,t_not_null);
1473   cast->init_req(0, control());
1474   cast = _gvn.transform( cast );
1475 
1476   // Scan for instances of 'obj' in the current JVM mapping.
1477   // These instances are known to be not-null after the test.
1478   if (do_replace_in_map)
1479     replace_in_map(obj, cast);
1480 
1481   return cast;                  // Return casted value
1482 }
1483 
1484 // Sometimes in intrinsics, we implicitly know an object is not null
1485 // (there's no actual null check) so we can cast it to not null. In
1486 // the course of optimizations, the input to the cast can become null.

1573 // These are layered on top of the factory methods in LoadNode and StoreNode,
1574 // and integrate with the parser's memory state and _gvn engine.
1575 //
1576 
1577 // factory methods in "int adr_idx"
1578 Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,
1579                           int adr_idx,
1580                           MemNode::MemOrd mo,
1581                           LoadNode::ControlDependency control_dependency,
1582                           bool require_atomic_access,
1583                           bool unaligned,
1584                           bool mismatched,
1585                           bool unsafe,
1586                           uint8_t barrier_data) {
1587   assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );
1588   const TypePtr* adr_type = NULL; // debug-mode-only argument
1589   debug_only(adr_type = C->get_adr_type(adr_idx));
1590   Node* mem = memory(adr_idx);
1591   Node* ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, require_atomic_access, unaligned, mismatched, unsafe, barrier_data);
1592   ld = _gvn.transform(ld);
1593 
1594   if (((bt == T_OBJECT || bt == T_PRIMITIVE_OBJECT) && C->do_escape_analysis()) || C->eliminate_boxing()) {
1595     // Improve graph before escape analysis and boxing elimination.
1596     record_for_igvn(ld);
1597   }
1598   return ld;
1599 }
1600 
1601 Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,
1602                                 int adr_idx,
1603                                 MemNode::MemOrd mo,
1604                                 bool require_atomic_access,
1605                                 bool unaligned,
1606                                 bool mismatched,
1607                                 bool unsafe) {
1608   assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
1609   const TypePtr* adr_type = NULL;
1610   debug_only(adr_type = C->get_adr_type(adr_idx));
1611   Node *mem = memory(adr_idx);
1612   Node* st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo, require_atomic_access);
1613   if (unaligned) {
1614     st->as_Store()->set_unaligned_access();

1618   }
1619   if (unsafe) {
1620     st->as_Store()->set_unsafe_access();
1621   }
1622   st = _gvn.transform(st);
1623   set_memory(st, adr_idx);
1624   // Back-to-back stores can only remove intermediate store with DU info
1625   // so push on worklist for optimizer.
1626   if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))
1627     record_for_igvn(st);
1628 
1629   return st;
1630 }
1631 
1632 Node* GraphKit::access_store_at(Node* obj,
1633                                 Node* adr,
1634                                 const TypePtr* adr_type,
1635                                 Node* val,
1636                                 const Type* val_type,
1637                                 BasicType bt,
1638                                 DecoratorSet decorators,
1639                                 bool safe_for_replace) {
1640   // Transformation of a value which could be NULL pointer (CastPP #NULL)
1641   // could be delayed during Parse (for example, in adjust_map_after_if()).
1642   // Execute transformation here to avoid barrier generation in such case.
1643   if (_gvn.type(val) == TypePtr::NULL_PTR) {
1644     val = _gvn.makecon(TypePtr::NULL_PTR);
1645   }
1646 
1647   if (stopped()) {
1648     return top(); // Dead path ?
1649   }
1650 
1651   assert(val != NULL, "not dead path");
1652   if (val->is_InlineType()) {
1653     // Store to non-flattened field. Buffer the inline type and make sure
1654     // the store is re-executed if the allocation triggers deoptimization.
1655     PreserveReexecuteState preexecs(this);
1656     jvms()->set_should_reexecute(true);
1657     val = val->as_InlineType()->buffer(this, safe_for_replace);
1658   }
1659 
1660   C2AccessValuePtr addr(adr, adr_type);
1661   C2AccessValue value(val, val_type);
1662   C2ParseAccess access(this, decorators | C2_WRITE_ACCESS, bt, obj, addr);
1663   if (access.is_raw()) {
1664     return _barrier_set->BarrierSetC2::store_at(access, value);
1665   } else {
1666     return _barrier_set->store_at(access, value);
1667   }
1668 }
1669 
1670 Node* GraphKit::access_load_at(Node* obj,   // containing obj
1671                                Node* adr,   // actual address to store val at
1672                                const TypePtr* adr_type,
1673                                const Type* val_type,
1674                                BasicType bt,
1675                                DecoratorSet decorators,
1676                                Node* ctl) {
1677   if (stopped()) {
1678     return top(); // Dead path ?
1679   }
1680 
1681   C2AccessValuePtr addr(adr, adr_type);
1682   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, obj, addr, ctl);
1683   if (access.is_raw()) {
1684     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1685   } else {
1686     return _barrier_set->load_at(access, val_type);
1687   }
1688 }
1689 
1690 Node* GraphKit::access_load(Node* adr,   // actual address to load val at
1691                             const Type* val_type,
1692                             BasicType bt,
1693                             DecoratorSet decorators) {
1694   if (stopped()) {
1695     return top(); // Dead path ?
1696   }
1697 
1698   C2AccessValuePtr addr(adr, adr->bottom_type()->is_ptr());
1699   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, NULL, addr);
1700   if (access.is_raw()) {
1701     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1702   } else {

1767                                      Node* new_val,
1768                                      const Type* value_type,
1769                                      BasicType bt,
1770                                      DecoratorSet decorators) {
1771   C2AccessValuePtr addr(adr, adr_type);
1772   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, bt, obj, addr, alias_idx);
1773   if (access.is_raw()) {
1774     return _barrier_set->BarrierSetC2::atomic_add_at(access, new_val, value_type);
1775   } else {
1776     return _barrier_set->atomic_add_at(access, new_val, value_type);
1777   }
1778 }
1779 
1780 void GraphKit::access_clone(Node* src, Node* dst, Node* size, bool is_array) {
1781   return _barrier_set->clone(this, src, dst, size, is_array);
1782 }
1783 
1784 //-------------------------array_element_address-------------------------
1785 Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,
1786                                       const TypeInt* sizetype, Node* ctrl) {
1787   const TypeAryPtr* arytype = _gvn.type(ary)->is_aryptr();
1788   uint shift = arytype->is_flat() ? arytype->flat_log_elem_size() : exact_log2(type2aelembytes(elembt));
1789   uint header = arrayOopDesc::base_offset_in_bytes(elembt);
1790 
1791   // short-circuit a common case (saves lots of confusing waste motion)
1792   jint idx_con = find_int_con(idx, -1);
1793   if (idx_con >= 0) {
1794     intptr_t offset = header + ((intptr_t)idx_con << shift);
1795     return basic_plus_adr(ary, offset);
1796   }
1797 
1798   // must be correct type for alignment purposes
1799   Node* base  = basic_plus_adr(ary, header);
1800   idx = Compile::conv_I2X_index(&_gvn, idx, sizetype, ctrl);
1801   Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) );
1802   return basic_plus_adr(ary, base, scale);
1803 }
1804 
1805 //-------------------------load_array_element-------------------------
1806 Node* GraphKit::load_array_element(Node* ary, Node* idx, const TypeAryPtr* arytype, bool set_ctrl) {
1807   const Type* elemtype = arytype->elem();
1808   BasicType elembt = elemtype->array_element_basic_type();
1809   assert(elembt != T_PRIMITIVE_OBJECT, "inline types are not supported by this method");
1810   Node* adr = array_element_address(ary, idx, elembt, arytype->size());
1811   if (elembt == T_NARROWOOP) {
1812     elembt = T_OBJECT; // To satisfy switch in LoadNode::make()
1813   }
1814   Node* ld = access_load_at(ary, adr, arytype, elemtype, elembt,
1815                             IN_HEAP | IS_ARRAY | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0));
1816   return ld;
1817 }
1818 
1819 //-------------------------set_arguments_for_java_call-------------------------
1820 // Arguments (pre-popped from the stack) are taken from the JVMS.
1821 void GraphKit::set_arguments_for_java_call(CallJavaNode* call, bool is_late_inline) {
1822   PreserveReexecuteState preexecs(this);
1823   if (EnableValhalla) {
1824     // Make sure the call is "re-executed", if buffering of inline type arguments triggers deoptimization.
1825     // At this point, the call hasn't been executed yet, so we will only ever execute the call once.
1826     jvms()->set_should_reexecute(true);
1827     int arg_size = method()->get_declared_signature_at_bci(bci())->arg_size_for_bc(java_bc());
1828     inc_sp(arg_size);
1829   }
1830   // Add the call arguments
1831   const TypeTuple* domain = call->tf()->domain_sig();
1832   uint nargs = domain->cnt();
1833   int arg_num = 0;
1834   for (uint i = TypeFunc::Parms, idx = TypeFunc::Parms; i < nargs; i++) {
1835     Node* arg = argument(i-TypeFunc::Parms);
1836     const Type* t = domain->field_at(i);
1837     if (t->is_inlinetypeptr() && call->method()->is_scalarized_arg(arg_num)) {
1838       // We don't pass inline type arguments by reference but instead pass each field of the inline type
1839       if (!arg->is_InlineType()) {
1840         assert(_gvn.type(arg)->is_zero_type() && !t->inline_klass()->is_null_free(), "Unexpected argument type");
1841         arg = InlineTypeNode::make_from_oop(this, arg, t->inline_klass(), t->inline_klass()->is_null_free());
1842       }
1843       InlineTypeNode* vt = arg->as_InlineType();
1844       vt->pass_fields(this, call, idx, true, !t->maybe_null());
1845       // If an inline type argument is passed as fields, attach the Method* to the call site
1846       // to be able to access the extended signature later via attached_method_before_pc().
1847       // For example, see CompiledMethod::preserve_callee_argument_oops().
1848       call->set_override_symbolic_info(true);
1849       arg_num++;
1850       continue;
1851     } else if (arg->is_InlineType()) {
1852       // Pass inline type argument via oop to callee
1853       arg = arg->as_InlineType()->buffer(this);
1854       if (!is_late_inline) {
1855         arg = arg->as_InlineType()->get_oop();
1856       }
1857     }
1858     if (t != Type::HALF) {
1859       arg_num++;
1860     }
1861     call->init_req(idx++, arg);
1862   }
1863 }
1864 
1865 //---------------------------set_edges_for_java_call---------------------------
1866 // Connect a newly created call into the current JVMS.
1867 // A return value node (if any) is returned from set_edges_for_java_call.
1868 void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) {
1869 
1870   // Add the predefined inputs:
1871   call->init_req( TypeFunc::Control, control() );
1872   call->init_req( TypeFunc::I_O    , i_o() );
1873   call->init_req( TypeFunc::Memory , reset_memory() );
1874   call->init_req( TypeFunc::FramePtr, frameptr() );
1875   call->init_req( TypeFunc::ReturnAdr, top() );
1876 
1877   add_safepoint_edges(call, must_throw);
1878 
1879   Node* xcall = _gvn.transform(call);
1880 
1881   if (xcall == top()) {
1882     set_control(top());
1883     return;
1884   }
1885   assert(xcall == call, "call identity is stable");
1886 
1887   // Re-use the current map to produce the result.
1888 
1889   set_control(_gvn.transform(new ProjNode(call, TypeFunc::Control)));
1890   set_i_o(    _gvn.transform(new ProjNode(call, TypeFunc::I_O    , separate_io_proj)));
1891   set_all_memory_call(xcall, separate_io_proj);
1892 
1893   //return xcall;   // no need, caller already has it
1894 }
1895 
1896 Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj, bool deoptimize) {
1897   if (stopped())  return top();  // maybe the call folded up?
1898 







1899   // Note:  Since any out-of-line call can produce an exception,
1900   // we always insert an I_O projection from the call into the result.
1901 
1902   make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj, deoptimize);
1903 
1904   if (separate_io_proj) {
1905     // The caller requested separate projections be used by the fall
1906     // through and exceptional paths, so replace the projections for
1907     // the fall through path.
1908     set_i_o(_gvn.transform( new ProjNode(call, TypeFunc::I_O) ));
1909     set_all_memory(_gvn.transform( new ProjNode(call, TypeFunc::Memory) ));
1910   }
1911 
1912   // Capture the return value, if any.
1913   Node* ret;
1914   if (call->method() == NULL || call->method()->return_type()->basic_type() == T_VOID) {
1915     ret = top();
1916   } else if (call->tf()->returns_inline_type_as_fields()) {
1917     // Return of multiple values (inline type fields): we create a
1918     // InlineType node, each field is a projection from the call.
1919     ciInlineKlass* vk = call->method()->return_type()->as_inline_klass();
1920     uint base_input = TypeFunc::Parms;
1921     ret = InlineTypeNode::make_from_multi(this, call, vk, base_input, false, call->method()->signature()->returns_null_free_inline_type());
1922   } else {
1923     ret = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1924   }
1925 
1926   return ret;
1927 }
1928 
1929 //--------------------set_predefined_input_for_runtime_call--------------------
1930 // Reading and setting the memory state is way conservative here.
1931 // The real problem is that I am not doing real Type analysis on memory,
1932 // so I cannot distinguish card mark stores from other stores.  Across a GC
1933 // point the Store Barrier and the card mark memory has to agree.  I cannot
1934 // have a card mark store and its barrier split across the GC point from
1935 // either above or below.  Here I get that to happen by reading ALL of memory.
1936 // A better answer would be to separate out card marks from other memory.
1937 // For now, return the input memory state, so that it can be reused
1938 // after the call, if this call has restricted memory effects.
1939 Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) {
1940   // Set fixed predefined input arguments
1941   Node* memory = reset_memory();
1942   Node* m = narrow_mem == NULL ? memory : narrow_mem;
1943   call->init_req( TypeFunc::Control,   control()  );
1944   call->init_req( TypeFunc::I_O,       top()      ); // does no i/o
1945   call->init_req( TypeFunc::Memory,    m          ); // may gc ptrs

1996     if (use->is_MergeMem()) {
1997       wl.push(use);
1998     }
1999   }
2000 }
2001 
2002 // Replace the call with the current state of the kit.
2003 void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes) {
2004   JVMState* ejvms = NULL;
2005   if (has_exceptions()) {
2006     ejvms = transfer_exceptions_into_jvms();
2007   }
2008 
2009   ReplacedNodes replaced_nodes = map()->replaced_nodes();
2010   ReplacedNodes replaced_nodes_exception;
2011   Node* ex_ctl = top();
2012 
2013   SafePointNode* final_state = stop();
2014 
2015   // Find all the needed outputs of this call
2016   CallProjections* callprojs = call->extract_projections(true);

2017 
2018   Unique_Node_List wl;
2019   Node* init_mem = call->in(TypeFunc::Memory);
2020   Node* final_mem = final_state->in(TypeFunc::Memory);
2021   Node* final_ctl = final_state->in(TypeFunc::Control);
2022   Node* final_io = final_state->in(TypeFunc::I_O);
2023 
2024   // Replace all the old call edges with the edges from the inlining result
2025   if (callprojs->fallthrough_catchproj != NULL) {
2026     C->gvn_replace_by(callprojs->fallthrough_catchproj, final_ctl);
2027   }
2028   if (callprojs->fallthrough_memproj != NULL) {
2029     if (final_mem->is_MergeMem()) {
2030       // Parser's exits MergeMem was not transformed but may be optimized
2031       final_mem = _gvn.transform(final_mem);
2032     }
2033     C->gvn_replace_by(callprojs->fallthrough_memproj,   final_mem);
2034     add_mergemem_users_to_worklist(wl, final_mem);
2035   }
2036   if (callprojs->fallthrough_ioproj != NULL) {
2037     C->gvn_replace_by(callprojs->fallthrough_ioproj,    final_io);
2038   }
2039 
2040   // Replace the result with the new result if it exists and is used
2041   if (callprojs->resproj[0] != NULL && result != NULL) {
2042     // If the inlined code is dead, the result projections for an inline type returned as
2043     // fields have not been replaced. They will go away once the call is replaced by TOP below.
2044     assert(callprojs->nb_resproj == 1 || (call->tf()->returns_inline_type_as_fields() && stopped()),
2045            "unexpected number of results");
2046     C->gvn_replace_by(callprojs->resproj[0], result);
2047   }
2048 
2049   if (ejvms == NULL) {
2050     // No exception edges to simply kill off those paths
2051     if (callprojs->catchall_catchproj != NULL) {
2052       C->gvn_replace_by(callprojs->catchall_catchproj, C->top());
2053     }
2054     if (callprojs->catchall_memproj != NULL) {
2055       C->gvn_replace_by(callprojs->catchall_memproj,   C->top());
2056     }
2057     if (callprojs->catchall_ioproj != NULL) {
2058       C->gvn_replace_by(callprojs->catchall_ioproj,    C->top());
2059     }
2060     // Replace the old exception object with top
2061     if (callprojs->exobj != NULL) {
2062       C->gvn_replace_by(callprojs->exobj, C->top());
2063     }
2064   } else {
2065     GraphKit ekit(ejvms);
2066 
2067     // Load my combined exception state into the kit, with all phis transformed:
2068     SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();
2069     replaced_nodes_exception = ex_map->replaced_nodes();
2070 
2071     Node* ex_oop = ekit.use_exception_state(ex_map);
2072 
2073     if (callprojs->catchall_catchproj != NULL) {
2074       C->gvn_replace_by(callprojs->catchall_catchproj, ekit.control());
2075       ex_ctl = ekit.control();
2076     }
2077     if (callprojs->catchall_memproj != NULL) {
2078       Node* ex_mem = ekit.reset_memory();
2079       C->gvn_replace_by(callprojs->catchall_memproj,   ex_mem);
2080       add_mergemem_users_to_worklist(wl, ex_mem);
2081     }
2082     if (callprojs->catchall_ioproj != NULL) {
2083       C->gvn_replace_by(callprojs->catchall_ioproj,    ekit.i_o());
2084     }
2085 
2086     // Replace the old exception object with the newly created one
2087     if (callprojs->exobj != NULL) {
2088       C->gvn_replace_by(callprojs->exobj, ex_oop);
2089     }
2090   }
2091 
2092   // Disconnect the call from the graph
2093   call->disconnect_inputs(C);
2094   C->gvn_replace_by(call, C->top());
2095 
2096   // Clean up any MergeMems that feed other MergeMems since the
2097   // optimizer doesn't like that.
2098   while (wl.size() > 0) {
2099     _gvn.transform(wl.pop());
2100   }
2101 
2102   if (callprojs->fallthrough_catchproj != NULL && !final_ctl->is_top() && do_replaced_nodes) {
2103     replaced_nodes.apply(C, final_ctl);
2104   }
2105   if (!ex_ctl->is_top() && do_replaced_nodes) {
2106     replaced_nodes_exception.apply(C, ex_ctl);
2107   }
2108 }
2109 
2110 
2111 //------------------------------increment_counter------------------------------
2112 // for statistics: increment a VM counter by 1
2113 
2114 void GraphKit::increment_counter(address counter_addr) {
2115   Node* adr1 = makecon(TypeRawPtr::make(counter_addr));
2116   increment_counter(adr1);
2117 }
2118 
2119 void GraphKit::increment_counter(Node* counter_addr) {
2120   int adr_type = Compile::AliasIdxRaw;
2121   Node* ctrl = control();
2122   Node* cnt  = make_load(ctrl, counter_addr, TypeLong::LONG, T_LONG, adr_type, MemNode::unordered);

2281  *
2282  * @param n          node that the type applies to
2283  * @param exact_kls  type from profiling
2284  * @param maybe_null did profiling see null?
2285  *
2286  * @return           node with improved type
2287  */
2288 Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, ProfilePtrKind ptr_kind) {
2289   const Type* current_type = _gvn.type(n);
2290   assert(UseTypeSpeculation, "type speculation must be on");
2291 
2292   const TypePtr* speculative = current_type->speculative();
2293 
2294   // Should the klass from the profile be recorded in the speculative type?
2295   if (current_type->would_improve_type(exact_kls, jvms()->depth())) {
2296     const TypeKlassPtr* tklass = TypeKlassPtr::make(exact_kls);
2297     const TypeOopPtr* xtype = tklass->as_instance_type();
2298     assert(xtype->klass_is_exact(), "Should be exact");
2299     // Any reason to believe n is not null (from this profiling or a previous one)?
2300     assert(ptr_kind != ProfileAlwaysNull, "impossible here");
2301     const TypePtr* ptr = (ptr_kind != ProfileNeverNull && current_type->speculative_maybe_null()) ? TypePtr::BOTTOM : TypePtr::NOTNULL;
2302     // record the new speculative type's depth
2303     speculative = xtype->cast_to_ptr_type(ptr->ptr())->is_ptr();
2304     speculative = speculative->with_inline_depth(jvms()->depth());
2305   } else if (current_type->would_improve_ptr(ptr_kind)) {
2306     // Profiling report that null was never seen so we can change the
2307     // speculative type to non null ptr.
2308     if (ptr_kind == ProfileAlwaysNull) {
2309       speculative = TypePtr::NULL_PTR;
2310     } else {
2311       assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement");
2312       const TypePtr* ptr = TypePtr::NOTNULL;
2313       if (speculative != NULL) {
2314         speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr();
2315       } else {
2316         speculative = ptr;
2317       }
2318     }
2319   }
2320 
2321   if (speculative != current_type->speculative()) {
2322     // Build a type with a speculative type (what we think we know
2323     // about the type but will need a guard when we use it)
2324     const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::Offset::bottom, TypeOopPtr::InstanceBot, speculative);
2325     // We're changing the type, we need a new CheckCast node to carry
2326     // the new type. The new type depends on the control: what
2327     // profiling tells us is only valid from here as far as we can
2328     // tell.
2329     Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));
2330     cast = _gvn.transform(cast);
2331     replace_in_map(n, cast);
2332     n = cast;
2333   }
2334 
2335   return n;
2336 }
2337 
2338 /**
2339  * Record profiling data from receiver profiling at an invoke with the
2340  * type system so that it can propagate it (speculation)
2341  *
2342  * @param n  receiver node
2343  *
2344  * @return   node with improved type
2345  */
2346 Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {
2347   if (!UseTypeSpeculation) {
2348     return n;
2349   }
2350   ciKlass* exact_kls = profile_has_unique_klass();
2351   ProfilePtrKind ptr_kind = ProfileMaybeNull;
2352   if ((java_bc() == Bytecodes::_checkcast ||
2353        java_bc() == Bytecodes::_instanceof ||
2354        java_bc() == Bytecodes::_aastore) &&
2355       method()->method_data()->is_mature()) {
2356     ciProfileData* data = method()->method_data()->bci_to_data(bci());
2357     if (data != NULL) {
2358       if (java_bc() == Bytecodes::_aastore) {
2359         ciKlass* array_type = NULL;
2360         ciKlass* element_type = NULL;
2361         ProfilePtrKind element_ptr = ProfileMaybeNull;
2362         bool flat_array = true;
2363         bool null_free_array = true;
2364         method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array);
2365         exact_kls = element_type;
2366         ptr_kind = element_ptr;
2367       } else {
2368         if (!data->as_BitData()->null_seen()) {
2369           ptr_kind = ProfileNeverNull;
2370         } else {
2371           assert(data->is_ReceiverTypeData(), "bad profile data type");
2372           ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
2373           uint i = 0;
2374           for (; i < call->row_limit(); i++) {
2375             ciKlass* receiver = call->receiver(i);
2376             if (receiver != NULL) {
2377               break;
2378             }
2379           }
2380           ptr_kind = (i == call->row_limit()) ? ProfileAlwaysNull : ProfileMaybeNull;
2381         }

2382       }
2383     }
2384   }
2385   return record_profile_for_speculation(n, exact_kls, ptr_kind);
2386 }
2387 
2388 /**
2389  * Record profiling data from argument profiling at an invoke with the
2390  * type system so that it can propagate it (speculation)
2391  *
2392  * @param dest_method  target method for the call
2393  * @param bc           what invoke bytecode is this?
2394  */
2395 void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {
2396   if (!UseTypeSpeculation) {
2397     return;
2398   }
2399   const TypeFunc* tf    = TypeFunc::make(dest_method);
2400   int             nargs = tf->domain_sig()->cnt() - TypeFunc::Parms;
2401   int skip = Bytecodes::has_receiver(bc) ? 1 : 0;
2402   for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {
2403     const Type *targ = tf->domain_sig()->field_at(j + TypeFunc::Parms);
2404     if (is_reference_type(targ->basic_type())) {
2405       ProfilePtrKind ptr_kind = ProfileMaybeNull;
2406       ciKlass* better_type = NULL;
2407       if (method()->argument_profiled_type(bci(), i, better_type, ptr_kind)) {
2408         record_profile_for_speculation(argument(j), better_type, ptr_kind);
2409       }
2410       i++;
2411     }
2412   }
2413 }
2414 
2415 /**
2416  * Record profiling data from parameter profiling at an invoke with
2417  * the type system so that it can propagate it (speculation)
2418  */
2419 void GraphKit::record_profiled_parameters_for_speculation() {
2420   if (!UseTypeSpeculation) {
2421     return;
2422   }
2423   for (int i = 0, j = 0; i < method()->arg_size() ; i++) {

2437  * the type system so that it can propagate it (speculation)
2438  */
2439 void GraphKit::record_profiled_return_for_speculation() {
2440   if (!UseTypeSpeculation) {
2441     return;
2442   }
2443   ProfilePtrKind ptr_kind = ProfileMaybeNull;
2444   ciKlass* better_type = NULL;
2445   if (method()->return_profiled_type(bci(), better_type, ptr_kind)) {
2446     // If profiling reports a single type for the return value,
2447     // feed it to the type system so it can propagate it as a
2448     // speculative type
2449     record_profile_for_speculation(stack(sp()-1), better_type, ptr_kind);
2450   }
2451 }
2452 
2453 void GraphKit::round_double_arguments(ciMethod* dest_method) {
2454   if (Matcher::strict_fp_requires_explicit_rounding) {
2455     // (Note:  TypeFunc::make has a cache that makes this fast.)
2456     const TypeFunc* tf    = TypeFunc::make(dest_method);
2457     int             nargs = tf->domain_sig()->cnt() - TypeFunc::Parms;
2458     for (int j = 0; j < nargs; j++) {
2459       const Type *targ = tf->domain_sig()->field_at(j + TypeFunc::Parms);
2460       if (targ->basic_type() == T_DOUBLE) {
2461         // If any parameters are doubles, they must be rounded before
2462         // the call, dprecision_rounding does gvn.transform
2463         Node *arg = argument(j);
2464         arg = dprecision_rounding(arg);
2465         set_argument(j, arg);
2466       }
2467     }
2468   }
2469 }
2470 
2471 // rounding for strict float precision conformance
2472 Node* GraphKit::precision_rounding(Node* n) {
2473   if (Matcher::strict_fp_requires_explicit_rounding) {
2474 #ifdef IA32
2475     if (UseSSE == 0) {
2476       return _gvn.transform(new RoundFloatNode(0, n));
2477     }
2478 #else
2479     Unimplemented();

2588                                   // The first NULL ends the list.
2589                                   Node* parm0, Node* parm1,
2590                                   Node* parm2, Node* parm3,
2591                                   Node* parm4, Node* parm5,
2592                                   Node* parm6, Node* parm7) {
2593   assert(call_addr != NULL, "must not call NULL targets");
2594 
2595   // Slow-path call
2596   bool is_leaf = !(flags & RC_NO_LEAF);
2597   bool has_io  = (!is_leaf && !(flags & RC_NO_IO));
2598   if (call_name == NULL) {
2599     assert(!is_leaf, "must supply name for leaf");
2600     call_name = OptoRuntime::stub_name(call_addr);
2601   }
2602   CallNode* call;
2603   if (!is_leaf) {
2604     call = new CallStaticJavaNode(call_type, call_addr, call_name, adr_type);
2605   } else if (flags & RC_NO_FP) {
2606     call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
2607   } else  if (flags & RC_VECTOR){
2608     uint num_bits = call_type->range_sig()->field_at(TypeFunc::Parms)->is_vect()->length_in_bytes() * BitsPerByte;
2609     call = new CallLeafVectorNode(call_type, call_addr, call_name, adr_type, num_bits);
2610   } else {
2611     call = new CallLeafNode(call_type, call_addr, call_name, adr_type);
2612   }
2613 
2614   // The following is similar to set_edges_for_java_call,
2615   // except that the memory effects of the call are restricted to AliasIdxRaw.
2616 
2617   // Slow path call has no side-effects, uses few values
2618   bool wide_in  = !(flags & RC_NARROW_MEM);
2619   bool wide_out = (C->get_alias_index(adr_type) == Compile::AliasIdxBot);
2620 
2621   Node* prev_mem = NULL;
2622   if (wide_in) {
2623     prev_mem = set_predefined_input_for_runtime_call(call);
2624   } else {
2625     assert(!wide_out, "narrow in => narrow out");
2626     Node* narrow_mem = memory(adr_type);
2627     prev_mem = set_predefined_input_for_runtime_call(call, narrow_mem);
2628   }

2668 
2669   if (has_io) {
2670     set_i_o(_gvn.transform(new ProjNode(call, TypeFunc::I_O)));
2671   }
2672   return call;
2673 
2674 }
2675 
2676 // i2b
2677 Node* GraphKit::sign_extend_byte(Node* in) {
2678   Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(24)));
2679   return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(24)));
2680 }
2681 
2682 // i2s
2683 Node* GraphKit::sign_extend_short(Node* in) {
2684   Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(16)));
2685   return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(16)));
2686 }
2687 
2688 
2689 //------------------------------merge_memory-----------------------------------
2690 // Merge memory from one path into the current memory state.
2691 void GraphKit::merge_memory(Node* new_mem, Node* region, int new_path) {
2692   for (MergeMemStream mms(merged_memory(), new_mem->as_MergeMem()); mms.next_non_empty2(); ) {
2693     Node* old_slice = mms.force_memory();
2694     Node* new_slice = mms.memory2();
2695     if (old_slice != new_slice) {
2696       PhiNode* phi;
2697       if (old_slice->is_Phi() && old_slice->as_Phi()->region() == region) {
2698         if (mms.is_empty()) {
2699           // clone base memory Phi's inputs for this memory slice
2700           assert(old_slice == mms.base_memory(), "sanity");
2701           phi = PhiNode::make(region, NULL, Type::MEMORY, mms.adr_type(C));
2702           _gvn.set_type(phi, Type::MEMORY);
2703           for (uint i = 1; i < phi->req(); i++) {
2704             phi->init_req(i, old_slice->in(i));
2705           }
2706         } else {
2707           phi = old_slice->as_Phi(); // Phi was generated already
2708         }

2922 
2923   // Now do a linear scan of the secondary super-klass array.  Again, no real
2924   // performance impact (too rare) but it's gotta be done.
2925   // Since the code is rarely used, there is no penalty for moving it
2926   // out of line, and it can only improve I-cache density.
2927   // The decision to inline or out-of-line this final check is platform
2928   // dependent, and is found in the AD file definition of PartialSubtypeCheck.
2929   Node* psc = gvn.transform(
2930     new PartialSubtypeCheckNode(*ctrl, subklass, superklass));
2931 
2932   IfNode *iff4 = gen_subtype_check_compare(*ctrl, psc, gvn.zerocon(T_OBJECT), BoolTest::ne, PROB_FAIR, gvn, T_ADDRESS);
2933   r_not_subtype->init_req(2, gvn.transform(new IfTrueNode (iff4)));
2934   r_ok_subtype ->init_req(3, gvn.transform(new IfFalseNode(iff4)));
2935 
2936   // Return false path; set default control to true path.
2937   *ctrl = gvn.transform(r_ok_subtype);
2938   return gvn.transform(r_not_subtype);
2939 }
2940 
2941 Node* GraphKit::gen_subtype_check(Node* obj_or_subklass, Node* superklass) {
2942   const Type* sub_t = _gvn.type(obj_or_subklass);
2943   if (sub_t->make_oopptr() != NULL && sub_t->make_oopptr()->is_inlinetypeptr()) {
2944     sub_t = TypeKlassPtr::make(sub_t->inline_klass());
2945     obj_or_subklass = makecon(sub_t);
2946   }
2947   bool expand_subtype_check = C->post_loop_opts_phase() ||   // macro node expansion is over
2948                               ExpandSubTypeCheckAtParseTime; // forced expansion
2949   if (expand_subtype_check) {
2950     MergeMemNode* mem = merged_memory();
2951     Node* ctrl = control();
2952     Node* subklass = obj_or_subklass;
2953     if (!sub_t->isa_klassptr()) {
2954       subklass = load_object_klass(obj_or_subklass);
2955     }

2956     Node* n = Phase::gen_subtype_check(subklass, superklass, &ctrl, mem, _gvn);
2957     set_control(ctrl);
2958     return n;
2959   }
2960 
2961   Node* check = _gvn.transform(new SubTypeCheckNode(C, obj_or_subklass, superklass));
2962   Node* bol = _gvn.transform(new BoolNode(check, BoolTest::eq));
2963   IfNode* iff = create_and_xform_if(control(), bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
2964   set_control(_gvn.transform(new IfTrueNode(iff)));
2965   return _gvn.transform(new IfFalseNode(iff));
2966 }
2967 
2968 // Profile-driven exact type check:
2969 Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,
2970                                     float prob, Node* *casted_receiver) {

2971   assert(!klass->is_interface(), "no exact type check on interfaces");
2972   Node* fail = top();
2973   const Type* rec_t = _gvn.type(receiver);
2974   if (rec_t->is_inlinetypeptr()) {
2975     if (klass->equals(rec_t->inline_klass())) {
2976       (*casted_receiver) = receiver; // Always passes
2977     } else {
2978       (*casted_receiver) = top();    // Always fails
2979       fail = control();
2980       set_control(top());
2981     }
2982     return fail;
2983   }
2984   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
2985   Node* recv_klass = load_object_klass(receiver);
2986   fail = type_check(recv_klass, tklass, prob);





2987 
2988   if (!stopped()) {
2989     const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
2990     const TypeOopPtr* recv_xtype = tklass->as_instance_type();
2991     assert(recv_xtype->klass_is_exact(), "");
2992 
2993     if (!receiver_type->higher_equal(recv_xtype)) { // ignore redundant casts
2994       // Subsume downstream occurrences of receiver with a cast to
2995       // recv_xtype, since now we know what the type will be.
2996       Node* cast = new CheckCastPPNode(control(), receiver, recv_xtype);
2997       Node* res = _gvn.transform(cast);
2998       if (recv_xtype->is_inlinetypeptr()) {
2999         assert(!gvn().type(res)->maybe_null(), "receiver should never be null");
3000         res = InlineTypeNode::make_from_oop(this, res, recv_xtype->inline_klass());
3001       }
3002       (*casted_receiver) = res;
3003       // (User must make the replace_in_map call.)
3004     }
3005   }
3006 
3007   return fail;
3008 }
3009 
3010 Node* GraphKit::type_check(Node* recv_klass, const TypeKlassPtr* tklass,
3011                            float prob) {
3012   Node* want_klass = makecon(tklass);
3013   Node* cmp = _gvn.transform(new CmpPNode(recv_klass, want_klass));
3014   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
3015   IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);
3016   set_control(_gvn.transform(new IfTrueNode (iff)));
3017   Node* fail = _gvn.transform(new IfFalseNode(iff));
3018   return fail;
3019 }
3020 
3021 //------------------------------subtype_check_receiver-------------------------
3022 Node* GraphKit::subtype_check_receiver(Node* receiver, ciKlass* klass,
3023                                        Node** casted_receiver) {
3024   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
3025   Node* want_klass = makecon(tklass);
3026 
3027   Node* slow_ctl = gen_subtype_check(receiver, want_klass);
3028 
3029   // Ignore interface type information until interface types are properly tracked.
3030   if (!stopped() && !klass->is_interface()) {
3031     const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
3032     const TypeOopPtr* recv_type = tklass->cast_to_exactness(false)->is_klassptr()->as_instance_type();
3033     if (receiver_type != NULL && !receiver_type->higher_equal(recv_type)) { // ignore redundant casts
3034       Node* cast = _gvn.transform(new CheckCastPPNode(control(), receiver, recv_type));
3035       if (recv_type->is_inlinetypeptr()) {
3036         cast = InlineTypeNode::make_from_oop(this, cast, recv_type->inline_klass());
3037       }
3038       (*casted_receiver) = cast;
3039     }
3040   }
3041 
3042   return slow_ctl;
3043 }
3044 
3045 //------------------------------seems_never_null-------------------------------
3046 // Use null_seen information if it is available from the profile.
3047 // If we see an unexpected null at a type check we record it and force a
3048 // recompile; the offending check will be recompiled to handle NULLs.
3049 // If we see several offending BCIs, then all checks in the
3050 // method will be recompiled.
3051 bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) {
3052   speculating = !_gvn.type(obj)->speculative_maybe_null();
3053   Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating);
3054   if (UncommonNullCast               // Cutout for this technique
3055       && obj != null()               // And not the -Xcomp stupid case?
3056       && !too_many_traps(reason)
3057       ) {
3058     if (speculating) {
3059       return true;
3060     }
3061     if (data == NULL)
3062       // Edge case:  no mature data.  Be optimistic here.
3063       return true;
3064     // If the profile has not seen a null, assume it won't happen.
3065     assert(java_bc() == Bytecodes::_checkcast ||
3066            java_bc() == Bytecodes::_instanceof ||
3067            java_bc() == Bytecodes::_aastore, "MDO must collect null_seen bit here");
3068     if (java_bc() == Bytecodes::_aastore) {
3069       return ((ciArrayLoadStoreData*)data->as_ArrayLoadStoreData())->element()->ptr_kind() == ProfileNeverNull;
3070     }
3071     return !data->as_BitData()->null_seen();
3072   }
3073   speculating = false;
3074   return false;
3075 }
3076 
3077 void GraphKit::guard_klass_being_initialized(Node* klass) {
3078   int init_state_off = in_bytes(InstanceKlass::init_state_offset());
3079   Node* adr = basic_plus_adr(top(), klass, init_state_off);
3080   Node* init_state = LoadNode::make(_gvn, NULL, immutable_memory(), adr,
3081                                     adr->bottom_type()->is_ptr(), TypeInt::BYTE,
3082                                     T_BYTE, MemNode::unordered);
3083   init_state = _gvn.transform(init_state);
3084 
3085   Node* being_initialized_state = makecon(TypeInt::make(InstanceKlass::being_initialized));
3086 
3087   Node* chk = _gvn.transform(new CmpINode(being_initialized_state, init_state));
3088   Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3089 
3090   { BuildCutout unless(this, tst, PROB_MAX);

3130 
3131 //------------------------maybe_cast_profiled_receiver-------------------------
3132 // If the profile has seen exactly one type, narrow to exactly that type.
3133 // Subsequent type checks will always fold up.
3134 Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,
3135                                              const TypeKlassPtr* require_klass,
3136                                              ciKlass* spec_klass,
3137                                              bool safe_for_replace) {
3138   if (!UseTypeProfile || !TypeProfileCasts) return NULL;
3139 
3140   Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != NULL);
3141 
3142   // Make sure we haven't already deoptimized from this tactic.
3143   if (too_many_traps_or_recompiles(reason))
3144     return NULL;
3145 
3146   // (No, this isn't a call, but it's enough like a virtual call
3147   // to use the same ciMethod accessor to get the profile info...)
3148   // If we have a speculative type use it instead of profiling (which
3149   // may not help us)
3150   ciKlass* exact_kls = spec_klass;
3151   if (exact_kls == NULL) {
3152     if (java_bc() == Bytecodes::_aastore) {
3153       ciKlass* array_type = NULL;
3154       ciKlass* element_type = NULL;
3155       ProfilePtrKind element_ptr = ProfileMaybeNull;
3156       bool flat_array = true;
3157       bool null_free_array = true;
3158       method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array);
3159       exact_kls = element_type;
3160     } else {
3161       exact_kls = profile_has_unique_klass();
3162     }
3163   }
3164   if (exact_kls != NULL) {// no cast failures here
3165     if (require_klass == NULL ||
3166         C->static_subtype_check(require_klass, TypeKlassPtr::make(exact_kls)) == Compile::SSC_always_true) {
3167       // If we narrow the type to match what the type profile sees or
3168       // the speculative type, we can then remove the rest of the
3169       // cast.
3170       // This is a win, even if the exact_kls is very specific,
3171       // because downstream operations, such as method calls,
3172       // will often benefit from the sharper type.
3173       Node* exact_obj = not_null_obj; // will get updated in place...
3174       Node* slow_ctl  = type_check_receiver(exact_obj, exact_kls, 1.0,
3175                                             &exact_obj);
3176       { PreserveJVMState pjvms(this);
3177         set_control(slow_ctl);
3178         uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
3179       }
3180       if (safe_for_replace) {
3181         replace_in_map(not_null_obj, exact_obj);
3182       }
3183       return exact_obj;

3273   // If not_null_obj is dead, only null-path is taken
3274   if (stopped()) {              // Doing instance-of on a NULL?
3275     set_control(null_ctl);
3276     return intcon(0);
3277   }
3278   region->init_req(_null_path, null_ctl);
3279   phi   ->init_req(_null_path, intcon(0)); // Set null path value
3280   if (null_ctl == top()) {
3281     // Do this eagerly, so that pattern matches like is_diamond_phi
3282     // will work even during parsing.
3283     assert(_null_path == PATH_LIMIT-1, "delete last");
3284     region->del_req(_null_path);
3285     phi   ->del_req(_null_path);
3286   }
3287 
3288   // Do we know the type check always succeed?
3289   bool known_statically = false;
3290   if (_gvn.type(superklass)->singleton()) {
3291     const TypeKlassPtr* superk = _gvn.type(superklass)->is_klassptr();
3292     const TypeKlassPtr* subk = _gvn.type(obj)->is_oopptr()->as_klass_type();
3293     if (subk != NULL && subk->is_loaded()) {
3294       int static_res = C->static_subtype_check(superk, subk);
3295       known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false);
3296     }
3297   }
3298 
3299   if (!known_statically) {
3300     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3301     // We may not have profiling here or it may not help us. If we
3302     // have a speculative type use it to perform an exact cast.
3303     ciKlass* spec_obj_type = obj_type->speculative_type();
3304     if (spec_obj_type != NULL || (ProfileDynamicTypes && data != NULL)) {
3305       Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, NULL, spec_obj_type, safe_for_replace);
3306       if (stopped()) {            // Profile disagrees with this path.
3307         set_control(null_ctl);    // Null is the only remaining possibility.
3308         return intcon(0);
3309       }
3310       if (cast_obj != NULL) {
3311         not_null_obj = cast_obj;
3312       }
3313     }

3329   record_for_igvn(region);
3330 
3331   // If we know the type check always succeeds then we don't use the
3332   // profiling data at this bytecode. Don't lose it, feed it to the
3333   // type system as a speculative type.
3334   if (safe_for_replace) {
3335     Node* casted_obj = record_profiled_receiver_for_speculation(obj);
3336     replace_in_map(obj, casted_obj);
3337   }
3338 
3339   return _gvn.transform(phi);
3340 }
3341 
3342 //-------------------------------gen_checkcast---------------------------------
3343 // Generate a checkcast idiom.  Used by both the checkcast bytecode and the
3344 // array store bytecode.  Stack must be as-if BEFORE doing the bytecode so the
3345 // uncommon-trap paths work.  Adjust stack after this call.
3346 // If failure_control is supplied and not null, it is filled in with
3347 // the control edge for the cast failure.  Otherwise, an appropriate
3348 // uncommon trap or exception is thrown.
3349 Node* GraphKit::gen_checkcast(Node *obj, Node* superklass, Node* *failure_control, bool null_free) {

3350   kill_dead_locals();           // Benefit all the uncommon traps
3351   const TypeKlassPtr* tk = _gvn.type(superklass)->is_klassptr();
3352   const TypeOopPtr* toop = tk->cast_to_exactness(false)->as_instance_type();
3353   bool safe_for_replace = (failure_control == NULL);
3354   assert(!null_free || toop->is_inlinetypeptr(), "must be an inline type pointer");
3355 
3356   // Fast cutout:  Check the case that the cast is vacuously true.
3357   // This detects the common cases where the test will short-circuit
3358   // away completely.  We do this before we perform the null check,
3359   // because if the test is going to turn into zero code, we don't
3360   // want a residual null check left around.  (Causes a slowdown,
3361   // for example, in some objArray manipulations, such as a[i]=a[j].)
3362   if (tk->singleton()) {
3363     const TypeKlassPtr* kptr = NULL;
3364     const Type* t = _gvn.type(obj);
3365     if (t->isa_oop_ptr()) {
3366       kptr = t->is_oopptr()->as_klass_type();
3367     } else if (obj->is_InlineType()) {
3368       ciInlineKlass* vk = t->inline_klass();
3369       kptr = TypeInstKlassPtr::make(TypePtr::NotNull, vk, Type::Offset(0), vk->flatten_array());
3370     }
3371     if (kptr != NULL) {
3372       switch (C->static_subtype_check(tk, kptr)) {
3373       case Compile::SSC_always_true:
3374         // If we know the type check always succeed then we don't use
3375         // the profiling data at this bytecode. Don't lose it, feed it
3376         // to the type system as a speculative type.
3377         obj = record_profiled_receiver_for_speculation(obj);
3378         if (null_free) {
3379           assert(safe_for_replace, "must be");
3380           obj = null_check(obj);
3381         }
3382         assert(stopped() || !toop->is_inlinetypeptr() || obj->is_InlineType(), "should have been scalarized");
3383         return obj;
3384       case Compile::SSC_always_false:
3385         if (null_free) {
3386           assert(safe_for_replace, "must be");
3387           obj = null_check(obj);
3388         }
3389         // It needs a null check because a null will *pass* the cast check.
3390         if (t->isa_oopptr() != NULL && !t->is_oopptr()->maybe_null()) {

3391           bool is_aastore = (java_bc() == Bytecodes::_aastore);
3392           Deoptimization::DeoptReason reason = is_aastore ?
3393             Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3394           builtin_throw(reason);
3395           return top();
3396         } else if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
3397           return null_assert(obj);
3398         }
3399         break; // Fall through to full check
3400       default:
3401         break;
3402       }
3403     }
3404   }
3405 
3406   ciProfileData* data = NULL;

3407   if (failure_control == NULL) {        // use MDO in regular case only
3408     assert(java_bc() == Bytecodes::_aastore ||
3409            java_bc() == Bytecodes::_checkcast,
3410            "interpreter profiles type checks only for these BCs");
3411     if (method()->method_data()->is_mature()) {
3412       data = method()->method_data()->bci_to_data(bci());
3413     }
3414   }
3415 
3416   // Make the merge point
3417   enum { _obj_path = 1, _null_path, PATH_LIMIT };
3418   RegionNode* region = new RegionNode(PATH_LIMIT);
3419   Node*       phi    = new PhiNode(region, toop);
3420   _gvn.set_type(region, Type::CONTROL);
3421   _gvn.set_type(phi, toop);
3422 
3423   C->set_has_split_ifs(true); // Has chance for split-if optimization
3424 
3425   // Use null-cast information if it is available
3426   bool speculative_not_null = false;
3427   bool never_see_null = ((failure_control == NULL)  // regular case only
3428                          && seems_never_null(obj, data, speculative_not_null));
3429 
3430   if (obj->is_InlineType()) {
3431     // Re-execute if buffering during triggers deoptimization
3432     PreserveReexecuteState preexecs(this);
3433     jvms()->set_should_reexecute(true);
3434     obj = obj->as_InlineType()->buffer(this, safe_for_replace);
3435   }
3436 
3437   // Null check; get casted pointer; set region slot 3
3438   Node* null_ctl = top();
3439   Node* not_null_obj = NULL;
3440   if (null_free) {
3441     assert(safe_for_replace, "must be");
3442     not_null_obj = null_check(obj);
3443   } else {
3444     not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3445   }
3446 
3447   // If not_null_obj is dead, only null-path is taken
3448   if (stopped()) {              // Doing instance-of on a NULL?
3449     set_control(null_ctl);
3450     if (toop->is_inlinetypeptr()) {
3451       return InlineTypeNode::make_null(_gvn, toop->inline_klass());
3452     }
3453     return null();
3454   }
3455   region->init_req(_null_path, null_ctl);
3456   phi   ->init_req(_null_path, null());  // Set null path value
3457   if (null_ctl == top()) {
3458     // Do this eagerly, so that pattern matches like is_diamond_phi
3459     // will work even during parsing.
3460     assert(_null_path == PATH_LIMIT-1, "delete last");
3461     region->del_req(_null_path);
3462     phi   ->del_req(_null_path);
3463   }
3464 
3465   Node* cast_obj = NULL;
3466   if (tk->klass_is_exact()) {
3467     // The following optimization tries to statically cast the speculative type of the object
3468     // (for example obtained during profiling) to the type of the superklass and then do a
3469     // dynamic check that the type of the object is what we expect. To work correctly
3470     // for checkcast and aastore the type of superklass should be exact.
3471     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3472     // We may not have profiling here or it may not help us. If we have
3473     // a speculative type use it to perform an exact cast.
3474     ciKlass* spec_obj_type = obj_type->speculative_type();
3475     if (spec_obj_type != NULL || data != NULL) {
3476       cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk, spec_obj_type, safe_for_replace);
3477       if (cast_obj != NULL) {
3478         if (failure_control != NULL) // failure is now impossible
3479           (*failure_control) = top();
3480         // adjust the type of the phi to the exact klass:
3481         phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
3482       }
3483     }
3484   }
3485 
3486   if (cast_obj == NULL) {
3487     // Generate the subtype check
3488     Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass);
3489 
3490     // Plug in success path into the merge
3491     cast_obj = _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop));
3492     // Failure path ends in uncommon trap (or may be dead - failure impossible)
3493     if (failure_control == NULL) {
3494       if (not_subtype_ctrl != top()) { // If failure is possible
3495         PreserveJVMState pjvms(this);
3496         set_control(not_subtype_ctrl);
3497         Node* obj_klass = NULL;
3498         if (not_null_obj->is_InlineType()) {
3499           obj_klass = makecon(TypeKlassPtr::make(_gvn.type(not_null_obj)->inline_klass()));
3500         } else {
3501           obj_klass = load_object_klass(not_null_obj);
3502         }
3503         bool is_aastore = (java_bc() == Bytecodes::_aastore);
3504         Deoptimization::DeoptReason reason = is_aastore ?
3505           Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3506         builtin_throw(reason);
3507       }
3508     } else {
3509       (*failure_control) = not_subtype_ctrl;
3510     }
3511   }
3512 
3513   region->init_req(_obj_path, control());
3514   phi   ->init_req(_obj_path, cast_obj);
3515 
3516   // A merge of NULL or Casted-NotNull obj
3517   Node* res = _gvn.transform(phi);
3518 
3519   // Note I do NOT always 'replace_in_map(obj,result)' here.
3520   //  if( tk->klass()->can_be_primary_super()  )
3521     // This means that if I successfully store an Object into an array-of-String
3522     // I 'forget' that the Object is really now known to be a String.  I have to
3523     // do this because we don't have true union types for interfaces - if I store
3524     // a Baz into an array-of-Interface and then tell the optimizer it's an
3525     // Interface, I forget that it's also a Baz and cannot do Baz-like field
3526     // references to it.  FIX THIS WHEN UNION TYPES APPEAR!
3527   //  replace_in_map( obj, res );
3528 
3529   // Return final merged results
3530   set_control( _gvn.transform(region) );
3531   record_for_igvn(region);
3532 
3533   bool not_inline = !toop->can_be_inline_type();
3534   bool not_flattened = !UseFlatArray || not_inline || (toop->is_inlinetypeptr() && !toop->inline_klass()->flatten_array());
3535   if (EnableValhalla && not_flattened) {
3536     // Check if obj has been loaded from an array
3537     obj = obj->isa_DecodeN() ? obj->in(1) : obj;
3538     Node* array = NULL;
3539     if (obj->isa_Load()) {
3540       Node* address = obj->in(MemNode::Address);
3541       if (address->isa_AddP()) {
3542         array = address->as_AddP()->in(AddPNode::Base);
3543       }
3544     } else if (obj->is_Phi()) {
3545       Node* region = obj->in(0);
3546       // TODO make this more robust (see JDK-8231346)
3547       if (region->req() == 3 && region->in(2) != NULL && region->in(2)->in(0) != NULL) {
3548         IfNode* iff = region->in(2)->in(0)->isa_If();
3549         if (iff != NULL) {
3550           iff->is_flat_array_check(&_gvn, &array);
3551         }
3552       }
3553     }
3554     if (array != NULL) {
3555       const TypeAryPtr* ary_t = _gvn.type(array)->isa_aryptr();
3556       if (ary_t != NULL) {
3557         if (!ary_t->is_not_null_free() && not_inline) {
3558           // Casting array element to a non-inline-type, mark array as not null-free.
3559           Node* cast = _gvn.transform(new CheckCastPPNode(control(), array, ary_t->cast_to_not_null_free()));
3560           replace_in_map(array, cast);
3561         } else if (!ary_t->is_not_flat()) {
3562           // Casting array element to a non-flattened type, mark array as not flat.
3563           Node* cast = _gvn.transform(new CheckCastPPNode(control(), array, ary_t->cast_to_not_flat()));
3564           replace_in_map(array, cast);
3565         }
3566       }
3567     }
3568   }
3569 
3570   if (!stopped() && !res->is_InlineType()) {
3571     res = record_profiled_receiver_for_speculation(res);
3572     if (toop->is_inlinetypeptr()) {
3573       Node* vt = InlineTypeNode::make_from_oop(this, res, toop->inline_klass(), !gvn().type(res)->maybe_null());
3574       res = vt;
3575       if (safe_for_replace) {
3576         replace_in_map(obj, vt);
3577         replace_in_map(not_null_obj, vt);
3578         replace_in_map(res, vt);
3579       }
3580     }
3581   }
3582   return res;
3583 }
3584 
3585 Node* GraphKit::inline_type_test(Node* obj, bool is_inline) {
3586   Node* mark_adr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
3587   Node* mark = make_load(NULL, mark_adr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
3588   Node* mask = MakeConX(markWord::inline_type_pattern);
3589   Node* masked = _gvn.transform(new AndXNode(mark, mask));
3590   Node* cmp = _gvn.transform(new CmpXNode(masked, mask));
3591   return _gvn.transform(new BoolNode(cmp, is_inline ? BoolTest::eq : BoolTest::ne));
3592 }
3593 
3594 Node* GraphKit::is_val_mirror(Node* mirror) {
3595   Node* p = basic_plus_adr(mirror, java_lang_Class::secondary_mirror_offset());
3596   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);
3597   Node* cmp = _gvn.transform(new CmpPNode(mirror, secondary_mirror));
3598   return _gvn.transform(new BoolNode(cmp, BoolTest::eq));
3599 }
3600 
3601 Node* GraphKit::array_lh_test(Node* klass, jint mask, jint val, bool eq) {
3602   Node* lh_adr = basic_plus_adr(klass, in_bytes(Klass::layout_helper_offset()));
3603   // Make sure to use immutable memory here to enable hoisting the check out of loops
3604   Node* lh_val = _gvn.transform(LoadNode::make(_gvn, NULL, immutable_memory(), lh_adr, lh_adr->bottom_type()->is_ptr(), TypeInt::INT, T_INT, MemNode::unordered));
3605   Node* masked = _gvn.transform(new AndINode(lh_val, intcon(mask)));
3606   Node* cmp = _gvn.transform(new CmpINode(masked, intcon(val)));
3607   return _gvn.transform(new BoolNode(cmp, eq ? BoolTest::eq : BoolTest::ne));
3608 }
3609 
3610 Node* GraphKit::flat_array_test(Node* array_or_klass, bool flat) {
3611   // We can't use immutable memory here because the mark word is mutable.
3612   // PhaseIdealLoop::move_flat_array_check_out_of_loop will make sure the
3613   // check is moved out of loops (mainly to enable loop unswitching).
3614   Node* mem = UseArrayMarkWordCheck ? memory(Compile::AliasIdxRaw) : immutable_memory();
3615   Node* cmp = _gvn.transform(new FlatArrayCheckNode(C, mem, array_or_klass));
3616   record_for_igvn(cmp); // Give it a chance to be optimized out by IGVN
3617   return _gvn.transform(new BoolNode(cmp, flat ? BoolTest::eq : BoolTest::ne));
3618 }
3619 
3620 Node* GraphKit::null_free_array_test(Node* klass, bool null_free) {
3621   return array_lh_test(klass, Klass::_lh_null_free_array_bit_inplace, 0, !null_free);
3622 }
3623 
3624 // Deoptimize if 'ary' is a null-free inline type array and 'val' is null
3625 Node* GraphKit::inline_array_null_guard(Node* ary, Node* val, int nargs, bool safe_for_replace) {
3626   RegionNode* region = new RegionNode(3);
3627   Node* null_ctl = top();
3628   null_check_oop(val, &null_ctl);
3629   if (null_ctl != top()) {
3630     PreserveJVMState pjvms(this);
3631     set_control(null_ctl);
3632     {
3633       // Deoptimize if null-free array
3634       BuildCutout unless(this, null_free_array_test(load_object_klass(ary), /* null_free = */ false), PROB_MAX);
3635       inc_sp(nargs);
3636       uncommon_trap(Deoptimization::Reason_null_check,
3637                     Deoptimization::Action_none);
3638     }
3639     region->init_req(1, control());
3640   }
3641   region->init_req(2, control());
3642   set_control(_gvn.transform(region));
3643   record_for_igvn(region);
3644   if (_gvn.type(val) == TypePtr::NULL_PTR) {
3645     // Since we were just successfully storing null, the array can't be null free.
3646     const TypeAryPtr* ary_t = _gvn.type(ary)->is_aryptr();
3647     ary_t = ary_t->cast_to_not_null_free();
3648     Node* cast = _gvn.transform(new CheckCastPPNode(control(), ary, ary_t));
3649     if (safe_for_replace) {
3650       replace_in_map(ary, cast);
3651     }
3652     ary = cast;
3653   }
3654   return ary;
3655 }
3656 
3657 //------------------------------next_monitor-----------------------------------
3658 // What number should be given to the next monitor?
3659 int GraphKit::next_monitor() {
3660   int current = jvms()->monitor_depth()* C->sync_stack_slots();
3661   int next = current + C->sync_stack_slots();
3662   // Keep the toplevel high water mark current:
3663   if (C->fixed_slots() < next)  C->set_fixed_slots(next);
3664   return current;
3665 }
3666 
3667 //------------------------------insert_mem_bar---------------------------------
3668 // Memory barrier to avoid floating things around
3669 // The membar serves as a pinch point between both control and all memory slices.
3670 Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {
3671   MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
3672   mb->init_req(TypeFunc::Control, control());
3673   mb->init_req(TypeFunc::Memory,  reset_memory());
3674   Node* membar = _gvn.transform(mb);

3702   }
3703   Node* membar = _gvn.transform(mb);
3704   set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3705   if (alias_idx == Compile::AliasIdxBot) {
3706     merged_memory()->set_base_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)));
3707   } else {
3708     set_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)),alias_idx);
3709   }
3710   return membar;
3711 }
3712 
3713 //------------------------------shared_lock------------------------------------
3714 // Emit locking code.
3715 FastLockNode* GraphKit::shared_lock(Node* obj) {
3716   // bci is either a monitorenter bc or InvocationEntryBci
3717   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3718   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3719 
3720   if( !GenerateSynchronizationCode )
3721     return NULL;                // Not locking things?
3722 
3723   if (stopped())                // Dead monitor?
3724     return NULL;
3725 
3726   assert(dead_locals_are_killed(), "should kill locals before sync. point");
3727 
3728   // Box the stack location
3729   Node* box = _gvn.transform(new BoxLockNode(next_monitor()));
3730   Node* mem = reset_memory();
3731 
3732   FastLockNode * flock = _gvn.transform(new FastLockNode(0, obj, box) )->as_FastLock();
3733 
3734   // Create the rtm counters for this fast lock if needed.
3735   flock->create_rtm_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3736 
3737   // Add monitor to debug info for the slow path.  If we block inside the
3738   // slow path and de-opt, we need the monitor hanging around
3739   map()->push_monitor( flock );
3740 
3741   const TypeFunc *tf = LockNode::lock_type();
3742   LockNode *lock = new LockNode(C, tf);

3771   }
3772 #endif
3773 
3774   return flock;
3775 }
3776 
3777 
3778 //------------------------------shared_unlock----------------------------------
3779 // Emit unlocking code.
3780 void GraphKit::shared_unlock(Node* box, Node* obj) {
3781   // bci is either a monitorenter bc or InvocationEntryBci
3782   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3783   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3784 
3785   if( !GenerateSynchronizationCode )
3786     return;
3787   if (stopped()) {               // Dead monitor?
3788     map()->pop_monitor();        // Kill monitor from debug info
3789     return;
3790   }
3791   assert(!obj->is_InlineType(), "should not unlock on inline type");
3792 
3793   // Memory barrier to avoid floating things down past the locked region
3794   insert_mem_bar(Op_MemBarReleaseLock);
3795 
3796   const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();
3797   UnlockNode *unlock = new UnlockNode(C, tf);
3798 #ifdef ASSERT
3799   unlock->set_dbg_jvms(sync_jvms());
3800 #endif
3801   uint raw_idx = Compile::AliasIdxRaw;
3802   unlock->init_req( TypeFunc::Control, control() );
3803   unlock->init_req( TypeFunc::Memory , memory(raw_idx) );
3804   unlock->init_req( TypeFunc::I_O    , top() )     ;   // does no i/o
3805   unlock->init_req( TypeFunc::FramePtr, frameptr() );
3806   unlock->init_req( TypeFunc::ReturnAdr, top() );
3807 
3808   unlock->init_req(TypeFunc::Parms + 0, obj);
3809   unlock->init_req(TypeFunc::Parms + 1, box);
3810   unlock = _gvn.transform(unlock)->as_Unlock();
3811 
3812   Node* mem = reset_memory();
3813 
3814   // unlock has no side-effects, sets few values
3815   set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);
3816 
3817   // Kill monitor from debug info
3818   map()->pop_monitor( );
3819 }
3820 
3821 //-------------------------------get_layout_helper-----------------------------
3822 // If the given klass is a constant or known to be an array,
3823 // fetch the constant layout helper value into constant_value
3824 // and return (Node*)NULL.  Otherwise, load the non-constant
3825 // layout helper value, and return the node which represents it.
3826 // This two-faced routine is useful because allocation sites
3827 // almost always feature constant types.
3828 Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {
3829   const TypeKlassPtr* inst_klass = _gvn.type(klass_node)->isa_klassptr();
3830   if (!StressReflectiveCode && inst_klass != NULL) {
3831     bool xklass = inst_klass->klass_is_exact();
3832     bool can_be_flattened = false;
3833     const TypeAryPtr* ary_type = inst_klass->as_instance_type()->isa_aryptr();
3834     if (UseFlatArray && !xklass && ary_type != NULL && !ary_type->is_null_free()) {
3835       // The runtime type of [LMyValue might be [QMyValue due to [QMyValue <: [LMyValue. Don't constant fold.
3836       const TypeOopPtr* elem = ary_type->elem()->make_oopptr();
3837       can_be_flattened = ary_type->can_be_inline_array() && (!elem->is_inlinetypeptr() || elem->inline_klass()->flatten_array());
3838     }
3839     if (!can_be_flattened && (xklass || inst_klass->isa_aryklassptr())) {
3840       jint lhelper;
3841       if (inst_klass->is_flat()) {
3842         lhelper = ary_type->flat_layout_helper();
3843       } else if (inst_klass->isa_aryklassptr()) {
3844         BasicType elem = ary_type->elem()->array_element_basic_type();
3845         if (is_reference_type(elem, true)) {
3846           elem = T_OBJECT;
3847         }
3848         lhelper = Klass::array_layout_helper(elem);
3849       } else {
3850         lhelper = inst_klass->is_instklassptr()->exact_klass()->layout_helper();
3851       }
3852       if (lhelper != Klass::_lh_neutral_value) {
3853         constant_value = lhelper;
3854         return (Node*) NULL;
3855       }
3856     }
3857   }
3858   constant_value = Klass::_lh_neutral_value;  // put in a known value
3859   Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset()));
3860   return make_load(NULL, lhp, TypeInt::INT, T_INT, MemNode::unordered);
3861 }
3862 
3863 // We just put in an allocate/initialize with a big raw-memory effect.
3864 // Hook selected additional alias categories on the initialization.
3865 static void hook_memory_on_init(GraphKit& kit, int alias_idx,
3866                                 MergeMemNode* init_in_merge,
3867                                 Node* init_out_raw) {
3868   DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());
3869   assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");
3870 
3871   Node* prevmem = kit.memory(alias_idx);
3872   init_in_merge->set_memory_at(alias_idx, prevmem);
3873   if (init_out_raw != NULL) {
3874     kit.set_memory(init_out_raw, alias_idx);
3875   }
3876 }
3877 
3878 //---------------------------set_output_for_allocation-------------------------
3879 Node* GraphKit::set_output_for_allocation(AllocateNode* alloc,
3880                                           const TypeOopPtr* oop_type,
3881                                           bool deoptimize_on_exception) {
3882   int rawidx = Compile::AliasIdxRaw;
3883   alloc->set_req( TypeFunc::FramePtr, frameptr() );
3884   add_safepoint_edges(alloc);
3885   Node* allocx = _gvn.transform(alloc);
3886   set_control( _gvn.transform(new ProjNode(allocx, TypeFunc::Control) ) );
3887   // create memory projection for i_o
3888   set_memory ( _gvn.transform( new ProjNode(allocx, TypeFunc::Memory, true) ), rawidx );
3889   make_slow_call_ex(allocx, env()->Throwable_klass(), true, deoptimize_on_exception);
3890 
3891   // create a memory projection as for the normal control path
3892   Node* malloc = _gvn.transform(new ProjNode(allocx, TypeFunc::Memory));
3893   set_memory(malloc, rawidx);
3894 
3895   // a normal slow-call doesn't change i_o, but an allocation does
3896   // we create a separate i_o projection for the normal control path
3897   set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) );
3898   Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) );
3899 
3900   // put in an initialization barrier
3901   InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,
3902                                                  rawoop)->as_Initialize();
3903   assert(alloc->initialization() == init,  "2-way macro link must work");
3904   assert(init ->allocation()     == alloc, "2-way macro link must work");
3905   {
3906     // Extract memory strands which may participate in the new object's
3907     // initialization, and source them from the new InitializeNode.
3908     // This will allow us to observe initializations when they occur,
3909     // and link them properly (as a group) to the InitializeNode.
3910     assert(init->in(InitializeNode::Memory) == malloc, "");
3911     MergeMemNode* minit_in = MergeMemNode::make(malloc);
3912     init->set_req(InitializeNode::Memory, minit_in);
3913     record_for_igvn(minit_in); // fold it up later, if possible
3914     _gvn.set_type(minit_in, Type::MEMORY);
3915     Node* minit_out = memory(rawidx);
3916     assert(minit_out->is_Proj() && minit_out->in(0) == init, "");
3917     // Add an edge in the MergeMem for the header fields so an access
3918     // to one of those has correct memory state
3919     set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::mark_offset_in_bytes())));
3920     set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes())));
3921     if (oop_type->isa_aryptr()) {
3922       const TypeAryPtr* arytype = oop_type->is_aryptr();
3923       if (arytype->is_flat()) {
3924         // Initially all flattened array accesses share a single slice
3925         // but that changes after parsing. Prepare the memory graph so
3926         // it can optimize flattened array accesses properly once they
3927         // don't share a single slice.
3928         assert(C->flattened_accesses_share_alias(), "should be set at parse time");
3929         C->set_flattened_accesses_share_alias(false);
3930         ciInlineKlass* vk = arytype->elem()->inline_klass();
3931         for (int i = 0, len = vk->nof_nonstatic_fields(); i < len; i++) {
3932           ciField* field = vk->nonstatic_field_at(i);
3933           if (field->offset() >= TrackedInitializationLimit * HeapWordSize)
3934             continue;  // do not bother to track really large numbers of fields
3935           int off_in_vt = field->offset() - vk->first_field_offset();
3936           const TypePtr* adr_type = arytype->with_field_offset(off_in_vt)->add_offset(Type::OffsetBot);
3937           int fieldidx = C->get_alias_index(adr_type, true);
3938           // Pass NULL for init_out. Having per flat array element field memory edges as uses of the Initialize node
3939           // can result in per flat array field Phis to be created which confuses the logic of
3940           // Compile::adjust_flattened_array_access_aliases().
3941           hook_memory_on_init(*this, fieldidx, minit_in, NULL);
3942         }
3943         C->set_flattened_accesses_share_alias(true);
3944         hook_memory_on_init(*this, C->get_alias_index(TypeAryPtr::INLINES), minit_in, minit_out);
3945       } else {
3946         const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);
3947         int            elemidx  = C->get_alias_index(telemref);
3948         hook_memory_on_init(*this, elemidx, minit_in, minit_out);
3949       }
3950     } else if (oop_type->isa_instptr()) {
3951       set_memory(minit_out, C->get_alias_index(oop_type)); // mark word
3952       ciInstanceKlass* ik = oop_type->is_instptr()->instance_klass();
3953       for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {
3954         ciField* field = ik->nonstatic_field_at(i);
3955         if (field->offset() >= TrackedInitializationLimit * HeapWordSize)
3956           continue;  // do not bother to track really large numbers of fields
3957         // Find (or create) the alias category for this field:
3958         int fieldidx = C->alias_type(field)->index();
3959         hook_memory_on_init(*this, fieldidx, minit_in, minit_out);
3960       }
3961     }
3962   }
3963 
3964   // Cast raw oop to the real thing...
3965   Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type);
3966   javaoop = _gvn.transform(javaoop);
3967   C->set_recent_alloc(control(), javaoop);
3968   assert(just_allocated_object(control()) == javaoop, "just allocated");
3969 
3970 #ifdef ASSERT
3971   { // Verify that the AllocateNode::Ideal_allocation recognizers work:

3982       assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");
3983     }
3984   }
3985 #endif //ASSERT
3986 
3987   return javaoop;
3988 }
3989 
3990 //---------------------------new_instance--------------------------------------
3991 // This routine takes a klass_node which may be constant (for a static type)
3992 // or may be non-constant (for reflective code).  It will work equally well
3993 // for either, and the graph will fold nicely if the optimizer later reduces
3994 // the type to a constant.
3995 // The optional arguments are for specialized use by intrinsics:
3996 //  - If 'extra_slow_test' if not null is an extra condition for the slow-path.
3997 //  - If 'return_size_val', report the total object size to the caller.
3998 //  - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
3999 Node* GraphKit::new_instance(Node* klass_node,
4000                              Node* extra_slow_test,
4001                              Node* *return_size_val,
4002                              bool deoptimize_on_exception,
4003                              InlineTypeNode* inline_type_node) {
4004   // Compute size in doublewords
4005   // The size is always an integral number of doublewords, represented
4006   // as a positive bytewise size stored in the klass's layout_helper.
4007   // The layout_helper also encodes (in a low bit) the need for a slow path.
4008   jint  layout_con = Klass::_lh_neutral_value;
4009   Node* layout_val = get_layout_helper(klass_node, layout_con);
4010   bool  layout_is_con = (layout_val == NULL);
4011 
4012   if (extra_slow_test == NULL)  extra_slow_test = intcon(0);
4013   // Generate the initial go-slow test.  It's either ALWAYS (return a
4014   // Node for 1) or NEVER (return a NULL) or perhaps (in the reflective
4015   // case) a computed value derived from the layout_helper.
4016   Node* initial_slow_test = NULL;
4017   if (layout_is_con) {
4018     assert(!StressReflectiveCode, "stress mode does not use these paths");
4019     bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);
4020     initial_slow_test = must_go_slow ? intcon(1) : extra_slow_test;
4021   } else {   // reflective case
4022     // This reflective path is used by Unsafe.allocateInstance.
4023     // (It may be stress-tested by specifying StressReflectiveCode.)
4024     // Basically, we want to get into the VM is there's an illegal argument.
4025     Node* bit = intcon(Klass::_lh_instance_slow_path_bit);
4026     initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) );
4027     if (extra_slow_test != intcon(0)) {
4028       initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) );
4029     }
4030     // (Macro-expander will further convert this to a Bool, if necessary.)

4041 
4042     // Clear the low bits to extract layout_helper_size_in_bytes:
4043     assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
4044     Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));
4045     size = _gvn.transform( new AndXNode(size, mask) );
4046   }
4047   if (return_size_val != NULL) {
4048     (*return_size_val) = size;
4049   }
4050 
4051   // This is a precise notnull oop of the klass.
4052   // (Actually, it need not be precise if this is a reflective allocation.)
4053   // It's what we cast the result to.
4054   const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();
4055   if (!tklass)  tklass = TypeInstKlassPtr::OBJECT;
4056   const TypeOopPtr* oop_type = tklass->as_instance_type();
4057 
4058   // Now generate allocation code
4059 
4060   // The entire memory state is needed for slow path of the allocation
4061   // since GC and deoptimization can happen.
4062   Node *mem = reset_memory();
4063   set_all_memory(mem); // Create new memory state
4064 
4065   AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP),
4066                                          control(), mem, i_o(),
4067                                          size, klass_node,
4068                                          initial_slow_test, inline_type_node);
4069 
4070   return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);
4071 }
4072 
4073 //-------------------------------new_array-------------------------------------
4074 // helper for newarray and anewarray
4075 // The 'length' parameter is (obviously) the length of the array.
4076 // See comments on new_instance for the meaning of the other arguments.
4077 Node* GraphKit::new_array(Node* klass_node,     // array klass (maybe variable)
4078                           Node* length,         // number of array elements
4079                           int   nargs,          // number of arguments to push back for uncommon trap
4080                           Node* *return_size_val,
4081                           bool deoptimize_on_exception) {
4082   jint  layout_con = Klass::_lh_neutral_value;
4083   Node* layout_val = get_layout_helper(klass_node, layout_con);
4084   bool  layout_is_con = (layout_val == NULL);
4085 
4086   if (!layout_is_con && !StressReflectiveCode &&
4087       !too_many_traps(Deoptimization::Reason_class_check)) {
4088     // This is a reflective array creation site.
4089     // Optimistically assume that it is a subtype of Object[],
4090     // so that we can fold up all the address arithmetic.
4091     layout_con = Klass::array_layout_helper(T_OBJECT);
4092     Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) );
4093     Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) );
4094     { BuildCutout unless(this, bol_lh, PROB_MAX);
4095       inc_sp(nargs);
4096       uncommon_trap(Deoptimization::Reason_class_check,
4097                     Deoptimization::Action_maybe_recompile);
4098     }
4099     layout_val = NULL;
4100     layout_is_con = true;
4101   }
4102 
4103   // Generate the initial go-slow test.  Make sure we do not overflow
4104   // if length is huge (near 2Gig) or negative!  We do not need
4105   // exact double-words here, just a close approximation of needed
4106   // double-words.  We can't add any offset or rounding bits, lest we
4107   // take a size -1 of bytes and make it positive.  Use an unsigned
4108   // compare, so negative sizes look hugely positive.
4109   int fast_size_limit = FastAllocateSizeLimit;
4110   if (layout_is_con) {
4111     assert(!StressReflectiveCode, "stress mode does not use these paths");
4112     // Increase the size limit if we have exact knowledge of array type.
4113     int log2_esize = Klass::layout_helper_log2_element_size(layout_con);
4114     fast_size_limit <<= MAX2(LogBytesPerLong - log2_esize, 0);
4115   }
4116 
4117   Node* initial_slow_cmp  = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) );
4118   Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) );
4119 
4120   // --- Size Computation ---
4121   // array_size = round_to_heap(array_header + (length << elem_shift));
4122   // where round_to_heap(x) == align_to(x, MinObjAlignmentInBytes)
4123   // and align_to(x, y) == ((x + y-1) & ~(y-1))
4124   // The rounding mask is strength-reduced, if possible.
4125   int round_mask = MinObjAlignmentInBytes - 1;
4126   Node* header_size = NULL;
4127   int   header_size_min  = arrayOopDesc::base_offset_in_bytes(T_BYTE);
4128   // (T_BYTE has the weakest alignment and size restrictions...)
4129   if (layout_is_con) {
4130     int       hsize  = Klass::layout_helper_header_size(layout_con);
4131     int       eshift = Klass::layout_helper_log2_element_size(layout_con);
4132     bool is_flat_array = Klass::layout_helper_is_flatArray(layout_con);
4133     if ((round_mask & ~right_n_bits(eshift)) == 0)
4134       round_mask = 0;  // strength-reduce it if it goes away completely
4135     assert(is_flat_array || (hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
4136     assert(header_size_min <= hsize, "generic minimum is smallest");
4137     header_size_min = hsize;
4138     header_size = intcon(hsize + round_mask);
4139   } else {
4140     Node* hss   = intcon(Klass::_lh_header_size_shift);
4141     Node* hsm   = intcon(Klass::_lh_header_size_mask);
4142     Node* hsize = _gvn.transform( new URShiftINode(layout_val, hss) );
4143     hsize       = _gvn.transform( new AndINode(hsize, hsm) );
4144     Node* mask  = intcon(round_mask);
4145     header_size = _gvn.transform( new AddINode(hsize, mask) );
4146   }
4147 
4148   Node* elem_shift = NULL;
4149   if (layout_is_con) {
4150     int eshift = Klass::layout_helper_log2_element_size(layout_con);
4151     if (eshift != 0)
4152       elem_shift = intcon(eshift);
4153   } else {
4154     // There is no need to mask or shift this value.
4155     // The semantics of LShiftINode include an implicit mask to 0x1F.

4199   // places, one where the length is sharply limited, and the other
4200   // after a successful allocation.
4201   Node* abody = lengthx;
4202   if (elem_shift != NULL)
4203     abody     = _gvn.transform( new LShiftXNode(lengthx, elem_shift) );
4204   Node* size  = _gvn.transform( new AddXNode(headerx, abody) );
4205   if (round_mask != 0) {
4206     Node* mask = MakeConX(~round_mask);
4207     size       = _gvn.transform( new AndXNode(size, mask) );
4208   }
4209   // else if round_mask == 0, the size computation is self-rounding
4210 
4211   if (return_size_val != NULL) {
4212     // This is the size
4213     (*return_size_val) = size;
4214   }
4215 
4216   // Now generate allocation code
4217 
4218   // The entire memory state is needed for slow path of the allocation
4219   // since GC and deoptimization can happen.
4220   Node *mem = reset_memory();
4221   set_all_memory(mem); // Create new memory state
4222 
4223   if (initial_slow_test->is_Bool()) {
4224     // Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.
4225     initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);
4226   }
4227 
4228   const TypeKlassPtr* ary_klass = _gvn.type(klass_node)->isa_klassptr();
4229   const TypeOopPtr* ary_type = ary_klass->as_instance_type();
4230   const TypeAryPtr* ary_ptr = ary_type->isa_aryptr();
4231 
4232   // Inline type array variants:
4233   // - null-ok:              MyValue.ref[] (ciObjArrayKlass "[LMyValue")
4234   // - null-free:            MyValue.val[] (ciObjArrayKlass "[QMyValue")
4235   // - null-free, flattened: MyValue.val[] (ciFlatArrayKlass "[QMyValue")
4236   // Check if array is a null-free, non-flattened inline type array
4237   // that needs to be initialized with the default inline type.
4238   Node* default_value = NULL;
4239   Node* raw_default_value = NULL;
4240   if (ary_ptr != NULL && ary_ptr->klass_is_exact()) {
4241     // Array type is known
4242     if (ary_ptr->is_null_free() && !ary_ptr->is_flat()) {
4243       ciInlineKlass* vk = ary_ptr->elem()->make_oopptr()->inline_klass();
4244       default_value = InlineTypeNode::default_oop(gvn(), vk);
4245     }
4246   } else if (ary_type->can_be_inline_array()) {
4247     // Array type is not known, add runtime checks
4248     assert(!ary_klass->klass_is_exact(), "unexpected exact type");
4249     Node* r = new RegionNode(3);
4250     default_value = new PhiNode(r, TypeInstPtr::BOTTOM);
4251 
4252     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);
4253     IfNode* iff = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
4254 
4255     // Null-free, non-flattened inline type array, initialize with the default value
4256     set_control(_gvn.transform(new IfTrueNode(iff)));
4257     Node* p = basic_plus_adr(klass_node, in_bytes(ArrayKlass::element_klass_offset()));
4258     Node* eklass = _gvn.transform(LoadKlassNode::make(_gvn, control(), immutable_memory(), p, TypeInstPtr::KLASS));
4259     Node* adr_fixed_block_addr = basic_plus_adr(eklass, in_bytes(InstanceKlass::adr_inlineklass_fixed_block_offset()));
4260     Node* adr_fixed_block = make_load(control(), adr_fixed_block_addr, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4261     Node* default_value_offset_addr = basic_plus_adr(adr_fixed_block, in_bytes(InlineKlass::default_value_offset_offset()));
4262     Node* default_value_offset = make_load(control(), default_value_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
4263     Node* elem_mirror = load_mirror_from_klass(eklass);
4264     Node* default_value_addr = basic_plus_adr(elem_mirror, ConvI2X(default_value_offset));
4265     Node* val = access_load_at(elem_mirror, default_value_addr, TypeInstPtr::MIRROR, TypeInstPtr::NOTNULL, T_OBJECT, IN_HEAP);
4266     r->init_req(1, control());
4267     default_value->init_req(1, val);
4268 
4269     // Otherwise initialize with all zero
4270     r->init_req(2, _gvn.transform(new IfFalseNode(iff)));
4271     default_value->init_req(2, null());
4272 
4273     set_control(_gvn.transform(r));
4274     default_value = _gvn.transform(default_value);
4275   }
4276   if (default_value != NULL) {
4277     if (UseCompressedOops) {
4278       // With compressed oops, the 64-bit init value is built from two 32-bit compressed oops
4279       default_value = _gvn.transform(new EncodePNode(default_value, default_value->bottom_type()->make_narrowoop()));
4280       Node* lower = _gvn.transform(new CastP2XNode(control(), default_value));
4281       Node* upper = _gvn.transform(new LShiftLNode(lower, intcon(32)));
4282       raw_default_value = _gvn.transform(new OrLNode(lower, upper));
4283     } else {
4284       raw_default_value = _gvn.transform(new CastP2XNode(control(), default_value));
4285     }
4286   }
4287 
4288   Node* valid_length_test = _gvn.intcon(1);
4289   if (ary_type->isa_aryptr()) {
4290     BasicType bt = ary_type->isa_aryptr()->elem()->array_element_basic_type();
4291     jint max = TypeAryPtr::max_array_length(bt);
4292     Node* valid_length_cmp  = _gvn.transform(new CmpUNode(length, intcon(max)));
4293     valid_length_test = _gvn.transform(new BoolNode(valid_length_cmp, BoolTest::le));
4294   }
4295 
4296   // Create the AllocateArrayNode and its result projections
4297   AllocateArrayNode* alloc
4298     = new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),
4299                             control(), mem, i_o(),
4300                             size, klass_node,
4301                             initial_slow_test,
4302                             length, valid_length_test,
4303                             default_value, raw_default_value);
4304   // Cast to correct type.  Note that the klass_node may be constant or not,
4305   // and in the latter case the actual array type will be inexact also.
4306   // (This happens via a non-constant argument to inline_native_newArray.)
4307   // In any case, the value of klass_node provides the desired array type.
4308   const TypeInt* length_type = _gvn.find_int_type(length);
4309   if (ary_type->isa_aryptr() && length_type != NULL) {
4310     // Try to get a better type than POS for the size
4311     ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
4312   }
4313 
4314   Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);
4315 
4316   array_ideal_length(alloc, ary_type, true);
4317   return javaoop;
4318 }
4319 
4320 // The following "Ideal_foo" functions are placed here because they recognize
4321 // the graph shapes created by the functions immediately above.
4322 
4323 //---------------------------Ideal_allocation----------------------------------

4437   set_all_memory(ideal.merged_memory());
4438   set_i_o(ideal.i_o());
4439   set_control(ideal.ctrl());
4440 }
4441 
4442 void GraphKit::final_sync(IdealKit& ideal) {
4443   // Final sync IdealKit and graphKit.
4444   sync_kit(ideal);
4445 }
4446 
4447 Node* GraphKit::load_String_length(Node* str, bool set_ctrl) {
4448   Node* len = load_array_length(load_String_value(str, set_ctrl));
4449   Node* coder = load_String_coder(str, set_ctrl);
4450   // Divide length by 2 if coder is UTF16
4451   return _gvn.transform(new RShiftINode(len, coder));
4452 }
4453 
4454 Node* GraphKit::load_String_value(Node* str, bool set_ctrl) {
4455   int value_offset = java_lang_String::value_offset();
4456   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4457                                                      false, NULL, Type::Offset(0));
4458   const TypePtr* value_field_type = string_type->add_offset(value_offset);
4459   const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull,
4460                                                   TypeAry::make(TypeInt::BYTE, TypeInt::POS, false, true, true),
4461                                                   ciTypeArrayKlass::make(T_BYTE), true, Type::Offset(0));
4462   Node* p = basic_plus_adr(str, str, value_offset);
4463   Node* load = access_load_at(str, p, value_field_type, value_type, T_OBJECT,
4464                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4465   return load;
4466 }
4467 
4468 Node* GraphKit::load_String_coder(Node* str, bool set_ctrl) {
4469   if (!CompactStrings) {
4470     return intcon(java_lang_String::CODER_UTF16);
4471   }
4472   int coder_offset = java_lang_String::coder_offset();
4473   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4474                                                      false, NULL, Type::Offset(0));
4475   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4476 
4477   Node* p = basic_plus_adr(str, str, coder_offset);
4478   Node* load = access_load_at(str, p, coder_field_type, TypeInt::BYTE, T_BYTE,
4479                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4480   return load;
4481 }
4482 
4483 void GraphKit::store_String_value(Node* str, Node* value) {
4484   int value_offset = java_lang_String::value_offset();
4485   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4486                                                      false, NULL, Type::Offset(0));
4487   const TypePtr* value_field_type = string_type->add_offset(value_offset);
4488 
4489   access_store_at(str,  basic_plus_adr(str, value_offset), value_field_type,
4490                   value, TypeAryPtr::BYTES, T_OBJECT, IN_HEAP | MO_UNORDERED);
4491 }
4492 
4493 void GraphKit::store_String_coder(Node* str, Node* value) {
4494   int coder_offset = java_lang_String::coder_offset();
4495   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4496                                                      false, NULL, Type::Offset(0));
4497   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4498 
4499   access_store_at(str, basic_plus_adr(str, coder_offset), coder_field_type,
4500                   value, TypeInt::BYTE, T_BYTE, IN_HEAP | MO_UNORDERED);
4501 }
4502 
4503 // Capture src and dst memory state with a MergeMemNode
4504 Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) {
4505   if (src_type == dst_type) {
4506     // Types are equal, we don't need a MergeMemNode
4507     return memory(src_type);
4508   }
4509   MergeMemNode* merge = MergeMemNode::make(map()->memory());
4510   record_for_igvn(merge); // fold it up later, if possible
4511   int src_idx = C->get_alias_index(src_type);
4512   int dst_idx = C->get_alias_index(dst_type);
4513   merge->set_memory_at(src_idx, memory(src_idx));
4514   merge->set_memory_at(dst_idx, memory(dst_idx));
4515   return merge;
4516 }

4589   i_char->init_req(2, AddI(i_char, intcon(2)));
4590 
4591   set_control(IfFalse(iff));
4592   set_memory(st, TypeAryPtr::BYTES);
4593 }
4594 
4595 Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) {
4596   if (!field->is_constant()) {
4597     return NULL; // Field not marked as constant.
4598   }
4599   ciInstance* holder = NULL;
4600   if (!field->is_static()) {
4601     ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop();
4602     if (const_oop != NULL && const_oop->is_instance()) {
4603       holder = const_oop->as_instance();
4604     }
4605   }
4606   const Type* con_type = Type::make_constant_from_field(field, holder, field->layout_type(),
4607                                                         /*is_unsigned_load=*/false);
4608   if (con_type != NULL) {
4609     Node* con = makecon(con_type);
4610     if (field->type()->is_inlinetype()) {
4611       con = InlineTypeNode::make_from_oop(this, con, field->type()->as_inline_klass(), field->is_null_free());
4612     } else if (con_type->is_inlinetypeptr()) {
4613       con = InlineTypeNode::make_from_oop(this, con, con_type->inline_klass(), field->is_null_free());
4614     }
4615     return con;
4616   }
4617   return NULL;
4618 }
4619 
4620 //---------------------------load_mirror_from_klass----------------------------
4621 // Given a klass oop, load its java mirror (a java.lang.Class oop).
4622 Node* GraphKit::load_mirror_from_klass(Node* klass) {
4623   Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
4624   Node* load = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4625   // mirror = ((OopHandle)mirror)->resolve();
4626   return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4627 }
< prev index next >