1 /*
   2  * Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   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/ciNativeEntryPoint.hpp"
  29 #include "ci/ciObjArray.hpp"
  30 #include "asm/register.hpp"
  31 #include "compiler/compileLog.hpp"
  32 #include "gc/shared/barrierSet.hpp"
  33 #include "gc/shared/c2/barrierSetC2.hpp"
  34 #include "interpreter/interpreter.hpp"
  35 #include "memory/resourceArea.hpp"
  36 #include "opto/addnode.hpp"
  37 #include "opto/castnode.hpp"
  38 #include "opto/convertnode.hpp"
  39 #include "opto/graphKit.hpp"
  40 #include "opto/idealKit.hpp"
  41 #include "opto/intrinsicnode.hpp"
  42 #include "opto/locknode.hpp"
  43 #include "opto/machnode.hpp"
  44 #include "opto/opaquenode.hpp"
  45 #include "opto/parse.hpp"
  46 #include "opto/rootnode.hpp"
  47 #include "opto/runtime.hpp"
  48 #include "opto/subtypenode.hpp"
  49 #include "runtime/deoptimization.hpp"
  50 #include "runtime/sharedRuntime.hpp"
  51 #include "utilities/bitMap.inline.hpp"
  52 #include "utilities/powerOfTwo.hpp"
  53 #include "utilities/growableArray.hpp"
  54 
  55 //----------------------------GraphKit-----------------------------------------
  56 // Main utility constructor.
  57 GraphKit::GraphKit(JVMState* jvms)
  58   : Phase(Phase::Parser),
  59     _env(C->env()),
  60     _gvn(*C->initial_gvn()),
  61     _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
  62 {
  63   _exceptions = jvms->map()->next_exception();
  64   if (_exceptions != NULL)  jvms->map()->set_next_exception(NULL);
  65   set_jvms(jvms);
  66 }
  67 
  68 // Private constructor for parser.
  69 GraphKit::GraphKit()
  70   : Phase(Phase::Parser),
  71     _env(C->env()),
  72     _gvn(*C->initial_gvn()),
  73     _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
  74 {
  75   _exceptions = NULL;
  76   set_map(NULL);
  77   debug_only(_sp = -99);
  78   debug_only(set_bci(-99));
  79 }
  80 
  81 
  82 
  83 //---------------------------clean_stack---------------------------------------
  84 // Clear away rubbish from the stack area of the JVM state.
  85 // This destroys any arguments that may be waiting on the stack.
  86 void GraphKit::clean_stack(int from_sp) {
  87   SafePointNode* map      = this->map();
  88   JVMState*      jvms     = this->jvms();
  89   int            stk_size = jvms->stk_size();
  90   int            stkoff   = jvms->stkoff();
  91   Node*          top      = this->top();
  92   for (int i = from_sp; i < stk_size; i++) {
  93     if (map->in(stkoff + i) != top) {
  94       map->set_req(stkoff + i, top);
  95     }
  96   }
  97 }
  98 
  99 
 100 //--------------------------------sync_jvms-----------------------------------
 101 // Make sure our current jvms agrees with our parse state.
 102 JVMState* GraphKit::sync_jvms() const {
 103   JVMState* jvms = this->jvms();
 104   jvms->set_bci(bci());       // Record the new bci in the JVMState
 105   jvms->set_sp(sp());         // Record the new sp in the JVMState
 106   assert(jvms_in_sync(), "jvms is now in sync");
 107   return jvms;
 108 }
 109 
 110 //--------------------------------sync_jvms_for_reexecute---------------------
 111 // Make sure our current jvms agrees with our parse state.  This version
 112 // uses the reexecute_sp for reexecuting bytecodes.
 113 JVMState* GraphKit::sync_jvms_for_reexecute() {
 114   JVMState* jvms = this->jvms();
 115   jvms->set_bci(bci());          // Record the new bci in the JVMState
 116   jvms->set_sp(reexecute_sp());  // Record the new sp in the JVMState
 117   return jvms;
 118 }
 119 
 120 #ifdef ASSERT
 121 bool GraphKit::jvms_in_sync() const {
 122   Parse* parse = is_Parse();
 123   if (parse == NULL) {
 124     if (bci() !=      jvms()->bci())          return false;
 125     if (sp()  != (int)jvms()->sp())           return false;
 126     return true;
 127   }
 128   if (jvms()->method() != parse->method())    return false;
 129   if (jvms()->bci()    != parse->bci())       return false;
 130   int jvms_sp = jvms()->sp();
 131   if (jvms_sp          != parse->sp())        return false;
 132   int jvms_depth = jvms()->depth();
 133   if (jvms_depth       != parse->depth())     return false;
 134   return true;
 135 }
 136 
 137 // Local helper checks for special internal merge points
 138 // used to accumulate and merge exception states.
 139 // They are marked by the region's in(0) edge being the map itself.
 140 // Such merge points must never "escape" into the parser at large,
 141 // until they have been handed to gvn.transform.
 142 static bool is_hidden_merge(Node* reg) {
 143   if (reg == NULL)  return false;
 144   if (reg->is_Phi()) {
 145     reg = reg->in(0);
 146     if (reg == NULL)  return false;
 147   }
 148   return reg->is_Region() && reg->in(0) != NULL && reg->in(0)->is_Root();
 149 }
 150 
 151 void GraphKit::verify_map() const {
 152   if (map() == NULL)  return;  // null map is OK
 153   assert(map()->req() <= jvms()->endoff(), "no extra garbage on map");
 154   assert(!map()->has_exceptions(),    "call add_exception_states_from 1st");
 155   assert(!is_hidden_merge(control()), "call use_exception_state, not set_map");
 156 }
 157 
 158 void GraphKit::verify_exception_state(SafePointNode* ex_map) {
 159   assert(ex_map->next_exception() == NULL, "not already part of a chain");
 160   assert(has_saved_ex_oop(ex_map), "every exception state has an ex_oop");
 161 }
 162 #endif
 163 
 164 //---------------------------stop_and_kill_map---------------------------------
 165 // Set _map to NULL, signalling a stop to further bytecode execution.
 166 // First smash the current map's control to a constant, to mark it dead.
 167 void GraphKit::stop_and_kill_map() {
 168   SafePointNode* dead_map = stop();
 169   if (dead_map != NULL) {
 170     dead_map->disconnect_inputs(C); // Mark the map as killed.
 171     assert(dead_map->is_killed(), "must be so marked");
 172   }
 173 }
 174 
 175 
 176 //--------------------------------stopped--------------------------------------
 177 // Tell if _map is NULL, or control is top.
 178 bool GraphKit::stopped() {
 179   if (map() == NULL)           return true;
 180   else if (control() == top()) return true;
 181   else                         return false;
 182 }
 183 
 184 
 185 //-----------------------------has_ex_handler----------------------------------
 186 // Tell if this method or any caller method has exception handlers.
 187 bool GraphKit::has_ex_handler() {
 188   for (JVMState* jvmsp = jvms(); jvmsp != NULL; jvmsp = jvmsp->caller()) {
 189     if (jvmsp->has_method() && jvmsp->method()->has_exception_handlers()) {
 190       return true;
 191     }
 192   }
 193   return false;
 194 }
 195 
 196 //------------------------------save_ex_oop------------------------------------
 197 // Save an exception without blowing stack contents or other JVM state.
 198 void GraphKit::set_saved_ex_oop(SafePointNode* ex_map, Node* ex_oop) {
 199   assert(!has_saved_ex_oop(ex_map), "clear ex-oop before setting again");
 200   ex_map->add_req(ex_oop);
 201   debug_only(verify_exception_state(ex_map));
 202 }
 203 
 204 inline static Node* common_saved_ex_oop(SafePointNode* ex_map, bool clear_it) {
 205   assert(GraphKit::has_saved_ex_oop(ex_map), "ex_oop must be there");
 206   Node* ex_oop = ex_map->in(ex_map->req()-1);
 207   if (clear_it)  ex_map->del_req(ex_map->req()-1);
 208   return ex_oop;
 209 }
 210 
 211 //-----------------------------saved_ex_oop------------------------------------
 212 // Recover a saved exception from its map.
 213 Node* GraphKit::saved_ex_oop(SafePointNode* ex_map) {
 214   return common_saved_ex_oop(ex_map, false);
 215 }
 216 
 217 //--------------------------clear_saved_ex_oop---------------------------------
 218 // Erase a previously saved exception from its map.
 219 Node* GraphKit::clear_saved_ex_oop(SafePointNode* ex_map) {
 220   return common_saved_ex_oop(ex_map, true);
 221 }
 222 
 223 #ifdef ASSERT
 224 //---------------------------has_saved_ex_oop----------------------------------
 225 // Erase a previously saved exception from its map.
 226 bool GraphKit::has_saved_ex_oop(SafePointNode* ex_map) {
 227   return ex_map->req() == ex_map->jvms()->endoff()+1;
 228 }
 229 #endif
 230 
 231 //-------------------------make_exception_state--------------------------------
 232 // Turn the current JVM state into an exception state, appending the ex_oop.
 233 SafePointNode* GraphKit::make_exception_state(Node* ex_oop) {
 234   sync_jvms();
 235   SafePointNode* ex_map = stop();  // do not manipulate this map any more
 236   set_saved_ex_oop(ex_map, ex_oop);
 237   return ex_map;
 238 }
 239 
 240 
 241 //--------------------------add_exception_state--------------------------------
 242 // Add an exception to my list of exceptions.
 243 void GraphKit::add_exception_state(SafePointNode* ex_map) {
 244   if (ex_map == NULL || ex_map->control() == top()) {
 245     return;
 246   }
 247 #ifdef ASSERT
 248   verify_exception_state(ex_map);
 249   if (has_exceptions()) {
 250     assert(ex_map->jvms()->same_calls_as(_exceptions->jvms()), "all collected exceptions must come from the same place");
 251   }
 252 #endif
 253 
 254   // If there is already an exception of exactly this type, merge with it.
 255   // In particular, null-checks and other low-level exceptions common up here.
 256   Node*       ex_oop  = saved_ex_oop(ex_map);
 257   const Type* ex_type = _gvn.type(ex_oop);
 258   if (ex_oop == top()) {
 259     // No action needed.
 260     return;
 261   }
 262   assert(ex_type->isa_instptr(), "exception must be an instance");
 263   for (SafePointNode* e2 = _exceptions; e2 != NULL; e2 = e2->next_exception()) {
 264     const Type* ex_type2 = _gvn.type(saved_ex_oop(e2));
 265     // We check sp also because call bytecodes can generate exceptions
 266     // both before and after arguments are popped!
 267     if (ex_type2 == ex_type
 268         && e2->_jvms->sp() == ex_map->_jvms->sp()) {
 269       combine_exception_states(ex_map, e2);
 270       return;
 271     }
 272   }
 273 
 274   // No pre-existing exception of the same type.  Chain it on the list.
 275   push_exception_state(ex_map);
 276 }
 277 
 278 //-----------------------add_exception_states_from-----------------------------
 279 void GraphKit::add_exception_states_from(JVMState* jvms) {
 280   SafePointNode* ex_map = jvms->map()->next_exception();
 281   if (ex_map != NULL) {
 282     jvms->map()->set_next_exception(NULL);
 283     for (SafePointNode* next_map; ex_map != NULL; ex_map = next_map) {
 284       next_map = ex_map->next_exception();
 285       ex_map->set_next_exception(NULL);
 286       add_exception_state(ex_map);
 287     }
 288   }
 289 }
 290 
 291 //-----------------------transfer_exceptions_into_jvms-------------------------
 292 JVMState* GraphKit::transfer_exceptions_into_jvms() {
 293   if (map() == NULL) {
 294     // We need a JVMS to carry the exceptions, but the map has gone away.
 295     // Create a scratch JVMS, cloned from any of the exception states...
 296     if (has_exceptions()) {
 297       _map = _exceptions;
 298       _map = clone_map();
 299       _map->set_next_exception(NULL);
 300       clear_saved_ex_oop(_map);
 301       debug_only(verify_map());
 302     } else {
 303       // ...or created from scratch
 304       JVMState* jvms = new (C) JVMState(_method, NULL);
 305       jvms->set_bci(_bci);
 306       jvms->set_sp(_sp);
 307       jvms->set_map(new SafePointNode(TypeFunc::Parms, jvms));
 308       set_jvms(jvms);
 309       for (uint i = 0; i < map()->req(); i++)  map()->init_req(i, top());
 310       set_all_memory(top());
 311       while (map()->req() < jvms->endoff())  map()->add_req(top());
 312     }
 313     // (This is a kludge, in case you didn't notice.)
 314     set_control(top());
 315   }
 316   JVMState* jvms = sync_jvms();
 317   assert(!jvms->map()->has_exceptions(), "no exceptions on this map yet");
 318   jvms->map()->set_next_exception(_exceptions);
 319   _exceptions = NULL;   // done with this set of exceptions
 320   return jvms;
 321 }
 322 
 323 static inline void add_n_reqs(Node* dstphi, Node* srcphi) {
 324   assert(is_hidden_merge(dstphi), "must be a special merge node");
 325   assert(is_hidden_merge(srcphi), "must be a special merge node");
 326   uint limit = srcphi->req();
 327   for (uint i = PhiNode::Input; i < limit; i++) {
 328     dstphi->add_req(srcphi->in(i));
 329   }
 330 }
 331 static inline void add_one_req(Node* dstphi, Node* src) {
 332   assert(is_hidden_merge(dstphi), "must be a special merge node");
 333   assert(!is_hidden_merge(src), "must not be a special merge node");
 334   dstphi->add_req(src);
 335 }
 336 
 337 //-----------------------combine_exception_states------------------------------
 338 // This helper function combines exception states by building phis on a
 339 // specially marked state-merging region.  These regions and phis are
 340 // untransformed, and can build up gradually.  The region is marked by
 341 // having a control input of its exception map, rather than NULL.  Such
 342 // regions do not appear except in this function, and in use_exception_state.
 343 void GraphKit::combine_exception_states(SafePointNode* ex_map, SafePointNode* phi_map) {
 344   if (failing())  return;  // dying anyway...
 345   JVMState* ex_jvms = ex_map->_jvms;
 346   assert(ex_jvms->same_calls_as(phi_map->_jvms), "consistent call chains");
 347   assert(ex_jvms->stkoff() == phi_map->_jvms->stkoff(), "matching locals");
 348   assert(ex_jvms->sp() == phi_map->_jvms->sp(), "matching stack sizes");
 349   assert(ex_jvms->monoff() == phi_map->_jvms->monoff(), "matching JVMS");
 350   assert(ex_jvms->scloff() == phi_map->_jvms->scloff(), "matching scalar replaced objects");
 351   assert(ex_map->req() == phi_map->req(), "matching maps");
 352   uint tos = ex_jvms->stkoff() + ex_jvms->sp();
 353   Node*         hidden_merge_mark = root();
 354   Node*         region  = phi_map->control();
 355   MergeMemNode* phi_mem = phi_map->merged_memory();
 356   MergeMemNode* ex_mem  = ex_map->merged_memory();
 357   if (region->in(0) != hidden_merge_mark) {
 358     // The control input is not (yet) a specially-marked region in phi_map.
 359     // Make it so, and build some phis.
 360     region = new RegionNode(2);
 361     _gvn.set_type(region, Type::CONTROL);
 362     region->set_req(0, hidden_merge_mark);  // marks an internal ex-state
 363     region->init_req(1, phi_map->control());
 364     phi_map->set_control(region);
 365     Node* io_phi = PhiNode::make(region, phi_map->i_o(), Type::ABIO);
 366     record_for_igvn(io_phi);
 367     _gvn.set_type(io_phi, Type::ABIO);
 368     phi_map->set_i_o(io_phi);
 369     for (MergeMemStream mms(phi_mem); mms.next_non_empty(); ) {
 370       Node* m = mms.memory();
 371       Node* m_phi = PhiNode::make(region, m, Type::MEMORY, mms.adr_type(C));
 372       record_for_igvn(m_phi);
 373       _gvn.set_type(m_phi, Type::MEMORY);
 374       mms.set_memory(m_phi);
 375     }
 376   }
 377 
 378   // Either or both of phi_map and ex_map might already be converted into phis.
 379   Node* ex_control = ex_map->control();
 380   // if there is special marking on ex_map also, we add multiple edges from src
 381   bool add_multiple = (ex_control->in(0) == hidden_merge_mark);
 382   // how wide was the destination phi_map, originally?
 383   uint orig_width = region->req();
 384 
 385   if (add_multiple) {
 386     add_n_reqs(region, ex_control);
 387     add_n_reqs(phi_map->i_o(), ex_map->i_o());
 388   } else {
 389     // ex_map has no merges, so we just add single edges everywhere
 390     add_one_req(region, ex_control);
 391     add_one_req(phi_map->i_o(), ex_map->i_o());
 392   }
 393   for (MergeMemStream mms(phi_mem, ex_mem); mms.next_non_empty2(); ) {
 394     if (mms.is_empty()) {
 395       // get a copy of the base memory, and patch some inputs into it
 396       const TypePtr* adr_type = mms.adr_type(C);
 397       Node* phi = mms.force_memory()->as_Phi()->slice_memory(adr_type);
 398       assert(phi->as_Phi()->region() == mms.base_memory()->in(0), "");
 399       mms.set_memory(phi);
 400       // Prepare to append interesting stuff onto the newly sliced phi:
 401       while (phi->req() > orig_width)  phi->del_req(phi->req()-1);
 402     }
 403     // Append stuff from ex_map:
 404     if (add_multiple) {
 405       add_n_reqs(mms.memory(), mms.memory2());
 406     } else {
 407       add_one_req(mms.memory(), mms.memory2());
 408     }
 409   }
 410   uint limit = ex_map->req();
 411   for (uint i = TypeFunc::Parms; i < limit; i++) {
 412     // Skip everything in the JVMS after tos.  (The ex_oop follows.)
 413     if (i == tos)  i = ex_jvms->monoff();
 414     Node* src = ex_map->in(i);
 415     Node* dst = phi_map->in(i);
 416     if (src != dst) {
 417       PhiNode* phi;
 418       if (dst->in(0) != region) {
 419         dst = phi = PhiNode::make(region, dst, _gvn.type(dst));
 420         record_for_igvn(phi);
 421         _gvn.set_type(phi, phi->type());
 422         phi_map->set_req(i, dst);
 423         // Prepare to append interesting stuff onto the new phi:
 424         while (dst->req() > orig_width)  dst->del_req(dst->req()-1);
 425       } else {
 426         assert(dst->is_Phi(), "nobody else uses a hidden region");
 427         phi = dst->as_Phi();
 428       }
 429       if (add_multiple && src->in(0) == ex_control) {
 430         // Both are phis.
 431         add_n_reqs(dst, src);
 432       } else {
 433         while (dst->req() < region->req())  add_one_req(dst, src);
 434       }
 435       const Type* srctype = _gvn.type(src);
 436       if (phi->type() != srctype) {
 437         const Type* dsttype = phi->type()->meet_speculative(srctype);
 438         if (phi->type() != dsttype) {
 439           phi->set_type(dsttype);
 440           _gvn.set_type(phi, dsttype);
 441         }
 442       }
 443     }
 444   }
 445   phi_map->merge_replaced_nodes_with(ex_map);
 446 }
 447 
 448 //--------------------------use_exception_state--------------------------------
 449 Node* GraphKit::use_exception_state(SafePointNode* phi_map) {
 450   if (failing()) { stop(); return top(); }
 451   Node* region = phi_map->control();
 452   Node* hidden_merge_mark = root();
 453   assert(phi_map->jvms()->map() == phi_map, "sanity: 1-1 relation");
 454   Node* ex_oop = clear_saved_ex_oop(phi_map);
 455   if (region->in(0) == hidden_merge_mark) {
 456     // Special marking for internal ex-states.  Process the phis now.
 457     region->set_req(0, region);  // now it's an ordinary region
 458     set_jvms(phi_map->jvms());   // ...so now we can use it as a map
 459     // Note: Setting the jvms also sets the bci and sp.
 460     set_control(_gvn.transform(region));
 461     uint tos = jvms()->stkoff() + sp();
 462     for (uint i = 1; i < tos; i++) {
 463       Node* x = phi_map->in(i);
 464       if (x->in(0) == region) {
 465         assert(x->is_Phi(), "expected a special phi");
 466         phi_map->set_req(i, _gvn.transform(x));
 467       }
 468     }
 469     for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
 470       Node* x = mms.memory();
 471       if (x->in(0) == region) {
 472         assert(x->is_Phi(), "nobody else uses a hidden region");
 473         mms.set_memory(_gvn.transform(x));
 474       }
 475     }
 476     if (ex_oop->in(0) == region) {
 477       assert(ex_oop->is_Phi(), "expected a special phi");
 478       ex_oop = _gvn.transform(ex_oop);
 479     }
 480   } else {
 481     set_jvms(phi_map->jvms());
 482   }
 483 
 484   assert(!is_hidden_merge(phi_map->control()), "hidden ex. states cleared");
 485   assert(!is_hidden_merge(phi_map->i_o()), "hidden ex. states cleared");
 486   return ex_oop;
 487 }
 488 
 489 //---------------------------------java_bc-------------------------------------
 490 Bytecodes::Code GraphKit::java_bc() const {
 491   ciMethod* method = this->method();
 492   int       bci    = this->bci();
 493   if (method != NULL && bci != InvocationEntryBci)
 494     return method->java_code_at_bci(bci);
 495   else
 496     return Bytecodes::_illegal;
 497 }
 498 
 499 void GraphKit::uncommon_trap_if_should_post_on_exceptions(Deoptimization::DeoptReason reason,
 500                                                           bool must_throw) {
 501     // if the exception capability is set, then we will generate code
 502     // to check the JavaThread.should_post_on_exceptions flag to see
 503     // if we actually need to report exception events (for this
 504     // thread).  If we don't need to report exception events, we will
 505     // take the normal fast path provided by add_exception_events.  If
 506     // exception event reporting is enabled for this thread, we will
 507     // take the uncommon_trap in the BuildCutout below.
 508 
 509     // first must access the should_post_on_exceptions_flag in this thread's JavaThread
 510     Node* jthread = _gvn.transform(new ThreadLocalNode());
 511     Node* adr = basic_plus_adr(top(), jthread, in_bytes(JavaThread::should_post_on_exceptions_flag_offset()));
 512     Node* should_post_flag = make_load(control(), adr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, MemNode::unordered);
 513 
 514     // Test the should_post_on_exceptions_flag vs. 0
 515     Node* chk = _gvn.transform( new CmpINode(should_post_flag, intcon(0)) );
 516     Node* tst = _gvn.transform( new BoolNode(chk, BoolTest::eq) );
 517 
 518     // Branch to slow_path if should_post_on_exceptions_flag was true
 519     { BuildCutout unless(this, tst, PROB_MAX);
 520       // Do not try anything fancy if we're notifying the VM on every throw.
 521       // Cf. case Bytecodes::_athrow in parse2.cpp.
 522       uncommon_trap(reason, Deoptimization::Action_none,
 523                     (ciKlass*)NULL, (char*)NULL, must_throw);
 524     }
 525 
 526 }
 527 
 528 //------------------------------builtin_throw----------------------------------
 529 void GraphKit::builtin_throw(Deoptimization::DeoptReason reason, Node* arg) {
 530   bool must_throw = true;
 531 
 532   // If this particular condition has not yet happened at this
 533   // bytecode, then use the uncommon trap mechanism, and allow for
 534   // a future recompilation if several traps occur here.
 535   // If the throw is hot, try to use a more complicated inline mechanism
 536   // which keeps execution inside the compiled code.
 537   bool treat_throw_as_hot = false;
 538   ciMethodData* md = method()->method_data();
 539 
 540   if (ProfileTraps) {
 541     if (too_many_traps(reason)) {
 542       treat_throw_as_hot = true;
 543     }
 544     // (If there is no MDO at all, assume it is early in
 545     // execution, and that any deopts are part of the
 546     // startup transient, and don't need to be remembered.)
 547 
 548     // Also, if there is a local exception handler, treat all throws
 549     // as hot if there has been at least one in this method.
 550     if (C->trap_count(reason) != 0
 551         && method()->method_data()->trap_count(reason) != 0
 552         && has_ex_handler()) {
 553         treat_throw_as_hot = true;
 554     }
 555   }
 556 
 557   // If this throw happens frequently, an uncommon trap might cause
 558   // a performance pothole.  If there is a local exception handler,
 559   // and if this particular bytecode appears to be deoptimizing often,
 560   // let us handle the throw inline, with a preconstructed instance.
 561   // Note:   If the deopt count has blown up, the uncommon trap
 562   // runtime is going to flush this nmethod, not matter what.
 563   if (treat_throw_as_hot
 564       && (!StackTraceInThrowable || OmitStackTraceInFastThrow)) {
 565     // If the throw is local, we use a pre-existing instance and
 566     // punt on the backtrace.  This would lead to a missing backtrace
 567     // (a repeat of 4292742) if the backtrace object is ever asked
 568     // for its backtrace.
 569     // Fixing this remaining case of 4292742 requires some flavor of
 570     // escape analysis.  Leave that for the future.
 571     ciInstance* ex_obj = NULL;
 572     switch (reason) {
 573     case Deoptimization::Reason_null_check:
 574       ex_obj = env()->NullPointerException_instance();
 575       break;
 576     case Deoptimization::Reason_div0_check:
 577       ex_obj = env()->ArithmeticException_instance();
 578       break;
 579     case Deoptimization::Reason_range_check:
 580       ex_obj = env()->ArrayIndexOutOfBoundsException_instance();
 581       break;
 582     case Deoptimization::Reason_class_check:
 583       if (java_bc() == Bytecodes::_aastore) {
 584         ex_obj = env()->ArrayStoreException_instance();
 585       } else {
 586         ex_obj = env()->ClassCastException_instance();
 587       }
 588       break;
 589     default:
 590       break;
 591     }
 592     if (failing()) { stop(); return; }  // exception allocation might fail
 593     if (ex_obj != NULL) {
 594       if (env()->jvmti_can_post_on_exceptions()) {
 595         // check if we must post exception events, take uncommon trap if so
 596         uncommon_trap_if_should_post_on_exceptions(reason, must_throw);
 597         // here if should_post_on_exceptions is false
 598         // continue on with the normal codegen
 599       }
 600 
 601       // Cheat with a preallocated exception object.
 602       if (C->log() != NULL)
 603         C->log()->elem("hot_throw preallocated='1' reason='%s'",
 604                        Deoptimization::trap_reason_name(reason));
 605       const TypeInstPtr* ex_con  = TypeInstPtr::make(ex_obj);
 606       Node*              ex_node = _gvn.transform(ConNode::make(ex_con));
 607 
 608       // Clear the detail message of the preallocated exception object.
 609       // Weblogic sometimes mutates the detail message of exceptions
 610       // using reflection.
 611       int offset = java_lang_Throwable::get_detailMessage_offset();
 612       const TypePtr* adr_typ = ex_con->add_offset(offset);
 613 
 614       Node *adr = basic_plus_adr(ex_node, ex_node, offset);
 615       const TypeOopPtr* val_type = TypeOopPtr::make_from_klass(env()->String_klass());
 616       Node *store = access_store_at(ex_node, adr, adr_typ, null(), val_type, T_OBJECT, IN_HEAP);
 617 
 618       add_exception_state(make_exception_state(ex_node));
 619       return;
 620     }
 621   }
 622 
 623   // %%% Maybe add entry to OptoRuntime which directly throws the exc.?
 624   // It won't be much cheaper than bailing to the interp., since we'll
 625   // have to pass up all the debug-info, and the runtime will have to
 626   // create the stack trace.
 627 
 628   // Usual case:  Bail to interpreter.
 629   // Reserve the right to recompile if we haven't seen anything yet.
 630 
 631   ciMethod* m = Deoptimization::reason_is_speculate(reason) ? C->method() : NULL;
 632   Deoptimization::DeoptAction action = Deoptimization::Action_maybe_recompile;
 633   if (treat_throw_as_hot
 634       && (method()->method_data()->trap_recompiled_at(bci(), m)
 635           || C->too_many_traps(reason))) {
 636     // We cannot afford to take more traps here.  Suffer in the interpreter.
 637     if (C->log() != NULL)
 638       C->log()->elem("hot_throw preallocated='0' reason='%s' mcount='%d'",
 639                      Deoptimization::trap_reason_name(reason),
 640                      C->trap_count(reason));
 641     action = Deoptimization::Action_none;
 642   }
 643 
 644   // "must_throw" prunes the JVM state to include only the stack, if there
 645   // are no local exception handlers.  This should cut down on register
 646   // allocation time and code size, by drastically reducing the number
 647   // of in-edges on the call to the uncommon trap.
 648 
 649   uncommon_trap(reason, action, (ciKlass*)NULL, (char*)NULL, must_throw);
 650 }
 651 
 652 
 653 //----------------------------PreserveJVMState---------------------------------
 654 PreserveJVMState::PreserveJVMState(GraphKit* kit, bool clone_map) {
 655   debug_only(kit->verify_map());
 656   _kit    = kit;
 657   _map    = kit->map();   // preserve the map
 658   _sp     = kit->sp();
 659   kit->set_map(clone_map ? kit->clone_map() : NULL);
 660 #ifdef ASSERT
 661   _bci    = kit->bci();
 662   Parse* parser = kit->is_Parse();
 663   int block = (parser == NULL || parser->block() == NULL) ? -1 : parser->block()->rpo();
 664   _block  = block;
 665 #endif
 666 }
 667 PreserveJVMState::~PreserveJVMState() {
 668   GraphKit* kit = _kit;
 669 #ifdef ASSERT
 670   assert(kit->bci() == _bci, "bci must not shift");
 671   Parse* parser = kit->is_Parse();
 672   int block = (parser == NULL || parser->block() == NULL) ? -1 : parser->block()->rpo();
 673   assert(block == _block,    "block must not shift");
 674 #endif
 675   kit->set_map(_map);
 676   kit->set_sp(_sp);
 677 }
 678 
 679 
 680 //-----------------------------BuildCutout-------------------------------------
 681 BuildCutout::BuildCutout(GraphKit* kit, Node* p, float prob, float cnt)
 682   : PreserveJVMState(kit)
 683 {
 684   assert(p->is_Con() || p->is_Bool(), "test must be a bool");
 685   SafePointNode* outer_map = _map;   // preserved map is caller's
 686   SafePointNode* inner_map = kit->map();
 687   IfNode* iff = kit->create_and_map_if(outer_map->control(), p, prob, cnt);
 688   outer_map->set_control(kit->gvn().transform( new IfTrueNode(iff) ));
 689   inner_map->set_control(kit->gvn().transform( new IfFalseNode(iff) ));
 690 }
 691 BuildCutout::~BuildCutout() {
 692   GraphKit* kit = _kit;
 693   assert(kit->stopped(), "cutout code must stop, throw, return, etc.");
 694 }
 695 
 696 //---------------------------PreserveReexecuteState----------------------------
 697 PreserveReexecuteState::PreserveReexecuteState(GraphKit* kit) {
 698   assert(!kit->stopped(), "must call stopped() before");
 699   _kit    =    kit;
 700   _sp     =    kit->sp();
 701   _reexecute = kit->jvms()->_reexecute;
 702 }
 703 PreserveReexecuteState::~PreserveReexecuteState() {
 704   if (_kit->stopped()) return;
 705   _kit->jvms()->_reexecute = _reexecute;
 706   _kit->set_sp(_sp);
 707 }
 708 
 709 //------------------------------clone_map--------------------------------------
 710 // Implementation of PreserveJVMState
 711 //
 712 // Only clone_map(...) here. If this function is only used in the
 713 // PreserveJVMState class we may want to get rid of this extra
 714 // function eventually and do it all there.
 715 
 716 SafePointNode* GraphKit::clone_map() {
 717   if (map() == NULL)  return NULL;
 718 
 719   // Clone the memory edge first
 720   Node* mem = MergeMemNode::make(map()->memory());
 721   gvn().set_type_bottom(mem);
 722 
 723   SafePointNode *clonemap = (SafePointNode*)map()->clone();
 724   JVMState* jvms = this->jvms();
 725   JVMState* clonejvms = jvms->clone_shallow(C);
 726   clonemap->set_memory(mem);
 727   clonemap->set_jvms(clonejvms);
 728   clonejvms->set_map(clonemap);
 729   record_for_igvn(clonemap);
 730   gvn().set_type_bottom(clonemap);
 731   return clonemap;
 732 }
 733 
 734 
 735 //-----------------------------set_map_clone-----------------------------------
 736 void GraphKit::set_map_clone(SafePointNode* m) {
 737   _map = m;
 738   _map = clone_map();
 739   _map->set_next_exception(NULL);
 740   debug_only(verify_map());
 741 }
 742 
 743 
 744 //----------------------------kill_dead_locals---------------------------------
 745 // Detect any locals which are known to be dead, and force them to top.
 746 void GraphKit::kill_dead_locals() {
 747   // Consult the liveness information for the locals.  If any
 748   // of them are unused, then they can be replaced by top().  This
 749   // should help register allocation time and cut down on the size
 750   // of the deoptimization information.
 751 
 752   // This call is made from many of the bytecode handling
 753   // subroutines called from the Big Switch in do_one_bytecode.
 754   // Every bytecode which might include a slow path is responsible
 755   // for killing its dead locals.  The more consistent we
 756   // are about killing deads, the fewer useless phis will be
 757   // constructed for them at various merge points.
 758 
 759   // bci can be -1 (InvocationEntryBci).  We return the entry
 760   // liveness for the method.
 761 
 762   if (method() == NULL || method()->code_size() == 0) {
 763     // We are building a graph for a call to a native method.
 764     // All locals are live.
 765     return;
 766   }
 767 
 768   ResourceMark rm;
 769 
 770   // Consult the liveness information for the locals.  If any
 771   // of them are unused, then they can be replaced by top().  This
 772   // should help register allocation time and cut down on the size
 773   // of the deoptimization information.
 774   MethodLivenessResult live_locals = method()->liveness_at_bci(bci());
 775 
 776   int len = (int)live_locals.size();
 777   assert(len <= jvms()->loc_size(), "too many live locals");
 778   for (int local = 0; local < len; local++) {
 779     if (!live_locals.at(local)) {
 780       set_local(local, top());
 781     }
 782   }
 783 }
 784 
 785 #ifdef ASSERT
 786 //-------------------------dead_locals_are_killed------------------------------
 787 // Return true if all dead locals are set to top in the map.
 788 // Used to assert "clean" debug info at various points.
 789 bool GraphKit::dead_locals_are_killed() {
 790   if (method() == NULL || method()->code_size() == 0) {
 791     // No locals need to be dead, so all is as it should be.
 792     return true;
 793   }
 794 
 795   // Make sure somebody called kill_dead_locals upstream.
 796   ResourceMark rm;
 797   for (JVMState* jvms = this->jvms(); jvms != NULL; jvms = jvms->caller()) {
 798     if (jvms->loc_size() == 0)  continue;  // no locals to consult
 799     SafePointNode* map = jvms->map();
 800     ciMethod* method = jvms->method();
 801     int       bci    = jvms->bci();
 802     if (jvms == this->jvms()) {
 803       bci = this->bci();  // it might not yet be synched
 804     }
 805     MethodLivenessResult live_locals = method->liveness_at_bci(bci);
 806     int len = (int)live_locals.size();
 807     if (!live_locals.is_valid() || len == 0)
 808       // This method is trivial, or is poisoned by a breakpoint.
 809       return true;
 810     assert(len == jvms->loc_size(), "live map consistent with locals map");
 811     for (int local = 0; local < len; local++) {
 812       if (!live_locals.at(local) && map->local(jvms, local) != top()) {
 813         if (PrintMiscellaneous && (Verbose || WizardMode)) {
 814           tty->print_cr("Zombie local %d: ", local);
 815           jvms->dump();
 816         }
 817         return false;
 818       }
 819     }
 820   }
 821   return true;
 822 }
 823 
 824 #endif //ASSERT
 825 
 826 // Helper function for enforcing certain bytecodes to reexecute if deoptimization happens.
 827 static bool should_reexecute_implied_by_bytecode(JVMState *jvms, bool is_anewarray) {
 828   ciMethod* cur_method = jvms->method();
 829   int       cur_bci   = jvms->bci();
 830   if (cur_method != NULL && cur_bci != InvocationEntryBci) {
 831     Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci);
 832     return Interpreter::bytecode_should_reexecute(code) ||
 833            (is_anewarray && code == Bytecodes::_multianewarray);
 834     // Reexecute _multianewarray bytecode which was replaced with
 835     // sequence of [a]newarray. See Parse::do_multianewarray().
 836     //
 837     // Note: interpreter should not have it set since this optimization
 838     // is limited by dimensions and guarded by flag so in some cases
 839     // multianewarray() runtime calls will be generated and
 840     // the bytecode should not be reexecutes (stack will not be reset).
 841   } else {
 842     return false;
 843   }
 844 }
 845 
 846 // Helper function for adding JVMState and debug information to node
 847 void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) {
 848   // Add the safepoint edges to the call (or other safepoint).
 849 
 850   // Make sure dead locals are set to top.  This
 851   // should help register allocation time and cut down on the size
 852   // of the deoptimization information.
 853   assert(dead_locals_are_killed(), "garbage in debug info before safepoint");
 854 
 855   // Walk the inline list to fill in the correct set of JVMState's
 856   // Also fill in the associated edges for each JVMState.
 857 
 858   // If the bytecode needs to be reexecuted we need to put
 859   // the arguments back on the stack.
 860   const bool should_reexecute = jvms()->should_reexecute();
 861   JVMState* youngest_jvms = should_reexecute ? sync_jvms_for_reexecute() : sync_jvms();
 862 
 863   // NOTE: set_bci (called from sync_jvms) might reset the reexecute bit to
 864   // undefined if the bci is different.  This is normal for Parse but it
 865   // should not happen for LibraryCallKit because only one bci is processed.
 866   assert(!is_LibraryCallKit() || (jvms()->should_reexecute() == should_reexecute),
 867          "in LibraryCallKit the reexecute bit should not change");
 868 
 869   // If we are guaranteed to throw, we can prune everything but the
 870   // input to the current bytecode.
 871   bool can_prune_locals = false;
 872   uint stack_slots_not_pruned = 0;
 873   int inputs = 0, depth = 0;
 874   if (must_throw) {
 875     assert(method() == youngest_jvms->method(), "sanity");
 876     if (compute_stack_effects(inputs, depth)) {
 877       can_prune_locals = true;
 878       stack_slots_not_pruned = inputs;
 879     }
 880   }
 881 
 882   if (env()->should_retain_local_variables()) {
 883     // At any safepoint, this method can get breakpointed, which would
 884     // then require an immediate deoptimization.
 885     can_prune_locals = false;  // do not prune locals
 886     stack_slots_not_pruned = 0;
 887   }
 888 
 889   // do not scribble on the input jvms
 890   JVMState* out_jvms = youngest_jvms->clone_deep(C);
 891   call->set_jvms(out_jvms); // Start jvms list for call node
 892 
 893   // For a known set of bytecodes, the interpreter should reexecute them if
 894   // deoptimization happens. We set the reexecute state for them here
 895   if (out_jvms->is_reexecute_undefined() && //don't change if already specified
 896       should_reexecute_implied_by_bytecode(out_jvms, call->is_AllocateArray())) {
 897 #ifdef ASSERT
 898     int inputs = 0, not_used; // initialized by GraphKit::compute_stack_effects()
 899     assert(method() == youngest_jvms->method(), "sanity");
 900     assert(compute_stack_effects(inputs, not_used), "unknown bytecode: %s", Bytecodes::name(java_bc()));
 901     assert(out_jvms->sp() >= (uint)inputs, "not enough operands for reexecution");
 902 #endif // ASSERT
 903     out_jvms->set_should_reexecute(true); //NOTE: youngest_jvms not changed
 904   }
 905 
 906   // Presize the call:
 907   DEBUG_ONLY(uint non_debug_edges = call->req());
 908   call->add_req_batch(top(), youngest_jvms->debug_depth());
 909   assert(call->req() == non_debug_edges + youngest_jvms->debug_depth(), "");
 910 
 911   // Set up edges so that the call looks like this:
 912   //  Call [state:] ctl io mem fptr retadr
 913   //       [parms:] parm0 ... parmN
 914   //       [root:]  loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN
 915   //    [...mid:]   loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN [...]
 916   //       [young:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN
 917   // Note that caller debug info precedes callee debug info.
 918 
 919   // Fill pointer walks backwards from "young:" to "root:" in the diagram above:
 920   uint debug_ptr = call->req();
 921 
 922   // Loop over the map input edges associated with jvms, add them
 923   // to the call node, & reset all offsets to match call node array.
 924   for (JVMState* in_jvms = youngest_jvms; in_jvms != NULL; ) {
 925     uint debug_end   = debug_ptr;
 926     uint debug_start = debug_ptr - in_jvms->debug_size();
 927     debug_ptr = debug_start;  // back up the ptr
 928 
 929     uint p = debug_start;  // walks forward in [debug_start, debug_end)
 930     uint j, k, l;
 931     SafePointNode* in_map = in_jvms->map();
 932     out_jvms->set_map(call);
 933 
 934     if (can_prune_locals) {
 935       assert(in_jvms->method() == out_jvms->method(), "sanity");
 936       // If the current throw can reach an exception handler in this JVMS,
 937       // then we must keep everything live that can reach that handler.
 938       // As a quick and dirty approximation, we look for any handlers at all.
 939       if (in_jvms->method()->has_exception_handlers()) {
 940         can_prune_locals = false;
 941       }
 942     }
 943 
 944     // Add the Locals
 945     k = in_jvms->locoff();
 946     l = in_jvms->loc_size();
 947     out_jvms->set_locoff(p);
 948     if (!can_prune_locals) {
 949       for (j = 0; j < l; j++)
 950         call->set_req(p++, in_map->in(k+j));
 951     } else {
 952       p += l;  // already set to top above by add_req_batch
 953     }
 954 
 955     // Add the Expression Stack
 956     k = in_jvms->stkoff();
 957     l = in_jvms->sp();
 958     out_jvms->set_stkoff(p);
 959     if (!can_prune_locals) {
 960       for (j = 0; j < l; j++)
 961         call->set_req(p++, in_map->in(k+j));
 962     } else if (can_prune_locals && stack_slots_not_pruned != 0) {
 963       // Divide stack into {S0,...,S1}, where S0 is set to top.
 964       uint s1 = stack_slots_not_pruned;
 965       stack_slots_not_pruned = 0;  // for next iteration
 966       if (s1 > l)  s1 = l;
 967       uint s0 = l - s1;
 968       p += s0;  // skip the tops preinstalled by add_req_batch
 969       for (j = s0; j < l; j++)
 970         call->set_req(p++, in_map->in(k+j));
 971     } else {
 972       p += l;  // already set to top above by add_req_batch
 973     }
 974 
 975     // Add the Monitors
 976     k = in_jvms->monoff();
 977     l = in_jvms->mon_size();
 978     out_jvms->set_monoff(p);
 979     for (j = 0; j < l; j++)
 980       call->set_req(p++, in_map->in(k+j));
 981 
 982     // Copy any scalar object fields.
 983     k = in_jvms->scloff();
 984     l = in_jvms->scl_size();
 985     out_jvms->set_scloff(p);
 986     for (j = 0; j < l; j++)
 987       call->set_req(p++, in_map->in(k+j));
 988 
 989     // Finish the new jvms.
 990     out_jvms->set_endoff(p);
 991 
 992     assert(out_jvms->endoff()     == debug_end,             "fill ptr must match");
 993     assert(out_jvms->depth()      == in_jvms->depth(),      "depth must match");
 994     assert(out_jvms->loc_size()   == in_jvms->loc_size(),   "size must match");
 995     assert(out_jvms->mon_size()   == in_jvms->mon_size(),   "size must match");
 996     assert(out_jvms->scl_size()   == in_jvms->scl_size(),   "size must match");
 997     assert(out_jvms->debug_size() == in_jvms->debug_size(), "size must match");
 998 
 999     // Update the two tail pointers in parallel.
1000     out_jvms = out_jvms->caller();
1001     in_jvms  = in_jvms->caller();
1002   }
1003 
1004   assert(debug_ptr == non_debug_edges, "debug info must fit exactly");
1005 
1006   // Test the correctness of JVMState::debug_xxx accessors:
1007   assert(call->jvms()->debug_start() == non_debug_edges, "");
1008   assert(call->jvms()->debug_end()   == call->req(), "");
1009   assert(call->jvms()->debug_depth() == call->req() - non_debug_edges, "");
1010 }
1011 
1012 bool GraphKit::compute_stack_effects(int& inputs, int& depth) {
1013   Bytecodes::Code code = java_bc();
1014   if (code == Bytecodes::_wide) {
1015     code = method()->java_code_at_bci(bci() + 1);
1016   }
1017 
1018   BasicType rtype = T_ILLEGAL;
1019   int       rsize = 0;
1020 
1021   if (code != Bytecodes::_illegal) {
1022     depth = Bytecodes::depth(code); // checkcast=0, athrow=-1
1023     rtype = Bytecodes::result_type(code); // checkcast=P, athrow=V
1024     if (rtype < T_CONFLICT)
1025       rsize = type2size[rtype];
1026   }
1027 
1028   switch (code) {
1029   case Bytecodes::_illegal:
1030     return false;
1031 
1032   case Bytecodes::_ldc:
1033   case Bytecodes::_ldc_w:
1034   case Bytecodes::_ldc2_w:
1035     inputs = 0;
1036     break;
1037 
1038   case Bytecodes::_dup:         inputs = 1;  break;
1039   case Bytecodes::_dup_x1:      inputs = 2;  break;
1040   case Bytecodes::_dup_x2:      inputs = 3;  break;
1041   case Bytecodes::_dup2:        inputs = 2;  break;
1042   case Bytecodes::_dup2_x1:     inputs = 3;  break;
1043   case Bytecodes::_dup2_x2:     inputs = 4;  break;
1044   case Bytecodes::_swap:        inputs = 2;  break;
1045   case Bytecodes::_arraylength: inputs = 1;  break;
1046 
1047   case Bytecodes::_getstatic:
1048   case Bytecodes::_putstatic:
1049   case Bytecodes::_getfield:
1050   case Bytecodes::_putfield:
1051     {
1052       bool ignored_will_link;
1053       ciField* field = method()->get_field_at_bci(bci(), ignored_will_link);
1054       int      size  = field->type()->size();
1055       bool is_get = (depth >= 0), is_static = (depth & 1);
1056       inputs = (is_static ? 0 : 1);
1057       if (is_get) {
1058         depth = size - inputs;
1059       } else {
1060         inputs += size;        // putxxx pops the value from the stack
1061         depth = - inputs;
1062       }
1063     }
1064     break;
1065 
1066   case Bytecodes::_invokevirtual:
1067   case Bytecodes::_invokespecial:
1068   case Bytecodes::_invokestatic:
1069   case Bytecodes::_invokedynamic:
1070   case Bytecodes::_invokeinterface:
1071     {
1072       bool ignored_will_link;
1073       ciSignature* declared_signature = NULL;
1074       ciMethod* ignored_callee = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
1075       assert(declared_signature != NULL, "cannot be null");
1076       inputs   = declared_signature->arg_size_for_bc(code);
1077       int size = declared_signature->return_type()->size();
1078       depth = size - inputs;
1079     }
1080     break;
1081 
1082   case Bytecodes::_multianewarray:
1083     {
1084       ciBytecodeStream iter(method());
1085       iter.reset_to_bci(bci());
1086       iter.next();
1087       inputs = iter.get_dimensions();
1088       assert(rsize == 1, "");
1089       depth = rsize - inputs;
1090     }
1091     break;
1092 
1093   case Bytecodes::_ireturn:
1094   case Bytecodes::_lreturn:
1095   case Bytecodes::_freturn:
1096   case Bytecodes::_dreturn:
1097   case Bytecodes::_areturn:
1098     assert(rsize == -depth, "");
1099     inputs = rsize;
1100     break;
1101 
1102   case Bytecodes::_jsr:
1103   case Bytecodes::_jsr_w:
1104     inputs = 0;
1105     depth  = 1;                  // S.B. depth=1, not zero
1106     break;
1107 
1108   default:
1109     // bytecode produces a typed result
1110     inputs = rsize - depth;
1111     assert(inputs >= 0, "");
1112     break;
1113   }
1114 
1115 #ifdef ASSERT
1116   // spot check
1117   int outputs = depth + inputs;
1118   assert(outputs >= 0, "sanity");
1119   switch (code) {
1120   case Bytecodes::_checkcast: assert(inputs == 1 && outputs == 1, ""); break;
1121   case Bytecodes::_athrow:    assert(inputs == 1 && outputs == 0, ""); break;
1122   case Bytecodes::_aload_0:   assert(inputs == 0 && outputs == 1, ""); break;
1123   case Bytecodes::_return:    assert(inputs == 0 && outputs == 0, ""); break;
1124   case Bytecodes::_drem:      assert(inputs == 4 && outputs == 2, ""); break;
1125   default:                    break;
1126   }
1127 #endif //ASSERT
1128 
1129   return true;
1130 }
1131 
1132 
1133 
1134 //------------------------------basic_plus_adr---------------------------------
1135 Node* GraphKit::basic_plus_adr(Node* base, Node* ptr, Node* offset) {
1136   // short-circuit a common case
1137   if (offset == intcon(0))  return ptr;
1138   return _gvn.transform( new AddPNode(base, ptr, offset) );
1139 }
1140 
1141 Node* GraphKit::ConvI2L(Node* offset) {
1142   // short-circuit a common case
1143   jint offset_con = find_int_con(offset, Type::OffsetBot);
1144   if (offset_con != Type::OffsetBot) {
1145     return longcon((jlong) offset_con);
1146   }
1147   return _gvn.transform( new ConvI2LNode(offset));
1148 }
1149 
1150 Node* GraphKit::ConvI2UL(Node* offset) {
1151   juint offset_con = (juint) find_int_con(offset, Type::OffsetBot);
1152   if (offset_con != (juint) Type::OffsetBot) {
1153     return longcon((julong) offset_con);
1154   }
1155   Node* conv = _gvn.transform( new ConvI2LNode(offset));
1156   Node* mask = _gvn.transform(ConLNode::make((julong) max_juint));
1157   return _gvn.transform( new AndLNode(conv, mask) );
1158 }
1159 
1160 Node* GraphKit::ConvL2I(Node* offset) {
1161   // short-circuit a common case
1162   jlong offset_con = find_long_con(offset, (jlong)Type::OffsetBot);
1163   if (offset_con != (jlong)Type::OffsetBot) {
1164     return intcon((int) offset_con);
1165   }
1166   return _gvn.transform( new ConvL2INode(offset));
1167 }
1168 
1169 //-------------------------load_object_klass-----------------------------------
1170 Node* GraphKit::load_object_klass(Node* obj) {
1171   // Special-case a fresh allocation to avoid building nodes:
1172   Node* akls = AllocateNode::Ideal_klass(obj, &_gvn);
1173   if (akls != NULL)  return akls;
1174   Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
1175   return _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), k_adr, TypeInstPtr::KLASS));
1176 }
1177 
1178 //-------------------------load_array_length-----------------------------------
1179 Node* GraphKit::load_array_length(Node* array) {
1180   // Special-case a fresh allocation to avoid building nodes:
1181   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(array, &_gvn);
1182   Node *alen;
1183   if (alloc == NULL) {
1184     Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes());
1185     alen = _gvn.transform( new LoadRangeNode(0, immutable_memory(), r_adr, TypeInt::POS));
1186   } else {
1187     alen = array_ideal_length(alloc, _gvn.type(array)->is_oopptr(), false);
1188   }
1189   return alen;
1190 }
1191 
1192 Node* GraphKit::array_ideal_length(AllocateArrayNode* alloc,
1193                                    const TypeOopPtr* oop_type,
1194                                    bool replace_length_in_map) {
1195   Node* length = alloc->Ideal_length();
1196   if (replace_length_in_map == false || map()->find_edge(length) >= 0) {
1197     Node* ccast = alloc->make_ideal_length(oop_type, &_gvn);
1198     if (ccast != length) {
1199       // do not transfrom ccast here, it might convert to top node for
1200       // negative array length and break assumptions in parsing stage.
1201       _gvn.set_type_bottom(ccast);
1202       record_for_igvn(ccast);
1203       if (replace_length_in_map) {
1204         replace_in_map(length, ccast);
1205       }
1206       return ccast;
1207     }
1208   }
1209   return length;
1210 }
1211 
1212 //------------------------------do_null_check----------------------------------
1213 // Helper function to do a NULL pointer check.  Returned value is
1214 // the incoming address with NULL casted away.  You are allowed to use the
1215 // not-null value only if you are control dependent on the test.
1216 #ifndef PRODUCT
1217 extern int explicit_null_checks_inserted,
1218            explicit_null_checks_elided;
1219 #endif
1220 Node* GraphKit::null_check_common(Node* value, BasicType type,
1221                                   // optional arguments for variations:
1222                                   bool assert_null,
1223                                   Node* *null_control,
1224                                   bool speculative) {
1225   assert(!assert_null || null_control == NULL, "not both at once");
1226   if (stopped())  return top();
1227   NOT_PRODUCT(explicit_null_checks_inserted++);
1228 
1229   // Construct NULL check
1230   Node *chk = NULL;
1231   switch(type) {
1232     case T_LONG   : chk = new CmpLNode(value, _gvn.zerocon(T_LONG)); break;
1233     case T_INT    : chk = new CmpINode(value, _gvn.intcon(0)); break;
1234     case T_ARRAY  : // fall through
1235       type = T_OBJECT;  // simplify further tests
1236     case T_OBJECT : {
1237       const Type *t = _gvn.type( value );
1238 
1239       const TypeOopPtr* tp = t->isa_oopptr();
1240       if (tp != NULL && tp->klass() != NULL && !tp->klass()->is_loaded()
1241           // Only for do_null_check, not any of its siblings:
1242           && !assert_null && null_control == NULL) {
1243         // Usually, any field access or invocation on an unloaded oop type
1244         // will simply fail to link, since the statically linked class is
1245         // likely also to be unloaded.  However, in -Xcomp mode, sometimes
1246         // the static class is loaded but the sharper oop type is not.
1247         // Rather than checking for this obscure case in lots of places,
1248         // we simply observe that a null check on an unloaded class
1249         // will always be followed by a nonsense operation, so we
1250         // can just issue the uncommon trap here.
1251         // Our access to the unloaded class will only be correct
1252         // after it has been loaded and initialized, which requires
1253         // a trip through the interpreter.
1254 #ifndef PRODUCT
1255         if (WizardMode) { tty->print("Null check of unloaded "); tp->klass()->print(); tty->cr(); }
1256 #endif
1257         uncommon_trap(Deoptimization::Reason_unloaded,
1258                       Deoptimization::Action_reinterpret,
1259                       tp->klass(), "!loaded");
1260         return top();
1261       }
1262 
1263       if (assert_null) {
1264         // See if the type is contained in NULL_PTR.
1265         // If so, then the value is already null.
1266         if (t->higher_equal(TypePtr::NULL_PTR)) {
1267           NOT_PRODUCT(explicit_null_checks_elided++);
1268           return value;           // Elided null assert quickly!
1269         }
1270       } else {
1271         // See if mixing in the NULL pointer changes type.
1272         // If so, then the NULL pointer was not allowed in the original
1273         // type.  In other words, "value" was not-null.
1274         if (t->meet(TypePtr::NULL_PTR) != t->remove_speculative()) {
1275           // same as: if (!TypePtr::NULL_PTR->higher_equal(t)) ...
1276           NOT_PRODUCT(explicit_null_checks_elided++);
1277           return value;           // Elided null check quickly!
1278         }
1279       }
1280       chk = new CmpPNode( value, null() );
1281       break;
1282     }
1283 
1284     default:
1285       fatal("unexpected type: %s", type2name(type));
1286   }
1287   assert(chk != NULL, "sanity check");
1288   chk = _gvn.transform(chk);
1289 
1290   BoolTest::mask btest = assert_null ? BoolTest::eq : BoolTest::ne;
1291   BoolNode *btst = new BoolNode( chk, btest);
1292   Node   *tst = _gvn.transform( btst );
1293 
1294   //-----------
1295   // if peephole optimizations occurred, a prior test existed.
1296   // If a prior test existed, maybe it dominates as we can avoid this test.
1297   if (tst != btst && type == T_OBJECT) {
1298     // At this point we want to scan up the CFG to see if we can
1299     // find an identical test (and so avoid this test altogether).
1300     Node *cfg = control();
1301     int depth = 0;
1302     while( depth < 16 ) {       // Limit search depth for speed
1303       if( cfg->Opcode() == Op_IfTrue &&
1304           cfg->in(0)->in(1) == tst ) {
1305         // Found prior test.  Use "cast_not_null" to construct an identical
1306         // CastPP (and hence hash to) as already exists for the prior test.
1307         // Return that casted value.
1308         if (assert_null) {
1309           replace_in_map(value, null());
1310           return null();  // do not issue the redundant test
1311         }
1312         Node *oldcontrol = control();
1313         set_control(cfg);
1314         Node *res = cast_not_null(value);
1315         set_control(oldcontrol);
1316         NOT_PRODUCT(explicit_null_checks_elided++);
1317         return res;
1318       }
1319       cfg = IfNode::up_one_dom(cfg, /*linear_only=*/ true);
1320       if (cfg == NULL)  break;  // Quit at region nodes
1321       depth++;
1322     }
1323   }
1324 
1325   //-----------
1326   // Branch to failure if null
1327   float ok_prob = PROB_MAX;  // a priori estimate:  nulls never happen
1328   Deoptimization::DeoptReason reason;
1329   if (assert_null) {
1330     reason = Deoptimization::reason_null_assert(speculative);
1331   } else if (type == T_OBJECT) {
1332     reason = Deoptimization::reason_null_check(speculative);
1333   } else {
1334     reason = Deoptimization::Reason_div0_check;
1335   }
1336   // %%% Since Reason_unhandled is not recorded on a per-bytecode basis,
1337   // ciMethodData::has_trap_at will return a conservative -1 if any
1338   // must-be-null assertion has failed.  This could cause performance
1339   // problems for a method after its first do_null_assert failure.
1340   // Consider using 'Reason_class_check' instead?
1341 
1342   // To cause an implicit null check, we set the not-null probability
1343   // to the maximum (PROB_MAX).  For an explicit check the probability
1344   // is set to a smaller value.
1345   if (null_control != NULL || too_many_traps(reason)) {
1346     // probability is less likely
1347     ok_prob =  PROB_LIKELY_MAG(3);
1348   } else if (!assert_null &&
1349              (ImplicitNullCheckThreshold > 0) &&
1350              method() != NULL &&
1351              (method()->method_data()->trap_count(reason)
1352               >= (uint)ImplicitNullCheckThreshold)) {
1353     ok_prob =  PROB_LIKELY_MAG(3);
1354   }
1355 
1356   if (null_control != NULL) {
1357     IfNode* iff = create_and_map_if(control(), tst, ok_prob, COUNT_UNKNOWN);
1358     Node* null_true = _gvn.transform( new IfFalseNode(iff));
1359     set_control(      _gvn.transform( new IfTrueNode(iff)));
1360 #ifndef PRODUCT
1361     if (null_true == top()) {
1362       explicit_null_checks_elided++;
1363     }
1364 #endif
1365     (*null_control) = null_true;
1366   } else {
1367     BuildCutout unless(this, tst, ok_prob);
1368     // Check for optimizer eliding test at parse time
1369     if (stopped()) {
1370       // Failure not possible; do not bother making uncommon trap.
1371       NOT_PRODUCT(explicit_null_checks_elided++);
1372     } else if (assert_null) {
1373       uncommon_trap(reason,
1374                     Deoptimization::Action_make_not_entrant,
1375                     NULL, "assert_null");
1376     } else {
1377       replace_in_map(value, zerocon(type));
1378       builtin_throw(reason);
1379     }
1380   }
1381 
1382   // Must throw exception, fall-thru not possible?
1383   if (stopped()) {
1384     return top();               // No result
1385   }
1386 
1387   if (assert_null) {
1388     // Cast obj to null on this path.
1389     replace_in_map(value, zerocon(type));
1390     return zerocon(type);
1391   }
1392 
1393   // Cast obj to not-null on this path, if there is no null_control.
1394   // (If there is a null_control, a non-null value may come back to haunt us.)
1395   if (type == T_OBJECT) {
1396     Node* cast = cast_not_null(value, false);
1397     if (null_control == NULL || (*null_control) == top())
1398       replace_in_map(value, cast);
1399     value = cast;
1400   }
1401 
1402   return value;
1403 }
1404 
1405 
1406 //------------------------------cast_not_null----------------------------------
1407 // Cast obj to not-null on this path
1408 Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) {
1409   const Type *t = _gvn.type(obj);
1410   const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL);
1411   // Object is already not-null?
1412   if( t == t_not_null ) return obj;
1413 
1414   Node *cast = new CastPPNode(obj,t_not_null);
1415   cast->init_req(0, control());
1416   cast = _gvn.transform( cast );
1417 
1418   // Scan for instances of 'obj' in the current JVM mapping.
1419   // These instances are known to be not-null after the test.
1420   if (do_replace_in_map)
1421     replace_in_map(obj, cast);
1422 
1423   return cast;                  // Return casted value
1424 }
1425 
1426 // Sometimes in intrinsics, we implicitly know an object is not null
1427 // (there's no actual null check) so we can cast it to not null. In
1428 // the course of optimizations, the input to the cast can become null.
1429 // In that case that data path will die and we need the control path
1430 // to become dead as well to keep the graph consistent. So we have to
1431 // add a check for null for which one branch can't be taken. It uses
1432 // an Opaque4 node that will cause the check to be removed after loop
1433 // opts so the test goes away and the compiled code doesn't execute a
1434 // useless check.
1435 Node* GraphKit::must_be_not_null(Node* value, bool do_replace_in_map) {
1436   if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(value))) {
1437     return value;
1438   }
1439   Node* chk = _gvn.transform(new CmpPNode(value, null()));
1440   Node *tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
1441   Node* opaq = _gvn.transform(new Opaque4Node(C, tst, intcon(1)));
1442   IfNode *iff = new IfNode(control(), opaq, PROB_MAX, COUNT_UNKNOWN);
1443   _gvn.set_type(iff, iff->Value(&_gvn));
1444   Node *if_f = _gvn.transform(new IfFalseNode(iff));
1445   Node *frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
1446   Node* halt = _gvn.transform(new HaltNode(if_f, frame, "unexpected null in intrinsic"));
1447   C->root()->add_req(halt);
1448   Node *if_t = _gvn.transform(new IfTrueNode(iff));
1449   set_control(if_t);
1450   return cast_not_null(value, do_replace_in_map);
1451 }
1452 
1453 
1454 //--------------------------replace_in_map-------------------------------------
1455 void GraphKit::replace_in_map(Node* old, Node* neww) {
1456   if (old == neww) {
1457     return;
1458   }
1459 
1460   map()->replace_edge(old, neww);
1461 
1462   // Note: This operation potentially replaces any edge
1463   // on the map.  This includes locals, stack, and monitors
1464   // of the current (innermost) JVM state.
1465 
1466   // don't let inconsistent types from profiling escape this
1467   // method
1468 
1469   const Type* told = _gvn.type(old);
1470   const Type* tnew = _gvn.type(neww);
1471 
1472   if (!tnew->higher_equal(told)) {
1473     return;
1474   }
1475 
1476   map()->record_replaced_node(old, neww);
1477 }
1478 
1479 
1480 //=============================================================================
1481 //--------------------------------memory---------------------------------------
1482 Node* GraphKit::memory(uint alias_idx) {
1483   MergeMemNode* mem = merged_memory();
1484   Node* p = mem->memory_at(alias_idx);
1485   assert(p != mem->empty_memory(), "empty");
1486   _gvn.set_type(p, Type::MEMORY);  // must be mapped
1487   return p;
1488 }
1489 
1490 //-----------------------------reset_memory------------------------------------
1491 Node* GraphKit::reset_memory() {
1492   Node* mem = map()->memory();
1493   // do not use this node for any more parsing!
1494   debug_only( map()->set_memory((Node*)NULL) );
1495   return _gvn.transform( mem );
1496 }
1497 
1498 //------------------------------set_all_memory---------------------------------
1499 void GraphKit::set_all_memory(Node* newmem) {
1500   Node* mergemem = MergeMemNode::make(newmem);
1501   gvn().set_type_bottom(mergemem);
1502   map()->set_memory(mergemem);
1503 }
1504 
1505 //------------------------------set_all_memory_call----------------------------
1506 void GraphKit::set_all_memory_call(Node* call, bool separate_io_proj) {
1507   Node* newmem = _gvn.transform( new ProjNode(call, TypeFunc::Memory, separate_io_proj) );
1508   set_all_memory(newmem);
1509 }
1510 
1511 //=============================================================================
1512 //
1513 // parser factory methods for MemNodes
1514 //
1515 // These are layered on top of the factory methods in LoadNode and StoreNode,
1516 // and integrate with the parser's memory state and _gvn engine.
1517 //
1518 
1519 // factory methods in "int adr_idx"
1520 Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,
1521                           int adr_idx,
1522                           MemNode::MemOrd mo,
1523                           LoadNode::ControlDependency control_dependency,
1524                           bool require_atomic_access,
1525                           bool unaligned,
1526                           bool mismatched,
1527                           bool unsafe,
1528                           uint8_t barrier_data) {
1529   assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );
1530   const TypePtr* adr_type = NULL; // debug-mode-only argument
1531   debug_only(adr_type = C->get_adr_type(adr_idx));
1532   Node* mem = memory(adr_idx);
1533   Node* ld;
1534   if (require_atomic_access && bt == T_LONG) {
1535     ld = LoadLNode::make_atomic(ctl, mem, adr, adr_type, t, mo, control_dependency, unaligned, mismatched, unsafe, barrier_data);
1536   } else if (require_atomic_access && bt == T_DOUBLE) {
1537     ld = LoadDNode::make_atomic(ctl, mem, adr, adr_type, t, mo, control_dependency, unaligned, mismatched, unsafe, barrier_data);
1538   } else {
1539     ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, unaligned, mismatched, unsafe, barrier_data);
1540   }
1541   ld = _gvn.transform(ld);
1542   if (((bt == T_OBJECT) && C->do_escape_analysis()) || C->eliminate_boxing()) {
1543     // Improve graph before escape analysis and boxing elimination.
1544     record_for_igvn(ld);
1545   }
1546   return ld;
1547 }
1548 
1549 Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,
1550                                 int adr_idx,
1551                                 MemNode::MemOrd mo,
1552                                 bool require_atomic_access,
1553                                 bool unaligned,
1554                                 bool mismatched,
1555                                 bool unsafe) {
1556   assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
1557   const TypePtr* adr_type = NULL;
1558   debug_only(adr_type = C->get_adr_type(adr_idx));
1559   Node *mem = memory(adr_idx);
1560   Node* st;
1561   if (require_atomic_access && bt == T_LONG) {
1562     st = StoreLNode::make_atomic(ctl, mem, adr, adr_type, val, mo);
1563   } else if (require_atomic_access && bt == T_DOUBLE) {
1564     st = StoreDNode::make_atomic(ctl, mem, adr, adr_type, val, mo);
1565   } else {
1566     st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo);
1567   }
1568   if (unaligned) {
1569     st->as_Store()->set_unaligned_access();
1570   }
1571   if (mismatched) {
1572     st->as_Store()->set_mismatched_access();
1573   }
1574   if (unsafe) {
1575     st->as_Store()->set_unsafe_access();
1576   }
1577   st = _gvn.transform(st);
1578   set_memory(st, adr_idx);
1579   // Back-to-back stores can only remove intermediate store with DU info
1580   // so push on worklist for optimizer.
1581   if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))
1582     record_for_igvn(st);
1583 
1584   return st;
1585 }
1586 
1587 Node* GraphKit::access_store_at(Node* obj,
1588                                 Node* adr,
1589                                 const TypePtr* adr_type,
1590                                 Node* val,
1591                                 const Type* val_type,
1592                                 BasicType bt,
1593                                 DecoratorSet decorators) {
1594   // Transformation of a value which could be NULL pointer (CastPP #NULL)
1595   // could be delayed during Parse (for example, in adjust_map_after_if()).
1596   // Execute transformation here to avoid barrier generation in such case.
1597   if (_gvn.type(val) == TypePtr::NULL_PTR) {
1598     val = _gvn.makecon(TypePtr::NULL_PTR);
1599   }
1600 
1601   if (stopped()) {
1602     return top(); // Dead path ?
1603   }
1604 
1605   assert(val != NULL, "not dead path");
1606 
1607   C2AccessValuePtr addr(adr, adr_type);
1608   C2AccessValue value(val, val_type);
1609   C2ParseAccess access(this, decorators | C2_WRITE_ACCESS, bt, obj, addr);
1610   if (access.is_raw()) {
1611     return _barrier_set->BarrierSetC2::store_at(access, value);
1612   } else {
1613     return _barrier_set->store_at(access, value);
1614   }
1615 }
1616 
1617 Node* GraphKit::access_load_at(Node* obj,   // containing obj
1618                                Node* adr,   // actual adress to store val at
1619                                const TypePtr* adr_type,
1620                                const Type* val_type,
1621                                BasicType bt,
1622                                DecoratorSet decorators) {
1623   if (stopped()) {
1624     return top(); // Dead path ?
1625   }
1626 
1627   C2AccessValuePtr addr(adr, adr_type);
1628   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, obj, addr);
1629   if (access.is_raw()) {
1630     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1631   } else {
1632     return _barrier_set->load_at(access, val_type);
1633   }
1634 }
1635 
1636 Node* GraphKit::access_load(Node* adr,   // actual adress to load val at
1637                             const Type* val_type,
1638                             BasicType bt,
1639                             DecoratorSet decorators) {
1640   if (stopped()) {
1641     return top(); // Dead path ?
1642   }
1643 
1644   C2AccessValuePtr addr(adr, adr->bottom_type()->is_ptr());
1645   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, NULL, addr);
1646   if (access.is_raw()) {
1647     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1648   } else {
1649     return _barrier_set->load_at(access, val_type);
1650   }
1651 }
1652 
1653 Node* GraphKit::access_atomic_cmpxchg_val_at(Node* obj,
1654                                              Node* adr,
1655                                              const TypePtr* adr_type,
1656                                              int alias_idx,
1657                                              Node* expected_val,
1658                                              Node* new_val,
1659                                              const Type* value_type,
1660                                              BasicType bt,
1661                                              DecoratorSet decorators) {
1662   C2AccessValuePtr addr(adr, adr_type);
1663   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,
1664                         bt, obj, addr, alias_idx);
1665   if (access.is_raw()) {
1666     return _barrier_set->BarrierSetC2::atomic_cmpxchg_val_at(access, expected_val, new_val, value_type);
1667   } else {
1668     return _barrier_set->atomic_cmpxchg_val_at(access, expected_val, new_val, value_type);
1669   }
1670 }
1671 
1672 Node* GraphKit::access_atomic_cmpxchg_bool_at(Node* obj,
1673                                               Node* adr,
1674                                               const TypePtr* adr_type,
1675                                               int alias_idx,
1676                                               Node* expected_val,
1677                                               Node* new_val,
1678                                               const Type* value_type,
1679                                               BasicType bt,
1680                                               DecoratorSet decorators) {
1681   C2AccessValuePtr addr(adr, adr_type);
1682   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,
1683                         bt, obj, addr, alias_idx);
1684   if (access.is_raw()) {
1685     return _barrier_set->BarrierSetC2::atomic_cmpxchg_bool_at(access, expected_val, new_val, value_type);
1686   } else {
1687     return _barrier_set->atomic_cmpxchg_bool_at(access, expected_val, new_val, value_type);
1688   }
1689 }
1690 
1691 Node* GraphKit::access_atomic_xchg_at(Node* obj,
1692                                       Node* adr,
1693                                       const TypePtr* adr_type,
1694                                       int alias_idx,
1695                                       Node* new_val,
1696                                       const Type* value_type,
1697                                       BasicType bt,
1698                                       DecoratorSet decorators) {
1699   C2AccessValuePtr addr(adr, adr_type);
1700   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,
1701                         bt, obj, addr, alias_idx);
1702   if (access.is_raw()) {
1703     return _barrier_set->BarrierSetC2::atomic_xchg_at(access, new_val, value_type);
1704   } else {
1705     return _barrier_set->atomic_xchg_at(access, new_val, value_type);
1706   }
1707 }
1708 
1709 Node* GraphKit::access_atomic_add_at(Node* obj,
1710                                      Node* adr,
1711                                      const TypePtr* adr_type,
1712                                      int alias_idx,
1713                                      Node* new_val,
1714                                      const Type* value_type,
1715                                      BasicType bt,
1716                                      DecoratorSet decorators) {
1717   C2AccessValuePtr addr(adr, adr_type);
1718   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, bt, obj, addr, alias_idx);
1719   if (access.is_raw()) {
1720     return _barrier_set->BarrierSetC2::atomic_add_at(access, new_val, value_type);
1721   } else {
1722     return _barrier_set->atomic_add_at(access, new_val, value_type);
1723   }
1724 }
1725 
1726 void GraphKit::access_clone(Node* src, Node* dst, Node* size, bool is_array) {
1727   return _barrier_set->clone(this, src, dst, size, is_array);
1728 }
1729 
1730 //-------------------------array_element_address-------------------------
1731 Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,
1732                                       const TypeInt* sizetype, Node* ctrl) {
1733   uint shift  = exact_log2(type2aelembytes(elembt));
1734   uint header = arrayOopDesc::base_offset_in_bytes(elembt);
1735 
1736   // short-circuit a common case (saves lots of confusing waste motion)
1737   jint idx_con = find_int_con(idx, -1);
1738   if (idx_con >= 0) {
1739     intptr_t offset = header + ((intptr_t)idx_con << shift);
1740     return basic_plus_adr(ary, offset);
1741   }
1742 
1743   // must be correct type for alignment purposes
1744   Node* base  = basic_plus_adr(ary, header);
1745   idx = Compile::conv_I2X_index(&_gvn, idx, sizetype, ctrl);
1746   Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) );
1747   return basic_plus_adr(ary, base, scale);
1748 }
1749 
1750 //-------------------------load_array_element-------------------------
1751 Node* GraphKit::load_array_element(Node* ary, Node* idx, const TypeAryPtr* arytype, bool set_ctrl) {
1752   const Type* elemtype = arytype->elem();
1753   BasicType elembt = elemtype->array_element_basic_type();
1754   Node* adr = array_element_address(ary, idx, elembt, arytype->size());
1755   if (elembt == T_NARROWOOP) {
1756     elembt = T_OBJECT; // To satisfy switch in LoadNode::make()
1757   }
1758   Node* ld = access_load_at(ary, adr, arytype, elemtype, elembt,
1759                             IN_HEAP | IS_ARRAY | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0));
1760   return ld;
1761 }
1762 
1763 //-------------------------set_arguments_for_java_call-------------------------
1764 // Arguments (pre-popped from the stack) are taken from the JVMS.
1765 void GraphKit::set_arguments_for_java_call(CallJavaNode* call) {
1766   // Add the call arguments:
1767   uint nargs = call->method()->arg_size();
1768   for (uint i = 0; i < nargs; i++) {
1769     Node* arg = argument(i);
1770     call->init_req(i + TypeFunc::Parms, arg);
1771   }
1772 }
1773 
1774 //---------------------------set_edges_for_java_call---------------------------
1775 // Connect a newly created call into the current JVMS.
1776 // A return value node (if any) is returned from set_edges_for_java_call.
1777 void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) {
1778 
1779   // Add the predefined inputs:
1780   call->init_req( TypeFunc::Control, control() );
1781   call->init_req( TypeFunc::I_O    , i_o() );
1782   call->init_req( TypeFunc::Memory , reset_memory() );
1783   call->init_req( TypeFunc::FramePtr, frameptr() );
1784   call->init_req( TypeFunc::ReturnAdr, top() );
1785 
1786   add_safepoint_edges(call, must_throw);
1787 
1788   Node* xcall = _gvn.transform(call);
1789 
1790   if (xcall == top()) {
1791     set_control(top());
1792     return;
1793   }
1794   assert(xcall == call, "call identity is stable");
1795 
1796   // Re-use the current map to produce the result.
1797 
1798   set_control(_gvn.transform(new ProjNode(call, TypeFunc::Control)));
1799   set_i_o(    _gvn.transform(new ProjNode(call, TypeFunc::I_O    , separate_io_proj)));
1800   set_all_memory_call(xcall, separate_io_proj);
1801 
1802   //return xcall;   // no need, caller already has it
1803 }
1804 
1805 Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj, bool deoptimize) {
1806   if (stopped())  return top();  // maybe the call folded up?
1807 
1808   // Capture the return value, if any.
1809   Node* ret;
1810   if (call->method() == NULL ||
1811       call->method()->return_type()->basic_type() == T_VOID)
1812         ret = top();
1813   else  ret = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1814 
1815   // Note:  Since any out-of-line call can produce an exception,
1816   // we always insert an I_O projection from the call into the result.
1817 
1818   make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj, deoptimize);
1819 
1820   if (separate_io_proj) {
1821     // The caller requested separate projections be used by the fall
1822     // through and exceptional paths, so replace the projections for
1823     // the fall through path.
1824     set_i_o(_gvn.transform( new ProjNode(call, TypeFunc::I_O) ));
1825     set_all_memory(_gvn.transform( new ProjNode(call, TypeFunc::Memory) ));
1826   }
1827   return ret;
1828 }
1829 
1830 //--------------------set_predefined_input_for_runtime_call--------------------
1831 // Reading and setting the memory state is way conservative here.
1832 // The real problem is that I am not doing real Type analysis on memory,
1833 // so I cannot distinguish card mark stores from other stores.  Across a GC
1834 // point the Store Barrier and the card mark memory has to agree.  I cannot
1835 // have a card mark store and its barrier split across the GC point from
1836 // either above or below.  Here I get that to happen by reading ALL of memory.
1837 // A better answer would be to separate out card marks from other memory.
1838 // For now, return the input memory state, so that it can be reused
1839 // after the call, if this call has restricted memory effects.
1840 Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) {
1841   // Set fixed predefined input arguments
1842   Node* memory = reset_memory();
1843   Node* m = narrow_mem == NULL ? memory : narrow_mem;
1844   call->init_req( TypeFunc::Control,   control()  );
1845   call->init_req( TypeFunc::I_O,       top()      ); // does no i/o
1846   call->init_req( TypeFunc::Memory,    m          ); // may gc ptrs
1847   call->init_req( TypeFunc::FramePtr,  frameptr() );
1848   call->init_req( TypeFunc::ReturnAdr, top()      );
1849   return memory;
1850 }
1851 
1852 //-------------------set_predefined_output_for_runtime_call--------------------
1853 // Set control and memory (not i_o) from the call.
1854 // If keep_mem is not NULL, use it for the output state,
1855 // except for the RawPtr output of the call, if hook_mem is TypeRawPtr::BOTTOM.
1856 // If hook_mem is NULL, this call produces no memory effects at all.
1857 // If hook_mem is a Java-visible memory slice (such as arraycopy operands),
1858 // then only that memory slice is taken from the call.
1859 // In the last case, we must put an appropriate memory barrier before
1860 // the call, so as to create the correct anti-dependencies on loads
1861 // preceding the call.
1862 void GraphKit::set_predefined_output_for_runtime_call(Node* call,
1863                                                       Node* keep_mem,
1864                                                       const TypePtr* hook_mem) {
1865   // no i/o
1866   set_control(_gvn.transform( new ProjNode(call,TypeFunc::Control) ));
1867   if (keep_mem) {
1868     // First clone the existing memory state
1869     set_all_memory(keep_mem);
1870     if (hook_mem != NULL) {
1871       // Make memory for the call
1872       Node* mem = _gvn.transform( new ProjNode(call, TypeFunc::Memory) );
1873       // Set the RawPtr memory state only.  This covers all the heap top/GC stuff
1874       // We also use hook_mem to extract specific effects from arraycopy stubs.
1875       set_memory(mem, hook_mem);
1876     }
1877     // ...else the call has NO memory effects.
1878 
1879     // Make sure the call advertises its memory effects precisely.
1880     // This lets us build accurate anti-dependences in gcm.cpp.
1881     assert(C->alias_type(call->adr_type()) == C->alias_type(hook_mem),
1882            "call node must be constructed correctly");
1883   } else {
1884     assert(hook_mem == NULL, "");
1885     // This is not a "slow path" call; all memory comes from the call.
1886     set_all_memory_call(call);
1887   }
1888 }
1889 
1890 // Keep track of MergeMems feeding into other MergeMems
1891 static void add_mergemem_users_to_worklist(Unique_Node_List& wl, Node* mem) {
1892   if (!mem->is_MergeMem()) {
1893     return;
1894   }
1895   for (SimpleDUIterator i(mem); i.has_next(); i.next()) {
1896     Node* use = i.get();
1897     if (use->is_MergeMem()) {
1898       wl.push(use);
1899     }
1900   }
1901 }
1902 
1903 // Replace the call with the current state of the kit.
1904 void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes) {
1905   JVMState* ejvms = NULL;
1906   if (has_exceptions()) {
1907     ejvms = transfer_exceptions_into_jvms();
1908   }
1909 
1910   ReplacedNodes replaced_nodes = map()->replaced_nodes();
1911   ReplacedNodes replaced_nodes_exception;
1912   Node* ex_ctl = top();
1913 
1914   SafePointNode* final_state = stop();
1915 
1916   // Find all the needed outputs of this call
1917   CallProjections callprojs;
1918   call->extract_projections(&callprojs, true);
1919 
1920   Unique_Node_List wl;
1921   Node* init_mem = call->in(TypeFunc::Memory);
1922   Node* final_mem = final_state->in(TypeFunc::Memory);
1923   Node* final_ctl = final_state->in(TypeFunc::Control);
1924   Node* final_io = final_state->in(TypeFunc::I_O);
1925 
1926   // Replace all the old call edges with the edges from the inlining result
1927   if (callprojs.fallthrough_catchproj != NULL) {
1928     C->gvn_replace_by(callprojs.fallthrough_catchproj, final_ctl);
1929   }
1930   if (callprojs.fallthrough_memproj != NULL) {
1931     if (final_mem->is_MergeMem()) {
1932       // Parser's exits MergeMem was not transformed but may be optimized
1933       final_mem = _gvn.transform(final_mem);
1934     }
1935     C->gvn_replace_by(callprojs.fallthrough_memproj,   final_mem);
1936     add_mergemem_users_to_worklist(wl, final_mem);
1937   }
1938   if (callprojs.fallthrough_ioproj != NULL) {
1939     C->gvn_replace_by(callprojs.fallthrough_ioproj,    final_io);
1940   }
1941 
1942   // Replace the result with the new result if it exists and is used
1943   if (callprojs.resproj != NULL && result != NULL) {
1944     C->gvn_replace_by(callprojs.resproj, result);
1945   }
1946 
1947   if (ejvms == NULL) {
1948     // No exception edges to simply kill off those paths
1949     if (callprojs.catchall_catchproj != NULL) {
1950       C->gvn_replace_by(callprojs.catchall_catchproj, C->top());
1951     }
1952     if (callprojs.catchall_memproj != NULL) {
1953       C->gvn_replace_by(callprojs.catchall_memproj,   C->top());
1954     }
1955     if (callprojs.catchall_ioproj != NULL) {
1956       C->gvn_replace_by(callprojs.catchall_ioproj,    C->top());
1957     }
1958     // Replace the old exception object with top
1959     if (callprojs.exobj != NULL) {
1960       C->gvn_replace_by(callprojs.exobj, C->top());
1961     }
1962   } else {
1963     GraphKit ekit(ejvms);
1964 
1965     // Load my combined exception state into the kit, with all phis transformed:
1966     SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();
1967     replaced_nodes_exception = ex_map->replaced_nodes();
1968 
1969     Node* ex_oop = ekit.use_exception_state(ex_map);
1970 
1971     if (callprojs.catchall_catchproj != NULL) {
1972       C->gvn_replace_by(callprojs.catchall_catchproj, ekit.control());
1973       ex_ctl = ekit.control();
1974     }
1975     if (callprojs.catchall_memproj != NULL) {
1976       Node* ex_mem = ekit.reset_memory();
1977       C->gvn_replace_by(callprojs.catchall_memproj,   ex_mem);
1978       add_mergemem_users_to_worklist(wl, ex_mem);
1979     }
1980     if (callprojs.catchall_ioproj != NULL) {
1981       C->gvn_replace_by(callprojs.catchall_ioproj,    ekit.i_o());
1982     }
1983 
1984     // Replace the old exception object with the newly created one
1985     if (callprojs.exobj != NULL) {
1986       C->gvn_replace_by(callprojs.exobj, ex_oop);
1987     }
1988   }
1989 
1990   // Disconnect the call from the graph
1991   call->disconnect_inputs(C);
1992   C->gvn_replace_by(call, C->top());
1993 
1994   // Clean up any MergeMems that feed other MergeMems since the
1995   // optimizer doesn't like that.
1996   while (wl.size() > 0) {
1997     _gvn.transform(wl.pop());
1998   }
1999 
2000   if (callprojs.fallthrough_catchproj != NULL && !final_ctl->is_top() && do_replaced_nodes) {
2001     replaced_nodes.apply(C, final_ctl);
2002   }
2003   if (!ex_ctl->is_top() && do_replaced_nodes) {
2004     replaced_nodes_exception.apply(C, ex_ctl);
2005   }
2006 }
2007 
2008 
2009 //------------------------------increment_counter------------------------------
2010 // for statistics: increment a VM counter by 1
2011 
2012 void GraphKit::increment_counter(address counter_addr) {
2013   Node* adr1 = makecon(TypeRawPtr::make(counter_addr));
2014   increment_counter(adr1);
2015 }
2016 
2017 void GraphKit::increment_counter(Node* counter_addr) {
2018   int adr_type = Compile::AliasIdxRaw;
2019   Node* ctrl = control();
2020   Node* cnt  = make_load(ctrl, counter_addr, TypeLong::LONG, T_LONG, adr_type, MemNode::unordered);
2021   Node* incr = _gvn.transform(new AddLNode(cnt, _gvn.longcon(1)));
2022   store_to_memory(ctrl, counter_addr, incr, T_LONG, adr_type, MemNode::unordered);
2023 }
2024 
2025 
2026 //------------------------------uncommon_trap----------------------------------
2027 // Bail out to the interpreter in mid-method.  Implemented by calling the
2028 // uncommon_trap blob.  This helper function inserts a runtime call with the
2029 // right debug info.
2030 void GraphKit::uncommon_trap(int trap_request,
2031                              ciKlass* klass, const char* comment,
2032                              bool must_throw,
2033                              bool keep_exact_action) {
2034   if (failing())  stop();
2035   if (stopped())  return; // trap reachable?
2036 
2037   // Note:  If ProfileTraps is true, and if a deopt. actually
2038   // occurs here, the runtime will make sure an MDO exists.  There is
2039   // no need to call method()->ensure_method_data() at this point.
2040 
2041   // Set the stack pointer to the right value for reexecution:
2042   set_sp(reexecute_sp());
2043 
2044 #ifdef ASSERT
2045   if (!must_throw) {
2046     // Make sure the stack has at least enough depth to execute
2047     // the current bytecode.
2048     int inputs, ignored_depth;
2049     if (compute_stack_effects(inputs, ignored_depth)) {
2050       assert(sp() >= inputs, "must have enough JVMS stack to execute %s: sp=%d, inputs=%d",
2051              Bytecodes::name(java_bc()), sp(), inputs);
2052     }
2053   }
2054 #endif
2055 
2056   Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);
2057   Deoptimization::DeoptAction action = Deoptimization::trap_request_action(trap_request);
2058 
2059   switch (action) {
2060   case Deoptimization::Action_maybe_recompile:
2061   case Deoptimization::Action_reinterpret:
2062     // Temporary fix for 6529811 to allow virtual calls to be sure they
2063     // get the chance to go from mono->bi->mega
2064     if (!keep_exact_action &&
2065         Deoptimization::trap_request_index(trap_request) < 0 &&
2066         too_many_recompiles(reason)) {
2067       // This BCI is causing too many recompilations.
2068       if (C->log() != NULL) {
2069         C->log()->elem("observe that='trap_action_change' reason='%s' from='%s' to='none'",
2070                 Deoptimization::trap_reason_name(reason),
2071                 Deoptimization::trap_action_name(action));
2072       }
2073       action = Deoptimization::Action_none;
2074       trap_request = Deoptimization::make_trap_request(reason, action);
2075     } else {
2076       C->set_trap_can_recompile(true);
2077     }
2078     break;
2079   case Deoptimization::Action_make_not_entrant:
2080     C->set_trap_can_recompile(true);
2081     break;
2082   case Deoptimization::Action_none:
2083   case Deoptimization::Action_make_not_compilable:
2084     break;
2085   default:
2086 #ifdef ASSERT
2087     fatal("unknown action %d: %s", action, Deoptimization::trap_action_name(action));
2088 #endif
2089     break;
2090   }
2091 
2092   if (TraceOptoParse) {
2093     char buf[100];
2094     tty->print_cr("Uncommon trap %s at bci:%d",
2095                   Deoptimization::format_trap_request(buf, sizeof(buf),
2096                                                       trap_request), bci());
2097   }
2098 
2099   CompileLog* log = C->log();
2100   if (log != NULL) {
2101     int kid = (klass == NULL)? -1: log->identify(klass);
2102     log->begin_elem("uncommon_trap bci='%d'", bci());
2103     char buf[100];
2104     log->print(" %s", Deoptimization::format_trap_request(buf, sizeof(buf),
2105                                                           trap_request));
2106     if (kid >= 0)         log->print(" klass='%d'", kid);
2107     if (comment != NULL)  log->print(" comment='%s'", comment);
2108     log->end_elem();
2109   }
2110 
2111   // Make sure any guarding test views this path as very unlikely
2112   Node *i0 = control()->in(0);
2113   if (i0 != NULL && i0->is_If()) {        // Found a guarding if test?
2114     IfNode *iff = i0->as_If();
2115     float f = iff->_prob;   // Get prob
2116     if (control()->Opcode() == Op_IfTrue) {
2117       if (f > PROB_UNLIKELY_MAG(4))
2118         iff->_prob = PROB_MIN;
2119     } else {
2120       if (f < PROB_LIKELY_MAG(4))
2121         iff->_prob = PROB_MAX;
2122     }
2123   }
2124 
2125   // Clear out dead values from the debug info.
2126   kill_dead_locals();
2127 
2128   // Now insert the uncommon trap subroutine call
2129   address call_addr = SharedRuntime::uncommon_trap_blob()->entry_point();
2130   const TypePtr* no_memory_effects = NULL;
2131   // Pass the index of the class to be loaded
2132   Node* call = make_runtime_call(RC_NO_LEAF | RC_UNCOMMON |
2133                                  (must_throw ? RC_MUST_THROW : 0),
2134                                  OptoRuntime::uncommon_trap_Type(),
2135                                  call_addr, "uncommon_trap", no_memory_effects,
2136                                  intcon(trap_request));
2137   assert(call->as_CallStaticJava()->uncommon_trap_request() == trap_request,
2138          "must extract request correctly from the graph");
2139   assert(trap_request != 0, "zero value reserved by uncommon_trap_request");
2140 
2141   call->set_req(TypeFunc::ReturnAdr, returnadr());
2142   // The debug info is the only real input to this call.
2143 
2144   // Halt-and-catch fire here.  The above call should never return!
2145   HaltNode* halt = new HaltNode(control(), frameptr(), "uncommon trap returned which should never happen"
2146                                                        PRODUCT_ONLY(COMMA /*reachable*/false));
2147   _gvn.set_type_bottom(halt);
2148   root()->add_req(halt);
2149 
2150   stop_and_kill_map();
2151 }
2152 
2153 
2154 //--------------------------just_allocated_object------------------------------
2155 // Report the object that was just allocated.
2156 // It must be the case that there are no intervening safepoints.
2157 // We use this to determine if an object is so "fresh" that
2158 // it does not require card marks.
2159 Node* GraphKit::just_allocated_object(Node* current_control) {
2160   Node* ctrl = current_control;
2161   // Object::<init> is invoked after allocation, most of invoke nodes
2162   // will be reduced, but a region node is kept in parse time, we check
2163   // the pattern and skip the region node if it degraded to a copy.
2164   if (ctrl != NULL && ctrl->is_Region() && ctrl->req() == 2 &&
2165       ctrl->as_Region()->is_copy()) {
2166     ctrl = ctrl->as_Region()->is_copy();
2167   }
2168   if (C->recent_alloc_ctl() == ctrl) {
2169    return C->recent_alloc_obj();
2170   }
2171   return NULL;
2172 }
2173 
2174 
2175 /**
2176  * Record profiling data exact_kls for Node n with the type system so
2177  * that it can propagate it (speculation)
2178  *
2179  * @param n          node that the type applies to
2180  * @param exact_kls  type from profiling
2181  * @param maybe_null did profiling see null?
2182  *
2183  * @return           node with improved type
2184  */
2185 Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, ProfilePtrKind ptr_kind) {
2186   const Type* current_type = _gvn.type(n);
2187   assert(UseTypeSpeculation, "type speculation must be on");
2188 
2189   const TypePtr* speculative = current_type->speculative();
2190 
2191   // Should the klass from the profile be recorded in the speculative type?
2192   if (current_type->would_improve_type(exact_kls, jvms()->depth())) {
2193     const TypeKlassPtr* tklass = TypeKlassPtr::make(exact_kls);
2194     const TypeOopPtr* xtype = tklass->as_instance_type();
2195     assert(xtype->klass_is_exact(), "Should be exact");
2196     // Any reason to believe n is not null (from this profiling or a previous one)?
2197     assert(ptr_kind != ProfileAlwaysNull, "impossible here");
2198     const TypePtr* ptr = (ptr_kind == ProfileMaybeNull && current_type->speculative_maybe_null()) ? TypePtr::BOTTOM : TypePtr::NOTNULL;
2199     // record the new speculative type's depth
2200     speculative = xtype->cast_to_ptr_type(ptr->ptr())->is_ptr();
2201     speculative = speculative->with_inline_depth(jvms()->depth());
2202   } else if (current_type->would_improve_ptr(ptr_kind)) {
2203     // Profiling report that null was never seen so we can change the
2204     // speculative type to non null ptr.
2205     if (ptr_kind == ProfileAlwaysNull) {
2206       speculative = TypePtr::NULL_PTR;
2207     } else {
2208       assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement");
2209       const TypePtr* ptr = TypePtr::NOTNULL;
2210       if (speculative != NULL) {
2211         speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr();
2212       } else {
2213         speculative = ptr;
2214       }
2215     }
2216   }
2217 
2218   if (speculative != current_type->speculative()) {
2219     // Build a type with a speculative type (what we think we know
2220     // about the type but will need a guard when we use it)
2221     const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::OffsetBot, TypeOopPtr::InstanceBot, speculative);
2222     // We're changing the type, we need a new CheckCast node to carry
2223     // the new type. The new type depends on the control: what
2224     // profiling tells us is only valid from here as far as we can
2225     // tell.
2226     Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));
2227     cast = _gvn.transform(cast);
2228     replace_in_map(n, cast);
2229     n = cast;
2230   }
2231 
2232   return n;
2233 }
2234 
2235 /**
2236  * Record profiling data from receiver profiling at an invoke with the
2237  * type system so that it can propagate it (speculation)
2238  *
2239  * @param n  receiver node
2240  *
2241  * @return   node with improved type
2242  */
2243 Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {
2244   if (!UseTypeSpeculation) {
2245     return n;
2246   }
2247   ciKlass* exact_kls = profile_has_unique_klass();
2248   ProfilePtrKind ptr_kind = ProfileMaybeNull;
2249   if ((java_bc() == Bytecodes::_checkcast ||
2250        java_bc() == Bytecodes::_instanceof ||
2251        java_bc() == Bytecodes::_aastore) &&
2252       method()->method_data()->is_mature()) {
2253     ciProfileData* data = method()->method_data()->bci_to_data(bci());
2254     if (data != NULL) {
2255       if (!data->as_BitData()->null_seen()) {
2256         ptr_kind = ProfileNeverNull;
2257       } else {
2258         assert(data->is_ReceiverTypeData(), "bad profile data type");
2259         ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
2260         uint i = 0;
2261         for (; i < call->row_limit(); i++) {
2262           ciKlass* receiver = call->receiver(i);
2263           if (receiver != NULL) {
2264             break;
2265           }
2266         }
2267         ptr_kind = (i == call->row_limit()) ? ProfileAlwaysNull : ProfileMaybeNull;
2268       }
2269     }
2270   }
2271   return record_profile_for_speculation(n, exact_kls, ptr_kind);
2272 }
2273 
2274 /**
2275  * Record profiling data from argument profiling at an invoke with the
2276  * type system so that it can propagate it (speculation)
2277  *
2278  * @param dest_method  target method for the call
2279  * @param bc           what invoke bytecode is this?
2280  */
2281 void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {
2282   if (!UseTypeSpeculation) {
2283     return;
2284   }
2285   const TypeFunc* tf    = TypeFunc::make(dest_method);
2286   int             nargs = tf->domain()->cnt() - TypeFunc::Parms;
2287   int skip = Bytecodes::has_receiver(bc) ? 1 : 0;
2288   for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {
2289     const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);
2290     if (is_reference_type(targ->basic_type())) {
2291       ProfilePtrKind ptr_kind = ProfileMaybeNull;
2292       ciKlass* better_type = NULL;
2293       if (method()->argument_profiled_type(bci(), i, better_type, ptr_kind)) {
2294         record_profile_for_speculation(argument(j), better_type, ptr_kind);
2295       }
2296       i++;
2297     }
2298   }
2299 }
2300 
2301 /**
2302  * Record profiling data from parameter profiling at an invoke with
2303  * the type system so that it can propagate it (speculation)
2304  */
2305 void GraphKit::record_profiled_parameters_for_speculation() {
2306   if (!UseTypeSpeculation) {
2307     return;
2308   }
2309   for (int i = 0, j = 0; i < method()->arg_size() ; i++) {
2310     if (_gvn.type(local(i))->isa_oopptr()) {
2311       ProfilePtrKind ptr_kind = ProfileMaybeNull;
2312       ciKlass* better_type = NULL;
2313       if (method()->parameter_profiled_type(j, better_type, ptr_kind)) {
2314         record_profile_for_speculation(local(i), better_type, ptr_kind);
2315       }
2316       j++;
2317     }
2318   }
2319 }
2320 
2321 /**
2322  * Record profiling data from return value profiling at an invoke with
2323  * the type system so that it can propagate it (speculation)
2324  */
2325 void GraphKit::record_profiled_return_for_speculation() {
2326   if (!UseTypeSpeculation) {
2327     return;
2328   }
2329   ProfilePtrKind ptr_kind = ProfileMaybeNull;
2330   ciKlass* better_type = NULL;
2331   if (method()->return_profiled_type(bci(), better_type, ptr_kind)) {
2332     // If profiling reports a single type for the return value,
2333     // feed it to the type system so it can propagate it as a
2334     // speculative type
2335     record_profile_for_speculation(stack(sp()-1), better_type, ptr_kind);
2336   }
2337 }
2338 
2339 void GraphKit::round_double_arguments(ciMethod* dest_method) {
2340   if (Matcher::strict_fp_requires_explicit_rounding) {
2341     // (Note:  TypeFunc::make has a cache that makes this fast.)
2342     const TypeFunc* tf    = TypeFunc::make(dest_method);
2343     int             nargs = tf->domain()->cnt() - TypeFunc::Parms;
2344     for (int j = 0; j < nargs; j++) {
2345       const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);
2346       if (targ->basic_type() == T_DOUBLE) {
2347         // If any parameters are doubles, they must be rounded before
2348         // the call, dstore_rounding does gvn.transform
2349         Node *arg = argument(j);
2350         arg = dstore_rounding(arg);
2351         set_argument(j, arg);
2352       }
2353     }
2354   }
2355 }
2356 
2357 // rounding for strict float precision conformance
2358 Node* GraphKit::precision_rounding(Node* n) {
2359   if (Matcher::strict_fp_requires_explicit_rounding) {
2360 #ifdef IA32
2361     if (UseSSE == 0) {
2362       return _gvn.transform(new RoundFloatNode(0, n));
2363     }
2364 #else
2365     Unimplemented();
2366 #endif // IA32
2367   }
2368   return n;
2369 }
2370 
2371 // rounding for strict double precision conformance
2372 Node* GraphKit::dprecision_rounding(Node *n) {
2373   if (Matcher::strict_fp_requires_explicit_rounding) {
2374 #ifdef IA32
2375     if (UseSSE < 2) {
2376       return _gvn.transform(new RoundDoubleNode(0, n));
2377     }
2378 #else
2379     Unimplemented();
2380 #endif // IA32
2381   }
2382   return n;
2383 }
2384 
2385 // rounding for non-strict double stores
2386 Node* GraphKit::dstore_rounding(Node* n) {
2387   if (Matcher::strict_fp_requires_explicit_rounding) {
2388 #ifdef IA32
2389     if (UseSSE < 2) {
2390       return _gvn.transform(new RoundDoubleNode(0, n));
2391     }
2392 #else
2393     Unimplemented();
2394 #endif // IA32
2395   }
2396   return n;
2397 }
2398 
2399 //=============================================================================
2400 // Generate a fast path/slow path idiom.  Graph looks like:
2401 // [foo] indicates that 'foo' is a parameter
2402 //
2403 //              [in]     NULL
2404 //                 \    /
2405 //                  CmpP
2406 //                  Bool ne
2407 //                   If
2408 //                  /  \
2409 //              True    False-<2>
2410 //              / |
2411 //             /  cast_not_null
2412 //           Load  |    |   ^
2413 //        [fast_test]   |   |
2414 // gvn to   opt_test    |   |
2415 //          /    \      |  <1>
2416 //      True     False  |
2417 //        |         \\  |
2418 //   [slow_call]     \[fast_result]
2419 //    Ctl   Val       \      \
2420 //     |               \      \
2421 //    Catch       <1>   \      \
2422 //   /    \        ^     \      \
2423 //  Ex    No_Ex    |      \      \
2424 //  |       \   \  |       \ <2>  \
2425 //  ...      \  [slow_res] |  |    \   [null_result]
2426 //            \         \--+--+---  |  |
2427 //             \           | /    \ | /
2428 //              --------Region     Phi
2429 //
2430 //=============================================================================
2431 // Code is structured as a series of driver functions all called 'do_XXX' that
2432 // call a set of helper functions.  Helper functions first, then drivers.
2433 
2434 //------------------------------null_check_oop---------------------------------
2435 // Null check oop.  Set null-path control into Region in slot 3.
2436 // Make a cast-not-nullness use the other not-null control.  Return cast.
2437 Node* GraphKit::null_check_oop(Node* value, Node* *null_control,
2438                                bool never_see_null,
2439                                bool safe_for_replace,
2440                                bool speculative) {
2441   // Initial NULL check taken path
2442   (*null_control) = top();
2443   Node* cast = null_check_common(value, T_OBJECT, false, null_control, speculative);
2444 
2445   // Generate uncommon_trap:
2446   if (never_see_null && (*null_control) != top()) {
2447     // If we see an unexpected null at a check-cast we record it and force a
2448     // recompile; the offending check-cast will be compiled to handle NULLs.
2449     // If we see more than one offending BCI, then all checkcasts in the
2450     // method will be compiled to handle NULLs.
2451     PreserveJVMState pjvms(this);
2452     set_control(*null_control);
2453     replace_in_map(value, null());
2454     Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculative);
2455     uncommon_trap(reason,
2456                   Deoptimization::Action_make_not_entrant);
2457     (*null_control) = top();    // NULL path is dead
2458   }
2459   if ((*null_control) == top() && safe_for_replace) {
2460     replace_in_map(value, cast);
2461   }
2462 
2463   // Cast away null-ness on the result
2464   return cast;
2465 }
2466 
2467 //------------------------------opt_iff----------------------------------------
2468 // Optimize the fast-check IfNode.  Set the fast-path region slot 2.
2469 // Return slow-path control.
2470 Node* GraphKit::opt_iff(Node* region, Node* iff) {
2471   IfNode *opt_iff = _gvn.transform(iff)->as_If();
2472 
2473   // Fast path taken; set region slot 2
2474   Node *fast_taken = _gvn.transform( new IfFalseNode(opt_iff) );
2475   region->init_req(2,fast_taken); // Capture fast-control
2476 
2477   // Fast path not-taken, i.e. slow path
2478   Node *slow_taken = _gvn.transform( new IfTrueNode(opt_iff) );
2479   return slow_taken;
2480 }
2481 
2482 //-----------------------------make_runtime_call-------------------------------
2483 Node* GraphKit::make_runtime_call(int flags,
2484                                   const TypeFunc* call_type, address call_addr,
2485                                   const char* call_name,
2486                                   const TypePtr* adr_type,
2487                                   // The following parms are all optional.
2488                                   // The first NULL ends the list.
2489                                   Node* parm0, Node* parm1,
2490                                   Node* parm2, Node* parm3,
2491                                   Node* parm4, Node* parm5,
2492                                   Node* parm6, Node* parm7,
2493                                   Node* parm8) {
2494   assert(call_addr != NULL, "must not call NULL targets");
2495 
2496   // Slow-path call
2497   bool is_leaf = !(flags & RC_NO_LEAF);
2498   bool has_io  = (!is_leaf && !(flags & RC_NO_IO));
2499   if (call_name == NULL) {
2500     assert(!is_leaf, "must supply name for leaf");
2501     call_name = OptoRuntime::stub_name(call_addr);
2502   }
2503   CallNode* call;
2504   if (!is_leaf) {
2505     call = new CallStaticJavaNode(call_type, call_addr, call_name, adr_type);
2506   } else if (flags & RC_NO_FP) {
2507     call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
2508   } else  if (flags & RC_VECTOR){
2509     uint num_bits = call_type->range()->field_at(TypeFunc::Parms)->is_vect()->length_in_bytes() * BitsPerByte;
2510     call = new CallLeafVectorNode(call_type, call_addr, call_name, adr_type, num_bits);
2511   } else {
2512     call = new CallLeafNode(call_type, call_addr, call_name, adr_type);
2513   }
2514 
2515   // The following is similar to set_edges_for_java_call,
2516   // except that the memory effects of the call are restricted to AliasIdxRaw.
2517 
2518   // Slow path call has no side-effects, uses few values
2519   bool wide_in  = !(flags & RC_NARROW_MEM);
2520   bool wide_out = (C->get_alias_index(adr_type) == Compile::AliasIdxBot);
2521 
2522   Node* prev_mem = NULL;
2523   if (wide_in) {
2524     prev_mem = set_predefined_input_for_runtime_call(call);
2525   } else {
2526     assert(!wide_out, "narrow in => narrow out");
2527     Node* narrow_mem = memory(adr_type);
2528     prev_mem = set_predefined_input_for_runtime_call(call, narrow_mem);
2529   }
2530 
2531   // Hook each parm in order.  Stop looking at the first NULL.
2532   if (parm0 != NULL) { call->init_req(TypeFunc::Parms+0, parm0);
2533   if (parm1 != NULL) { call->init_req(TypeFunc::Parms+1, parm1);
2534   if (parm2 != NULL) { call->init_req(TypeFunc::Parms+2, parm2);
2535   if (parm3 != NULL) { call->init_req(TypeFunc::Parms+3, parm3);
2536   if (parm4 != NULL) { call->init_req(TypeFunc::Parms+4, parm4);
2537   if (parm5 != NULL) { call->init_req(TypeFunc::Parms+5, parm5);
2538   if (parm6 != NULL) { call->init_req(TypeFunc::Parms+6, parm6);
2539   if (parm7 != NULL) { call->init_req(TypeFunc::Parms+7, parm7);
2540   if (parm8 != NULL) { call->init_req(TypeFunc::Parms+8, parm8);
2541   /* close each nested if ===> */  } } } } } } } } }
2542   assert(call->in(call->req()-1) != NULL, "must initialize all parms");
2543 
2544   if (!is_leaf) {
2545     // Non-leaves can block and take safepoints:
2546     add_safepoint_edges(call, ((flags & RC_MUST_THROW) != 0));
2547   }
2548   // Non-leaves can throw exceptions:
2549   if (has_io) {
2550     call->set_req(TypeFunc::I_O, i_o());
2551   }
2552 
2553   if (flags & RC_UNCOMMON) {
2554     // Set the count to a tiny probability.  Cf. Estimate_Block_Frequency.
2555     // (An "if" probability corresponds roughly to an unconditional count.
2556     // Sort of.)
2557     call->set_cnt(PROB_UNLIKELY_MAG(4));
2558   }
2559 
2560   Node* c = _gvn.transform(call);
2561   assert(c == call, "cannot disappear");
2562 
2563   if (wide_out) {
2564     // Slow path call has full side-effects.
2565     set_predefined_output_for_runtime_call(call);
2566   } else {
2567     // Slow path call has few side-effects, and/or sets few values.
2568     set_predefined_output_for_runtime_call(call, prev_mem, adr_type);
2569   }
2570 
2571   if (has_io) {
2572     set_i_o(_gvn.transform(new ProjNode(call, TypeFunc::I_O)));
2573   }
2574   return call;
2575 
2576 }
2577 
2578 // i2b
2579 Node* GraphKit::sign_extend_byte(Node* in) {
2580   Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(24)));
2581   return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(24)));
2582 }
2583 
2584 // i2s
2585 Node* GraphKit::sign_extend_short(Node* in) {
2586   Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(16)));
2587   return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(16)));
2588 }
2589 
2590 //-----------------------------make_native_call-------------------------------
2591 Node* GraphKit::make_native_call(address call_addr, const TypeFunc* call_type, uint nargs, ciNativeEntryPoint* nep) {
2592   // Select just the actual call args to pass on
2593   // [MethodHandle fallback, long addr, HALF addr, ... args , NativeEntryPoint nep]
2594   //                                             |          |
2595   //                                             V          V
2596   //                                             [ ... args ]
2597   uint n_filtered_args = nargs - 4; // -fallback, -addr (2), -nep;
2598   ResourceMark rm;
2599   Node** argument_nodes = NEW_RESOURCE_ARRAY(Node*, n_filtered_args);
2600   const Type** arg_types = TypeTuple::fields(n_filtered_args);
2601   GrowableArray<VMReg> arg_regs(C->comp_arena(), n_filtered_args, n_filtered_args, VMRegImpl::Bad());
2602 
2603   VMReg* argRegs = nep->argMoves();
2604   {
2605     for (uint vm_arg_pos = 0, java_arg_read_pos = 0;
2606         vm_arg_pos < n_filtered_args; vm_arg_pos++) {
2607       uint vm_unfiltered_arg_pos = vm_arg_pos + 3; // +3 to skip fallback handle argument and addr (2 since long)
2608       Node* node = argument(vm_unfiltered_arg_pos);
2609       const Type* type = call_type->domain()->field_at(TypeFunc::Parms + vm_unfiltered_arg_pos);
2610       VMReg reg = type == Type::HALF
2611         ? VMRegImpl::Bad()
2612         : argRegs[java_arg_read_pos++];
2613 
2614       argument_nodes[vm_arg_pos] = node;
2615       arg_types[TypeFunc::Parms + vm_arg_pos] = type;
2616       arg_regs.at_put(vm_arg_pos, reg);
2617     }
2618   }
2619 
2620   uint n_returns = call_type->range()->cnt() - TypeFunc::Parms;
2621   GrowableArray<VMReg> ret_regs(C->comp_arena(), n_returns, n_returns, VMRegImpl::Bad());
2622   const Type** ret_types = TypeTuple::fields(n_returns);
2623 
2624   VMReg* retRegs = nep->returnMoves();
2625   {
2626     for (uint vm_ret_pos = 0, java_ret_read_pos = 0;
2627         vm_ret_pos < n_returns; vm_ret_pos++) { // 0 or 1
2628       const Type* type = call_type->range()->field_at(TypeFunc::Parms + vm_ret_pos);
2629       VMReg reg = type == Type::HALF
2630         ? VMRegImpl::Bad()
2631         : retRegs[java_ret_read_pos++];
2632 
2633       ret_regs.at_put(vm_ret_pos, reg);
2634       ret_types[TypeFunc::Parms + vm_ret_pos] = type;
2635     }
2636   }
2637 
2638   const TypeFunc* new_call_type = TypeFunc::make(
2639     TypeTuple::make(TypeFunc::Parms + n_filtered_args, arg_types),
2640     TypeTuple::make(TypeFunc::Parms + n_returns, ret_types)
2641   );
2642 
2643   if (nep->need_transition()) {
2644     RuntimeStub* invoker = SharedRuntime::make_native_invoker(call_addr,
2645                                                               nep->shadow_space(),
2646                                                               arg_regs, ret_regs);
2647     if (invoker == NULL) {
2648       C->record_failure("native invoker not implemented on this platform");
2649       return NULL;
2650     }
2651     C->add_native_invoker(invoker);
2652     call_addr = invoker->code_begin();
2653   }
2654   assert(call_addr != NULL, "sanity");
2655 
2656   CallNativeNode* call = new CallNativeNode(new_call_type, call_addr, nep->name(), TypePtr::BOTTOM,
2657                                             arg_regs,
2658                                             ret_regs,
2659                                             nep->shadow_space(),
2660                                             nep->need_transition());
2661 
2662   if (call->_need_transition) {
2663     add_safepoint_edges(call);
2664   }
2665 
2666   set_predefined_input_for_runtime_call(call);
2667 
2668   for (uint i = 0; i < n_filtered_args; i++) {
2669     call->init_req(i + TypeFunc::Parms, argument_nodes[i]);
2670   }
2671 
2672   Node* c = gvn().transform(call);
2673   assert(c == call, "cannot disappear");
2674 
2675   set_predefined_output_for_runtime_call(call);
2676 
2677   Node* ret;
2678   if (method() == NULL || method()->return_type()->basic_type() == T_VOID) {
2679     ret = top();
2680   } else {
2681     ret =  gvn().transform(new ProjNode(call, TypeFunc::Parms));
2682     // Unpack native results if needed
2683     // Need this method type since it's unerased
2684     switch (nep->method_type()->rtype()->basic_type()) {
2685       case T_CHAR:
2686         ret = _gvn.transform(new AndINode(ret, _gvn.intcon(0xFFFF)));
2687         break;
2688       case T_BYTE:
2689         ret = sign_extend_byte(ret);
2690         break;
2691       case T_SHORT:
2692         ret = sign_extend_short(ret);
2693         break;
2694       default: // do nothing
2695         break;
2696     }
2697   }
2698 
2699   push_node(method()->return_type()->basic_type(), ret);
2700 
2701   return call;
2702 }
2703 
2704 //------------------------------merge_memory-----------------------------------
2705 // Merge memory from one path into the current memory state.
2706 void GraphKit::merge_memory(Node* new_mem, Node* region, int new_path) {
2707   for (MergeMemStream mms(merged_memory(), new_mem->as_MergeMem()); mms.next_non_empty2(); ) {
2708     Node* old_slice = mms.force_memory();
2709     Node* new_slice = mms.memory2();
2710     if (old_slice != new_slice) {
2711       PhiNode* phi;
2712       if (old_slice->is_Phi() && old_slice->as_Phi()->region() == region) {
2713         if (mms.is_empty()) {
2714           // clone base memory Phi's inputs for this memory slice
2715           assert(old_slice == mms.base_memory(), "sanity");
2716           phi = PhiNode::make(region, NULL, Type::MEMORY, mms.adr_type(C));
2717           _gvn.set_type(phi, Type::MEMORY);
2718           for (uint i = 1; i < phi->req(); i++) {
2719             phi->init_req(i, old_slice->in(i));
2720           }
2721         } else {
2722           phi = old_slice->as_Phi(); // Phi was generated already
2723         }
2724       } else {
2725         phi = PhiNode::make(region, old_slice, Type::MEMORY, mms.adr_type(C));
2726         _gvn.set_type(phi, Type::MEMORY);
2727       }
2728       phi->set_req(new_path, new_slice);
2729       mms.set_memory(phi);
2730     }
2731   }
2732 }
2733 
2734 //------------------------------make_slow_call_ex------------------------------
2735 // Make the exception handler hookups for the slow call
2736 void GraphKit::make_slow_call_ex(Node* call, ciInstanceKlass* ex_klass, bool separate_io_proj, bool deoptimize) {
2737   if (stopped())  return;
2738 
2739   // Make a catch node with just two handlers:  fall-through and catch-all
2740   Node* i_o  = _gvn.transform( new ProjNode(call, TypeFunc::I_O, separate_io_proj) );
2741   Node* catc = _gvn.transform( new CatchNode(control(), i_o, 2) );
2742   Node* norm = _gvn.transform( new CatchProjNode(catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci) );
2743   Node* excp = _gvn.transform( new CatchProjNode(catc, CatchProjNode::catch_all_index,    CatchProjNode::no_handler_bci) );
2744 
2745   { PreserveJVMState pjvms(this);
2746     set_control(excp);
2747     set_i_o(i_o);
2748 
2749     if (excp != top()) {
2750       if (deoptimize) {
2751         // Deoptimize if an exception is caught. Don't construct exception state in this case.
2752         uncommon_trap(Deoptimization::Reason_unhandled,
2753                       Deoptimization::Action_none);
2754       } else {
2755         // Create an exception state also.
2756         // Use an exact type if the caller has a specific exception.
2757         const Type* ex_type = TypeOopPtr::make_from_klass_unique(ex_klass)->cast_to_ptr_type(TypePtr::NotNull);
2758         Node*       ex_oop  = new CreateExNode(ex_type, control(), i_o);
2759         add_exception_state(make_exception_state(_gvn.transform(ex_oop)));
2760       }
2761     }
2762   }
2763 
2764   // Get the no-exception control from the CatchNode.
2765   set_control(norm);
2766 }
2767 
2768 static IfNode* gen_subtype_check_compare(Node* ctrl, Node* in1, Node* in2, BoolTest::mask test, float p, PhaseGVN& gvn, BasicType bt) {
2769   Node* cmp = NULL;
2770   switch(bt) {
2771   case T_INT: cmp = new CmpINode(in1, in2); break;
2772   case T_ADDRESS: cmp = new CmpPNode(in1, in2); break;
2773   default: fatal("unexpected comparison type %s", type2name(bt));
2774   }
2775   gvn.transform(cmp);
2776   Node* bol = gvn.transform(new BoolNode(cmp, test));
2777   IfNode* iff = new IfNode(ctrl, bol, p, COUNT_UNKNOWN);
2778   gvn.transform(iff);
2779   if (!bol->is_Con()) gvn.record_for_igvn(iff);
2780   return iff;
2781 }
2782 
2783 //-------------------------------gen_subtype_check-----------------------------
2784 // Generate a subtyping check.  Takes as input the subtype and supertype.
2785 // Returns 2 values: sets the default control() to the true path and returns
2786 // the false path.  Only reads invariant memory; sets no (visible) memory.
2787 // The PartialSubtypeCheckNode sets the hidden 1-word cache in the encoding
2788 // but that's not exposed to the optimizer.  This call also doesn't take in an
2789 // Object; if you wish to check an Object you need to load the Object's class
2790 // prior to coming here.
2791 Node* Phase::gen_subtype_check(Node* subklass, Node* superklass, Node** ctrl, Node* mem, PhaseGVN& gvn) {
2792   Compile* C = gvn.C;
2793   if ((*ctrl)->is_top()) {
2794     return C->top();
2795   }
2796 
2797   // Fast check for identical types, perhaps identical constants.
2798   // The types can even be identical non-constants, in cases
2799   // involving Array.newInstance, Object.clone, etc.
2800   if (subklass == superklass)
2801     return C->top();             // false path is dead; no test needed.
2802 
2803   if (gvn.type(superklass)->singleton()) {
2804     ciKlass* superk = gvn.type(superklass)->is_klassptr()->klass();
2805     ciKlass* subk   = gvn.type(subklass)->is_klassptr()->klass();
2806 
2807     // In the common case of an exact superklass, try to fold up the
2808     // test before generating code.  You may ask, why not just generate
2809     // the code and then let it fold up?  The answer is that the generated
2810     // code will necessarily include null checks, which do not always
2811     // completely fold away.  If they are also needless, then they turn
2812     // into a performance loss.  Example:
2813     //    Foo[] fa = blah(); Foo x = fa[0]; fa[1] = x;
2814     // Here, the type of 'fa' is often exact, so the store check
2815     // of fa[1]=x will fold up, without testing the nullness of x.
2816     switch (C->static_subtype_check(superk, subk)) {
2817     case Compile::SSC_always_false:
2818       {
2819         Node* always_fail = *ctrl;
2820         *ctrl = gvn.C->top();
2821         return always_fail;
2822       }
2823     case Compile::SSC_always_true:
2824       return C->top();
2825     case Compile::SSC_easy_test:
2826       {
2827         // Just do a direct pointer compare and be done.
2828         IfNode* iff = gen_subtype_check_compare(*ctrl, subklass, superklass, BoolTest::eq, PROB_STATIC_FREQUENT, gvn, T_ADDRESS);
2829         *ctrl = gvn.transform(new IfTrueNode(iff));
2830         return gvn.transform(new IfFalseNode(iff));
2831       }
2832     case Compile::SSC_full_test:
2833       break;
2834     default:
2835       ShouldNotReachHere();
2836     }
2837   }
2838 
2839   // %%% Possible further optimization:  Even if the superklass is not exact,
2840   // if the subklass is the unique subtype of the superklass, the check
2841   // will always succeed.  We could leave a dependency behind to ensure this.
2842 
2843   // First load the super-klass's check-offset
2844   Node *p1 = gvn.transform(new AddPNode(superklass, superklass, gvn.MakeConX(in_bytes(Klass::super_check_offset_offset()))));
2845   Node* m = C->immutable_memory();
2846   Node *chk_off = gvn.transform(new LoadINode(NULL, m, p1, gvn.type(p1)->is_ptr(), TypeInt::INT, MemNode::unordered));
2847   int cacheoff_con = in_bytes(Klass::secondary_super_cache_offset());
2848   bool might_be_cache = (gvn.find_int_con(chk_off, cacheoff_con) == cacheoff_con);
2849 
2850   // Load from the sub-klass's super-class display list, or a 1-word cache of
2851   // the secondary superclass list, or a failing value with a sentinel offset
2852   // if the super-klass is an interface or exceptionally deep in the Java
2853   // hierarchy and we have to scan the secondary superclass list the hard way.
2854   // Worst-case type is a little odd: NULL is allowed as a result (usually
2855   // klass loads can never produce a NULL).
2856   Node *chk_off_X = chk_off;
2857 #ifdef _LP64
2858   chk_off_X = gvn.transform(new ConvI2LNode(chk_off_X));
2859 #endif
2860   Node *p2 = gvn.transform(new AddPNode(subklass,subklass,chk_off_X));
2861   // For some types like interfaces the following loadKlass is from a 1-word
2862   // cache which is mutable so can't use immutable memory.  Other
2863   // types load from the super-class display table which is immutable.
2864   Node *kmem = C->immutable_memory();
2865   // secondary_super_cache is not immutable but can be treated as such because:
2866   // - no ideal node writes to it in a way that could cause an
2867   //   incorrect/missed optimization of the following Load.
2868   // - it's a cache so, worse case, not reading the latest value
2869   //   wouldn't cause incorrect execution
2870   if (might_be_cache && mem != NULL) {
2871     kmem = mem->is_MergeMem() ? mem->as_MergeMem()->memory_at(C->get_alias_index(gvn.type(p2)->is_ptr())) : mem;
2872   }
2873   Node *nkls = gvn.transform(LoadKlassNode::make(gvn, NULL, kmem, p2, gvn.type(p2)->is_ptr(), TypeInstKlassPtr::OBJECT_OR_NULL));
2874 
2875   // Compile speed common case: ARE a subtype and we canNOT fail
2876   if( superklass == nkls )
2877     return C->top();             // false path is dead; no test needed.
2878 
2879   // See if we get an immediate positive hit.  Happens roughly 83% of the
2880   // time.  Test to see if the value loaded just previously from the subklass
2881   // is exactly the superklass.
2882   IfNode *iff1 = gen_subtype_check_compare(*ctrl, superklass, nkls, BoolTest::eq, PROB_LIKELY(0.83f), gvn, T_ADDRESS);
2883   Node *iftrue1 = gvn.transform( new IfTrueNode (iff1));
2884   *ctrl = gvn.transform(new IfFalseNode(iff1));
2885 
2886   // Compile speed common case: Check for being deterministic right now.  If
2887   // chk_off is a constant and not equal to cacheoff then we are NOT a
2888   // subklass.  In this case we need exactly the 1 test above and we can
2889   // return those results immediately.
2890   if (!might_be_cache) {
2891     Node* not_subtype_ctrl = *ctrl;
2892     *ctrl = iftrue1; // We need exactly the 1 test above
2893     return not_subtype_ctrl;
2894   }
2895 
2896   // Gather the various success & failures here
2897   RegionNode *r_ok_subtype = new RegionNode(4);
2898   gvn.record_for_igvn(r_ok_subtype);
2899   RegionNode *r_not_subtype = new RegionNode(3);
2900   gvn.record_for_igvn(r_not_subtype);
2901 
2902   r_ok_subtype->init_req(1, iftrue1);
2903 
2904   // Check for immediate negative hit.  Happens roughly 11% of the time (which
2905   // is roughly 63% of the remaining cases).  Test to see if the loaded
2906   // check-offset points into the subklass display list or the 1-element
2907   // cache.  If it points to the display (and NOT the cache) and the display
2908   // missed then it's not a subtype.
2909   Node *cacheoff = gvn.intcon(cacheoff_con);
2910   IfNode *iff2 = gen_subtype_check_compare(*ctrl, chk_off, cacheoff, BoolTest::ne, PROB_LIKELY(0.63f), gvn, T_INT);
2911   r_not_subtype->init_req(1, gvn.transform(new IfTrueNode (iff2)));
2912   *ctrl = gvn.transform(new IfFalseNode(iff2));
2913 
2914   // Check for self.  Very rare to get here, but it is taken 1/3 the time.
2915   // No performance impact (too rare) but allows sharing of secondary arrays
2916   // which has some footprint reduction.
2917   IfNode *iff3 = gen_subtype_check_compare(*ctrl, subklass, superklass, BoolTest::eq, PROB_LIKELY(0.36f), gvn, T_ADDRESS);
2918   r_ok_subtype->init_req(2, gvn.transform(new IfTrueNode(iff3)));
2919   *ctrl = gvn.transform(new IfFalseNode(iff3));
2920 
2921   // -- Roads not taken here: --
2922   // We could also have chosen to perform the self-check at the beginning
2923   // of this code sequence, as the assembler does.  This would not pay off
2924   // the same way, since the optimizer, unlike the assembler, can perform
2925   // static type analysis to fold away many successful self-checks.
2926   // Non-foldable self checks work better here in second position, because
2927   // the initial primary superclass check subsumes a self-check for most
2928   // types.  An exception would be a secondary type like array-of-interface,
2929   // which does not appear in its own primary supertype display.
2930   // Finally, we could have chosen to move the self-check into the
2931   // PartialSubtypeCheckNode, and from there out-of-line in a platform
2932   // dependent manner.  But it is worthwhile to have the check here,
2933   // where it can be perhaps be optimized.  The cost in code space is
2934   // small (register compare, branch).
2935 
2936   // Now do a linear scan of the secondary super-klass array.  Again, no real
2937   // performance impact (too rare) but it's gotta be done.
2938   // Since the code is rarely used, there is no penalty for moving it
2939   // out of line, and it can only improve I-cache density.
2940   // The decision to inline or out-of-line this final check is platform
2941   // dependent, and is found in the AD file definition of PartialSubtypeCheck.
2942   Node* psc = gvn.transform(
2943     new PartialSubtypeCheckNode(*ctrl, subklass, superklass));
2944 
2945   IfNode *iff4 = gen_subtype_check_compare(*ctrl, psc, gvn.zerocon(T_OBJECT), BoolTest::ne, PROB_FAIR, gvn, T_ADDRESS);
2946   r_not_subtype->init_req(2, gvn.transform(new IfTrueNode (iff4)));
2947   r_ok_subtype ->init_req(3, gvn.transform(new IfFalseNode(iff4)));
2948 
2949   // Return false path; set default control to true path.
2950   *ctrl = gvn.transform(r_ok_subtype);
2951   return gvn.transform(r_not_subtype);
2952 }
2953 
2954 Node* GraphKit::gen_subtype_check(Node* obj_or_subklass, Node* superklass) {
2955   bool expand_subtype_check = C->post_loop_opts_phase() ||   // macro node expansion is over
2956                               ExpandSubTypeCheckAtParseTime; // forced expansion
2957   if (expand_subtype_check) {
2958     MergeMemNode* mem = merged_memory();
2959     Node* ctrl = control();
2960     Node* subklass = obj_or_subklass;
2961     if (!_gvn.type(obj_or_subklass)->isa_klassptr()) {
2962       subklass = load_object_klass(obj_or_subklass);
2963     }
2964 
2965     Node* n = Phase::gen_subtype_check(subklass, superklass, &ctrl, mem, _gvn);
2966     set_control(ctrl);
2967     return n;
2968   }
2969 
2970   Node* check = _gvn.transform(new SubTypeCheckNode(C, obj_or_subklass, superklass));
2971   Node* bol = _gvn.transform(new BoolNode(check, BoolTest::eq));
2972   IfNode* iff = create_and_xform_if(control(), bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
2973   set_control(_gvn.transform(new IfTrueNode(iff)));
2974   return _gvn.transform(new IfFalseNode(iff));
2975 }
2976 
2977 // Profile-driven exact type check:
2978 Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,
2979                                     float prob,
2980                                     Node* *casted_receiver) {
2981   assert(!klass->is_interface(), "no exact type check on interfaces");
2982 
2983   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
2984   Node* recv_klass = load_object_klass(receiver);
2985   Node* want_klass = makecon(tklass);
2986   Node* cmp = _gvn.transform(new CmpPNode(recv_klass, want_klass));
2987   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
2988   IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);
2989   set_control( _gvn.transform(new IfTrueNode (iff)));
2990   Node* fail = _gvn.transform(new IfFalseNode(iff));
2991 
2992   if (!stopped()) {
2993     const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
2994     const TypeOopPtr* recvx_type = tklass->as_instance_type();
2995     assert(recvx_type->klass_is_exact(), "");
2996 
2997     if (!receiver_type->higher_equal(recvx_type)) { // ignore redundant casts
2998       // Subsume downstream occurrences of receiver with a cast to
2999       // recv_xtype, since now we know what the type will be.
3000       Node* cast = new CheckCastPPNode(control(), receiver, recvx_type);
3001       (*casted_receiver) = _gvn.transform(cast);
3002       // (User must make the replace_in_map call.)
3003     }
3004   }
3005 
3006   return fail;
3007 }
3008 
3009 //------------------------------subtype_check_receiver-------------------------
3010 Node* GraphKit::subtype_check_receiver(Node* receiver, ciKlass* klass,
3011                                        Node** casted_receiver) {
3012   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
3013   Node* want_klass = makecon(tklass);
3014 
3015   Node* slow_ctl = gen_subtype_check(receiver, want_klass);
3016 
3017   // Ignore interface type information until interface types are properly tracked.
3018   if (!stopped() && !klass->is_interface()) {
3019     const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
3020     const TypeOopPtr* recv_type = tklass->cast_to_exactness(false)->is_klassptr()->as_instance_type();
3021     if (!receiver_type->higher_equal(recv_type)) { // ignore redundant casts
3022       Node* cast = new CheckCastPPNode(control(), receiver, recv_type);
3023       (*casted_receiver) = _gvn.transform(cast);
3024     }
3025   }
3026 
3027   return slow_ctl;
3028 }
3029 
3030 //------------------------------seems_never_null-------------------------------
3031 // Use null_seen information if it is available from the profile.
3032 // If we see an unexpected null at a type check we record it and force a
3033 // recompile; the offending check will be recompiled to handle NULLs.
3034 // If we see several offending BCIs, then all checks in the
3035 // method will be recompiled.
3036 bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) {
3037   speculating = !_gvn.type(obj)->speculative_maybe_null();
3038   Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating);
3039   if (UncommonNullCast               // Cutout for this technique
3040       && obj != null()               // And not the -Xcomp stupid case?
3041       && !too_many_traps(reason)
3042       ) {
3043     if (speculating) {
3044       return true;
3045     }
3046     if (data == NULL)
3047       // Edge case:  no mature data.  Be optimistic here.
3048       return true;
3049     // If the profile has not seen a null, assume it won't happen.
3050     assert(java_bc() == Bytecodes::_checkcast ||
3051            java_bc() == Bytecodes::_instanceof ||
3052            java_bc() == Bytecodes::_aastore, "MDO must collect null_seen bit here");
3053     return !data->as_BitData()->null_seen();
3054   }
3055   speculating = false;
3056   return false;
3057 }
3058 
3059 void GraphKit::guard_klass_being_initialized(Node* klass) {
3060   int init_state_off = in_bytes(InstanceKlass::init_state_offset());
3061   Node* adr = basic_plus_adr(top(), klass, init_state_off);
3062   Node* init_state = LoadNode::make(_gvn, NULL, immutable_memory(), adr,
3063                                     adr->bottom_type()->is_ptr(), TypeInt::BYTE,
3064                                     T_BYTE, MemNode::unordered);
3065   init_state = _gvn.transform(init_state);
3066 
3067   Node* being_initialized_state = makecon(TypeInt::make(InstanceKlass::being_initialized));
3068 
3069   Node* chk = _gvn.transform(new CmpINode(being_initialized_state, init_state));
3070   Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3071 
3072   { BuildCutout unless(this, tst, PROB_MAX);
3073     uncommon_trap(Deoptimization::Reason_initialized, Deoptimization::Action_reinterpret);
3074   }
3075 }
3076 
3077 void GraphKit::guard_init_thread(Node* klass) {
3078   int init_thread_off = in_bytes(InstanceKlass::init_thread_offset());
3079   Node* adr = basic_plus_adr(top(), klass, init_thread_off);
3080 
3081   Node* init_thread = LoadNode::make(_gvn, NULL, immutable_memory(), adr,
3082                                      adr->bottom_type()->is_ptr(), TypePtr::NOTNULL,
3083                                      T_ADDRESS, MemNode::unordered);
3084   init_thread = _gvn.transform(init_thread);
3085 
3086   Node* cur_thread = _gvn.transform(new ThreadLocalNode());
3087 
3088   Node* chk = _gvn.transform(new CmpPNode(cur_thread, init_thread));
3089   Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3090 
3091   { BuildCutout unless(this, tst, PROB_MAX);
3092     uncommon_trap(Deoptimization::Reason_uninitialized, Deoptimization::Action_none);
3093   }
3094 }
3095 
3096 void GraphKit::clinit_barrier(ciInstanceKlass* ik, ciMethod* context) {
3097   if (ik->is_being_initialized()) {
3098     if (C->needs_clinit_barrier(ik, context)) {
3099       Node* klass = makecon(TypeKlassPtr::make(ik));
3100       guard_klass_being_initialized(klass);
3101       guard_init_thread(klass);
3102       insert_mem_bar(Op_MemBarCPUOrder);
3103     }
3104   } else if (ik->is_initialized()) {
3105     return; // no barrier needed
3106   } else {
3107     uncommon_trap(Deoptimization::Reason_uninitialized,
3108                   Deoptimization::Action_reinterpret,
3109                   NULL);
3110   }
3111 }
3112 
3113 //------------------------maybe_cast_profiled_receiver-------------------------
3114 // If the profile has seen exactly one type, narrow to exactly that type.
3115 // Subsequent type checks will always fold up.
3116 Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,
3117                                              ciKlass* require_klass,
3118                                              ciKlass* spec_klass,
3119                                              bool safe_for_replace) {
3120   if (!UseTypeProfile || !TypeProfileCasts) return NULL;
3121 
3122   Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != NULL);
3123 
3124   // Make sure we haven't already deoptimized from this tactic.
3125   if (too_many_traps_or_recompiles(reason))
3126     return NULL;
3127 
3128   // (No, this isn't a call, but it's enough like a virtual call
3129   // to use the same ciMethod accessor to get the profile info...)
3130   // If we have a speculative type use it instead of profiling (which
3131   // may not help us)
3132   ciKlass* exact_kls = spec_klass == NULL ? profile_has_unique_klass() : spec_klass;
3133   if (exact_kls != NULL) {// no cast failures here
3134     if (require_klass == NULL ||
3135         C->static_subtype_check(require_klass, exact_kls) == Compile::SSC_always_true) {
3136       // If we narrow the type to match what the type profile sees or
3137       // the speculative type, we can then remove the rest of the
3138       // cast.
3139       // This is a win, even if the exact_kls is very specific,
3140       // because downstream operations, such as method calls,
3141       // will often benefit from the sharper type.
3142       Node* exact_obj = not_null_obj; // will get updated in place...
3143       Node* slow_ctl  = type_check_receiver(exact_obj, exact_kls, 1.0,
3144                                             &exact_obj);
3145       { PreserveJVMState pjvms(this);
3146         set_control(slow_ctl);
3147         uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
3148       }
3149       if (safe_for_replace) {
3150         replace_in_map(not_null_obj, exact_obj);
3151       }
3152       return exact_obj;
3153     }
3154     // assert(ssc == Compile::SSC_always_true)... except maybe the profile lied to us.
3155   }
3156 
3157   return NULL;
3158 }
3159 
3160 /**
3161  * Cast obj to type and emit guard unless we had too many traps here
3162  * already
3163  *
3164  * @param obj       node being casted
3165  * @param type      type to cast the node to
3166  * @param not_null  true if we know node cannot be null
3167  */
3168 Node* GraphKit::maybe_cast_profiled_obj(Node* obj,
3169                                         ciKlass* type,
3170                                         bool not_null) {
3171   if (stopped()) {
3172     return obj;
3173   }
3174 
3175   // type == NULL if profiling tells us this object is always null
3176   if (type != NULL) {
3177     Deoptimization::DeoptReason class_reason = Deoptimization::Reason_speculate_class_check;
3178     Deoptimization::DeoptReason null_reason = Deoptimization::Reason_speculate_null_check;
3179 
3180     if (!too_many_traps_or_recompiles(null_reason) &&
3181         !too_many_traps_or_recompiles(class_reason)) {
3182       Node* not_null_obj = NULL;
3183       // not_null is true if we know the object is not null and
3184       // there's no need for a null check
3185       if (!not_null) {
3186         Node* null_ctl = top();
3187         not_null_obj = null_check_oop(obj, &null_ctl, true, true, true);
3188         assert(null_ctl->is_top(), "no null control here");
3189       } else {
3190         not_null_obj = obj;
3191       }
3192 
3193       Node* exact_obj = not_null_obj;
3194       ciKlass* exact_kls = type;
3195       Node* slow_ctl  = type_check_receiver(exact_obj, exact_kls, 1.0,
3196                                             &exact_obj);
3197       {
3198         PreserveJVMState pjvms(this);
3199         set_control(slow_ctl);
3200         uncommon_trap_exact(class_reason, Deoptimization::Action_maybe_recompile);
3201       }
3202       replace_in_map(not_null_obj, exact_obj);
3203       obj = exact_obj;
3204     }
3205   } else {
3206     if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
3207       Node* exact_obj = null_assert(obj);
3208       replace_in_map(obj, exact_obj);
3209       obj = exact_obj;
3210     }
3211   }
3212   return obj;
3213 }
3214 
3215 //-------------------------------gen_instanceof--------------------------------
3216 // Generate an instance-of idiom.  Used by both the instance-of bytecode
3217 // and the reflective instance-of call.
3218 Node* GraphKit::gen_instanceof(Node* obj, Node* superklass, bool safe_for_replace) {
3219   kill_dead_locals();           // Benefit all the uncommon traps
3220   assert( !stopped(), "dead parse path should be checked in callers" );
3221   assert(!TypePtr::NULL_PTR->higher_equal(_gvn.type(superklass)->is_klassptr()),
3222          "must check for not-null not-dead klass in callers");
3223 
3224   // Make the merge point
3225   enum { _obj_path = 1, _fail_path, _null_path, PATH_LIMIT };
3226   RegionNode* region = new RegionNode(PATH_LIMIT);
3227   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
3228   C->set_has_split_ifs(true); // Has chance for split-if optimization
3229 
3230   ciProfileData* data = NULL;
3231   if (java_bc() == Bytecodes::_instanceof) {  // Only for the bytecode
3232     data = method()->method_data()->bci_to_data(bci());
3233   }
3234   bool speculative_not_null = false;
3235   bool never_see_null = (ProfileDynamicTypes  // aggressive use of profile
3236                          && seems_never_null(obj, data, speculative_not_null));
3237 
3238   // Null check; get casted pointer; set region slot 3
3239   Node* null_ctl = top();
3240   Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3241 
3242   // If not_null_obj is dead, only null-path is taken
3243   if (stopped()) {              // Doing instance-of on a NULL?
3244     set_control(null_ctl);
3245     return intcon(0);
3246   }
3247   region->init_req(_null_path, null_ctl);
3248   phi   ->init_req(_null_path, intcon(0)); // Set null path value
3249   if (null_ctl == top()) {
3250     // Do this eagerly, so that pattern matches like is_diamond_phi
3251     // will work even during parsing.
3252     assert(_null_path == PATH_LIMIT-1, "delete last");
3253     region->del_req(_null_path);
3254     phi   ->del_req(_null_path);
3255   }
3256 
3257   // Do we know the type check always succeed?
3258   bool known_statically = false;
3259   if (_gvn.type(superklass)->singleton()) {
3260     ciKlass* superk = _gvn.type(superklass)->is_klassptr()->klass();
3261     ciKlass* subk = _gvn.type(obj)->is_oopptr()->klass();
3262     if (subk != NULL && subk->is_loaded()) {
3263       int static_res = C->static_subtype_check(superk, subk);
3264       known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false);
3265     }
3266   }
3267 
3268   if (!known_statically) {
3269     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3270     // We may not have profiling here or it may not help us. If we
3271     // have a speculative type use it to perform an exact cast.
3272     ciKlass* spec_obj_type = obj_type->speculative_type();
3273     if (spec_obj_type != NULL || (ProfileDynamicTypes && data != NULL)) {
3274       Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, NULL, spec_obj_type, safe_for_replace);
3275       if (stopped()) {            // Profile disagrees with this path.
3276         set_control(null_ctl);    // Null is the only remaining possibility.
3277         return intcon(0);
3278       }
3279       if (cast_obj != NULL) {
3280         not_null_obj = cast_obj;
3281       }
3282     }
3283   }
3284 
3285   // Generate the subtype check
3286   Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass);
3287 
3288   // Plug in the success path to the general merge in slot 1.
3289   region->init_req(_obj_path, control());
3290   phi   ->init_req(_obj_path, intcon(1));
3291 
3292   // Plug in the failing path to the general merge in slot 2.
3293   region->init_req(_fail_path, not_subtype_ctrl);
3294   phi   ->init_req(_fail_path, intcon(0));
3295 
3296   // Return final merged results
3297   set_control( _gvn.transform(region) );
3298   record_for_igvn(region);
3299 
3300   // If we know the type check always succeeds then we don't use the
3301   // profiling data at this bytecode. Don't lose it, feed it to the
3302   // type system as a speculative type.
3303   if (safe_for_replace) {
3304     Node* casted_obj = record_profiled_receiver_for_speculation(obj);
3305     replace_in_map(obj, casted_obj);
3306   }
3307 
3308   return _gvn.transform(phi);
3309 }
3310 
3311 //-------------------------------gen_checkcast---------------------------------
3312 // Generate a checkcast idiom.  Used by both the checkcast bytecode and the
3313 // array store bytecode.  Stack must be as-if BEFORE doing the bytecode so the
3314 // uncommon-trap paths work.  Adjust stack after this call.
3315 // If failure_control is supplied and not null, it is filled in with
3316 // the control edge for the cast failure.  Otherwise, an appropriate
3317 // uncommon trap or exception is thrown.
3318 Node* GraphKit::gen_checkcast(Node *obj, Node* superklass,
3319                               Node* *failure_control) {
3320   kill_dead_locals();           // Benefit all the uncommon traps
3321   const TypeKlassPtr *tk = _gvn.type(superklass)->is_klassptr();
3322   const Type *toop = TypeOopPtr::make_from_klass(tk->klass());
3323 
3324   // Fast cutout:  Check the case that the cast is vacuously true.
3325   // This detects the common cases where the test will short-circuit
3326   // away completely.  We do this before we perform the null check,
3327   // because if the test is going to turn into zero code, we don't
3328   // want a residual null check left around.  (Causes a slowdown,
3329   // for example, in some objArray manipulations, such as a[i]=a[j].)
3330   if (tk->singleton()) {
3331     const TypeOopPtr* objtp = _gvn.type(obj)->isa_oopptr();
3332     if (objtp != NULL && objtp->klass() != NULL) {
3333       switch (C->static_subtype_check(tk->klass(), objtp->klass())) {
3334       case Compile::SSC_always_true:
3335         // If we know the type check always succeed then we don't use
3336         // the profiling data at this bytecode. Don't lose it, feed it
3337         // to the type system as a speculative type.
3338         return record_profiled_receiver_for_speculation(obj);
3339       case Compile::SSC_always_false:
3340         // It needs a null check because a null will *pass* the cast check.
3341         // A non-null value will always produce an exception.
3342         if (!objtp->maybe_null()) {
3343           builtin_throw(Deoptimization::Reason_class_check, makecon(TypeKlassPtr::make(objtp->klass())));
3344           return top();
3345         } else if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
3346           return null_assert(obj);
3347         }
3348         break; // Fall through to full check
3349       }
3350     }
3351   }
3352 
3353   ciProfileData* data = NULL;
3354   bool safe_for_replace = false;
3355   if (failure_control == NULL) {        // use MDO in regular case only
3356     assert(java_bc() == Bytecodes::_aastore ||
3357            java_bc() == Bytecodes::_checkcast,
3358            "interpreter profiles type checks only for these BCs");
3359     data = method()->method_data()->bci_to_data(bci());
3360     safe_for_replace = true;
3361   }
3362 
3363   // Make the merge point
3364   enum { _obj_path = 1, _null_path, PATH_LIMIT };
3365   RegionNode* region = new RegionNode(PATH_LIMIT);
3366   Node*       phi    = new PhiNode(region, toop);
3367   C->set_has_split_ifs(true); // Has chance for split-if optimization
3368 
3369   // Use null-cast information if it is available
3370   bool speculative_not_null = false;
3371   bool never_see_null = ((failure_control == NULL)  // regular case only
3372                          && seems_never_null(obj, data, speculative_not_null));
3373 
3374   // Null check; get casted pointer; set region slot 3
3375   Node* null_ctl = top();
3376   Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3377 
3378   // If not_null_obj is dead, only null-path is taken
3379   if (stopped()) {              // Doing instance-of on a NULL?
3380     set_control(null_ctl);
3381     return null();
3382   }
3383   region->init_req(_null_path, null_ctl);
3384   phi   ->init_req(_null_path, null());  // Set null path value
3385   if (null_ctl == top()) {
3386     // Do this eagerly, so that pattern matches like is_diamond_phi
3387     // will work even during parsing.
3388     assert(_null_path == PATH_LIMIT-1, "delete last");
3389     region->del_req(_null_path);
3390     phi   ->del_req(_null_path);
3391   }
3392 
3393   Node* cast_obj = NULL;
3394   if (tk->klass_is_exact()) {
3395     // The following optimization tries to statically cast the speculative type of the object
3396     // (for example obtained during profiling) to the type of the superklass and then do a
3397     // dynamic check that the type of the object is what we expect. To work correctly
3398     // for checkcast and aastore the type of superklass should be exact.
3399     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3400     // We may not have profiling here or it may not help us. If we have
3401     // a speculative type use it to perform an exact cast.
3402     ciKlass* spec_obj_type = obj_type->speculative_type();
3403     if (spec_obj_type != NULL || data != NULL) {
3404       cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk->klass(), spec_obj_type, safe_for_replace);
3405       if (cast_obj != NULL) {
3406         if (failure_control != NULL) // failure is now impossible
3407           (*failure_control) = top();
3408         // adjust the type of the phi to the exact klass:
3409         phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
3410       }
3411     }
3412   }
3413 
3414   if (cast_obj == NULL) {
3415     // Generate the subtype check
3416     Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass );
3417 
3418     // Plug in success path into the merge
3419     cast_obj = _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop));
3420     // Failure path ends in uncommon trap (or may be dead - failure impossible)
3421     if (failure_control == NULL) {
3422       if (not_subtype_ctrl != top()) { // If failure is possible
3423         PreserveJVMState pjvms(this);
3424         set_control(not_subtype_ctrl);
3425         builtin_throw(Deoptimization::Reason_class_check, load_object_klass(not_null_obj));
3426       }
3427     } else {
3428       (*failure_control) = not_subtype_ctrl;
3429     }
3430   }
3431 
3432   region->init_req(_obj_path, control());
3433   phi   ->init_req(_obj_path, cast_obj);
3434 
3435   // A merge of NULL or Casted-NotNull obj
3436   Node* res = _gvn.transform(phi);
3437 
3438   // Note I do NOT always 'replace_in_map(obj,result)' here.
3439   //  if( tk->klass()->can_be_primary_super()  )
3440     // This means that if I successfully store an Object into an array-of-String
3441     // I 'forget' that the Object is really now known to be a String.  I have to
3442     // do this because we don't have true union types for interfaces - if I store
3443     // a Baz into an array-of-Interface and then tell the optimizer it's an
3444     // Interface, I forget that it's also a Baz and cannot do Baz-like field
3445     // references to it.  FIX THIS WHEN UNION TYPES APPEAR!
3446   //  replace_in_map( obj, res );
3447 
3448   // Return final merged results
3449   set_control( _gvn.transform(region) );
3450   record_for_igvn(region);
3451 
3452   return record_profiled_receiver_for_speculation(res);
3453 }
3454 
3455 //------------------------------next_monitor-----------------------------------
3456 // What number should be given to the next monitor?
3457 int GraphKit::next_monitor() {
3458   int current = jvms()->monitor_depth()* C->sync_stack_slots();
3459   int next = current + C->sync_stack_slots();
3460   // Keep the toplevel high water mark current:
3461   if (C->fixed_slots() < next)  C->set_fixed_slots(next);
3462   return current;
3463 }
3464 
3465 //------------------------------insert_mem_bar---------------------------------
3466 // Memory barrier to avoid floating things around
3467 // The membar serves as a pinch point between both control and all memory slices.
3468 Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {
3469   MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
3470   mb->init_req(TypeFunc::Control, control());
3471   mb->init_req(TypeFunc::Memory,  reset_memory());
3472   Node* membar = _gvn.transform(mb);
3473   set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3474   set_all_memory_call(membar);
3475   return membar;
3476 }
3477 
3478 //-------------------------insert_mem_bar_volatile----------------------------
3479 // Memory barrier to avoid floating things around
3480 // The membar serves as a pinch point between both control and memory(alias_idx).
3481 // If you want to make a pinch point on all memory slices, do not use this
3482 // function (even with AliasIdxBot); use insert_mem_bar() instead.
3483 Node* GraphKit::insert_mem_bar_volatile(int opcode, int alias_idx, Node* precedent) {
3484   // When Parse::do_put_xxx updates a volatile field, it appends a series
3485   // of MemBarVolatile nodes, one for *each* volatile field alias category.
3486   // The first membar is on the same memory slice as the field store opcode.
3487   // This forces the membar to follow the store.  (Bug 6500685 broke this.)
3488   // All the other membars (for other volatile slices, including AliasIdxBot,
3489   // which stands for all unknown volatile slices) are control-dependent
3490   // on the first membar.  This prevents later volatile loads or stores
3491   // from sliding up past the just-emitted store.
3492 
3493   MemBarNode* mb = MemBarNode::make(C, opcode, alias_idx, precedent);
3494   mb->set_req(TypeFunc::Control,control());
3495   if (alias_idx == Compile::AliasIdxBot) {
3496     mb->set_req(TypeFunc::Memory, merged_memory()->base_memory());
3497   } else {
3498     assert(!(opcode == Op_Initialize && alias_idx != Compile::AliasIdxRaw), "fix caller");
3499     mb->set_req(TypeFunc::Memory, memory(alias_idx));
3500   }
3501   Node* membar = _gvn.transform(mb);
3502   set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3503   if (alias_idx == Compile::AliasIdxBot) {
3504     merged_memory()->set_base_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)));
3505   } else {
3506     set_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)),alias_idx);
3507   }
3508   return membar;
3509 }
3510 
3511 //------------------------------shared_lock------------------------------------
3512 // Emit locking code.
3513 FastLockNode* GraphKit::shared_lock(Node* obj) {
3514   // bci is either a monitorenter bc or InvocationEntryBci
3515   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3516   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3517 
3518   if( !GenerateSynchronizationCode )
3519     return NULL;                // Not locking things?
3520   if (stopped())                // Dead monitor?
3521     return NULL;
3522 
3523   assert(dead_locals_are_killed(), "should kill locals before sync. point");
3524 
3525   // Box the stack location
3526   Node* box = _gvn.transform(new BoxLockNode(next_monitor()));
3527   Node* mem = reset_memory();
3528 
3529   FastLockNode * flock = _gvn.transform(new FastLockNode(0, obj, box) )->as_FastLock();
3530 
3531   // Create the rtm counters for this fast lock if needed.
3532   flock->create_rtm_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3533 
3534   // Add monitor to debug info for the slow path.  If we block inside the
3535   // slow path and de-opt, we need the monitor hanging around
3536   map()->push_monitor( flock );
3537 
3538   const TypeFunc *tf = LockNode::lock_type();
3539   LockNode *lock = new LockNode(C, tf);
3540 
3541   lock->init_req( TypeFunc::Control, control() );
3542   lock->init_req( TypeFunc::Memory , mem );
3543   lock->init_req( TypeFunc::I_O    , top() )     ;   // does no i/o
3544   lock->init_req( TypeFunc::FramePtr, frameptr() );
3545   lock->init_req( TypeFunc::ReturnAdr, top() );
3546 
3547   lock->init_req(TypeFunc::Parms + 0, obj);
3548   lock->init_req(TypeFunc::Parms + 1, box);
3549   lock->init_req(TypeFunc::Parms + 2, flock);
3550   add_safepoint_edges(lock);
3551 
3552   lock = _gvn.transform( lock )->as_Lock();
3553 
3554   // lock has no side-effects, sets few values
3555   set_predefined_output_for_runtime_call(lock, mem, TypeRawPtr::BOTTOM);
3556 
3557   insert_mem_bar(Op_MemBarAcquireLock);
3558 
3559   // Add this to the worklist so that the lock can be eliminated
3560   record_for_igvn(lock);
3561 
3562 #ifndef PRODUCT
3563   if (PrintLockStatistics) {
3564     // Update the counter for this lock.  Don't bother using an atomic
3565     // operation since we don't require absolute accuracy.
3566     lock->create_lock_counter(map()->jvms());
3567     increment_counter(lock->counter()->addr());
3568   }
3569 #endif
3570 
3571   return flock;
3572 }
3573 
3574 
3575 //------------------------------shared_unlock----------------------------------
3576 // Emit unlocking code.
3577 void GraphKit::shared_unlock(Node* box, Node* obj) {
3578   // bci is either a monitorenter bc or InvocationEntryBci
3579   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3580   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3581 
3582   if( !GenerateSynchronizationCode )
3583     return;
3584   if (stopped()) {               // Dead monitor?
3585     map()->pop_monitor();        // Kill monitor from debug info
3586     return;
3587   }
3588 
3589   // Memory barrier to avoid floating things down past the locked region
3590   insert_mem_bar(Op_MemBarReleaseLock);
3591 
3592   const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();
3593   UnlockNode *unlock = new UnlockNode(C, tf);
3594 #ifdef ASSERT
3595   unlock->set_dbg_jvms(sync_jvms());
3596 #endif
3597   uint raw_idx = Compile::AliasIdxRaw;
3598   unlock->init_req( TypeFunc::Control, control() );
3599   unlock->init_req( TypeFunc::Memory , memory(raw_idx) );
3600   unlock->init_req( TypeFunc::I_O    , top() )     ;   // does no i/o
3601   unlock->init_req( TypeFunc::FramePtr, frameptr() );
3602   unlock->init_req( TypeFunc::ReturnAdr, top() );
3603 
3604   unlock->init_req(TypeFunc::Parms + 0, obj);
3605   unlock->init_req(TypeFunc::Parms + 1, box);
3606   unlock = _gvn.transform(unlock)->as_Unlock();
3607 
3608   Node* mem = reset_memory();
3609 
3610   // unlock has no side-effects, sets few values
3611   set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);
3612 
3613   // Kill monitor from debug info
3614   map()->pop_monitor( );
3615 }
3616 
3617 //-------------------------------get_layout_helper-----------------------------
3618 // If the given klass is a constant or known to be an array,
3619 // fetch the constant layout helper value into constant_value
3620 // and return (Node*)NULL.  Otherwise, load the non-constant
3621 // layout helper value, and return the node which represents it.
3622 // This two-faced routine is useful because allocation sites
3623 // almost always feature constant types.
3624 Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {
3625   const TypeKlassPtr* inst_klass = _gvn.type(klass_node)->isa_klassptr();
3626   if (!StressReflectiveCode && inst_klass != NULL) {
3627     ciKlass* klass = inst_klass->klass();
3628     bool    xklass = inst_klass->klass_is_exact();
3629     if (xklass || klass->is_array_klass()) {
3630       jint lhelper = klass->layout_helper();
3631       if (lhelper != Klass::_lh_neutral_value) {
3632         constant_value = lhelper;
3633         return (Node*) NULL;
3634       }
3635     }
3636   }
3637   constant_value = Klass::_lh_neutral_value;  // put in a known value
3638   Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset()));
3639   return make_load(NULL, lhp, TypeInt::INT, T_INT, MemNode::unordered);
3640 }
3641 
3642 // We just put in an allocate/initialize with a big raw-memory effect.
3643 // Hook selected additional alias categories on the initialization.
3644 static void hook_memory_on_init(GraphKit& kit, int alias_idx,
3645                                 MergeMemNode* init_in_merge,
3646                                 Node* init_out_raw) {
3647   DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());
3648   assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");
3649 
3650   Node* prevmem = kit.memory(alias_idx);
3651   init_in_merge->set_memory_at(alias_idx, prevmem);
3652   kit.set_memory(init_out_raw, alias_idx);
3653 }
3654 
3655 //---------------------------set_output_for_allocation-------------------------
3656 Node* GraphKit::set_output_for_allocation(AllocateNode* alloc,
3657                                           const TypeOopPtr* oop_type,
3658                                           bool deoptimize_on_exception) {
3659   int rawidx = Compile::AliasIdxRaw;
3660   alloc->set_req( TypeFunc::FramePtr, frameptr() );
3661   add_safepoint_edges(alloc);
3662   Node* allocx = _gvn.transform(alloc);
3663   set_control( _gvn.transform(new ProjNode(allocx, TypeFunc::Control) ) );
3664   // create memory projection for i_o
3665   set_memory ( _gvn.transform( new ProjNode(allocx, TypeFunc::Memory, true) ), rawidx );
3666   make_slow_call_ex(allocx, env()->Throwable_klass(), true, deoptimize_on_exception);
3667 
3668   // create a memory projection as for the normal control path
3669   Node* malloc = _gvn.transform(new ProjNode(allocx, TypeFunc::Memory));
3670   set_memory(malloc, rawidx);
3671 
3672   // a normal slow-call doesn't change i_o, but an allocation does
3673   // we create a separate i_o projection for the normal control path
3674   set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) );
3675   Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) );
3676 
3677   // put in an initialization barrier
3678   InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,
3679                                                  rawoop)->as_Initialize();
3680   assert(alloc->initialization() == init,  "2-way macro link must work");
3681   assert(init ->allocation()     == alloc, "2-way macro link must work");
3682   {
3683     // Extract memory strands which may participate in the new object's
3684     // initialization, and source them from the new InitializeNode.
3685     // This will allow us to observe initializations when they occur,
3686     // and link them properly (as a group) to the InitializeNode.
3687     assert(init->in(InitializeNode::Memory) == malloc, "");
3688     MergeMemNode* minit_in = MergeMemNode::make(malloc);
3689     init->set_req(InitializeNode::Memory, minit_in);
3690     record_for_igvn(minit_in); // fold it up later, if possible
3691     Node* minit_out = memory(rawidx);
3692     assert(minit_out->is_Proj() && minit_out->in(0) == init, "");
3693     // Add an edge in the MergeMem for the header fields so an access
3694     // to one of those has correct memory state
3695     set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::mark_offset_in_bytes())));
3696     set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes())));
3697     if (oop_type->isa_aryptr()) {
3698       const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);
3699       int            elemidx  = C->get_alias_index(telemref);
3700       hook_memory_on_init(*this, elemidx, minit_in, minit_out);
3701     } else if (oop_type->isa_instptr()) {
3702       ciInstanceKlass* ik = oop_type->klass()->as_instance_klass();
3703       for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {
3704         ciField* field = ik->nonstatic_field_at(i);
3705         if (field->offset() >= TrackedInitializationLimit * HeapWordSize)
3706           continue;  // do not bother to track really large numbers of fields
3707         // Find (or create) the alias category for this field:
3708         int fieldidx = C->alias_type(field)->index();
3709         hook_memory_on_init(*this, fieldidx, minit_in, minit_out);
3710       }
3711     }
3712   }
3713 
3714   // Cast raw oop to the real thing...
3715   Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type);
3716   javaoop = _gvn.transform(javaoop);
3717   C->set_recent_alloc(control(), javaoop);
3718   assert(just_allocated_object(control()) == javaoop, "just allocated");
3719 
3720 #ifdef ASSERT
3721   { // Verify that the AllocateNode::Ideal_allocation recognizers work:
3722     assert(AllocateNode::Ideal_allocation(rawoop, &_gvn) == alloc,
3723            "Ideal_allocation works");
3724     assert(AllocateNode::Ideal_allocation(javaoop, &_gvn) == alloc,
3725            "Ideal_allocation works");
3726     if (alloc->is_AllocateArray()) {
3727       assert(AllocateArrayNode::Ideal_array_allocation(rawoop, &_gvn) == alloc->as_AllocateArray(),
3728              "Ideal_allocation works");
3729       assert(AllocateArrayNode::Ideal_array_allocation(javaoop, &_gvn) == alloc->as_AllocateArray(),
3730              "Ideal_allocation works");
3731     } else {
3732       assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");
3733     }
3734   }
3735 #endif //ASSERT
3736 
3737   return javaoop;
3738 }
3739 
3740 //---------------------------new_instance--------------------------------------
3741 // This routine takes a klass_node which may be constant (for a static type)
3742 // or may be non-constant (for reflective code).  It will work equally well
3743 // for either, and the graph will fold nicely if the optimizer later reduces
3744 // the type to a constant.
3745 // The optional arguments are for specialized use by intrinsics:
3746 //  - If 'extra_slow_test' if not null is an extra condition for the slow-path.
3747 //  - If 'return_size_val', report the the total object size to the caller.
3748 //  - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
3749 Node* GraphKit::new_instance(Node* klass_node,
3750                              Node* extra_slow_test,
3751                              Node* *return_size_val,
3752                              bool deoptimize_on_exception) {
3753   // Compute size in doublewords
3754   // The size is always an integral number of doublewords, represented
3755   // as a positive bytewise size stored in the klass's layout_helper.
3756   // The layout_helper also encodes (in a low bit) the need for a slow path.
3757   jint  layout_con = Klass::_lh_neutral_value;
3758   Node* layout_val = get_layout_helper(klass_node, layout_con);
3759   int   layout_is_con = (layout_val == NULL);
3760 
3761   if (extra_slow_test == NULL)  extra_slow_test = intcon(0);
3762   // Generate the initial go-slow test.  It's either ALWAYS (return a
3763   // Node for 1) or NEVER (return a NULL) or perhaps (in the reflective
3764   // case) a computed value derived from the layout_helper.
3765   Node* initial_slow_test = NULL;
3766   if (layout_is_con) {
3767     assert(!StressReflectiveCode, "stress mode does not use these paths");
3768     bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);
3769     initial_slow_test = must_go_slow ? intcon(1) : extra_slow_test;
3770   } else {   // reflective case
3771     // This reflective path is used by Unsafe.allocateInstance.
3772     // (It may be stress-tested by specifying StressReflectiveCode.)
3773     // Basically, we want to get into the VM is there's an illegal argument.
3774     Node* bit = intcon(Klass::_lh_instance_slow_path_bit);
3775     initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) );
3776     if (extra_slow_test != intcon(0)) {
3777       initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) );
3778     }
3779     // (Macro-expander will further convert this to a Bool, if necessary.)
3780   }
3781 
3782   // Find the size in bytes.  This is easy; it's the layout_helper.
3783   // The size value must be valid even if the slow path is taken.
3784   Node* size = NULL;
3785   if (layout_is_con) {
3786     size = MakeConX(Klass::layout_helper_size_in_bytes(layout_con));
3787   } else {   // reflective case
3788     // This reflective path is used by clone and Unsafe.allocateInstance.
3789     size = ConvI2X(layout_val);
3790 
3791     // Clear the low bits to extract layout_helper_size_in_bytes:
3792     assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
3793     Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));
3794     size = _gvn.transform( new AndXNode(size, mask) );
3795   }
3796   if (return_size_val != NULL) {
3797     (*return_size_val) = size;
3798   }
3799 
3800   // This is a precise notnull oop of the klass.
3801   // (Actually, it need not be precise if this is a reflective allocation.)
3802   // It's what we cast the result to.
3803   const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();
3804   if (!tklass)  tklass = TypeInstKlassPtr::OBJECT;
3805   const TypeOopPtr* oop_type = tklass->as_instance_type();
3806 
3807   // Now generate allocation code
3808 
3809   // The entire memory state is needed for slow path of the allocation
3810   // since GC and deoptimization can happened.
3811   Node *mem = reset_memory();
3812   set_all_memory(mem); // Create new memory state
3813 
3814   AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP),
3815                                          control(), mem, i_o(),
3816                                          size, klass_node,
3817                                          initial_slow_test);
3818 
3819   return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);
3820 }
3821 
3822 //-------------------------------new_array-------------------------------------
3823 // helper for both newarray and anewarray
3824 // The 'length' parameter is (obviously) the length of the array.
3825 // See comments on new_instance for the meaning of the other arguments.
3826 Node* GraphKit::new_array(Node* klass_node,     // array klass (maybe variable)
3827                           Node* length,         // number of array elements
3828                           int   nargs,          // number of arguments to push back for uncommon trap
3829                           Node* *return_size_val,
3830                           bool deoptimize_on_exception) {
3831   jint  layout_con = Klass::_lh_neutral_value;
3832   Node* layout_val = get_layout_helper(klass_node, layout_con);
3833   int   layout_is_con = (layout_val == NULL);
3834 
3835   if (!layout_is_con && !StressReflectiveCode &&
3836       !too_many_traps(Deoptimization::Reason_class_check)) {
3837     // This is a reflective array creation site.
3838     // Optimistically assume that it is a subtype of Object[],
3839     // so that we can fold up all the address arithmetic.
3840     layout_con = Klass::array_layout_helper(T_OBJECT);
3841     Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) );
3842     Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) );
3843     { BuildCutout unless(this, bol_lh, PROB_MAX);
3844       inc_sp(nargs);
3845       uncommon_trap(Deoptimization::Reason_class_check,
3846                     Deoptimization::Action_maybe_recompile);
3847     }
3848     layout_val = NULL;
3849     layout_is_con = true;
3850   }
3851 
3852   // Generate the initial go-slow test.  Make sure we do not overflow
3853   // if length is huge (near 2Gig) or negative!  We do not need
3854   // exact double-words here, just a close approximation of needed
3855   // double-words.  We can't add any offset or rounding bits, lest we
3856   // take a size -1 of bytes and make it positive.  Use an unsigned
3857   // compare, so negative sizes look hugely positive.
3858   int fast_size_limit = FastAllocateSizeLimit;
3859   if (layout_is_con) {
3860     assert(!StressReflectiveCode, "stress mode does not use these paths");
3861     // Increase the size limit if we have exact knowledge of array type.
3862     int log2_esize = Klass::layout_helper_log2_element_size(layout_con);
3863     fast_size_limit <<= (LogBytesPerLong - log2_esize);
3864   }
3865 
3866   Node* initial_slow_cmp  = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) );
3867   Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) );
3868 
3869   // --- Size Computation ---
3870   // array_size = round_to_heap(array_header + (length << elem_shift));
3871   // where round_to_heap(x) == align_to(x, MinObjAlignmentInBytes)
3872   // and align_to(x, y) == ((x + y-1) & ~(y-1))
3873   // The rounding mask is strength-reduced, if possible.
3874   int round_mask = MinObjAlignmentInBytes - 1;
3875   Node* header_size = NULL;
3876   int   header_size_min  = arrayOopDesc::base_offset_in_bytes(T_BYTE);
3877   // (T_BYTE has the weakest alignment and size restrictions...)
3878   if (layout_is_con) {
3879     int       hsize  = Klass::layout_helper_header_size(layout_con);
3880     int       eshift = Klass::layout_helper_log2_element_size(layout_con);
3881     BasicType etype  = Klass::layout_helper_element_type(layout_con);
3882     if ((round_mask & ~right_n_bits(eshift)) == 0)
3883       round_mask = 0;  // strength-reduce it if it goes away completely
3884     assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
3885     assert(header_size_min <= hsize, "generic minimum is smallest");
3886     header_size_min = hsize;
3887     header_size = intcon(hsize + round_mask);
3888   } else {
3889     Node* hss   = intcon(Klass::_lh_header_size_shift);
3890     Node* hsm   = intcon(Klass::_lh_header_size_mask);
3891     Node* hsize = _gvn.transform( new URShiftINode(layout_val, hss) );
3892     hsize       = _gvn.transform( new AndINode(hsize, hsm) );
3893     Node* mask  = intcon(round_mask);
3894     header_size = _gvn.transform( new AddINode(hsize, mask) );
3895   }
3896 
3897   Node* elem_shift = NULL;
3898   if (layout_is_con) {
3899     int eshift = Klass::layout_helper_log2_element_size(layout_con);
3900     if (eshift != 0)
3901       elem_shift = intcon(eshift);
3902   } else {
3903     // There is no need to mask or shift this value.
3904     // The semantics of LShiftINode include an implicit mask to 0x1F.
3905     assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
3906     elem_shift = layout_val;
3907   }
3908 
3909   // Transition to native address size for all offset calculations:
3910   Node* lengthx = ConvI2X(length);
3911   Node* headerx = ConvI2X(header_size);
3912 #ifdef _LP64
3913   { const TypeInt* tilen = _gvn.find_int_type(length);
3914     if (tilen != NULL && tilen->_lo < 0) {
3915       // Add a manual constraint to a positive range.  Cf. array_element_address.
3916       jint size_max = fast_size_limit;
3917       if (size_max > tilen->_hi)  size_max = tilen->_hi;
3918       const TypeInt* tlcon = TypeInt::make(0, size_max, Type::WidenMin);
3919 
3920       // Only do a narrow I2L conversion if the range check passed.
3921       IfNode* iff = new IfNode(control(), initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
3922       _gvn.transform(iff);
3923       RegionNode* region = new RegionNode(3);
3924       _gvn.set_type(region, Type::CONTROL);
3925       lengthx = new PhiNode(region, TypeLong::LONG);
3926       _gvn.set_type(lengthx, TypeLong::LONG);
3927 
3928       // Range check passed. Use ConvI2L node with narrow type.
3929       Node* passed = IfFalse(iff);
3930       region->init_req(1, passed);
3931       // Make I2L conversion control dependent to prevent it from
3932       // floating above the range check during loop optimizations.
3933       lengthx->init_req(1, C->constrained_convI2L(&_gvn, length, tlcon, passed));
3934 
3935       // Range check failed. Use ConvI2L with wide type because length may be invalid.
3936       region->init_req(2, IfTrue(iff));
3937       lengthx->init_req(2, ConvI2X(length));
3938 
3939       set_control(region);
3940       record_for_igvn(region);
3941       record_for_igvn(lengthx);
3942     }
3943   }
3944 #endif
3945 
3946   // Combine header size (plus rounding) and body size.  Then round down.
3947   // This computation cannot overflow, because it is used only in two
3948   // places, one where the length is sharply limited, and the other
3949   // after a successful allocation.
3950   Node* abody = lengthx;
3951   if (elem_shift != NULL)
3952     abody     = _gvn.transform( new LShiftXNode(lengthx, elem_shift) );
3953   Node* size  = _gvn.transform( new AddXNode(headerx, abody) );
3954   if (round_mask != 0) {
3955     Node* mask = MakeConX(~round_mask);
3956     size       = _gvn.transform( new AndXNode(size, mask) );
3957   }
3958   // else if round_mask == 0, the size computation is self-rounding
3959 
3960   if (return_size_val != NULL) {
3961     // This is the size
3962     (*return_size_val) = size;
3963   }
3964 
3965   // Now generate allocation code
3966 
3967   // The entire memory state is needed for slow path of the allocation
3968   // since GC and deoptimization can happened.
3969   Node *mem = reset_memory();
3970   set_all_memory(mem); // Create new memory state
3971 
3972   if (initial_slow_test->is_Bool()) {
3973     // Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.
3974     initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);
3975   }
3976 
3977   // Create the AllocateArrayNode and its result projections
3978   AllocateArrayNode* alloc
3979     = new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),
3980                             control(), mem, i_o(),
3981                             size, klass_node,
3982                             initial_slow_test,
3983                             length);
3984 
3985   // Cast to correct type.  Note that the klass_node may be constant or not,
3986   // and in the latter case the actual array type will be inexact also.
3987   // (This happens via a non-constant argument to inline_native_newArray.)
3988   // In any case, the value of klass_node provides the desired array type.
3989   const TypeInt* length_type = _gvn.find_int_type(length);
3990   const TypeOopPtr* ary_type = _gvn.type(klass_node)->is_klassptr()->as_instance_type();
3991   if (ary_type->isa_aryptr() && length_type != NULL) {
3992     // Try to get a better type than POS for the size
3993     ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
3994   }
3995 
3996   Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);
3997 
3998   array_ideal_length(alloc, ary_type, true);
3999   return javaoop;
4000 }
4001 
4002 // The following "Ideal_foo" functions are placed here because they recognize
4003 // the graph shapes created by the functions immediately above.
4004 
4005 //---------------------------Ideal_allocation----------------------------------
4006 // Given an oop pointer or raw pointer, see if it feeds from an AllocateNode.
4007 AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseTransform* phase) {
4008   if (ptr == NULL) {     // reduce dumb test in callers
4009     return NULL;
4010   }
4011 
4012   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4013   ptr = bs->step_over_gc_barrier(ptr);
4014 
4015   if (ptr->is_CheckCastPP()) { // strip only one raw-to-oop cast
4016     ptr = ptr->in(1);
4017     if (ptr == NULL) return NULL;
4018   }
4019   // Return NULL for allocations with several casts:
4020   //   j.l.reflect.Array.newInstance(jobject, jint)
4021   //   Object.clone()
4022   // to keep more precise type from last cast.
4023   if (ptr->is_Proj()) {
4024     Node* allo = ptr->in(0);
4025     if (allo != NULL && allo->is_Allocate()) {
4026       return allo->as_Allocate();
4027     }
4028   }
4029   // Report failure to match.
4030   return NULL;
4031 }
4032 
4033 // Fancy version which also strips off an offset (and reports it to caller).
4034 AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseTransform* phase,
4035                                              intptr_t& offset) {
4036   Node* base = AddPNode::Ideal_base_and_offset(ptr, phase, offset);
4037   if (base == NULL)  return NULL;
4038   return Ideal_allocation(base, phase);
4039 }
4040 
4041 // Trace Initialize <- Proj[Parm] <- Allocate
4042 AllocateNode* InitializeNode::allocation() {
4043   Node* rawoop = in(InitializeNode::RawAddress);
4044   if (rawoop->is_Proj()) {
4045     Node* alloc = rawoop->in(0);
4046     if (alloc->is_Allocate()) {
4047       return alloc->as_Allocate();
4048     }
4049   }
4050   return NULL;
4051 }
4052 
4053 // Trace Allocate -> Proj[Parm] -> Initialize
4054 InitializeNode* AllocateNode::initialization() {
4055   ProjNode* rawoop = proj_out_or_null(AllocateNode::RawAddress);
4056   if (rawoop == NULL)  return NULL;
4057   for (DUIterator_Fast imax, i = rawoop->fast_outs(imax); i < imax; i++) {
4058     Node* init = rawoop->fast_out(i);
4059     if (init->is_Initialize()) {
4060       assert(init->as_Initialize()->allocation() == this, "2-way link");
4061       return init->as_Initialize();
4062     }
4063   }
4064   return NULL;
4065 }
4066 
4067 //----------------------------- loop predicates ---------------------------
4068 
4069 //------------------------------add_predicate_impl----------------------------
4070 void GraphKit::add_empty_predicate_impl(Deoptimization::DeoptReason reason, int nargs) {
4071   // Too many traps seen?
4072   if (too_many_traps(reason)) {
4073 #ifdef ASSERT
4074     if (TraceLoopPredicate) {
4075       int tc = C->trap_count(reason);
4076       tty->print("too many traps=%s tcount=%d in ",
4077                     Deoptimization::trap_reason_name(reason), tc);
4078       method()->print(); // which method has too many predicate traps
4079       tty->cr();
4080     }
4081 #endif
4082     // We cannot afford to take more traps here,
4083     // do not generate predicate.
4084     return;
4085   }
4086 
4087   Node *cont    = _gvn.intcon(1);
4088   Node* opq     = _gvn.transform(new Opaque1Node(C, cont));
4089   Node *bol     = _gvn.transform(new Conv2BNode(opq));
4090   IfNode* iff   = create_and_map_if(control(), bol, PROB_MAX, COUNT_UNKNOWN);
4091   Node* iffalse = _gvn.transform(new IfFalseNode(iff));
4092   C->add_predicate_opaq(opq);
4093   {
4094     PreserveJVMState pjvms(this);
4095     set_control(iffalse);
4096     inc_sp(nargs);
4097     uncommon_trap(reason, Deoptimization::Action_maybe_recompile);
4098   }
4099   Node* iftrue = _gvn.transform(new IfTrueNode(iff));
4100   set_control(iftrue);
4101 }
4102 
4103 //------------------------------add_predicate---------------------------------
4104 void GraphKit::add_empty_predicates(int nargs) {
4105   // These loop predicates remain empty. All concrete loop predicates are inserted above the corresponding
4106   // empty loop predicate later by 'PhaseIdealLoop::create_new_if_for_predicate'. All concrete loop predicates of
4107   // a specific kind (normal, profile or limit check) share the same uncommon trap as the empty loop predicate.
4108   if (UseLoopPredicate) {
4109     add_empty_predicate_impl(Deoptimization::Reason_predicate, nargs);
4110   }
4111   if (UseProfiledLoopPredicate) {
4112     add_empty_predicate_impl(Deoptimization::Reason_profile_predicate, nargs);
4113   }
4114   // loop's limit check predicate should be near the loop.
4115   add_empty_predicate_impl(Deoptimization::Reason_loop_limit_check, nargs);
4116 }
4117 
4118 void GraphKit::sync_kit(IdealKit& ideal) {
4119   set_all_memory(ideal.merged_memory());
4120   set_i_o(ideal.i_o());
4121   set_control(ideal.ctrl());
4122 }
4123 
4124 void GraphKit::final_sync(IdealKit& ideal) {
4125   // Final sync IdealKit and graphKit.
4126   sync_kit(ideal);
4127 }
4128 
4129 Node* GraphKit::load_String_length(Node* str, bool set_ctrl) {
4130   Node* len = load_array_length(load_String_value(str, set_ctrl));
4131   Node* coder = load_String_coder(str, set_ctrl);
4132   // Divide length by 2 if coder is UTF16
4133   return _gvn.transform(new RShiftINode(len, coder));
4134 }
4135 
4136 Node* GraphKit::load_String_value(Node* str, bool set_ctrl) {
4137   int value_offset = java_lang_String::value_offset();
4138   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4139                                                      false, NULL, 0);
4140   const TypePtr* value_field_type = string_type->add_offset(value_offset);
4141   const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull,
4142                                                   TypeAry::make(TypeInt::BYTE, TypeInt::POS),
4143                                                   ciTypeArrayKlass::make(T_BYTE), true, 0);
4144   Node* p = basic_plus_adr(str, str, value_offset);
4145   Node* load = access_load_at(str, p, value_field_type, value_type, T_OBJECT,
4146                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4147   return load;
4148 }
4149 
4150 Node* GraphKit::load_String_coder(Node* str, bool set_ctrl) {
4151   if (!CompactStrings) {
4152     return intcon(java_lang_String::CODER_UTF16);
4153   }
4154   int coder_offset = java_lang_String::coder_offset();
4155   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4156                                                      false, NULL, 0);
4157   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4158 
4159   Node* p = basic_plus_adr(str, str, coder_offset);
4160   Node* load = access_load_at(str, p, coder_field_type, TypeInt::BYTE, T_BYTE,
4161                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4162   return load;
4163 }
4164 
4165 void GraphKit::store_String_value(Node* str, Node* value) {
4166   int value_offset = java_lang_String::value_offset();
4167   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4168                                                      false, NULL, 0);
4169   const TypePtr* value_field_type = string_type->add_offset(value_offset);
4170 
4171   access_store_at(str,  basic_plus_adr(str, value_offset), value_field_type,
4172                   value, TypeAryPtr::BYTES, T_OBJECT, IN_HEAP | MO_UNORDERED);
4173 }
4174 
4175 void GraphKit::store_String_coder(Node* str, Node* value) {
4176   int coder_offset = java_lang_String::coder_offset();
4177   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4178                                                      false, NULL, 0);
4179   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4180 
4181   access_store_at(str, basic_plus_adr(str, coder_offset), coder_field_type,
4182                   value, TypeInt::BYTE, T_BYTE, IN_HEAP | MO_UNORDERED);
4183 }
4184 
4185 // Capture src and dst memory state with a MergeMemNode
4186 Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) {
4187   if (src_type == dst_type) {
4188     // Types are equal, we don't need a MergeMemNode
4189     return memory(src_type);
4190   }
4191   MergeMemNode* merge = MergeMemNode::make(map()->memory());
4192   record_for_igvn(merge); // fold it up later, if possible
4193   int src_idx = C->get_alias_index(src_type);
4194   int dst_idx = C->get_alias_index(dst_type);
4195   merge->set_memory_at(src_idx, memory(src_idx));
4196   merge->set_memory_at(dst_idx, memory(dst_idx));
4197   return merge;
4198 }
4199 
4200 Node* GraphKit::compress_string(Node* src, const TypeAryPtr* src_type, Node* dst, Node* count) {
4201   assert(Matcher::match_rule_supported(Op_StrCompressedCopy), "Intrinsic not supported");
4202   assert(src_type == TypeAryPtr::BYTES || src_type == TypeAryPtr::CHARS, "invalid source type");
4203   // If input and output memory types differ, capture both states to preserve
4204   // the dependency between preceding and subsequent loads/stores.
4205   // For example, the following program:
4206   //  StoreB
4207   //  compress_string
4208   //  LoadB
4209   // has this memory graph (use->def):
4210   //  LoadB -> compress_string -> CharMem
4211   //             ... -> StoreB -> ByteMem
4212   // The intrinsic hides the dependency between LoadB and StoreB, causing
4213   // the load to read from memory not containing the result of the StoreB.
4214   // The correct memory graph should look like this:
4215   //  LoadB -> compress_string -> MergeMem(CharMem, StoreB(ByteMem))
4216   Node* mem = capture_memory(src_type, TypeAryPtr::BYTES);
4217   StrCompressedCopyNode* str = new StrCompressedCopyNode(control(), mem, src, dst, count);
4218   Node* res_mem = _gvn.transform(new SCMemProjNode(_gvn.transform(str)));
4219   set_memory(res_mem, TypeAryPtr::BYTES);
4220   return str;
4221 }
4222 
4223 void GraphKit::inflate_string(Node* src, Node* dst, const TypeAryPtr* dst_type, Node* count) {
4224   assert(Matcher::match_rule_supported(Op_StrInflatedCopy), "Intrinsic not supported");
4225   assert(dst_type == TypeAryPtr::BYTES || dst_type == TypeAryPtr::CHARS, "invalid dest type");
4226   // Capture src and dst memory (see comment in 'compress_string').
4227   Node* mem = capture_memory(TypeAryPtr::BYTES, dst_type);
4228   StrInflatedCopyNode* str = new StrInflatedCopyNode(control(), mem, src, dst, count);
4229   set_memory(_gvn.transform(str), dst_type);
4230 }
4231 
4232 void GraphKit::inflate_string_slow(Node* src, Node* dst, Node* start, Node* count) {
4233   /**
4234    * int i_char = start;
4235    * for (int i_byte = 0; i_byte < count; i_byte++) {
4236    *   dst[i_char++] = (char)(src[i_byte] & 0xff);
4237    * }
4238    */
4239   add_empty_predicates();
4240   C->set_has_loops(true);
4241 
4242   RegionNode* head = new RegionNode(3);
4243   head->init_req(1, control());
4244   gvn().set_type(head, Type::CONTROL);
4245   record_for_igvn(head);
4246 
4247   Node* i_byte = new PhiNode(head, TypeInt::INT);
4248   i_byte->init_req(1, intcon(0));
4249   gvn().set_type(i_byte, TypeInt::INT);
4250   record_for_igvn(i_byte);
4251 
4252   Node* i_char = new PhiNode(head, TypeInt::INT);
4253   i_char->init_req(1, start);
4254   gvn().set_type(i_char, TypeInt::INT);
4255   record_for_igvn(i_char);
4256 
4257   Node* mem = PhiNode::make(head, memory(TypeAryPtr::BYTES), Type::MEMORY, TypeAryPtr::BYTES);
4258   gvn().set_type(mem, Type::MEMORY);
4259   record_for_igvn(mem);
4260   set_control(head);
4261   set_memory(mem, TypeAryPtr::BYTES);
4262   Node* ch = load_array_element(src, i_byte, TypeAryPtr::BYTES, /* set_ctrl */ true);
4263   Node* st = store_to_memory(control(), array_element_address(dst, i_char, T_BYTE),
4264                              AndI(ch, intcon(0xff)), T_CHAR, TypeAryPtr::BYTES, MemNode::unordered,
4265                              false, false, true /* mismatched */);
4266 
4267   IfNode* iff = create_and_map_if(head, Bool(CmpI(i_byte, count), BoolTest::lt), PROB_FAIR, COUNT_UNKNOWN);
4268   head->init_req(2, IfTrue(iff));
4269   mem->init_req(2, st);
4270   i_byte->init_req(2, AddI(i_byte, intcon(1)));
4271   i_char->init_req(2, AddI(i_char, intcon(2)));
4272 
4273   set_control(IfFalse(iff));
4274   set_memory(st, TypeAryPtr::BYTES);
4275 }
4276 
4277 Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) {
4278   if (!field->is_constant()) {
4279     return NULL; // Field not marked as constant.
4280   }
4281   ciInstance* holder = NULL;
4282   if (!field->is_static()) {
4283     ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop();
4284     if (const_oop != NULL && const_oop->is_instance()) {
4285       holder = const_oop->as_instance();
4286     }
4287   }
4288   const Type* con_type = Type::make_constant_from_field(field, holder, field->layout_type(),
4289                                                         /*is_unsigned_load=*/false);
4290   if (con_type != NULL) {
4291     return makecon(con_type);
4292   }
4293   return NULL;
4294 }