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