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