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