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