1 /*
   2  * Copyright (c) 1999, 2025, 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/macroAssembler.hpp"
  26 #include "ci/ciArrayKlass.hpp"
  27 #include "ci/ciFlatArrayKlass.hpp"
  28 #include "ci/ciInstanceKlass.hpp"
  29 #include "ci/ciSymbols.hpp"
  30 #include "ci/ciUtilities.inline.hpp"
  31 #include "classfile/vmIntrinsics.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/compileLog.hpp"
  34 #include "gc/shared/barrierSet.hpp"
  35 #include "gc/shared/c2/barrierSetC2.hpp"
  36 #include "jfr/support/jfrIntrinsics.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "oops/accessDecorators.hpp"
  39 #include "oops/klass.inline.hpp"
  40 #include "oops/layoutKind.hpp"
  41 #include "oops/objArrayKlass.hpp"
  42 #include "opto/addnode.hpp"
  43 #include "opto/arraycopynode.hpp"
  44 #include "opto/c2compiler.hpp"
  45 #include "opto/castnode.hpp"
  46 #include "opto/cfgnode.hpp"
  47 #include "opto/convertnode.hpp"
  48 #include "opto/countbitsnode.hpp"
  49 #include "opto/graphKit.hpp"
  50 #include "opto/idealKit.hpp"
  51 #include "opto/inlinetypenode.hpp"
  52 #include "opto/library_call.hpp"
  53 #include "opto/mathexactnode.hpp"
  54 #include "opto/mulnode.hpp"
  55 #include "opto/narrowptrnode.hpp"
  56 #include "opto/opaquenode.hpp"
  57 #include "opto/opcodes.hpp"
  58 #include "opto/parse.hpp"
  59 #include "opto/rootnode.hpp"
  60 #include "opto/runtime.hpp"
  61 #include "opto/subnode.hpp"
  62 #include "opto/type.hpp"
  63 #include "opto/vectornode.hpp"
  64 #include "prims/jvmtiExport.hpp"
  65 #include "prims/jvmtiThreadState.hpp"
  66 #include "prims/unsafe.hpp"
  67 #include "runtime/jniHandles.inline.hpp"
  68 #include "runtime/objectMonitor.hpp"
  69 #include "runtime/sharedRuntime.hpp"
  70 #include "runtime/stubRoutines.hpp"
  71 #include "utilities/globalDefinitions.hpp"
  72 #include "utilities/macros.hpp"
  73 #include "utilities/powerOfTwo.hpp"
  74 
  75 //---------------------------make_vm_intrinsic----------------------------
  76 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  77   vmIntrinsicID id = m->intrinsic_id();
  78   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  79 
  80   if (!m->is_loaded()) {
  81     // Do not attempt to inline unloaded methods.
  82     return nullptr;
  83   }
  84 
  85   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  86   bool is_available = false;
  87 
  88   {
  89     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  90     // the compiler must transition to '_thread_in_vm' state because both
  91     // methods access VM-internal data.
  92     VM_ENTRY_MARK;
  93     methodHandle mh(THREAD, m->get_Method());
  94     is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
  95     if (is_available && is_virtual) {
  96       is_available = vmIntrinsics::does_virtual_dispatch(id);
  97     }
  98   }
  99 
 100   if (is_available) {
 101     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
 102     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
 103     return new LibraryIntrinsic(m, is_virtual,
 104                                 vmIntrinsics::predicates_needed(id),
 105                                 vmIntrinsics::does_virtual_dispatch(id),
 106                                 id);
 107   } else {
 108     return nullptr;
 109   }
 110 }
 111 
 112 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 113   LibraryCallKit kit(jvms, this);
 114   Compile* C = kit.C;
 115   int nodes = C->unique();
 116 #ifndef PRODUCT
 117   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 118     char buf[1000];
 119     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 120     tty->print_cr("Intrinsic %s", str);
 121   }
 122 #endif
 123   ciMethod* callee = kit.callee();
 124   const int bci    = kit.bci();
 125 #ifdef ASSERT
 126   Node* ctrl = kit.control();
 127 #endif
 128   // Try to inline the intrinsic.
 129   if (callee->check_intrinsic_candidate() &&
 130       kit.try_to_inline(_last_predicate)) {
 131     const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
 132                                           : "(intrinsic)";
 133     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 134     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 135     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 136     if (C->log()) {
 137       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 138                      vmIntrinsics::name_at(intrinsic_id()),
 139                      (is_virtual() ? " virtual='1'" : ""),
 140                      C->unique() - nodes);
 141     }
 142     // Push the result from the inlined method onto the stack.
 143     kit.push_result();
 144     return kit.transfer_exceptions_into_jvms();
 145   }
 146 
 147   // The intrinsic bailed out
 148   assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
 149   if (jvms->has_method()) {
 150     // Not a root compile.
 151     const char* msg;
 152     if (callee->intrinsic_candidate()) {
 153       msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 154     } else {
 155       msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
 156                          : "failed to inline (intrinsic), method not annotated";
 157     }
 158     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 159     C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
 160   } else {
 161     // Root compile
 162     ResourceMark rm;
 163     stringStream msg_stream;
 164     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 165                      vmIntrinsics::name_at(intrinsic_id()),
 166                      is_virtual() ? " (virtual)" : "", bci);
 167     const char *msg = msg_stream.freeze();
 168     log_debug(jit, inlining)("%s", msg);
 169     if (C->print_intrinsics() || C->print_inlining()) {
 170       tty->print("%s", msg);
 171     }
 172   }
 173   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 174 
 175   return nullptr;
 176 }
 177 
 178 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
 179   LibraryCallKit kit(jvms, this);
 180   Compile* C = kit.C;
 181   int nodes = C->unique();
 182   _last_predicate = predicate;
 183 #ifndef PRODUCT
 184   assert(is_predicated() && predicate < predicates_count(), "sanity");
 185   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 186     char buf[1000];
 187     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 188     tty->print_cr("Predicate for intrinsic %s", str);
 189   }
 190 #endif
 191   ciMethod* callee = kit.callee();
 192   const int bci    = kit.bci();
 193 
 194   Node* slow_ctl = kit.try_to_predicate(predicate);
 195   if (!kit.failing()) {
 196     const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
 197                                           : "(intrinsic, predicate)";
 198     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 199     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 200 
 201     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 202     if (C->log()) {
 203       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
 204                      vmIntrinsics::name_at(intrinsic_id()),
 205                      (is_virtual() ? " virtual='1'" : ""),
 206                      C->unique() - nodes);
 207     }
 208     return slow_ctl; // Could be null if the check folds.
 209   }
 210 
 211   // The intrinsic bailed out
 212   if (jvms->has_method()) {
 213     // Not a root compile.
 214     const char* msg = "failed to generate predicate for intrinsic";
 215     CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 216     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 217   } else {
 218     // Root compile
 219     ResourceMark rm;
 220     stringStream msg_stream;
 221     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 222                      vmIntrinsics::name_at(intrinsic_id()),
 223                      is_virtual() ? " (virtual)" : "", bci);
 224     const char *msg = msg_stream.freeze();
 225     log_debug(jit, inlining)("%s", msg);
 226     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 227   }
 228   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 229   return nullptr;
 230 }
 231 
 232 bool LibraryCallKit::try_to_inline(int predicate) {
 233   // Handle symbolic names for otherwise undistinguished boolean switches:
 234   const bool is_store       = true;
 235   const bool is_compress    = true;
 236   const bool is_static      = true;
 237   const bool is_volatile    = true;
 238 
 239   if (!jvms()->has_method()) {
 240     // Root JVMState has a null method.
 241     assert(map()->memory()->Opcode() == Op_Parm, "");
 242     // Insert the memory aliasing node
 243     set_all_memory(reset_memory());
 244   }
 245   assert(merged_memory(), "");
 246 
 247   switch (intrinsic_id()) {
 248   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 249   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
 250   case vmIntrinsics::_getClass:                 return inline_native_getClass();
 251 
 252   case vmIntrinsics::_ceil:
 253   case vmIntrinsics::_floor:
 254   case vmIntrinsics::_rint:
 255   case vmIntrinsics::_dsin:
 256   case vmIntrinsics::_dcos:
 257   case vmIntrinsics::_dtan:
 258   case vmIntrinsics::_dtanh:
 259   case vmIntrinsics::_dcbrt:
 260   case vmIntrinsics::_dabs:
 261   case vmIntrinsics::_fabs:
 262   case vmIntrinsics::_iabs:
 263   case vmIntrinsics::_labs:
 264   case vmIntrinsics::_datan2:
 265   case vmIntrinsics::_dsqrt:
 266   case vmIntrinsics::_dsqrt_strict:
 267   case vmIntrinsics::_dexp:
 268   case vmIntrinsics::_dlog:
 269   case vmIntrinsics::_dlog10:
 270   case vmIntrinsics::_dpow:
 271   case vmIntrinsics::_dcopySign:
 272   case vmIntrinsics::_fcopySign:
 273   case vmIntrinsics::_dsignum:
 274   case vmIntrinsics::_roundF:
 275   case vmIntrinsics::_roundD:
 276   case vmIntrinsics::_fsignum:                  return inline_math_native(intrinsic_id());
 277 
 278   case vmIntrinsics::_notify:
 279   case vmIntrinsics::_notifyAll:
 280     return inline_notify(intrinsic_id());
 281 
 282   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
 283   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
 284   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
 285   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
 286   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
 287   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
 288   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
 289   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
 290   case vmIntrinsics::_multiplyHigh:             return inline_math_multiplyHigh();
 291   case vmIntrinsics::_unsignedMultiplyHigh:     return inline_math_unsignedMultiplyHigh();
 292   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
 293   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
 294   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
 295   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
 296 
 297   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
 298 
 299   case vmIntrinsics::_arraySort:                return inline_array_sort();
 300   case vmIntrinsics::_arrayPartition:           return inline_array_partition();
 301 
 302   case vmIntrinsics::_compareToL:               return inline_string_compareTo(StrIntrinsicNode::LL);
 303   case vmIntrinsics::_compareToU:               return inline_string_compareTo(StrIntrinsicNode::UU);
 304   case vmIntrinsics::_compareToLU:              return inline_string_compareTo(StrIntrinsicNode::LU);
 305   case vmIntrinsics::_compareToUL:              return inline_string_compareTo(StrIntrinsicNode::UL);
 306 
 307   case vmIntrinsics::_indexOfL:                 return inline_string_indexOf(StrIntrinsicNode::LL);
 308   case vmIntrinsics::_indexOfU:                 return inline_string_indexOf(StrIntrinsicNode::UU);
 309   case vmIntrinsics::_indexOfUL:                return inline_string_indexOf(StrIntrinsicNode::UL);
 310   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
 311   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
 312   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
 313   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar(StrIntrinsicNode::U);
 314   case vmIntrinsics::_indexOfL_char:            return inline_string_indexOfChar(StrIntrinsicNode::L);
 315 
 316   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
 317 
 318   case vmIntrinsics::_vectorizedHashCode:       return inline_vectorizedHashCode();
 319 
 320   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
 321   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
 322   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
 323   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
 324 
 325   case vmIntrinsics::_compressStringC:
 326   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
 327   case vmIntrinsics::_inflateStringC:
 328   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
 329 
 330   case vmIntrinsics::_makePrivateBuffer:        return inline_unsafe_make_private_buffer();
 331   case vmIntrinsics::_finishPrivateBuffer:      return inline_unsafe_finish_private_buffer();
 332   case vmIntrinsics::_getReference:             return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false);
 333   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_store, T_BOOLEAN,  Relaxed, false);
 334   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_store, T_BYTE,     Relaxed, false);
 335   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, false);
 336   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, false);
 337   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_store, T_INT,      Relaxed, false);
 338   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_store, T_LONG,     Relaxed, false);
 339   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_store, T_FLOAT,    Relaxed, false);
 340   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_store, T_DOUBLE,   Relaxed, false);
 341   case vmIntrinsics::_getValue:                 return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false, true);
 342 
 343   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 344   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 345   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 346   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 347   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 348   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 349   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 350   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 351   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
 352   case vmIntrinsics::_putValue:                 return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false, true);
 353 
 354   case vmIntrinsics::_getReferenceVolatile:     return inline_unsafe_access(!is_store, T_OBJECT,   Volatile, false);
 355   case vmIntrinsics::_getBooleanVolatile:       return inline_unsafe_access(!is_store, T_BOOLEAN,  Volatile, false);
 356   case vmIntrinsics::_getByteVolatile:          return inline_unsafe_access(!is_store, T_BYTE,     Volatile, false);
 357   case vmIntrinsics::_getShortVolatile:         return inline_unsafe_access(!is_store, T_SHORT,    Volatile, false);
 358   case vmIntrinsics::_getCharVolatile:          return inline_unsafe_access(!is_store, T_CHAR,     Volatile, false);
 359   case vmIntrinsics::_getIntVolatile:           return inline_unsafe_access(!is_store, T_INT,      Volatile, false);
 360   case vmIntrinsics::_getLongVolatile:          return inline_unsafe_access(!is_store, T_LONG,     Volatile, false);
 361   case vmIntrinsics::_getFloatVolatile:         return inline_unsafe_access(!is_store, T_FLOAT,    Volatile, false);
 362   case vmIntrinsics::_getDoubleVolatile:        return inline_unsafe_access(!is_store, T_DOUBLE,   Volatile, false);
 363 
 364   case vmIntrinsics::_putReferenceVolatile:     return inline_unsafe_access( is_store, T_OBJECT,   Volatile, false);
 365   case vmIntrinsics::_putBooleanVolatile:       return inline_unsafe_access( is_store, T_BOOLEAN,  Volatile, false);
 366   case vmIntrinsics::_putByteVolatile:          return inline_unsafe_access( is_store, T_BYTE,     Volatile, false);
 367   case vmIntrinsics::_putShortVolatile:         return inline_unsafe_access( is_store, T_SHORT,    Volatile, false);
 368   case vmIntrinsics::_putCharVolatile:          return inline_unsafe_access( is_store, T_CHAR,     Volatile, false);
 369   case vmIntrinsics::_putIntVolatile:           return inline_unsafe_access( is_store, T_INT,      Volatile, false);
 370   case vmIntrinsics::_putLongVolatile:          return inline_unsafe_access( is_store, T_LONG,     Volatile, false);
 371   case vmIntrinsics::_putFloatVolatile:         return inline_unsafe_access( is_store, T_FLOAT,    Volatile, false);
 372   case vmIntrinsics::_putDoubleVolatile:        return inline_unsafe_access( is_store, T_DOUBLE,   Volatile, false);
 373 
 374   case vmIntrinsics::_getShortUnaligned:        return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, true);
 375   case vmIntrinsics::_getCharUnaligned:         return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, true);
 376   case vmIntrinsics::_getIntUnaligned:          return inline_unsafe_access(!is_store, T_INT,      Relaxed, true);
 377   case vmIntrinsics::_getLongUnaligned:         return inline_unsafe_access(!is_store, T_LONG,     Relaxed, true);
 378 
 379   case vmIntrinsics::_putShortUnaligned:        return inline_unsafe_access( is_store, T_SHORT,    Relaxed, true);
 380   case vmIntrinsics::_putCharUnaligned:         return inline_unsafe_access( is_store, T_CHAR,     Relaxed, true);
 381   case vmIntrinsics::_putIntUnaligned:          return inline_unsafe_access( is_store, T_INT,      Relaxed, true);
 382   case vmIntrinsics::_putLongUnaligned:         return inline_unsafe_access( is_store, T_LONG,     Relaxed, true);
 383 
 384   case vmIntrinsics::_getReferenceAcquire:      return inline_unsafe_access(!is_store, T_OBJECT,   Acquire, false);
 385   case vmIntrinsics::_getBooleanAcquire:        return inline_unsafe_access(!is_store, T_BOOLEAN,  Acquire, false);
 386   case vmIntrinsics::_getByteAcquire:           return inline_unsafe_access(!is_store, T_BYTE,     Acquire, false);
 387   case vmIntrinsics::_getShortAcquire:          return inline_unsafe_access(!is_store, T_SHORT,    Acquire, false);
 388   case vmIntrinsics::_getCharAcquire:           return inline_unsafe_access(!is_store, T_CHAR,     Acquire, false);
 389   case vmIntrinsics::_getIntAcquire:            return inline_unsafe_access(!is_store, T_INT,      Acquire, false);
 390   case vmIntrinsics::_getLongAcquire:           return inline_unsafe_access(!is_store, T_LONG,     Acquire, false);
 391   case vmIntrinsics::_getFloatAcquire:          return inline_unsafe_access(!is_store, T_FLOAT,    Acquire, false);
 392   case vmIntrinsics::_getDoubleAcquire:         return inline_unsafe_access(!is_store, T_DOUBLE,   Acquire, false);
 393 
 394   case vmIntrinsics::_putReferenceRelease:      return inline_unsafe_access( is_store, T_OBJECT,   Release, false);
 395   case vmIntrinsics::_putBooleanRelease:        return inline_unsafe_access( is_store, T_BOOLEAN,  Release, false);
 396   case vmIntrinsics::_putByteRelease:           return inline_unsafe_access( is_store, T_BYTE,     Release, false);
 397   case vmIntrinsics::_putShortRelease:          return inline_unsafe_access( is_store, T_SHORT,    Release, false);
 398   case vmIntrinsics::_putCharRelease:           return inline_unsafe_access( is_store, T_CHAR,     Release, false);
 399   case vmIntrinsics::_putIntRelease:            return inline_unsafe_access( is_store, T_INT,      Release, false);
 400   case vmIntrinsics::_putLongRelease:           return inline_unsafe_access( is_store, T_LONG,     Release, false);
 401   case vmIntrinsics::_putFloatRelease:          return inline_unsafe_access( is_store, T_FLOAT,    Release, false);
 402   case vmIntrinsics::_putDoubleRelease:         return inline_unsafe_access( is_store, T_DOUBLE,   Release, false);
 403 
 404   case vmIntrinsics::_getReferenceOpaque:       return inline_unsafe_access(!is_store, T_OBJECT,   Opaque, false);
 405   case vmIntrinsics::_getBooleanOpaque:         return inline_unsafe_access(!is_store, T_BOOLEAN,  Opaque, false);
 406   case vmIntrinsics::_getByteOpaque:            return inline_unsafe_access(!is_store, T_BYTE,     Opaque, false);
 407   case vmIntrinsics::_getShortOpaque:           return inline_unsafe_access(!is_store, T_SHORT,    Opaque, false);
 408   case vmIntrinsics::_getCharOpaque:            return inline_unsafe_access(!is_store, T_CHAR,     Opaque, false);
 409   case vmIntrinsics::_getIntOpaque:             return inline_unsafe_access(!is_store, T_INT,      Opaque, false);
 410   case vmIntrinsics::_getLongOpaque:            return inline_unsafe_access(!is_store, T_LONG,     Opaque, false);
 411   case vmIntrinsics::_getFloatOpaque:           return inline_unsafe_access(!is_store, T_FLOAT,    Opaque, false);
 412   case vmIntrinsics::_getDoubleOpaque:          return inline_unsafe_access(!is_store, T_DOUBLE,   Opaque, false);
 413 
 414   case vmIntrinsics::_putReferenceOpaque:       return inline_unsafe_access( is_store, T_OBJECT,   Opaque, false);
 415   case vmIntrinsics::_putBooleanOpaque:         return inline_unsafe_access( is_store, T_BOOLEAN,  Opaque, false);
 416   case vmIntrinsics::_putByteOpaque:            return inline_unsafe_access( is_store, T_BYTE,     Opaque, false);
 417   case vmIntrinsics::_putShortOpaque:           return inline_unsafe_access( is_store, T_SHORT,    Opaque, false);
 418   case vmIntrinsics::_putCharOpaque:            return inline_unsafe_access( is_store, T_CHAR,     Opaque, false);
 419   case vmIntrinsics::_putIntOpaque:             return inline_unsafe_access( is_store, T_INT,      Opaque, false);
 420   case vmIntrinsics::_putLongOpaque:            return inline_unsafe_access( is_store, T_LONG,     Opaque, false);
 421   case vmIntrinsics::_putFloatOpaque:           return inline_unsafe_access( is_store, T_FLOAT,    Opaque, false);
 422   case vmIntrinsics::_putDoubleOpaque:          return inline_unsafe_access( is_store, T_DOUBLE,   Opaque, false);
 423 
 424   case vmIntrinsics::_getFlatValue:             return inline_unsafe_flat_access(!is_store, Relaxed);
 425   case vmIntrinsics::_putFlatValue:             return inline_unsafe_flat_access( is_store, Relaxed);
 426 
 427   case vmIntrinsics::_compareAndSetReference:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap,      Volatile);
 428   case vmIntrinsics::_compareAndSetByte:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap,      Volatile);
 429   case vmIntrinsics::_compareAndSetShort:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap,      Volatile);
 430   case vmIntrinsics::_compareAndSetInt:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap,      Volatile);
 431   case vmIntrinsics::_compareAndSetLong:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap,      Volatile);
 432 
 433   case vmIntrinsics::_weakCompareAndSetReferencePlain:     return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
 434   case vmIntrinsics::_weakCompareAndSetReferenceAcquire:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
 435   case vmIntrinsics::_weakCompareAndSetReferenceRelease:   return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
 436   case vmIntrinsics::_weakCompareAndSetReference:          return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
 437   case vmIntrinsics::_weakCompareAndSetBytePlain:          return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Relaxed);
 438   case vmIntrinsics::_weakCompareAndSetByteAcquire:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Acquire);
 439   case vmIntrinsics::_weakCompareAndSetByteRelease:        return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Release);
 440   case vmIntrinsics::_weakCompareAndSetByte:               return inline_unsafe_load_store(T_BYTE,   LS_cmp_swap_weak, Volatile);
 441   case vmIntrinsics::_weakCompareAndSetShortPlain:         return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Relaxed);
 442   case vmIntrinsics::_weakCompareAndSetShortAcquire:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Acquire);
 443   case vmIntrinsics::_weakCompareAndSetShortRelease:       return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Release);
 444   case vmIntrinsics::_weakCompareAndSetShort:              return inline_unsafe_load_store(T_SHORT,  LS_cmp_swap_weak, Volatile);
 445   case vmIntrinsics::_weakCompareAndSetIntPlain:           return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Relaxed);
 446   case vmIntrinsics::_weakCompareAndSetIntAcquire:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Acquire);
 447   case vmIntrinsics::_weakCompareAndSetIntRelease:         return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Release);
 448   case vmIntrinsics::_weakCompareAndSetInt:                return inline_unsafe_load_store(T_INT,    LS_cmp_swap_weak, Volatile);
 449   case vmIntrinsics::_weakCompareAndSetLongPlain:          return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Relaxed);
 450   case vmIntrinsics::_weakCompareAndSetLongAcquire:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Acquire);
 451   case vmIntrinsics::_weakCompareAndSetLongRelease:        return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Release);
 452   case vmIntrinsics::_weakCompareAndSetLong:               return inline_unsafe_load_store(T_LONG,   LS_cmp_swap_weak, Volatile);
 453 
 454   case vmIntrinsics::_compareAndExchangeReference:         return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Volatile);
 455   case vmIntrinsics::_compareAndExchangeReferenceAcquire:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Acquire);
 456   case vmIntrinsics::_compareAndExchangeReferenceRelease:  return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange,  Release);
 457   case vmIntrinsics::_compareAndExchangeByte:              return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Volatile);
 458   case vmIntrinsics::_compareAndExchangeByteAcquire:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Acquire);
 459   case vmIntrinsics::_compareAndExchangeByteRelease:       return inline_unsafe_load_store(T_BYTE,   LS_cmp_exchange,  Release);
 460   case vmIntrinsics::_compareAndExchangeShort:             return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Volatile);
 461   case vmIntrinsics::_compareAndExchangeShortAcquire:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Acquire);
 462   case vmIntrinsics::_compareAndExchangeShortRelease:      return inline_unsafe_load_store(T_SHORT,  LS_cmp_exchange,  Release);
 463   case vmIntrinsics::_compareAndExchangeInt:               return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Volatile);
 464   case vmIntrinsics::_compareAndExchangeIntAcquire:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Acquire);
 465   case vmIntrinsics::_compareAndExchangeIntRelease:        return inline_unsafe_load_store(T_INT,    LS_cmp_exchange,  Release);
 466   case vmIntrinsics::_compareAndExchangeLong:              return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Volatile);
 467   case vmIntrinsics::_compareAndExchangeLongAcquire:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Acquire);
 468   case vmIntrinsics::_compareAndExchangeLongRelease:       return inline_unsafe_load_store(T_LONG,   LS_cmp_exchange,  Release);
 469 
 470   case vmIntrinsics::_getAndAddByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_add,       Volatile);
 471   case vmIntrinsics::_getAndAddShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_add,       Volatile);
 472   case vmIntrinsics::_getAndAddInt:                     return inline_unsafe_load_store(T_INT,    LS_get_add,       Volatile);
 473   case vmIntrinsics::_getAndAddLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_add,       Volatile);
 474 
 475   case vmIntrinsics::_getAndSetByte:                    return inline_unsafe_load_store(T_BYTE,   LS_get_set,       Volatile);
 476   case vmIntrinsics::_getAndSetShort:                   return inline_unsafe_load_store(T_SHORT,  LS_get_set,       Volatile);
 477   case vmIntrinsics::_getAndSetInt:                     return inline_unsafe_load_store(T_INT,    LS_get_set,       Volatile);
 478   case vmIntrinsics::_getAndSetLong:                    return inline_unsafe_load_store(T_LONG,   LS_get_set,       Volatile);
 479   case vmIntrinsics::_getAndSetReference:               return inline_unsafe_load_store(T_OBJECT, LS_get_set,       Volatile);
 480 
 481   case vmIntrinsics::_loadFence:
 482   case vmIntrinsics::_storeFence:
 483   case vmIntrinsics::_storeStoreFence:
 484   case vmIntrinsics::_fullFence:                return inline_unsafe_fence(intrinsic_id());
 485 
 486   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 487 
 488   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 489   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 490   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 491 
 492   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 493   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 494 
 495   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 496   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 497 
 498 #if INCLUDE_JVMTI
 499   case vmIntrinsics::_notifyJvmtiVThreadStart:   return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_start()),
 500                                                                                          "notifyJvmtiStart", true, false);
 501   case vmIntrinsics::_notifyJvmtiVThreadEnd:     return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_end()),
 502                                                                                          "notifyJvmtiEnd", false, true);
 503   case vmIntrinsics::_notifyJvmtiVThreadMount:   return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_mount()),
 504                                                                                          "notifyJvmtiMount", false, false);
 505   case vmIntrinsics::_notifyJvmtiVThreadUnmount: return inline_native_notify_jvmti_funcs(CAST_FROM_FN_PTR(address, OptoRuntime::notify_jvmti_vthread_unmount()),
 506                                                                                          "notifyJvmtiUnmount", false, false);
 507   case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
 508 #endif
 509 
 510 #ifdef JFR_HAVE_INTRINSICS
 511   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
 512   case vmIntrinsics::_getEventWriter:           return inline_native_getEventWriter();
 513   case vmIntrinsics::_jvm_commit:               return inline_native_jvm_commit();
 514 #endif
 515   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 516   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 517   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 518   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 519   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 520   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 521   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 522   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
 523   case vmIntrinsics::_getLength:                return inline_native_getLength();
 524   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 525   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 526   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 527   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 528   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 529   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 530   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 531 
 532   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 533   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);
 534   case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
 535   case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
 536   case vmIntrinsics::_newNullableAtomicArray:     return inline_newArray(/* null_free */ false, /* atomic */ true);
 537 
 538   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 539 
 540   case vmIntrinsics::_isInstance:
 541   case vmIntrinsics::_isHidden:
 542   case vmIntrinsics::_getSuperclass:
 543   case vmIntrinsics::_getClassAccessFlags:      return inline_native_Class_query(intrinsic_id());
 544 
 545   case vmIntrinsics::_floatToRawIntBits:
 546   case vmIntrinsics::_floatToIntBits:
 547   case vmIntrinsics::_intBitsToFloat:
 548   case vmIntrinsics::_doubleToRawLongBits:
 549   case vmIntrinsics::_doubleToLongBits:
 550   case vmIntrinsics::_longBitsToDouble:
 551   case vmIntrinsics::_floatToFloat16:
 552   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
 553   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
 554   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
 555   case vmIntrinsics::_floatIsFinite:
 556   case vmIntrinsics::_floatIsInfinite:
 557   case vmIntrinsics::_doubleIsFinite:
 558   case vmIntrinsics::_doubleIsInfinite:         return inline_fp_range_check(intrinsic_id());
 559 
 560   case vmIntrinsics::_numberOfLeadingZeros_i:
 561   case vmIntrinsics::_numberOfLeadingZeros_l:
 562   case vmIntrinsics::_numberOfTrailingZeros_i:
 563   case vmIntrinsics::_numberOfTrailingZeros_l:
 564   case vmIntrinsics::_bitCount_i:
 565   case vmIntrinsics::_bitCount_l:
 566   case vmIntrinsics::_reverse_i:
 567   case vmIntrinsics::_reverse_l:
 568   case vmIntrinsics::_reverseBytes_i:
 569   case vmIntrinsics::_reverseBytes_l:
 570   case vmIntrinsics::_reverseBytes_s:
 571   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
 572 
 573   case vmIntrinsics::_compress_i:
 574   case vmIntrinsics::_compress_l:
 575   case vmIntrinsics::_expand_i:
 576   case vmIntrinsics::_expand_l:                 return inline_bitshuffle_methods(intrinsic_id());
 577 
 578   case vmIntrinsics::_compareUnsigned_i:
 579   case vmIntrinsics::_compareUnsigned_l:        return inline_compare_unsigned(intrinsic_id());
 580 
 581   case vmIntrinsics::_divideUnsigned_i:
 582   case vmIntrinsics::_divideUnsigned_l:
 583   case vmIntrinsics::_remainderUnsigned_i:
 584   case vmIntrinsics::_remainderUnsigned_l:      return inline_divmod_methods(intrinsic_id());
 585 
 586   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
 587 
 588   case vmIntrinsics::_Reference_get0:           return inline_reference_get0();
 589   case vmIntrinsics::_Reference_refersTo0:      return inline_reference_refersTo0(false);
 590   case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
 591   case vmIntrinsics::_Reference_clear0:         return inline_reference_clear0(false);
 592   case vmIntrinsics::_PhantomReference_clear0:  return inline_reference_clear0(true);
 593 
 594   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 595 
 596   case vmIntrinsics::_aescrypt_encryptBlock:
 597   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 598 
 599   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 600   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 601     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 602 
 603   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 604   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 605     return inline_electronicCodeBook_AESCrypt(intrinsic_id());
 606 
 607   case vmIntrinsics::_counterMode_AESCrypt:
 608     return inline_counterMode_AESCrypt(intrinsic_id());
 609 
 610   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 611     return inline_galoisCounterMode_AESCrypt();
 612 
 613   case vmIntrinsics::_md5_implCompress:
 614   case vmIntrinsics::_sha_implCompress:
 615   case vmIntrinsics::_sha2_implCompress:
 616   case vmIntrinsics::_sha5_implCompress:
 617   case vmIntrinsics::_sha3_implCompress:
 618     return inline_digestBase_implCompress(intrinsic_id());
 619   case vmIntrinsics::_double_keccak:
 620     return inline_double_keccak();
 621 
 622   case vmIntrinsics::_digestBase_implCompressMB:
 623     return inline_digestBase_implCompressMB(predicate);
 624 
 625   case vmIntrinsics::_multiplyToLen:
 626     return inline_multiplyToLen();
 627 
 628   case vmIntrinsics::_squareToLen:
 629     return inline_squareToLen();
 630 
 631   case vmIntrinsics::_mulAdd:
 632     return inline_mulAdd();
 633 
 634   case vmIntrinsics::_montgomeryMultiply:
 635     return inline_montgomeryMultiply();
 636   case vmIntrinsics::_montgomerySquare:
 637     return inline_montgomerySquare();
 638 
 639   case vmIntrinsics::_bigIntegerRightShiftWorker:
 640     return inline_bigIntegerShift(true);
 641   case vmIntrinsics::_bigIntegerLeftShiftWorker:
 642     return inline_bigIntegerShift(false);
 643 
 644   case vmIntrinsics::_vectorizedMismatch:
 645     return inline_vectorizedMismatch();
 646 
 647   case vmIntrinsics::_ghash_processBlocks:
 648     return inline_ghash_processBlocks();
 649   case vmIntrinsics::_chacha20Block:
 650     return inline_chacha20Block();
 651   case vmIntrinsics::_kyberNtt:
 652     return inline_kyberNtt();
 653   case vmIntrinsics::_kyberInverseNtt:
 654     return inline_kyberInverseNtt();
 655   case vmIntrinsics::_kyberNttMult:
 656     return inline_kyberNttMult();
 657   case vmIntrinsics::_kyberAddPoly_2:
 658     return inline_kyberAddPoly_2();
 659   case vmIntrinsics::_kyberAddPoly_3:
 660     return inline_kyberAddPoly_3();
 661   case vmIntrinsics::_kyber12To16:
 662     return inline_kyber12To16();
 663   case vmIntrinsics::_kyberBarrettReduce:
 664     return inline_kyberBarrettReduce();
 665   case vmIntrinsics::_dilithiumAlmostNtt:
 666     return inline_dilithiumAlmostNtt();
 667   case vmIntrinsics::_dilithiumAlmostInverseNtt:
 668     return inline_dilithiumAlmostInverseNtt();
 669   case vmIntrinsics::_dilithiumNttMult:
 670     return inline_dilithiumNttMult();
 671   case vmIntrinsics::_dilithiumMontMulByConstant:
 672     return inline_dilithiumMontMulByConstant();
 673   case vmIntrinsics::_dilithiumDecomposePoly:
 674     return inline_dilithiumDecomposePoly();
 675   case vmIntrinsics::_base64_encodeBlock:
 676     return inline_base64_encodeBlock();
 677   case vmIntrinsics::_base64_decodeBlock:
 678     return inline_base64_decodeBlock();
 679   case vmIntrinsics::_poly1305_processBlocks:
 680     return inline_poly1305_processBlocks();
 681   case vmIntrinsics::_intpoly_montgomeryMult_P256:
 682     return inline_intpoly_montgomeryMult_P256();
 683   case vmIntrinsics::_intpoly_assign:
 684     return inline_intpoly_assign();
 685   case vmIntrinsics::_encodeISOArray:
 686   case vmIntrinsics::_encodeByteISOArray:
 687     return inline_encodeISOArray(false);
 688   case vmIntrinsics::_encodeAsciiArray:
 689     return inline_encodeISOArray(true);
 690 
 691   case vmIntrinsics::_updateCRC32:
 692     return inline_updateCRC32();
 693   case vmIntrinsics::_updateBytesCRC32:
 694     return inline_updateBytesCRC32();
 695   case vmIntrinsics::_updateByteBufferCRC32:
 696     return inline_updateByteBufferCRC32();
 697 
 698   case vmIntrinsics::_updateBytesCRC32C:
 699     return inline_updateBytesCRC32C();
 700   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 701     return inline_updateDirectByteBufferCRC32C();
 702 
 703   case vmIntrinsics::_updateBytesAdler32:
 704     return inline_updateBytesAdler32();
 705   case vmIntrinsics::_updateByteBufferAdler32:
 706     return inline_updateByteBufferAdler32();
 707 
 708   case vmIntrinsics::_profileBoolean:
 709     return inline_profileBoolean();
 710   case vmIntrinsics::_isCompileConstant:
 711     return inline_isCompileConstant();
 712 
 713   case vmIntrinsics::_countPositives:
 714     return inline_countPositives();
 715 
 716   case vmIntrinsics::_fmaD:
 717   case vmIntrinsics::_fmaF:
 718     return inline_fma(intrinsic_id());
 719 
 720   case vmIntrinsics::_isDigit:
 721   case vmIntrinsics::_isLowerCase:
 722   case vmIntrinsics::_isUpperCase:
 723   case vmIntrinsics::_isWhitespace:
 724     return inline_character_compare(intrinsic_id());
 725 
 726   case vmIntrinsics::_min:
 727   case vmIntrinsics::_max:
 728   case vmIntrinsics::_min_strict:
 729   case vmIntrinsics::_max_strict:
 730   case vmIntrinsics::_minL:
 731   case vmIntrinsics::_maxL:
 732   case vmIntrinsics::_minF:
 733   case vmIntrinsics::_maxF:
 734   case vmIntrinsics::_minD:
 735   case vmIntrinsics::_maxD:
 736   case vmIntrinsics::_minF_strict:
 737   case vmIntrinsics::_maxF_strict:
 738   case vmIntrinsics::_minD_strict:
 739   case vmIntrinsics::_maxD_strict:
 740     return inline_min_max(intrinsic_id());
 741 
 742   case vmIntrinsics::_VectorUnaryOp:
 743     return inline_vector_nary_operation(1);
 744   case vmIntrinsics::_VectorBinaryOp:
 745     return inline_vector_nary_operation(2);
 746   case vmIntrinsics::_VectorUnaryLibOp:
 747     return inline_vector_call(1);
 748   case vmIntrinsics::_VectorBinaryLibOp:
 749     return inline_vector_call(2);
 750   case vmIntrinsics::_VectorTernaryOp:
 751     return inline_vector_nary_operation(3);
 752   case vmIntrinsics::_VectorFromBitsCoerced:
 753     return inline_vector_frombits_coerced();
 754   case vmIntrinsics::_VectorMaskOp:
 755     return inline_vector_mask_operation();
 756   case vmIntrinsics::_VectorLoadOp:
 757     return inline_vector_mem_operation(/*is_store=*/false);
 758   case vmIntrinsics::_VectorLoadMaskedOp:
 759     return inline_vector_mem_masked_operation(/*is_store*/false);
 760   case vmIntrinsics::_VectorStoreOp:
 761     return inline_vector_mem_operation(/*is_store=*/true);
 762   case vmIntrinsics::_VectorStoreMaskedOp:
 763     return inline_vector_mem_masked_operation(/*is_store=*/true);
 764   case vmIntrinsics::_VectorGatherOp:
 765     return inline_vector_gather_scatter(/*is_scatter*/ false);
 766   case vmIntrinsics::_VectorScatterOp:
 767     return inline_vector_gather_scatter(/*is_scatter*/ true);
 768   case vmIntrinsics::_VectorReductionCoerced:
 769     return inline_vector_reduction();
 770   case vmIntrinsics::_VectorTest:
 771     return inline_vector_test();
 772   case vmIntrinsics::_VectorBlend:
 773     return inline_vector_blend();
 774   case vmIntrinsics::_VectorRearrange:
 775     return inline_vector_rearrange();
 776   case vmIntrinsics::_VectorSelectFrom:
 777     return inline_vector_select_from();
 778   case vmIntrinsics::_VectorCompare:
 779     return inline_vector_compare();
 780   case vmIntrinsics::_VectorBroadcastInt:
 781     return inline_vector_broadcast_int();
 782   case vmIntrinsics::_VectorConvert:
 783     return inline_vector_convert();
 784   case vmIntrinsics::_VectorInsert:
 785     return inline_vector_insert();
 786   case vmIntrinsics::_VectorExtract:
 787     return inline_vector_extract();
 788   case vmIntrinsics::_VectorCompressExpand:
 789     return inline_vector_compress_expand();
 790   case vmIntrinsics::_VectorSelectFromTwoVectorOp:
 791     return inline_vector_select_from_two_vectors();
 792   case vmIntrinsics::_IndexVector:
 793     return inline_index_vector();
 794   case vmIntrinsics::_IndexPartiallyInUpperRange:
 795     return inline_index_partially_in_upper_range();
 796 
 797   case vmIntrinsics::_getObjectSize:
 798     return inline_getObjectSize();
 799 
 800   case vmIntrinsics::_blackhole:
 801     return inline_blackhole();
 802 
 803   default:
 804     // If you get here, it may be that someone has added a new intrinsic
 805     // to the list in vmIntrinsics.hpp without implementing it here.
 806 #ifndef PRODUCT
 807     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 808       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 809                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 810     }
 811 #endif
 812     return false;
 813   }
 814 }
 815 
 816 Node* LibraryCallKit::try_to_predicate(int predicate) {
 817   if (!jvms()->has_method()) {
 818     // Root JVMState has a null method.
 819     assert(map()->memory()->Opcode() == Op_Parm, "");
 820     // Insert the memory aliasing node
 821     set_all_memory(reset_memory());
 822   }
 823   assert(merged_memory(), "");
 824 
 825   switch (intrinsic_id()) {
 826   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 827     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 828   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 829     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 830   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 831     return inline_electronicCodeBook_AESCrypt_predicate(false);
 832   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 833     return inline_electronicCodeBook_AESCrypt_predicate(true);
 834   case vmIntrinsics::_counterMode_AESCrypt:
 835     return inline_counterMode_AESCrypt_predicate();
 836   case vmIntrinsics::_digestBase_implCompressMB:
 837     return inline_digestBase_implCompressMB_predicate(predicate);
 838   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 839     return inline_galoisCounterMode_AESCrypt_predicate();
 840 
 841   default:
 842     // If you get here, it may be that someone has added a new intrinsic
 843     // to the list in vmIntrinsics.hpp without implementing it here.
 844 #ifndef PRODUCT
 845     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 846       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 847                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 848     }
 849 #endif
 850     Node* slow_ctl = control();
 851     set_control(top()); // No fast path intrinsic
 852     return slow_ctl;
 853   }
 854 }
 855 
 856 //------------------------------set_result-------------------------------
 857 // Helper function for finishing intrinsics.
 858 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 859   record_for_igvn(region);
 860   set_control(_gvn.transform(region));
 861   set_result( _gvn.transform(value));
 862   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 863 }
 864 
 865 //------------------------------generate_guard---------------------------
 866 // Helper function for generating guarded fast-slow graph structures.
 867 // The given 'test', if true, guards a slow path.  If the test fails
 868 // then a fast path can be taken.  (We generally hope it fails.)
 869 // In all cases, GraphKit::control() is updated to the fast path.
 870 // The returned value represents the control for the slow path.
 871 // The return value is never 'top'; it is either a valid control
 872 // or null if it is obvious that the slow path can never be taken.
 873 // Also, if region and the slow control are not null, the slow edge
 874 // is appended to the region.
 875 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 876   if (stopped()) {
 877     // Already short circuited.
 878     return nullptr;
 879   }
 880 
 881   // Build an if node and its projections.
 882   // If test is true we take the slow path, which we assume is uncommon.
 883   if (_gvn.type(test) == TypeInt::ZERO) {
 884     // The slow branch is never taken.  No need to build this guard.
 885     return nullptr;
 886   }
 887 
 888   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 889 
 890   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
 891   if (if_slow == top()) {
 892     // The slow branch is never taken.  No need to build this guard.
 893     return nullptr;
 894   }
 895 
 896   if (region != nullptr)
 897     region->add_req(if_slow);
 898 
 899   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
 900   set_control(if_fast);
 901 
 902   return if_slow;
 903 }
 904 
 905 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 906   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 907 }
 908 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 909   return generate_guard(test, region, PROB_FAIR);
 910 }
 911 
 912 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 913                                                      Node* *pos_index) {
 914   if (stopped())
 915     return nullptr;                // already stopped
 916   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 917     return nullptr;                // index is already adequately typed
 918   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
 919   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 920   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 921   if (is_neg != nullptr && pos_index != nullptr) {
 922     // Emulate effect of Parse::adjust_map_after_if.
 923     Node* ccast = new CastIINode(control(), index, TypeInt::POS);
 924     (*pos_index) = _gvn.transform(ccast);
 925   }
 926   return is_neg;
 927 }
 928 
 929 // Make sure that 'position' is a valid limit index, in [0..length].
 930 // There are two equivalent plans for checking this:
 931 //   A. (offset + copyLength)  unsigned<=  arrayLength
 932 //   B. offset  <=  (arrayLength - copyLength)
 933 // We require that all of the values above, except for the sum and
 934 // difference, are already known to be non-negative.
 935 // Plan A is robust in the face of overflow, if offset and copyLength
 936 // are both hugely positive.
 937 //
 938 // Plan B is less direct and intuitive, but it does not overflow at
 939 // all, since the difference of two non-negatives is always
 940 // representable.  Whenever Java methods must perform the equivalent
 941 // check they generally use Plan B instead of Plan A.
 942 // For the moment we use Plan A.
 943 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 944                                                   Node* subseq_length,
 945                                                   Node* array_length,
 946                                                   RegionNode* region) {
 947   if (stopped())
 948     return nullptr;                // already stopped
 949   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 950   if (zero_offset && subseq_length->eqv_uncast(array_length))
 951     return nullptr;                // common case of whole-array copy
 952   Node* last = subseq_length;
 953   if (!zero_offset)             // last += offset
 954     last = _gvn.transform(new AddINode(last, offset));
 955   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
 956   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 957   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 958   return is_over;
 959 }
 960 
 961 // Emit range checks for the given String.value byte array
 962 void LibraryCallKit::generate_string_range_check(Node* array, Node* offset, Node* count, bool char_count) {
 963   if (stopped()) {
 964     return; // already stopped
 965   }
 966   RegionNode* bailout = new RegionNode(1);
 967   record_for_igvn(bailout);
 968   if (char_count) {
 969     // Convert char count to byte count
 970     count = _gvn.transform(new LShiftINode(count, intcon(1)));
 971   }
 972 
 973   // Offset and count must not be negative
 974   generate_negative_guard(offset, bailout);
 975   generate_negative_guard(count, bailout);
 976   // Offset + count must not exceed length of array
 977   generate_limit_guard(offset, count, load_array_length(array), bailout);
 978 
 979   if (bailout->req() > 1) {
 980     PreserveJVMState pjvms(this);
 981     set_control(_gvn.transform(bailout));
 982     uncommon_trap(Deoptimization::Reason_intrinsic,
 983                   Deoptimization::Action_maybe_recompile);
 984   }
 985 }
 986 
 987 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
 988                                             bool is_immutable) {
 989   ciKlass* thread_klass = env()->Thread_klass();
 990   const Type* thread_type
 991     = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
 992 
 993   Node* thread = _gvn.transform(new ThreadLocalNode());
 994   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(handle_offset));
 995   tls_output = thread;
 996 
 997   Node* thread_obj_handle
 998     = (is_immutable
 999       ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1000         TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1001       : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1002   thread_obj_handle = _gvn.transform(thread_obj_handle);
1003 
1004   DecoratorSet decorators = IN_NATIVE;
1005   if (is_immutable) {
1006     decorators |= C2_IMMUTABLE_MEMORY;
1007   }
1008   return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1009 }
1010 
1011 //--------------------------generate_current_thread--------------------
1012 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1013   return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1014                                /*is_immutable*/false);
1015 }
1016 
1017 //--------------------------generate_virtual_thread--------------------
1018 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1019   return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1020                                !C->method()->changes_current_thread());
1021 }
1022 
1023 //------------------------------make_string_method_node------------------------
1024 // Helper method for String intrinsic functions. This version is called with
1025 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1026 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1027 // containing the lengths of str1 and str2.
1028 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1029   Node* result = nullptr;
1030   switch (opcode) {
1031   case Op_StrIndexOf:
1032     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1033                                 str1_start, cnt1, str2_start, cnt2, ae);
1034     break;
1035   case Op_StrComp:
1036     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1037                              str1_start, cnt1, str2_start, cnt2, ae);
1038     break;
1039   case Op_StrEquals:
1040     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1041     // Use the constant length if there is one because optimized match rule may exist.
1042     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1043                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1044     break;
1045   default:
1046     ShouldNotReachHere();
1047     return nullptr;
1048   }
1049 
1050   // All these intrinsics have checks.
1051   C->set_has_split_ifs(true); // Has chance for split-if optimization
1052   clear_upper_avx();
1053 
1054   return _gvn.transform(result);
1055 }
1056 
1057 //------------------------------inline_string_compareTo------------------------
1058 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1059   Node* arg1 = argument(0);
1060   Node* arg2 = argument(1);
1061 
1062   arg1 = must_be_not_null(arg1, true);
1063   arg2 = must_be_not_null(arg2, true);
1064 
1065   // Get start addr and length of first argument
1066   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1067   Node* arg1_cnt    = load_array_length(arg1);
1068 
1069   // Get start addr and length of second argument
1070   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1071   Node* arg2_cnt    = load_array_length(arg2);
1072 
1073   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1074   set_result(result);
1075   return true;
1076 }
1077 
1078 //------------------------------inline_string_equals------------------------
1079 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1080   Node* arg1 = argument(0);
1081   Node* arg2 = argument(1);
1082 
1083   // paths (plus control) merge
1084   RegionNode* region = new RegionNode(3);
1085   Node* phi = new PhiNode(region, TypeInt::BOOL);
1086 
1087   if (!stopped()) {
1088 
1089     arg1 = must_be_not_null(arg1, true);
1090     arg2 = must_be_not_null(arg2, true);
1091 
1092     // Get start addr and length of first argument
1093     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1094     Node* arg1_cnt    = load_array_length(arg1);
1095 
1096     // Get start addr and length of second argument
1097     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1098     Node* arg2_cnt    = load_array_length(arg2);
1099 
1100     // Check for arg1_cnt != arg2_cnt
1101     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1102     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1103     Node* if_ne = generate_slow_guard(bol, nullptr);
1104     if (if_ne != nullptr) {
1105       phi->init_req(2, intcon(0));
1106       region->init_req(2, if_ne);
1107     }
1108 
1109     // Check for count == 0 is done by assembler code for StrEquals.
1110 
1111     if (!stopped()) {
1112       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1113       phi->init_req(1, equals);
1114       region->init_req(1, control());
1115     }
1116   }
1117 
1118   // post merge
1119   set_control(_gvn.transform(region));
1120   record_for_igvn(region);
1121 
1122   set_result(_gvn.transform(phi));
1123   return true;
1124 }
1125 
1126 //------------------------------inline_array_equals----------------------------
1127 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1128   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1129   Node* arg1 = argument(0);
1130   Node* arg2 = argument(1);
1131 
1132   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1133   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1134   clear_upper_avx();
1135 
1136   return true;
1137 }
1138 
1139 
1140 //------------------------------inline_countPositives------------------------------
1141 bool LibraryCallKit::inline_countPositives() {
1142   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1143     return false;
1144   }
1145 
1146   assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1147   // no receiver since it is static method
1148   Node* ba         = argument(0);
1149   Node* offset     = argument(1);
1150   Node* len        = argument(2);
1151 
1152   ba = must_be_not_null(ba, true);
1153 
1154   // Range checks
1155   generate_string_range_check(ba, offset, len, false);
1156   if (stopped()) {
1157     return true;
1158   }
1159   Node* ba_start = array_element_address(ba, offset, T_BYTE);
1160   Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1161   set_result(_gvn.transform(result));
1162   clear_upper_avx();
1163   return true;
1164 }
1165 
1166 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1167   Node* index = argument(0);
1168   Node* length = bt == T_INT ? argument(1) : argument(2);
1169   if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1170     return false;
1171   }
1172 
1173   // check that length is positive
1174   Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1175   Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1176 
1177   {
1178     BuildCutout unless(this, len_pos_bol, PROB_MAX);
1179     uncommon_trap(Deoptimization::Reason_intrinsic,
1180                   Deoptimization::Action_make_not_entrant);
1181   }
1182 
1183   if (stopped()) {
1184     // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1185     return true;
1186   }
1187 
1188   // length is now known positive, add a cast node to make this explicit
1189   jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1190   Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1191       control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1192       ConstraintCastNode::RegularDependency, bt);
1193   casted_length = _gvn.transform(casted_length);
1194   replace_in_map(length, casted_length);
1195   length = casted_length;
1196 
1197   // Use an unsigned comparison for the range check itself
1198   Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1199   BoolTest::mask btest = BoolTest::lt;
1200   Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1201   RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1202   _gvn.set_type(rc, rc->Value(&_gvn));
1203   if (!rc_bool->is_Con()) {
1204     record_for_igvn(rc);
1205   }
1206   set_control(_gvn.transform(new IfTrueNode(rc)));
1207   {
1208     PreserveJVMState pjvms(this);
1209     set_control(_gvn.transform(new IfFalseNode(rc)));
1210     uncommon_trap(Deoptimization::Reason_range_check,
1211                   Deoptimization::Action_make_not_entrant);
1212   }
1213 
1214   if (stopped()) {
1215     // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1216     return true;
1217   }
1218 
1219   // index is now known to be >= 0 and < length, cast it
1220   Node* result = ConstraintCastNode::make_cast_for_basic_type(
1221       control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1222       ConstraintCastNode::RegularDependency, bt);
1223   result = _gvn.transform(result);
1224   set_result(result);
1225   replace_in_map(index, result);
1226   return true;
1227 }
1228 
1229 //------------------------------inline_string_indexOf------------------------
1230 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1231   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1232     return false;
1233   }
1234   Node* src = argument(0);
1235   Node* tgt = argument(1);
1236 
1237   // Make the merge point
1238   RegionNode* result_rgn = new RegionNode(4);
1239   Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1240 
1241   src = must_be_not_null(src, true);
1242   tgt = must_be_not_null(tgt, true);
1243 
1244   // Get start addr and length of source string
1245   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1246   Node* src_count = load_array_length(src);
1247 
1248   // Get start addr and length of substring
1249   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1250   Node* tgt_count = load_array_length(tgt);
1251 
1252   Node* result = nullptr;
1253   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1254 
1255   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1256     // Divide src size by 2 if String is UTF16 encoded
1257     src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1258   }
1259   if (ae == StrIntrinsicNode::UU) {
1260     // Divide substring size by 2 if String is UTF16 encoded
1261     tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1262   }
1263 
1264   if (call_opt_stub) {
1265     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1266                                    StubRoutines::_string_indexof_array[ae],
1267                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1268                                    src_count, tgt_start, tgt_count);
1269     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1270   } else {
1271     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1272                                result_rgn, result_phi, ae);
1273   }
1274   if (result != nullptr) {
1275     result_phi->init_req(3, result);
1276     result_rgn->init_req(3, control());
1277   }
1278   set_control(_gvn.transform(result_rgn));
1279   record_for_igvn(result_rgn);
1280   set_result(_gvn.transform(result_phi));
1281 
1282   return true;
1283 }
1284 
1285 //-----------------------------inline_string_indexOfI-----------------------
1286 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1287   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1288     return false;
1289   }
1290   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1291     return false;
1292   }
1293 
1294   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1295   Node* src         = argument(0); // byte[]
1296   Node* src_count   = argument(1); // char count
1297   Node* tgt         = argument(2); // byte[]
1298   Node* tgt_count   = argument(3); // char count
1299   Node* from_index  = argument(4); // char index
1300 
1301   src = must_be_not_null(src, true);
1302   tgt = must_be_not_null(tgt, true);
1303 
1304   // Multiply byte array index by 2 if String is UTF16 encoded
1305   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1306   src_count = _gvn.transform(new SubINode(src_count, from_index));
1307   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1308   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1309 
1310   // Range checks
1311   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL);
1312   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU);
1313   if (stopped()) {
1314     return true;
1315   }
1316 
1317   RegionNode* region = new RegionNode(5);
1318   Node* phi = new PhiNode(region, TypeInt::INT);
1319   Node* result = nullptr;
1320 
1321   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1322 
1323   if (call_opt_stub) {
1324     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1325                                    StubRoutines::_string_indexof_array[ae],
1326                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1327                                    src_count, tgt_start, tgt_count);
1328     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1329   } else {
1330     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1331                                region, phi, ae);
1332   }
1333   if (result != nullptr) {
1334     // The result is index relative to from_index if substring was found, -1 otherwise.
1335     // Generate code which will fold into cmove.
1336     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1337     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1338 
1339     Node* if_lt = generate_slow_guard(bol, nullptr);
1340     if (if_lt != nullptr) {
1341       // result == -1
1342       phi->init_req(3, result);
1343       region->init_req(3, if_lt);
1344     }
1345     if (!stopped()) {
1346       result = _gvn.transform(new AddINode(result, from_index));
1347       phi->init_req(4, result);
1348       region->init_req(4, control());
1349     }
1350   }
1351 
1352   set_control(_gvn.transform(region));
1353   record_for_igvn(region);
1354   set_result(_gvn.transform(phi));
1355   clear_upper_avx();
1356 
1357   return true;
1358 }
1359 
1360 // Create StrIndexOfNode with fast path checks
1361 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1362                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1363   // Check for substr count > string count
1364   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1365   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1366   Node* if_gt = generate_slow_guard(bol, nullptr);
1367   if (if_gt != nullptr) {
1368     phi->init_req(1, intcon(-1));
1369     region->init_req(1, if_gt);
1370   }
1371   if (!stopped()) {
1372     // Check for substr count == 0
1373     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1374     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1375     Node* if_zero = generate_slow_guard(bol, nullptr);
1376     if (if_zero != nullptr) {
1377       phi->init_req(2, intcon(0));
1378       region->init_req(2, if_zero);
1379     }
1380   }
1381   if (!stopped()) {
1382     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1383   }
1384   return nullptr;
1385 }
1386 
1387 //-----------------------------inline_string_indexOfChar-----------------------
1388 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1389   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1390     return false;
1391   }
1392   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1393     return false;
1394   }
1395   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1396   Node* src         = argument(0); // byte[]
1397   Node* int_ch      = argument(1);
1398   Node* from_index  = argument(2);
1399   Node* max         = argument(3);
1400 
1401   src = must_be_not_null(src, true);
1402 
1403   Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1404   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1405   Node* src_count = _gvn.transform(new SubINode(max, from_index));
1406 
1407   // Range checks
1408   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U);
1409 
1410   // Check for int_ch >= 0
1411   Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1412   Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1413   {
1414     BuildCutout unless(this, int_ch_bol, PROB_MAX);
1415     uncommon_trap(Deoptimization::Reason_intrinsic,
1416                   Deoptimization::Action_maybe_recompile);
1417   }
1418   if (stopped()) {
1419     return true;
1420   }
1421 
1422   RegionNode* region = new RegionNode(3);
1423   Node* phi = new PhiNode(region, TypeInt::INT);
1424 
1425   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1426   C->set_has_split_ifs(true); // Has chance for split-if optimization
1427   _gvn.transform(result);
1428 
1429   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1430   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1431 
1432   Node* if_lt = generate_slow_guard(bol, nullptr);
1433   if (if_lt != nullptr) {
1434     // result == -1
1435     phi->init_req(2, result);
1436     region->init_req(2, if_lt);
1437   }
1438   if (!stopped()) {
1439     result = _gvn.transform(new AddINode(result, from_index));
1440     phi->init_req(1, result);
1441     region->init_req(1, control());
1442   }
1443   set_control(_gvn.transform(region));
1444   record_for_igvn(region);
1445   set_result(_gvn.transform(phi));
1446   clear_upper_avx();
1447 
1448   return true;
1449 }
1450 //---------------------------inline_string_copy---------------------
1451 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1452 //   int StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1453 //   int StringUTF16.compress(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1454 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1455 //   void StringLatin1.inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1456 //   void StringLatin1.inflate(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1457 bool LibraryCallKit::inline_string_copy(bool compress) {
1458   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1459     return false;
1460   }
1461   int nargs = 5;  // 2 oops, 3 ints
1462   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1463 
1464   Node* src         = argument(0);
1465   Node* src_offset  = argument(1);
1466   Node* dst         = argument(2);
1467   Node* dst_offset  = argument(3);
1468   Node* length      = argument(4);
1469 
1470   // Check for allocation before we add nodes that would confuse
1471   // tightly_coupled_allocation()
1472   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1473 
1474   // Figure out the size and type of the elements we will be copying.
1475   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1476   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1477   if (src_type == nullptr || dst_type == nullptr) {
1478     return false;
1479   }
1480   BasicType src_elem = src_type->elem()->array_element_basic_type();
1481   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1482   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1483          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1484          "Unsupported array types for inline_string_copy");
1485 
1486   src = must_be_not_null(src, true);
1487   dst = must_be_not_null(dst, true);
1488 
1489   // Convert char[] offsets to byte[] offsets
1490   bool convert_src = (compress && src_elem == T_BYTE);
1491   bool convert_dst = (!compress && dst_elem == T_BYTE);
1492   if (convert_src) {
1493     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1494   } else if (convert_dst) {
1495     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1496   }
1497 
1498   // Range checks
1499   generate_string_range_check(src, src_offset, length, convert_src);
1500   generate_string_range_check(dst, dst_offset, length, convert_dst);
1501   if (stopped()) {
1502     return true;
1503   }
1504 
1505   Node* src_start = array_element_address(src, src_offset, src_elem);
1506   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1507   // 'src_start' points to src array + scaled offset
1508   // 'dst_start' points to dst array + scaled offset
1509   Node* count = nullptr;
1510   if (compress) {
1511     count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1512   } else {
1513     inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1514   }
1515 
1516   if (alloc != nullptr) {
1517     if (alloc->maybe_set_complete(&_gvn)) {
1518       // "You break it, you buy it."
1519       InitializeNode* init = alloc->initialization();
1520       assert(init->is_complete(), "we just did this");
1521       init->set_complete_with_arraycopy();
1522       assert(dst->is_CheckCastPP(), "sanity");
1523       assert(dst->in(0)->in(0) == init, "dest pinned");
1524     }
1525     // Do not let stores that initialize this object be reordered with
1526     // a subsequent store that would make this object accessible by
1527     // other threads.
1528     // Record what AllocateNode this StoreStore protects so that
1529     // escape analysis can go from the MemBarStoreStoreNode to the
1530     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1531     // based on the escape status of the AllocateNode.
1532     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1533   }
1534   if (compress) {
1535     set_result(_gvn.transform(count));
1536   }
1537   clear_upper_avx();
1538 
1539   return true;
1540 }
1541 
1542 #ifdef _LP64
1543 #define XTOP ,top() /*additional argument*/
1544 #else  //_LP64
1545 #define XTOP        /*no additional argument*/
1546 #endif //_LP64
1547 
1548 //------------------------inline_string_toBytesU--------------------------
1549 // public static byte[] StringUTF16.toBytes(char[] value, int off, int len)
1550 bool LibraryCallKit::inline_string_toBytesU() {
1551   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1552     return false;
1553   }
1554   // Get the arguments.
1555   Node* value     = argument(0);
1556   Node* offset    = argument(1);
1557   Node* length    = argument(2);
1558 
1559   Node* newcopy = nullptr;
1560 
1561   // Set the original stack and the reexecute bit for the interpreter to reexecute
1562   // the bytecode that invokes StringUTF16.toBytes() if deoptimization happens.
1563   { PreserveReexecuteState preexecs(this);
1564     jvms()->set_should_reexecute(true);
1565 
1566     // Check if a null path was taken unconditionally.
1567     value = null_check(value);
1568 
1569     RegionNode* bailout = new RegionNode(1);
1570     record_for_igvn(bailout);
1571 
1572     // Range checks
1573     generate_negative_guard(offset, bailout);
1574     generate_negative_guard(length, bailout);
1575     generate_limit_guard(offset, length, load_array_length(value), bailout);
1576     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1577     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout);
1578 
1579     if (bailout->req() > 1) {
1580       PreserveJVMState pjvms(this);
1581       set_control(_gvn.transform(bailout));
1582       uncommon_trap(Deoptimization::Reason_intrinsic,
1583                     Deoptimization::Action_maybe_recompile);
1584     }
1585     if (stopped()) {
1586       return true;
1587     }
1588 
1589     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1590     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1591     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1592     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1593     guarantee(alloc != nullptr, "created above");
1594 
1595     // Calculate starting addresses.
1596     Node* src_start = array_element_address(value, offset, T_CHAR);
1597     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1598 
1599     // Check if dst array address is aligned to HeapWordSize
1600     bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1601     // If true, then check if src array address is aligned to HeapWordSize
1602     if (aligned) {
1603       const TypeInt* toffset = gvn().type(offset)->is_int();
1604       aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1605                                        toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1606     }
1607 
1608     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1609     const char* copyfunc_name = "arraycopy";
1610     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1611     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1612                       OptoRuntime::fast_arraycopy_Type(),
1613                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1614                       src_start, dst_start, ConvI2X(length) XTOP);
1615     // Do not let reads from the cloned object float above the arraycopy.
1616     if (alloc->maybe_set_complete(&_gvn)) {
1617       // "You break it, you buy it."
1618       InitializeNode* init = alloc->initialization();
1619       assert(init->is_complete(), "we just did this");
1620       init->set_complete_with_arraycopy();
1621       assert(newcopy->is_CheckCastPP(), "sanity");
1622       assert(newcopy->in(0)->in(0) == init, "dest pinned");
1623     }
1624     // Do not let stores that initialize this object be reordered with
1625     // a subsequent store that would make this object accessible by
1626     // other threads.
1627     // Record what AllocateNode this StoreStore protects so that
1628     // escape analysis can go from the MemBarStoreStoreNode to the
1629     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1630     // based on the escape status of the AllocateNode.
1631     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1632   } // original reexecute is set back here
1633 
1634   C->set_has_split_ifs(true); // Has chance for split-if optimization
1635   if (!stopped()) {
1636     set_result(newcopy);
1637   }
1638   clear_upper_avx();
1639 
1640   return true;
1641 }
1642 
1643 //------------------------inline_string_getCharsU--------------------------
1644 // public void StringUTF16.getChars(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1645 bool LibraryCallKit::inline_string_getCharsU() {
1646   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1647     return false;
1648   }
1649 
1650   // Get the arguments.
1651   Node* src       = argument(0);
1652   Node* src_begin = argument(1);
1653   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1654   Node* dst       = argument(3);
1655   Node* dst_begin = argument(4);
1656 
1657   // Check for allocation before we add nodes that would confuse
1658   // tightly_coupled_allocation()
1659   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1660 
1661   // Check if a null path was taken unconditionally.
1662   src = null_check(src);
1663   dst = null_check(dst);
1664   if (stopped()) {
1665     return true;
1666   }
1667 
1668   // Get length and convert char[] offset to byte[] offset
1669   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1670   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1671 
1672   // Range checks
1673   generate_string_range_check(src, src_begin, length, true);
1674   generate_string_range_check(dst, dst_begin, length, false);
1675   if (stopped()) {
1676     return true;
1677   }
1678 
1679   if (!stopped()) {
1680     // Calculate starting addresses.
1681     Node* src_start = array_element_address(src, src_begin, T_BYTE);
1682     Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1683 
1684     // Check if array addresses are aligned to HeapWordSize
1685     const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1686     const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1687     bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1688                    tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1689 
1690     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1691     const char* copyfunc_name = "arraycopy";
1692     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1693     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1694                       OptoRuntime::fast_arraycopy_Type(),
1695                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1696                       src_start, dst_start, ConvI2X(length) XTOP);
1697     // Do not let reads from the cloned object float above the arraycopy.
1698     if (alloc != nullptr) {
1699       if (alloc->maybe_set_complete(&_gvn)) {
1700         // "You break it, you buy it."
1701         InitializeNode* init = alloc->initialization();
1702         assert(init->is_complete(), "we just did this");
1703         init->set_complete_with_arraycopy();
1704         assert(dst->is_CheckCastPP(), "sanity");
1705         assert(dst->in(0)->in(0) == init, "dest pinned");
1706       }
1707       // Do not let stores that initialize this object be reordered with
1708       // a subsequent store that would make this object accessible by
1709       // other threads.
1710       // Record what AllocateNode this StoreStore protects so that
1711       // escape analysis can go from the MemBarStoreStoreNode to the
1712       // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1713       // based on the escape status of the AllocateNode.
1714       insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1715     } else {
1716       insert_mem_bar(Op_MemBarCPUOrder);
1717     }
1718   }
1719 
1720   C->set_has_split_ifs(true); // Has chance for split-if optimization
1721   return true;
1722 }
1723 
1724 //----------------------inline_string_char_access----------------------------
1725 // Store/Load char to/from byte[] array.
1726 // static void StringUTF16.putChar(byte[] val, int index, int c)
1727 // static char StringUTF16.getChar(byte[] val, int index)
1728 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1729   Node* value  = argument(0);
1730   Node* index  = argument(1);
1731   Node* ch = is_store ? argument(2) : nullptr;
1732 
1733   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1734   // correctly requires matched array shapes.
1735   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1736           "sanity: byte[] and char[] bases agree");
1737   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1738           "sanity: byte[] and char[] scales agree");
1739 
1740   // Bail when getChar over constants is requested: constant folding would
1741   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1742   // Java method would constant fold nicely instead.
1743   if (!is_store && value->is_Con() && index->is_Con()) {
1744     return false;
1745   }
1746 
1747   // Save state and restore on bailout
1748   uint old_sp = sp();
1749   SafePointNode* old_map = clone_map();
1750 
1751   value = must_be_not_null(value, true);
1752 
1753   Node* adr = array_element_address(value, index, T_CHAR);
1754   if (adr->is_top()) {
1755     set_map(old_map);
1756     set_sp(old_sp);
1757     return false;
1758   }
1759   destruct_map_clone(old_map);
1760   if (is_store) {
1761     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1762   } else {
1763     ch = access_load_at(value, adr, TypeAryPtr::BYTES, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
1764     set_result(ch);
1765   }
1766   return true;
1767 }
1768 
1769 
1770 //------------------------------inline_math-----------------------------------
1771 // public static double Math.abs(double)
1772 // public static double Math.sqrt(double)
1773 // public static double Math.log(double)
1774 // public static double Math.log10(double)
1775 // public static double Math.round(double)
1776 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1777   Node* arg = argument(0);
1778   Node* n = nullptr;
1779   switch (id) {
1780   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1781   case vmIntrinsics::_dsqrt:
1782   case vmIntrinsics::_dsqrt_strict:
1783                               n = new SqrtDNode(C, control(),  arg);  break;
1784   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1785   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1786   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1787   case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1788   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1789   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1790   default:  fatal_unexpected_iid(id);  break;
1791   }
1792   set_result(_gvn.transform(n));
1793   return true;
1794 }
1795 
1796 //------------------------------inline_math-----------------------------------
1797 // public static float Math.abs(float)
1798 // public static int Math.abs(int)
1799 // public static long Math.abs(long)
1800 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1801   Node* arg = argument(0);
1802   Node* n = nullptr;
1803   switch (id) {
1804   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
1805   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
1806   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
1807   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1808   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1809   case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1810   default:  fatal_unexpected_iid(id);  break;
1811   }
1812   set_result(_gvn.transform(n));
1813   return true;
1814 }
1815 
1816 //------------------------------runtime_math-----------------------------
1817 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1818   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1819          "must be (DD)D or (D)D type");
1820 
1821   // Inputs
1822   Node* a = argument(0);
1823   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1824 
1825   const TypePtr* no_memory_effects = nullptr;
1826   Node* trig = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
1827                                  no_memory_effects,
1828                                  a, top(), b, b ? top() : nullptr);
1829   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1830 #ifdef ASSERT
1831   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1832   assert(value_top == top(), "second value must be top");
1833 #endif
1834 
1835   set_result(value);
1836   return true;
1837 }
1838 
1839 //------------------------------inline_math_pow-----------------------------
1840 bool LibraryCallKit::inline_math_pow() {
1841   Node* exp = argument(2);
1842   const TypeD* d = _gvn.type(exp)->isa_double_constant();
1843   if (d != nullptr) {
1844     if (d->getd() == 2.0) {
1845       // Special case: pow(x, 2.0) => x * x
1846       Node* base = argument(0);
1847       set_result(_gvn.transform(new MulDNode(base, base)));
1848       return true;
1849     } else if (d->getd() == 0.5 && Matcher::match_rule_supported(Op_SqrtD)) {
1850       // Special case: pow(x, 0.5) => sqrt(x)
1851       Node* base = argument(0);
1852       Node* zero = _gvn.zerocon(T_DOUBLE);
1853 
1854       RegionNode* region = new RegionNode(3);
1855       Node* phi = new PhiNode(region, Type::DOUBLE);
1856 
1857       Node* cmp  = _gvn.transform(new CmpDNode(base, zero));
1858       // According to the API specs, pow(-0.0, 0.5) = 0.0 and sqrt(-0.0) = -0.0.
1859       // So pow(-0.0, 0.5) shouldn't be replaced with sqrt(-0.0).
1860       // -0.0/+0.0 are both excluded since floating-point comparison doesn't distinguish -0.0 from +0.0.
1861       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::le));
1862 
1863       Node* if_pow = generate_slow_guard(test, nullptr);
1864       Node* value_sqrt = _gvn.transform(new SqrtDNode(C, control(), base));
1865       phi->init_req(1, value_sqrt);
1866       region->init_req(1, control());
1867 
1868       if (if_pow != nullptr) {
1869         set_control(if_pow);
1870         address target = StubRoutines::dpow() != nullptr ? StubRoutines::dpow() :
1871                                                         CAST_FROM_FN_PTR(address, SharedRuntime::dpow);
1872         const TypePtr* no_memory_effects = nullptr;
1873         Node* trig = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(), target, "POW",
1874                                        no_memory_effects, base, top(), exp, top());
1875         Node* value_pow = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1876 #ifdef ASSERT
1877         Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1878         assert(value_top == top(), "second value must be top");
1879 #endif
1880         phi->init_req(2, value_pow);
1881         region->init_req(2, _gvn.transform(new ProjNode(trig, TypeFunc::Control)));
1882       }
1883 
1884       C->set_has_split_ifs(true); // Has chance for split-if optimization
1885       set_control(_gvn.transform(region));
1886       record_for_igvn(region);
1887       set_result(_gvn.transform(phi));
1888 
1889       return true;
1890     }
1891   }
1892 
1893   return StubRoutines::dpow() != nullptr ?
1894     runtime_math(OptoRuntime::Math_DD_D_Type(), StubRoutines::dpow(),  "dpow") :
1895     runtime_math(OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow),  "POW");
1896 }
1897 
1898 //------------------------------inline_math_native-----------------------------
1899 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1900   switch (id) {
1901   case vmIntrinsics::_dsin:
1902     return StubRoutines::dsin() != nullptr ?
1903       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1904       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin),   "SIN");
1905   case vmIntrinsics::_dcos:
1906     return StubRoutines::dcos() != nullptr ?
1907       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1908       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos),   "COS");
1909   case vmIntrinsics::_dtan:
1910     return StubRoutines::dtan() != nullptr ?
1911       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1912       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1913   case vmIntrinsics::_dtanh:
1914     return StubRoutines::dtanh() != nullptr ?
1915       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1916   case vmIntrinsics::_dcbrt:
1917     return StubRoutines::dcbrt() != nullptr ?
1918       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1919   case vmIntrinsics::_dexp:
1920     return StubRoutines::dexp() != nullptr ?
1921       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1922       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp),  "EXP");
1923   case vmIntrinsics::_dlog:
1924     return StubRoutines::dlog() != nullptr ?
1925       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1926       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog),   "LOG");
1927   case vmIntrinsics::_dlog10:
1928     return StubRoutines::dlog10() != nullptr ?
1929       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1930       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1931 
1932   case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1933   case vmIntrinsics::_ceil:
1934   case vmIntrinsics::_floor:
1935   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1936 
1937   case vmIntrinsics::_dsqrt:
1938   case vmIntrinsics::_dsqrt_strict:
1939                               return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1940   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
1941   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
1942   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
1943   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
1944 
1945   case vmIntrinsics::_dpow:      return inline_math_pow();
1946   case vmIntrinsics::_dcopySign: return inline_double_math(id);
1947   case vmIntrinsics::_fcopySign: return inline_math(id);
1948   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1949   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1950   case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1951 
1952    // These intrinsics are not yet correctly implemented
1953   case vmIntrinsics::_datan2:
1954     return false;
1955 
1956   default:
1957     fatal_unexpected_iid(id);
1958     return false;
1959   }
1960 }
1961 
1962 //----------------------------inline_notify-----------------------------------*
1963 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1964   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1965   address func;
1966   if (id == vmIntrinsics::_notify) {
1967     func = OptoRuntime::monitor_notify_Java();
1968   } else {
1969     func = OptoRuntime::monitor_notifyAll_Java();
1970   }
1971   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1972   make_slow_call_ex(call, env()->Throwable_klass(), false);
1973   return true;
1974 }
1975 
1976 
1977 //----------------------------inline_min_max-----------------------------------
1978 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1979   Node* a = nullptr;
1980   Node* b = nullptr;
1981   Node* n = nullptr;
1982   switch (id) {
1983     case vmIntrinsics::_min:
1984     case vmIntrinsics::_max:
1985     case vmIntrinsics::_minF:
1986     case vmIntrinsics::_maxF:
1987     case vmIntrinsics::_minF_strict:
1988     case vmIntrinsics::_maxF_strict:
1989     case vmIntrinsics::_min_strict:
1990     case vmIntrinsics::_max_strict:
1991       assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
1992       a = argument(0);
1993       b = argument(1);
1994       break;
1995     case vmIntrinsics::_minD:
1996     case vmIntrinsics::_maxD:
1997     case vmIntrinsics::_minD_strict:
1998     case vmIntrinsics::_maxD_strict:
1999       assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
2000       a = argument(0);
2001       b = argument(2);
2002       break;
2003     case vmIntrinsics::_minL:
2004     case vmIntrinsics::_maxL:
2005       assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
2006       a = argument(0);
2007       b = argument(2);
2008       break;
2009     default:
2010       fatal_unexpected_iid(id);
2011       break;
2012   }
2013 
2014   switch (id) {
2015     case vmIntrinsics::_min:
2016     case vmIntrinsics::_min_strict:
2017       n = new MinINode(a, b);
2018       break;
2019     case vmIntrinsics::_max:
2020     case vmIntrinsics::_max_strict:
2021       n = new MaxINode(a, b);
2022       break;
2023     case vmIntrinsics::_minF:
2024     case vmIntrinsics::_minF_strict:
2025       n = new MinFNode(a, b);
2026       break;
2027     case vmIntrinsics::_maxF:
2028     case vmIntrinsics::_maxF_strict:
2029       n = new MaxFNode(a, b);
2030       break;
2031     case vmIntrinsics::_minD:
2032     case vmIntrinsics::_minD_strict:
2033       n = new MinDNode(a, b);
2034       break;
2035     case vmIntrinsics::_maxD:
2036     case vmIntrinsics::_maxD_strict:
2037       n = new MaxDNode(a, b);
2038       break;
2039     case vmIntrinsics::_minL:
2040       n = new MinLNode(_gvn.C, a, b);
2041       break;
2042     case vmIntrinsics::_maxL:
2043       n = new MaxLNode(_gvn.C, a, b);
2044       break;
2045     default:
2046       fatal_unexpected_iid(id);
2047       break;
2048   }
2049 
2050   set_result(_gvn.transform(n));
2051   return true;
2052 }
2053 
2054 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2055   if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2056                                    env()->ArithmeticException_instance())) {
2057     // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2058     // so let's bail out intrinsic rather than risking deopting again.
2059     return false;
2060   }
2061 
2062   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2063   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2064   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2065   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2066 
2067   {
2068     PreserveJVMState pjvms(this);
2069     PreserveReexecuteState preexecs(this);
2070     jvms()->set_should_reexecute(true);
2071 
2072     set_control(slow_path);
2073     set_i_o(i_o());
2074 
2075     builtin_throw(Deoptimization::Reason_intrinsic,
2076                   env()->ArithmeticException_instance(),
2077                   /*allow_too_many_traps*/ false);
2078   }
2079 
2080   set_control(fast_path);
2081   set_result(math);
2082   return true;
2083 }
2084 
2085 template <typename OverflowOp>
2086 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2087   typedef typename OverflowOp::MathOp MathOp;
2088 
2089   MathOp* mathOp = new MathOp(arg1, arg2);
2090   Node* operation = _gvn.transform( mathOp );
2091   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2092   return inline_math_mathExact(operation, ofcheck);
2093 }
2094 
2095 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2096   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2097 }
2098 
2099 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2100   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2101 }
2102 
2103 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2104   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2105 }
2106 
2107 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2108   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2109 }
2110 
2111 bool LibraryCallKit::inline_math_negateExactI() {
2112   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2113 }
2114 
2115 bool LibraryCallKit::inline_math_negateExactL() {
2116   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2117 }
2118 
2119 bool LibraryCallKit::inline_math_multiplyExactI() {
2120   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2121 }
2122 
2123 bool LibraryCallKit::inline_math_multiplyExactL() {
2124   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2125 }
2126 
2127 bool LibraryCallKit::inline_math_multiplyHigh() {
2128   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2129   return true;
2130 }
2131 
2132 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2133   set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2134   return true;
2135 }
2136 
2137 inline int
2138 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2139   const TypePtr* base_type = TypePtr::NULL_PTR;
2140   if (base != nullptr)  base_type = _gvn.type(base)->isa_ptr();
2141   if (base_type == nullptr) {
2142     // Unknown type.
2143     return Type::AnyPtr;
2144   } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2145     // Since this is a null+long form, we have to switch to a rawptr.
2146     base   = _gvn.transform(new CastX2PNode(offset));
2147     offset = MakeConX(0);
2148     return Type::RawPtr;
2149   } else if (base_type->base() == Type::RawPtr) {
2150     return Type::RawPtr;
2151   } else if (base_type->isa_oopptr()) {
2152     // Base is never null => always a heap address.
2153     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2154       return Type::OopPtr;
2155     }
2156     // Offset is small => always a heap address.
2157     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2158     if (offset_type != nullptr &&
2159         base_type->offset() == 0 &&     // (should always be?)
2160         offset_type->_lo >= 0 &&
2161         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2162       return Type::OopPtr;
2163     } else if (type == T_OBJECT) {
2164       // off heap access to an oop doesn't make any sense. Has to be on
2165       // heap.
2166       return Type::OopPtr;
2167     }
2168     // Otherwise, it might either be oop+off or null+addr.
2169     return Type::AnyPtr;
2170   } else {
2171     // No information:
2172     return Type::AnyPtr;
2173   }
2174 }
2175 
2176 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2177   Node* uncasted_base = base;
2178   int kind = classify_unsafe_addr(uncasted_base, offset, type);
2179   if (kind == Type::RawPtr) {
2180     return basic_plus_adr(top(), uncasted_base, offset);
2181   } else if (kind == Type::AnyPtr) {
2182     assert(base == uncasted_base, "unexpected base change");
2183     if (can_cast) {
2184       if (!_gvn.type(base)->speculative_maybe_null() &&
2185           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2186         // According to profiling, this access is always on
2187         // heap. Casting the base to not null and thus avoiding membars
2188         // around the access should allow better optimizations
2189         Node* null_ctl = top();
2190         base = null_check_oop(base, &null_ctl, true, true, true);
2191         assert(null_ctl->is_top(), "no null control here");
2192         return basic_plus_adr(base, offset);
2193       } else if (_gvn.type(base)->speculative_always_null() &&
2194                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2195         // According to profiling, this access is always off
2196         // heap.
2197         base = null_assert(base);
2198         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2199         offset = MakeConX(0);
2200         return basic_plus_adr(top(), raw_base, offset);
2201       }
2202     }
2203     // We don't know if it's an on heap or off heap access. Fall back
2204     // to raw memory access.
2205     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2206     return basic_plus_adr(top(), raw, offset);
2207   } else {
2208     assert(base == uncasted_base, "unexpected base change");
2209     // We know it's an on heap access so base can't be null
2210     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2211       base = must_be_not_null(base, true);
2212     }
2213     return basic_plus_adr(base, offset);
2214   }
2215 }
2216 
2217 //--------------------------inline_number_methods-----------------------------
2218 // inline int     Integer.numberOfLeadingZeros(int)
2219 // inline int        Long.numberOfLeadingZeros(long)
2220 //
2221 // inline int     Integer.numberOfTrailingZeros(int)
2222 // inline int        Long.numberOfTrailingZeros(long)
2223 //
2224 // inline int     Integer.bitCount(int)
2225 // inline int        Long.bitCount(long)
2226 //
2227 // inline char  Character.reverseBytes(char)
2228 // inline short     Short.reverseBytes(short)
2229 // inline int     Integer.reverseBytes(int)
2230 // inline long       Long.reverseBytes(long)
2231 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2232   Node* arg = argument(0);
2233   Node* n = nullptr;
2234   switch (id) {
2235   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg); break;
2236   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg); break;
2237   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg); break;
2238   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg); break;
2239   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg); break;
2240   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg); break;
2241   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(     arg); break;
2242   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode(      arg); break;
2243   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode(      arg); break;
2244   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode(      arg); break;
2245   case vmIntrinsics::_reverse_i:                n = new ReverseINode(           arg); break;
2246   case vmIntrinsics::_reverse_l:                n = new ReverseLNode(           arg); break;
2247   default:  fatal_unexpected_iid(id);  break;
2248   }
2249   set_result(_gvn.transform(n));
2250   return true;
2251 }
2252 
2253 //--------------------------inline_bitshuffle_methods-----------------------------
2254 // inline int Integer.compress(int, int)
2255 // inline int Integer.expand(int, int)
2256 // inline long Long.compress(long, long)
2257 // inline long Long.expand(long, long)
2258 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2259   Node* n = nullptr;
2260   switch (id) {
2261     case vmIntrinsics::_compress_i:  n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2262     case vmIntrinsics::_expand_i:    n = new ExpandBitsNode(argument(0),  argument(1), TypeInt::INT); break;
2263     case vmIntrinsics::_compress_l:  n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2264     case vmIntrinsics::_expand_l:    n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2265     default:  fatal_unexpected_iid(id);  break;
2266   }
2267   set_result(_gvn.transform(n));
2268   return true;
2269 }
2270 
2271 //--------------------------inline_number_methods-----------------------------
2272 // inline int Integer.compareUnsigned(int, int)
2273 // inline int    Long.compareUnsigned(long, long)
2274 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2275   Node* arg1 = argument(0);
2276   Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2277   Node* n = nullptr;
2278   switch (id) {
2279     case vmIntrinsics::_compareUnsigned_i:   n = new CmpU3Node(arg1, arg2);  break;
2280     case vmIntrinsics::_compareUnsigned_l:   n = new CmpUL3Node(arg1, arg2); break;
2281     default:  fatal_unexpected_iid(id);  break;
2282   }
2283   set_result(_gvn.transform(n));
2284   return true;
2285 }
2286 
2287 //--------------------------inline_unsigned_divmod_methods-----------------------------
2288 // inline int Integer.divideUnsigned(int, int)
2289 // inline int Integer.remainderUnsigned(int, int)
2290 // inline long Long.divideUnsigned(long, long)
2291 // inline long Long.remainderUnsigned(long, long)
2292 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2293   Node* n = nullptr;
2294   switch (id) {
2295     case vmIntrinsics::_divideUnsigned_i: {
2296       zero_check_int(argument(1));
2297       // Compile-time detect of null-exception
2298       if (stopped()) {
2299         return true; // keep the graph constructed so far
2300       }
2301       n = new UDivINode(control(), argument(0), argument(1));
2302       break;
2303     }
2304     case vmIntrinsics::_divideUnsigned_l: {
2305       zero_check_long(argument(2));
2306       // Compile-time detect of null-exception
2307       if (stopped()) {
2308         return true; // keep the graph constructed so far
2309       }
2310       n = new UDivLNode(control(), argument(0), argument(2));
2311       break;
2312     }
2313     case vmIntrinsics::_remainderUnsigned_i: {
2314       zero_check_int(argument(1));
2315       // Compile-time detect of null-exception
2316       if (stopped()) {
2317         return true; // keep the graph constructed so far
2318       }
2319       n = new UModINode(control(), argument(0), argument(1));
2320       break;
2321     }
2322     case vmIntrinsics::_remainderUnsigned_l: {
2323       zero_check_long(argument(2));
2324       // Compile-time detect of null-exception
2325       if (stopped()) {
2326         return true; // keep the graph constructed so far
2327       }
2328       n = new UModLNode(control(), argument(0), argument(2));
2329       break;
2330     }
2331     default:  fatal_unexpected_iid(id);  break;
2332   }
2333   set_result(_gvn.transform(n));
2334   return true;
2335 }
2336 
2337 //----------------------------inline_unsafe_access----------------------------
2338 
2339 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2340   // Attempt to infer a sharper value type from the offset and base type.
2341   ciKlass* sharpened_klass = nullptr;
2342   bool null_free = false;
2343 
2344   // See if it is an instance field, with an object type.
2345   if (alias_type->field() != nullptr) {
2346     if (alias_type->field()->type()->is_klass()) {
2347       sharpened_klass = alias_type->field()->type()->as_klass();
2348       null_free = alias_type->field()->is_null_free();
2349     }
2350   }
2351 
2352   const TypeOopPtr* result = nullptr;
2353   // See if it is a narrow oop array.
2354   if (adr_type->isa_aryptr()) {
2355     if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2356       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2357       null_free = adr_type->is_aryptr()->is_null_free();
2358       if (elem_type != nullptr && elem_type->is_loaded()) {
2359         // Sharpen the value type.
2360         result = elem_type;
2361       }
2362     }
2363   }
2364 
2365   // The sharpened class might be unloaded if there is no class loader
2366   // contraint in place.
2367   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2368     // Sharpen the value type.
2369     result = TypeOopPtr::make_from_klass(sharpened_klass);
2370     if (null_free) {
2371       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2372     }
2373   }
2374   if (result != nullptr) {
2375 #ifndef PRODUCT
2376     if (C->print_intrinsics() || C->print_inlining()) {
2377       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2378       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2379     }
2380 #endif
2381   }
2382   return result;
2383 }
2384 
2385 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2386   switch (kind) {
2387       case Relaxed:
2388         return MO_UNORDERED;
2389       case Opaque:
2390         return MO_RELAXED;
2391       case Acquire:
2392         return MO_ACQUIRE;
2393       case Release:
2394         return MO_RELEASE;
2395       case Volatile:
2396         return MO_SEQ_CST;
2397       default:
2398         ShouldNotReachHere();
2399         return 0;
2400   }
2401 }
2402 
2403 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned, const bool is_flat) {
2404   if (callee()->is_static())  return false;  // caller must have the capability!
2405   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2406   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2407   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2408   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2409 
2410   if (is_reference_type(type)) {
2411     decorators |= ON_UNKNOWN_OOP_REF;
2412   }
2413 
2414   if (unaligned) {
2415     decorators |= C2_UNALIGNED;
2416   }
2417 
2418 #ifndef PRODUCT
2419   {
2420     ResourceMark rm;
2421     // Check the signatures.
2422     ciSignature* sig = callee()->signature();
2423 #ifdef ASSERT
2424     if (!is_store) {
2425       // Object getReference(Object base, int/long offset), etc.
2426       BasicType rtype = sig->return_type()->basic_type();
2427       assert(rtype == type, "getter must return the expected value");
2428       assert(sig->count() == 2 || (is_flat && sig->count() == 3), "oop getter has 2 or 3 arguments");
2429       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2430       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2431     } else {
2432       // void putReference(Object base, int/long offset, Object x), etc.
2433       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2434       assert(sig->count() == 3 || (is_flat && sig->count() == 4), "oop putter has 3 arguments");
2435       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2436       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2437       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2438       assert(vtype == type, "putter must accept the expected value");
2439     }
2440 #endif // ASSERT
2441  }
2442 #endif //PRODUCT
2443 
2444   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2445 
2446   Node* receiver = argument(0);  // type: oop
2447 
2448   // Build address expression.
2449   Node* heap_base_oop = top();
2450 
2451   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2452   Node* base = argument(1);  // type: oop
2453   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2454   Node* offset = argument(2);  // type: long
2455   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2456   // to be plain byte offsets, which are also the same as those accepted
2457   // by oopDesc::field_addr.
2458   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2459          "fieldOffset must be byte-scaled");
2460 
2461   ciInlineKlass* inline_klass = nullptr;
2462   if (is_flat) {
2463     const TypeInstPtr* cls = _gvn.type(argument(4))->isa_instptr();
2464     if (cls == nullptr || cls->const_oop() == nullptr) {
2465       return false;
2466     }
2467     ciType* mirror_type = cls->const_oop()->as_instance()->java_mirror_type();
2468     if (!mirror_type->is_inlinetype()) {
2469       return false;
2470     }
2471     inline_klass = mirror_type->as_inline_klass();
2472   }
2473 
2474   if (base->is_InlineType()) {
2475     assert(!is_store, "InlineTypeNodes are non-larval value objects");
2476     InlineTypeNode* vt = base->as_InlineType();
2477     if (offset->is_Con()) {
2478       long off = find_long_con(offset, 0);
2479       ciInlineKlass* vk = vt->type()->inline_klass();
2480       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2481         return false;
2482       }
2483 
2484       ciField* field = vk->get_non_flat_field_by_offset(off);
2485       if (field != nullptr) {
2486         BasicType bt = type2field[field->type()->basic_type()];
2487         if (bt == T_ARRAY || bt == T_NARROWOOP) {
2488           bt = T_OBJECT;
2489         }
2490         if (bt == type && (!field->is_flat() || field->type() == inline_klass)) {
2491           Node* value = vt->field_value_by_offset(off, false);
2492           if (value->is_InlineType()) {
2493             value = value->as_InlineType()->adjust_scalarization_depth(this);
2494           }
2495           set_result(value);
2496           return true;
2497         }
2498       }
2499     }
2500     {
2501       // Re-execute the unsafe access if allocation triggers deoptimization.
2502       PreserveReexecuteState preexecs(this);
2503       jvms()->set_should_reexecute(true);
2504       vt = vt->buffer(this);
2505     }
2506     base = vt->get_oop();
2507   }
2508 
2509   // 32-bit machines ignore the high half!
2510   offset = ConvL2X(offset);
2511 
2512   // Save state and restore on bailout
2513   uint old_sp = sp();
2514   SafePointNode* old_map = clone_map();
2515 
2516   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2517   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2518 
2519   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2520     if (type != T_OBJECT && (inline_klass == nullptr || !inline_klass->has_object_fields())) {
2521       decorators |= IN_NATIVE; // off-heap primitive access
2522     } else {
2523       set_map(old_map);
2524       set_sp(old_sp);
2525       return false; // off-heap oop accesses are not supported
2526     }
2527   } else {
2528     heap_base_oop = base; // on-heap or mixed access
2529   }
2530 
2531   // Can base be null? Otherwise, always on-heap access.
2532   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2533 
2534   if (!can_access_non_heap) {
2535     decorators |= IN_HEAP;
2536   }
2537 
2538   Node* val = is_store ? argument(4 + (is_flat ? 1 : 0)) : nullptr;
2539 
2540   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2541   if (adr_type == TypePtr::NULL_PTR) {
2542     set_map(old_map);
2543     set_sp(old_sp);
2544     return false; // off-heap access with zero address
2545   }
2546 
2547   // Try to categorize the address.
2548   Compile::AliasType* alias_type = C->alias_type(adr_type);
2549   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2550 
2551   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2552       alias_type->adr_type() == TypeAryPtr::RANGE) {
2553     set_map(old_map);
2554     set_sp(old_sp);
2555     return false; // not supported
2556   }
2557 
2558   bool mismatched = false;
2559   BasicType bt = T_ILLEGAL;
2560   ciField* field = nullptr;
2561   if (adr_type->isa_instptr()) {
2562     const TypeInstPtr* instptr = adr_type->is_instptr();
2563     ciInstanceKlass* k = instptr->instance_klass();
2564     int off = instptr->offset();
2565     if (instptr->const_oop() != nullptr &&
2566         k == ciEnv::current()->Class_klass() &&
2567         instptr->offset() >= (k->size_helper() * wordSize)) {
2568       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2569       field = k->get_field_by_offset(off, true);
2570     } else {
2571       field = k->get_non_flat_field_by_offset(off);
2572     }
2573     if (field != nullptr) {
2574       bt = type2field[field->type()->basic_type()];
2575     }
2576     if (bt != alias_type->basic_type()) {
2577       // Type mismatch. Is it an access to a nested flat field?
2578       field = k->get_field_by_offset(off, false);
2579       if (field != nullptr) {
2580         bt = type2field[field->type()->basic_type()];
2581       }
2582     }
2583     assert(bt == alias_type->basic_type() || is_flat, "should match");
2584   } else {
2585     bt = alias_type->basic_type();
2586   }
2587 
2588   if (bt != T_ILLEGAL) {
2589     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2590     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2591       // Alias type doesn't differentiate between byte[] and boolean[]).
2592       // Use address type to get the element type.
2593       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2594     }
2595     if (is_reference_type(bt, true)) {
2596       // accessing an array field with getReference is not a mismatch
2597       bt = T_OBJECT;
2598     }
2599     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2600       // Don't intrinsify mismatched object accesses
2601       set_map(old_map);
2602       set_sp(old_sp);
2603       return false;
2604     }
2605     mismatched = (bt != type);
2606   } else if (alias_type->adr_type()->isa_oopptr()) {
2607     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2608   }
2609 
2610   if (is_flat) {
2611     if (adr_type->isa_instptr()) {
2612       if (field == nullptr || field->type() != inline_klass) {
2613         mismatched = true;
2614       }
2615     } else if (adr_type->isa_aryptr()) {
2616       const Type* elem = adr_type->is_aryptr()->elem();
2617       if (!adr_type->is_flat() || elem->inline_klass() != inline_klass) {
2618         mismatched = true;
2619       }
2620     } else {
2621       mismatched = true;
2622     }
2623     if (is_store) {
2624       const Type* val_t = _gvn.type(val);
2625       if (!val_t->is_inlinetypeptr() || val_t->inline_klass() != inline_klass) {
2626         set_map(old_map);
2627         set_sp(old_sp);
2628         return false;
2629       }
2630     }
2631   }
2632 
2633   destruct_map_clone(old_map);
2634   assert(!mismatched || is_flat || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2635 
2636   if (mismatched) {
2637     decorators |= C2_MISMATCHED;
2638   }
2639 
2640   // First guess at the value type.
2641   const Type *value_type = Type::get_const_basic_type(type);
2642 
2643   // Figure out the memory ordering.
2644   decorators |= mo_decorator_for_access_kind(kind);
2645 
2646   if (!is_store) {
2647     if (type == T_OBJECT && !is_flat) {
2648       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2649       if (tjp != nullptr) {
2650         value_type = tjp;
2651       }
2652     }
2653   }
2654 
2655   receiver = null_check(receiver);
2656   if (stopped()) {
2657     return true;
2658   }
2659   // Heap pointers get a null-check from the interpreter,
2660   // as a courtesy.  However, this is not guaranteed by Unsafe,
2661   // and it is not possible to fully distinguish unintended nulls
2662   // from intended ones in this API.
2663 
2664   if (!is_store) {
2665     Node* p = nullptr;
2666     // Try to constant fold a load from a constant field
2667 
2668     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2669       // final or stable field
2670       p = make_constant_from_field(field, heap_base_oop);
2671     }
2672 
2673     if (p == nullptr) { // Could not constant fold the load
2674       if (is_flat) {
2675         p = InlineTypeNode::make_from_flat(this, inline_klass, base, adr, adr_type, false, false, true);
2676       } else {
2677         p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2678         const TypeOopPtr* ptr = value_type->make_oopptr();
2679         if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2680           // Load a non-flattened inline type from memory
2681           p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2682         }
2683       }
2684       // Normalize the value returned by getBoolean in the following cases
2685       if (type == T_BOOLEAN &&
2686           (mismatched ||
2687            heap_base_oop == top() ||                  // - heap_base_oop is null or
2688            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2689                                                       //   and the unsafe access is made to large offset
2690                                                       //   (i.e., larger than the maximum offset necessary for any
2691                                                       //   field access)
2692             ) {
2693           IdealKit ideal = IdealKit(this);
2694 #define __ ideal.
2695           IdealVariable normalized_result(ideal);
2696           __ declarations_done();
2697           __ set(normalized_result, p);
2698           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2699           __ set(normalized_result, ideal.ConI(1));
2700           ideal.end_if();
2701           final_sync(ideal);
2702           p = __ value(normalized_result);
2703 #undef __
2704       }
2705     }
2706     if (type == T_ADDRESS) {
2707       p = gvn().transform(new CastP2XNode(nullptr, p));
2708       p = ConvX2UL(p);
2709     }
2710     // The load node has the control of the preceding MemBarCPUOrder.  All
2711     // following nodes will have the control of the MemBarCPUOrder inserted at
2712     // the end of this method.  So, pushing the load onto the stack at a later
2713     // point is fine.
2714     set_result(p);
2715   } else {
2716     if (bt == T_ADDRESS) {
2717       // Repackage the long as a pointer.
2718       val = ConvL2X(val);
2719       val = gvn().transform(new CastX2PNode(val));
2720     }
2721     if (is_flat) {
2722       val->as_InlineType()->store_flat(this, base, adr, false, false, true, decorators);
2723     } else {
2724       access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2725     }
2726   }
2727 
2728   return true;
2729 }
2730 
2731 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2732 #ifdef ASSERT
2733   {
2734     ResourceMark rm;
2735     // Check the signatures.
2736     ciSignature* sig = callee()->signature();
2737     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2738     assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2739     assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2740     assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2741     if (is_store) {
2742       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2743       assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2744       assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2745     } else {
2746       assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2747       assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2748     }
2749  }
2750 #endif // ASSERT
2751 
2752   assert(kind == Relaxed, "Only plain accesses for now");
2753   if (callee()->is_static()) {
2754     // caller must have the capability!
2755     return false;
2756   }
2757   C->set_has_unsafe_access(true);
2758 
2759   const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2760   if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2761     // parameter valueType is not a constant
2762     return false;
2763   }
2764   ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2765   if (!mirror_type->is_inlinetype()) {
2766     // Dead code
2767     return false;
2768   }
2769   ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2770 
2771   const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2772   if (layout_type == nullptr || !layout_type->is_con()) {
2773     // parameter layoutKind is not a constant
2774     return false;
2775   }
2776   assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2777          layout_type->get_con() <= static_cast<int>(LayoutKind::UNKNOWN),
2778          "invalid layoutKind %d", layout_type->get_con());
2779   LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2780   assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NON_ATOMIC_FLAT ||
2781          layout == LayoutKind::ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2782          "unexpected layoutKind %d", layout_type->get_con());
2783 
2784   null_check(argument(0));
2785   if (stopped()) {
2786     return true;
2787   }
2788 
2789   Node* base = must_be_not_null(argument(1), true);
2790   Node* offset = argument(2);
2791   const Type* base_type = _gvn.type(base);
2792 
2793   Node* ptr;
2794   bool immutable_memory = false;
2795   DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2796   if (base_type->isa_instptr()) {
2797     const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2798     if (offset_type == nullptr || !offset_type->is_con()) {
2799       // Offset into a non-array should be a constant
2800       decorators |= C2_MISMATCHED;
2801     } else {
2802       int offset_con = checked_cast<int>(offset_type->get_con());
2803       ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2804       ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2805       if (field == nullptr) {
2806         assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2807         decorators |= C2_MISMATCHED;
2808       } else {
2809         assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2810                offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2811         immutable_memory = field->is_strict() && field->is_final();
2812 
2813         if (base->is_InlineType()) {
2814           assert(!is_store, "Cannot store into a non-larval value object");
2815           set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2816           return true;
2817         }
2818       }
2819     }
2820 
2821     if (base->is_InlineType()) {
2822       assert(!is_store, "Cannot store into a non-larval value object");
2823       base = base->as_InlineType()->buffer(this, true);
2824     }
2825     ptr = basic_plus_adr(base, ConvL2X(offset));
2826   } else if (base_type->isa_aryptr()) {
2827     decorators |= IS_ARRAY;
2828     if (layout == LayoutKind::REFERENCE) {
2829       if (!base_type->is_aryptr()->is_not_flat()) {
2830         const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2831         Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::StrongDependency));
2832         replace_in_map(base, new_base);
2833         base = new_base;
2834       }
2835       ptr = basic_plus_adr(base, ConvL2X(offset));
2836     } else {
2837       if (UseArrayFlattening) {
2838         // Flat array must have an exact type
2839         bool is_null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2840         bool is_atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2841         Node* new_base = cast_to_flat_array(base, value_klass, is_null_free, !is_null_free, is_atomic);
2842         replace_in_map(base, new_base);
2843         base = new_base;
2844         ptr = basic_plus_adr(base, ConvL2X(offset));
2845         const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2846         if (ptr_type->field_offset().get() != 0) {
2847           ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::StrongDependency));
2848         }
2849       } else {
2850         uncommon_trap(Deoptimization::Reason_intrinsic,
2851                       Deoptimization::Action_none);
2852         return true;
2853       }
2854     }
2855   } else {
2856     decorators |= C2_MISMATCHED;
2857     ptr = basic_plus_adr(base, ConvL2X(offset));
2858   }
2859 
2860   if (is_store) {
2861     Node* value = argument(6);
2862     const Type* value_type = _gvn.type(value);
2863     if (!value_type->is_inlinetypeptr()) {
2864       value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2865       Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::StrongDependency));
2866       new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2867       replace_in_map(value, new_value);
2868       value = new_value;
2869     }
2870 
2871     assert(value_type->inline_klass() == value_klass, "value is of type %s while valueType is %s", value_type->inline_klass()->name()->as_utf8(), value_klass->name()->as_utf8());
2872     if (layout == LayoutKind::REFERENCE) {
2873       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2874       access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2875     } else {
2876       bool atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2877       bool null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2878       value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2879     }
2880 
2881     return true;
2882   } else {
2883     decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2884     InlineTypeNode* result;
2885     if (layout == LayoutKind::REFERENCE) {
2886       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2887       Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2888       result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2889     } else {
2890       bool atomic = layout != LayoutKind::NON_ATOMIC_FLAT;
2891       bool null_free = layout != LayoutKind::NULLABLE_ATOMIC_FLAT;
2892       result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2893     }
2894 
2895     set_result(result);
2896     return true;
2897   }
2898 }
2899 
2900 bool LibraryCallKit::inline_unsafe_make_private_buffer() {
2901   Node* receiver = argument(0);
2902   Node* value = argument(1);
2903 
2904   const Type* type = gvn().type(value);
2905   if (!type->is_inlinetypeptr()) {
2906     C->record_method_not_compilable("value passed to Unsafe::makePrivateBuffer is not of a constant value type");
2907     return false;
2908   }
2909 
2910   null_check(receiver);
2911   if (stopped()) {
2912     return true;
2913   }
2914 
2915   value = null_check(value);
2916   if (stopped()) {
2917     return true;
2918   }
2919 
2920   ciInlineKlass* vk = type->inline_klass();
2921   Node* klass = makecon(TypeKlassPtr::make(vk));
2922   Node* obj = new_instance(klass);
2923   AllocateNode::Ideal_allocation(obj)->_larval = true;
2924 
2925   assert(value->is_InlineType(), "must be an InlineTypeNode");
2926   Node* payload_ptr = basic_plus_adr(obj, vk->payload_offset());
2927   value->as_InlineType()->store_flat(this, obj, payload_ptr, false, true, true, IN_HEAP | MO_UNORDERED);
2928 
2929   set_result(obj);
2930   return true;
2931 }
2932 
2933 bool LibraryCallKit::inline_unsafe_finish_private_buffer() {
2934   Node* receiver = argument(0);
2935   Node* buffer = argument(1);
2936 
2937   const Type* type = gvn().type(buffer);
2938   if (!type->is_inlinetypeptr()) {
2939     C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer is not of a constant value type");
2940     return false;
2941   }
2942 
2943   AllocateNode* alloc = AllocateNode::Ideal_allocation(buffer);
2944   if (alloc == nullptr) {
2945     C->record_method_not_compilable("value passed to Unsafe::finishPrivateBuffer must be allocated by Unsafe::makePrivateBuffer");
2946     return false;
2947   }
2948 
2949   null_check(receiver);
2950   if (stopped()) {
2951     return true;
2952   }
2953 
2954   // Unset the larval bit in the object header
2955   Node* old_header = make_load(control(), buffer, TypeX_X, TypeX_X->basic_type(), MemNode::unordered, LoadNode::Pinned);
2956   Node* new_header = gvn().transform(new AndXNode(old_header, MakeConX(~markWord::larval_bit_in_place)));
2957   access_store_at(buffer, buffer, type->is_ptr(), new_header, TypeX_X, TypeX_X->basic_type(), MO_UNORDERED | IN_HEAP);
2958 
2959   // We must ensure that the buffer is properly published
2960   insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
2961   assert(!type->maybe_null(), "result of an allocation should not be null");
2962   set_result(InlineTypeNode::make_from_oop(this, buffer, type->inline_klass()));
2963   return true;
2964 }
2965 
2966 //----------------------------inline_unsafe_load_store----------------------------
2967 // This method serves a couple of different customers (depending on LoadStoreKind):
2968 //
2969 // LS_cmp_swap:
2970 //
2971 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2972 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
2973 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
2974 //
2975 // LS_cmp_swap_weak:
2976 //
2977 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
2978 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
2979 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2980 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2981 //
2982 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
2983 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
2984 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
2985 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
2986 //
2987 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
2988 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
2989 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
2990 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
2991 //
2992 // LS_cmp_exchange:
2993 //
2994 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2995 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2996 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2997 //
2998 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
2999 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
3000 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
3001 //
3002 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
3003 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
3004 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
3005 //
3006 // LS_get_add:
3007 //
3008 //   int  getAndAddInt( Object o, long offset, int  delta)
3009 //   long getAndAddLong(Object o, long offset, long delta)
3010 //
3011 // LS_get_set:
3012 //
3013 //   int    getAndSet(Object o, long offset, int    newValue)
3014 //   long   getAndSet(Object o, long offset, long   newValue)
3015 //   Object getAndSet(Object o, long offset, Object newValue)
3016 //
3017 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
3018   // This basic scheme here is the same as inline_unsafe_access, but
3019   // differs in enough details that combining them would make the code
3020   // overly confusing.  (This is a true fact! I originally combined
3021   // them, but even I was confused by it!) As much code/comments as
3022   // possible are retained from inline_unsafe_access though to make
3023   // the correspondences clearer. - dl
3024 
3025   if (callee()->is_static())  return false;  // caller must have the capability!
3026 
3027   DecoratorSet decorators = C2_UNSAFE_ACCESS;
3028   decorators |= mo_decorator_for_access_kind(access_kind);
3029 
3030 #ifndef PRODUCT
3031   BasicType rtype;
3032   {
3033     ResourceMark rm;
3034     // Check the signatures.
3035     ciSignature* sig = callee()->signature();
3036     rtype = sig->return_type()->basic_type();
3037     switch(kind) {
3038       case LS_get_add:
3039       case LS_get_set: {
3040       // Check the signatures.
3041 #ifdef ASSERT
3042       assert(rtype == type, "get and set must return the expected type");
3043       assert(sig->count() == 3, "get and set has 3 arguments");
3044       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
3045       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
3046       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
3047       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
3048 #endif // ASSERT
3049         break;
3050       }
3051       case LS_cmp_swap:
3052       case LS_cmp_swap_weak: {
3053       // Check the signatures.
3054 #ifdef ASSERT
3055       assert(rtype == T_BOOLEAN, "CAS must return boolean");
3056       assert(sig->count() == 4, "CAS has 4 arguments");
3057       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3058       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3059 #endif // ASSERT
3060         break;
3061       }
3062       case LS_cmp_exchange: {
3063       // Check the signatures.
3064 #ifdef ASSERT
3065       assert(rtype == type, "CAS must return the expected type");
3066       assert(sig->count() == 4, "CAS has 4 arguments");
3067       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
3068       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
3069 #endif // ASSERT
3070         break;
3071       }
3072       default:
3073         ShouldNotReachHere();
3074     }
3075   }
3076 #endif //PRODUCT
3077 
3078   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
3079 
3080   // Get arguments:
3081   Node* receiver = nullptr;
3082   Node* base     = nullptr;
3083   Node* offset   = nullptr;
3084   Node* oldval   = nullptr;
3085   Node* newval   = nullptr;
3086   switch(kind) {
3087     case LS_cmp_swap:
3088     case LS_cmp_swap_weak:
3089     case LS_cmp_exchange: {
3090       const bool two_slot_type = type2size[type] == 2;
3091       receiver = argument(0);  // type: oop
3092       base     = argument(1);  // type: oop
3093       offset   = argument(2);  // type: long
3094       oldval   = argument(4);  // type: oop, int, or long
3095       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
3096       break;
3097     }
3098     case LS_get_add:
3099     case LS_get_set: {
3100       receiver = argument(0);  // type: oop
3101       base     = argument(1);  // type: oop
3102       offset   = argument(2);  // type: long
3103       oldval   = nullptr;
3104       newval   = argument(4);  // type: oop, int, or long
3105       break;
3106     }
3107     default:
3108       ShouldNotReachHere();
3109   }
3110 
3111   // Build field offset expression.
3112   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
3113   // to be plain byte offsets, which are also the same as those accepted
3114   // by oopDesc::field_addr.
3115   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
3116   // 32-bit machines ignore the high half of long offsets
3117   offset = ConvL2X(offset);
3118   // Save state and restore on bailout
3119   uint old_sp = sp();
3120   SafePointNode* old_map = clone_map();
3121   Node* adr = make_unsafe_address(base, offset,type, false);
3122   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
3123 
3124   Compile::AliasType* alias_type = C->alias_type(adr_type);
3125   BasicType bt = alias_type->basic_type();
3126   if (bt != T_ILLEGAL &&
3127       (is_reference_type(bt) != (type == T_OBJECT))) {
3128     // Don't intrinsify mismatched object accesses.
3129     set_map(old_map);
3130     set_sp(old_sp);
3131     return false;
3132   }
3133 
3134   destruct_map_clone(old_map);
3135 
3136   // For CAS, unlike inline_unsafe_access, there seems no point in
3137   // trying to refine types. Just use the coarse types here.
3138   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
3139   const Type *value_type = Type::get_const_basic_type(type);
3140 
3141   switch (kind) {
3142     case LS_get_set:
3143     case LS_cmp_exchange: {
3144       if (type == T_OBJECT) {
3145         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
3146         if (tjp != nullptr) {
3147           value_type = tjp;
3148         }
3149       }
3150       break;
3151     }
3152     case LS_cmp_swap:
3153     case LS_cmp_swap_weak:
3154     case LS_get_add:
3155       break;
3156     default:
3157       ShouldNotReachHere();
3158   }
3159 
3160   // Null check receiver.
3161   receiver = null_check(receiver);
3162   if (stopped()) {
3163     return true;
3164   }
3165 
3166   int alias_idx = C->get_alias_index(adr_type);
3167 
3168   if (is_reference_type(type)) {
3169     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3170 
3171     if (oldval != nullptr && oldval->is_InlineType()) {
3172       // Re-execute the unsafe access if allocation triggers deoptimization.
3173       PreserveReexecuteState preexecs(this);
3174       jvms()->set_should_reexecute(true);
3175       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3176     }
3177     if (newval != nullptr && newval->is_InlineType()) {
3178       // Re-execute the unsafe access if allocation triggers deoptimization.
3179       PreserveReexecuteState preexecs(this);
3180       jvms()->set_should_reexecute(true);
3181       newval = newval->as_InlineType()->buffer(this)->get_oop();
3182     }
3183 
3184     // Transformation of a value which could be null pointer (CastPP #null)
3185     // could be delayed during Parse (for example, in adjust_map_after_if()).
3186     // Execute transformation here to avoid barrier generation in such case.
3187     if (_gvn.type(newval) == TypePtr::NULL_PTR)
3188       newval = _gvn.makecon(TypePtr::NULL_PTR);
3189 
3190     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3191       // Refine the value to a null constant, when it is known to be null
3192       oldval = _gvn.makecon(TypePtr::NULL_PTR);
3193     }
3194   }
3195 
3196   Node* result = nullptr;
3197   switch (kind) {
3198     case LS_cmp_exchange: {
3199       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3200                                             oldval, newval, value_type, type, decorators);
3201       break;
3202     }
3203     case LS_cmp_swap_weak:
3204       decorators |= C2_WEAK_CMPXCHG;
3205     case LS_cmp_swap: {
3206       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3207                                              oldval, newval, value_type, type, decorators);
3208       break;
3209     }
3210     case LS_get_set: {
3211       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3212                                      newval, value_type, type, decorators);
3213       break;
3214     }
3215     case LS_get_add: {
3216       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3217                                     newval, value_type, type, decorators);
3218       break;
3219     }
3220     default:
3221       ShouldNotReachHere();
3222   }
3223 
3224   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3225   set_result(result);
3226   return true;
3227 }
3228 
3229 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3230   // Regardless of form, don't allow previous ld/st to move down,
3231   // then issue acquire, release, or volatile mem_bar.
3232   insert_mem_bar(Op_MemBarCPUOrder);
3233   switch(id) {
3234     case vmIntrinsics::_loadFence:
3235       insert_mem_bar(Op_LoadFence);
3236       return true;
3237     case vmIntrinsics::_storeFence:
3238       insert_mem_bar(Op_StoreFence);
3239       return true;
3240     case vmIntrinsics::_storeStoreFence:
3241       insert_mem_bar(Op_StoreStoreFence);
3242       return true;
3243     case vmIntrinsics::_fullFence:
3244       insert_mem_bar(Op_MemBarVolatile);
3245       return true;
3246     default:
3247       fatal_unexpected_iid(id);
3248       return false;
3249   }
3250 }
3251 
3252 bool LibraryCallKit::inline_onspinwait() {
3253   insert_mem_bar(Op_OnSpinWait);
3254   return true;
3255 }
3256 
3257 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3258   if (!kls->is_Con()) {
3259     return true;
3260   }
3261   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3262   if (klsptr == nullptr) {
3263     return true;
3264   }
3265   ciInstanceKlass* ik = klsptr->instance_klass();
3266   // don't need a guard for a klass that is already initialized
3267   return !ik->is_initialized();
3268 }
3269 
3270 //----------------------------inline_unsafe_writeback0-------------------------
3271 // public native void Unsafe.writeback0(long address)
3272 bool LibraryCallKit::inline_unsafe_writeback0() {
3273   if (!Matcher::has_match_rule(Op_CacheWB)) {
3274     return false;
3275   }
3276 #ifndef PRODUCT
3277   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3278   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3279   ciSignature* sig = callee()->signature();
3280   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3281 #endif
3282   null_check_receiver();  // null-check, then ignore
3283   Node *addr = argument(1);
3284   addr = new CastX2PNode(addr);
3285   addr = _gvn.transform(addr);
3286   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3287   flush = _gvn.transform(flush);
3288   set_memory(flush, TypeRawPtr::BOTTOM);
3289   return true;
3290 }
3291 
3292 //----------------------------inline_unsafe_writeback0-------------------------
3293 // public native void Unsafe.writeback0(long address)
3294 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3295   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3296     return false;
3297   }
3298   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3299     return false;
3300   }
3301 #ifndef PRODUCT
3302   assert(Matcher::has_match_rule(Op_CacheWB),
3303          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3304                 : "found match rule for CacheWBPostSync but not CacheWB"));
3305 
3306 #endif
3307   null_check_receiver();  // null-check, then ignore
3308   Node *sync;
3309   if (is_pre) {
3310     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3311   } else {
3312     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3313   }
3314   sync = _gvn.transform(sync);
3315   set_memory(sync, TypeRawPtr::BOTTOM);
3316   return true;
3317 }
3318 
3319 //----------------------------inline_unsafe_allocate---------------------------
3320 // public native Object Unsafe.allocateInstance(Class<?> cls);
3321 bool LibraryCallKit::inline_unsafe_allocate() {
3322 
3323 #if INCLUDE_JVMTI
3324   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3325     return false;
3326   }
3327 #endif //INCLUDE_JVMTI
3328 
3329   if (callee()->is_static())  return false;  // caller must have the capability!
3330 
3331   null_check_receiver();  // null-check, then ignore
3332   Node* cls = null_check(argument(1));
3333   if (stopped())  return true;
3334 
3335   Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3336   kls = null_check(kls);
3337   if (stopped())  return true;  // argument was like int.class
3338 
3339 #if INCLUDE_JVMTI
3340     // Don't try to access new allocated obj in the intrinsic.
3341     // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3342     // Deoptimize and allocate in interpreter instead.
3343     Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3344     Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3345     Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3346     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3347     {
3348       BuildCutout unless(this, tst, PROB_MAX);
3349       uncommon_trap(Deoptimization::Reason_intrinsic,
3350                     Deoptimization::Action_make_not_entrant);
3351     }
3352     if (stopped()) {
3353       return true;
3354     }
3355 #endif //INCLUDE_JVMTI
3356 
3357   Node* test = nullptr;
3358   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3359     // Note:  The argument might still be an illegal value like
3360     // Serializable.class or Object[].class.   The runtime will handle it.
3361     // But we must make an explicit check for initialization.
3362     Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3363     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3364     // can generate code to load it as unsigned byte.
3365     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3366     Node* bits = intcon(InstanceKlass::fully_initialized);
3367     test = _gvn.transform(new SubINode(inst, bits));
3368     // The 'test' is non-zero if we need to take a slow path.
3369   }
3370   Node* obj = nullptr;
3371   const TypeInstKlassPtr* tkls = _gvn.type(kls)->isa_instklassptr();
3372   if (tkls != nullptr && tkls->instance_klass()->is_inlinetype()) {
3373     obj = InlineTypeNode::make_all_zero(_gvn, tkls->instance_klass()->as_inline_klass())->buffer(this);
3374   } else {
3375     obj = new_instance(kls, test);
3376   }
3377   set_result(obj);
3378   return true;
3379 }
3380 
3381 //------------------------inline_native_time_funcs--------------
3382 // inline code for System.currentTimeMillis() and System.nanoTime()
3383 // these have the same type and signature
3384 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3385   const TypeFunc* tf = OptoRuntime::void_long_Type();
3386   const TypePtr* no_memory_effects = nullptr;
3387   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3388   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3389 #ifdef ASSERT
3390   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3391   assert(value_top == top(), "second value must be top");
3392 #endif
3393   set_result(value);
3394   return true;
3395 }
3396 
3397 
3398 #if INCLUDE_JVMTI
3399 
3400 // When notifications are disabled then just update the VTMS transition bit and return.
3401 // Otherwise, the bit is updated in the given function call implementing JVMTI notification protocol.
3402 bool LibraryCallKit::inline_native_notify_jvmti_funcs(address funcAddr, const char* funcName, bool is_start, bool is_end) {
3403   if (!DoJVMTIVirtualThreadTransitions) {
3404     return true;
3405   }
3406   Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3407   IdealKit ideal(this);
3408 
3409   Node* ONE = ideal.ConI(1);
3410   Node* hide = is_start ? ideal.ConI(0) : (is_end ? ideal.ConI(1) : _gvn.transform(argument(1)));
3411   Node* addr = makecon(TypeRawPtr::make((address)&JvmtiVTMSTransitionDisabler::_VTMS_notify_jvmti_events));
3412   Node* notify_jvmti_enabled = ideal.load(ideal.ctrl(), addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3413 
3414   ideal.if_then(notify_jvmti_enabled, BoolTest::eq, ONE); {
3415     sync_kit(ideal);
3416     // if notifyJvmti enabled then make a call to the given SharedRuntime function
3417     const TypeFunc* tf = OptoRuntime::notify_jvmti_vthread_Type();
3418     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, hide);
3419     ideal.sync_kit(this);
3420   } ideal.else_(); {
3421     // set hide value to the VTMS transition bit in current JavaThread and VirtualThread object
3422     Node* thread = ideal.thread();
3423     Node* jt_addr = basic_plus_adr(thread, in_bytes(JavaThread::is_in_VTMS_transition_offset()));
3424     Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_VTMS_transition_offset());
3425 
3426     sync_kit(ideal);
3427     access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), hide, _gvn.type(hide), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3428     access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), hide, _gvn.type(hide), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3429 
3430     ideal.sync_kit(this);
3431   } ideal.end_if();
3432   final_sync(ideal);
3433 
3434   return true;
3435 }
3436 
3437 // Always update the is_disable_suspend bit.
3438 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3439   if (!DoJVMTIVirtualThreadTransitions) {
3440     return true;
3441   }
3442   IdealKit ideal(this);
3443 
3444   {
3445     // unconditionally update the is_disable_suspend bit in current JavaThread
3446     Node* thread = ideal.thread();
3447     Node* arg = _gvn.transform(argument(0)); // argument for notification
3448     Node* addr = basic_plus_adr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3449     const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3450 
3451     sync_kit(ideal);
3452     access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3453     ideal.sync_kit(this);
3454   }
3455   final_sync(ideal);
3456 
3457   return true;
3458 }
3459 
3460 #endif // INCLUDE_JVMTI
3461 
3462 #ifdef JFR_HAVE_INTRINSICS
3463 
3464 /**
3465  * if oop->klass != null
3466  *   // normal class
3467  *   epoch = _epoch_state ? 2 : 1
3468  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3469  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3470  *   }
3471  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3472  * else
3473  *   // primitive class
3474  *   if oop->array_klass != null
3475  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3476  *   else
3477  *     id = LAST_TYPE_ID + 1 // void class path
3478  *   if (!signaled)
3479  *     signaled = true
3480  */
3481 bool LibraryCallKit::inline_native_classID() {
3482   Node* cls = argument(0);
3483 
3484   IdealKit ideal(this);
3485 #define __ ideal.
3486   IdealVariable result(ideal); __ declarations_done();
3487   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3488                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
3489                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3490 
3491 
3492   __ if_then(kls, BoolTest::ne, null()); {
3493     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3494     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3495 
3496     Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3497     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3498     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3499     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3500     mask = _gvn.transform(new OrLNode(mask, epoch));
3501     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3502 
3503     float unlikely  = PROB_UNLIKELY(0.999);
3504     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3505       sync_kit(ideal);
3506       make_runtime_call(RC_LEAF,
3507                         OptoRuntime::class_id_load_barrier_Type(),
3508                         CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3509                         "class id load barrier",
3510                         TypePtr::BOTTOM,
3511                         kls);
3512       ideal.sync_kit(this);
3513     } __ end_if();
3514 
3515     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3516   } __ else_(); {
3517     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3518                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3519                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3520     __ if_then(array_kls, BoolTest::ne, null()); {
3521       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3522       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3523       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3524       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3525     } __ else_(); {
3526       // void class case
3527       ideal.set(result, _gvn.transform(longcon(LAST_TYPE_ID + 1)));
3528     } __ end_if();
3529 
3530     Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3531     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3532     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3533       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3534     } __ end_if();
3535   } __ end_if();
3536 
3537   final_sync(ideal);
3538   set_result(ideal.value(result));
3539 #undef __
3540   return true;
3541 }
3542 
3543 //------------------------inline_native_jvm_commit------------------
3544 bool LibraryCallKit::inline_native_jvm_commit() {
3545   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3546 
3547   // Save input memory and i_o state.
3548   Node* input_memory_state = reset_memory();
3549   set_all_memory(input_memory_state);
3550   Node* input_io_state = i_o();
3551 
3552   // TLS.
3553   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3554   // Jfr java buffer.
3555   Node* java_buffer_offset = _gvn.transform(new AddPNode(top(), tls_ptr, _gvn.transform(MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR)))));
3556   Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3557   Node* java_buffer_pos_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET)))));
3558 
3559   // Load the current value of the notified field in the JfrThreadLocal.
3560   Node* notified_offset = basic_plus_adr(top(), tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3561   Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3562 
3563   // Test for notification.
3564   Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3565   Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3566   IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3567 
3568   // True branch, is notified.
3569   Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3570   set_control(is_notified);
3571 
3572   // Reset notified state.
3573   store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3574   Node* notified_reset_memory = reset_memory();
3575 
3576   // Iff notified, the return address of the commit method is the current position of the backing java buffer. This is used to reset the event writer.
3577   Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3578   // Convert the machine-word to a long.
3579   Node* current_pos = _gvn.transform(ConvX2L(current_pos_X));
3580 
3581   // False branch, not notified.
3582   Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3583   set_control(not_notified);
3584   set_all_memory(input_memory_state);
3585 
3586   // Arg is the next position as a long.
3587   Node* arg = argument(0);
3588   // Convert long to machine-word.
3589   Node* next_pos_X = _gvn.transform(ConvL2X(arg));
3590 
3591   // Store the next_position to the underlying jfr java buffer.
3592   store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3593 
3594   Node* commit_memory = reset_memory();
3595   set_all_memory(commit_memory);
3596 
3597   // Now load the flags from off the java buffer and decide if the buffer is a lease. If so, it needs to be returned post-commit.
3598   Node* java_buffer_flags_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET)))));
3599   Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3600   Node* lease_constant = _gvn.transform(_gvn.intcon(4));
3601 
3602   // And flags with lease constant.
3603   Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3604 
3605   // Branch on lease to conditionalize returning the leased java buffer.
3606   Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3607   Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3608   IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3609 
3610   // False branch, not a lease.
3611   Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3612 
3613   // True branch, is lease.
3614   Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3615   set_control(is_lease);
3616 
3617   // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3618   Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3619                                               OptoRuntime::void_void_Type(),
3620                                               SharedRuntime::jfr_return_lease(),
3621                                               "return_lease", TypePtr::BOTTOM);
3622   Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3623 
3624   RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3625   record_for_igvn(lease_compare_rgn);
3626   PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3627   record_for_igvn(lease_compare_mem);
3628   PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3629   record_for_igvn(lease_compare_io);
3630   PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3631   record_for_igvn(lease_result_value);
3632 
3633   // Update control and phi nodes.
3634   lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3635   lease_compare_rgn->init_req(_false_path, not_lease);
3636 
3637   lease_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3638   lease_compare_mem->init_req(_false_path, commit_memory);
3639 
3640   lease_compare_io->init_req(_true_path, i_o());
3641   lease_compare_io->init_req(_false_path, input_io_state);
3642 
3643   lease_result_value->init_req(_true_path, null()); // if the lease was returned, return 0.
3644   lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3645 
3646   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3647   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3648   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3649   PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3650 
3651   // Update control and phi nodes.
3652   result_rgn->init_req(_true_path, is_notified);
3653   result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3654 
3655   result_mem->init_req(_true_path, notified_reset_memory);
3656   result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3657 
3658   result_io->init_req(_true_path, input_io_state);
3659   result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3660 
3661   result_value->init_req(_true_path, current_pos);
3662   result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3663 
3664   // Set output state.
3665   set_control(_gvn.transform(result_rgn));
3666   set_all_memory(_gvn.transform(result_mem));
3667   set_i_o(_gvn.transform(result_io));
3668   set_result(result_rgn, result_value);
3669   return true;
3670 }
3671 
3672 /*
3673  * The intrinsic is a model of this pseudo-code:
3674  *
3675  * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3676  * jobject h_event_writer = tl->java_event_writer();
3677  * if (h_event_writer == nullptr) {
3678  *   return nullptr;
3679  * }
3680  * oop threadObj = Thread::threadObj();
3681  * oop vthread = java_lang_Thread::vthread(threadObj);
3682  * traceid tid;
3683  * bool pinVirtualThread;
3684  * bool excluded;
3685  * if (vthread != threadObj) {  // i.e. current thread is virtual
3686  *   tid = java_lang_Thread::tid(vthread);
3687  *   u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3688  *   pinVirtualThread = VMContinuations;
3689  *   excluded = vthread_epoch_raw & excluded_mask;
3690  *   if (!excluded) {
3691  *     traceid current_epoch = JfrTraceIdEpoch::current_generation();
3692  *     u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3693  *     if (vthread_epoch != current_epoch) {
3694  *       write_checkpoint();
3695  *     }
3696  *   }
3697  * } else {
3698  *   tid = java_lang_Thread::tid(threadObj);
3699  *   u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3700  *   pinVirtualThread = false;
3701  *   excluded = thread_epoch_raw & excluded_mask;
3702  * }
3703  * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3704  * traceid tid_in_event_writer = getField(event_writer, "threadID");
3705  * if (tid_in_event_writer != tid) {
3706  *   setField(event_writer, "pinVirtualThread", pinVirtualThread);
3707  *   setField(event_writer, "excluded", excluded);
3708  *   setField(event_writer, "threadID", tid);
3709  * }
3710  * return event_writer
3711  */
3712 bool LibraryCallKit::inline_native_getEventWriter() {
3713   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3714 
3715   // Save input memory and i_o state.
3716   Node* input_memory_state = reset_memory();
3717   set_all_memory(input_memory_state);
3718   Node* input_io_state = i_o();
3719 
3720   // The most significant bit of the u2 is used to denote thread exclusion
3721   Node* excluded_shift = _gvn.intcon(15);
3722   Node* excluded_mask = _gvn.intcon(1 << 15);
3723   // The epoch generation is the range [1-32767]
3724   Node* epoch_mask = _gvn.intcon(32767);
3725 
3726   // TLS
3727   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3728 
3729   // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3730   Node* jobj_ptr = basic_plus_adr(top(), tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3731 
3732   // Load the eventwriter jobject handle.
3733   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3734 
3735   // Null check the jobject handle.
3736   Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3737   Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3738   IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3739 
3740   // False path, jobj is null.
3741   Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3742 
3743   // True path, jobj is not null.
3744   Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3745 
3746   set_control(jobj_is_not_null);
3747 
3748   // Load the threadObj for the CarrierThread.
3749   Node* threadObj = generate_current_thread(tls_ptr);
3750 
3751   // Load the vthread.
3752   Node* vthread = generate_virtual_thread(tls_ptr);
3753 
3754   // If vthread != threadObj, this is a virtual thread.
3755   Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3756   Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3757   IfNode* iff_vthread_not_equal_threadObj =
3758     create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3759 
3760   // False branch, fallback to threadObj.
3761   Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3762   set_control(vthread_equal_threadObj);
3763 
3764   // Load the tid field from the vthread object.
3765   Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3766 
3767   // Load the raw epoch value from the threadObj.
3768   Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3769   Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3770                                              _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3771                                              TypeInt::CHAR, T_CHAR,
3772                                              IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3773 
3774   // Mask off the excluded information from the epoch.
3775   Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3776 
3777   // True branch, this is a virtual thread.
3778   Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3779   set_control(vthread_not_equal_threadObj);
3780 
3781   // Load the tid field from the vthread object.
3782   Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3783 
3784   // Continuation support determines if a virtual thread should be pinned.
3785   Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3786   Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3787 
3788   // Load the raw epoch value from the vthread.
3789   Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3790   Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3791                                            TypeInt::CHAR, T_CHAR,
3792                                            IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3793 
3794   // Mask off the excluded information from the epoch.
3795   Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(excluded_mask)));
3796 
3797   // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3798   Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, _gvn.transform(excluded_mask)));
3799   Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3800   IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3801 
3802   // False branch, vthread is excluded, no need to write epoch info.
3803   Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3804 
3805   // True branch, vthread is included, update epoch info.
3806   Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3807   set_control(included);
3808 
3809   // Get epoch value.
3810   Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(epoch_mask)));
3811 
3812   // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3813   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3814   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3815 
3816   // Compare the epoch in the vthread to the current epoch generation.
3817   Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3818   Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3819   IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3820 
3821   // False path, epoch is equal, checkpoint information is valid.
3822   Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3823 
3824   // True path, epoch is not equal, write a checkpoint for the vthread.
3825   Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3826 
3827   set_control(epoch_is_not_equal);
3828 
3829   // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3830   // The call also updates the native thread local thread id and the vthread with the current epoch.
3831   Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3832                                                   OptoRuntime::jfr_write_checkpoint_Type(),
3833                                                   SharedRuntime::jfr_write_checkpoint(),
3834                                                   "write_checkpoint", TypePtr::BOTTOM);
3835   Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3836 
3837   // vthread epoch != current epoch
3838   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3839   record_for_igvn(epoch_compare_rgn);
3840   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3841   record_for_igvn(epoch_compare_mem);
3842   PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3843   record_for_igvn(epoch_compare_io);
3844 
3845   // Update control and phi nodes.
3846   epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3847   epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3848   epoch_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3849   epoch_compare_mem->init_req(_false_path, input_memory_state);
3850   epoch_compare_io->init_req(_true_path, i_o());
3851   epoch_compare_io->init_req(_false_path, input_io_state);
3852 
3853   // excluded != true
3854   RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3855   record_for_igvn(exclude_compare_rgn);
3856   PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3857   record_for_igvn(exclude_compare_mem);
3858   PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3859   record_for_igvn(exclude_compare_io);
3860 
3861   // Update control and phi nodes.
3862   exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3863   exclude_compare_rgn->init_req(_false_path, excluded);
3864   exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3865   exclude_compare_mem->init_req(_false_path, input_memory_state);
3866   exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3867   exclude_compare_io->init_req(_false_path, input_io_state);
3868 
3869   // vthread != threadObj
3870   RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3871   record_for_igvn(vthread_compare_rgn);
3872   PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3873   PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3874   record_for_igvn(vthread_compare_io);
3875   PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3876   record_for_igvn(tid);
3877   PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3878   record_for_igvn(exclusion);
3879   PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
3880   record_for_igvn(pinVirtualThread);
3881 
3882   // Update control and phi nodes.
3883   vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
3884   vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
3885   vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
3886   vthread_compare_mem->init_req(_false_path, input_memory_state);
3887   vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
3888   vthread_compare_io->init_req(_false_path, input_io_state);
3889   tid->init_req(_true_path, _gvn.transform(vthread_tid));
3890   tid->init_req(_false_path, _gvn.transform(thread_obj_tid));
3891   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
3892   exclusion->init_req(_false_path, _gvn.transform(threadObj_is_excluded));
3893   pinVirtualThread->init_req(_true_path, _gvn.transform(continuation_support));
3894   pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
3895 
3896   // Update branch state.
3897   set_control(_gvn.transform(vthread_compare_rgn));
3898   set_all_memory(_gvn.transform(vthread_compare_mem));
3899   set_i_o(_gvn.transform(vthread_compare_io));
3900 
3901   // Load the event writer oop by dereferencing the jobject handle.
3902   ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
3903   assert(klass_EventWriter->is_loaded(), "invariant");
3904   ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
3905   const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
3906   const TypeOopPtr* const xtype = aklass->as_instance_type();
3907   Node* jobj_untagged = _gvn.transform(new AddPNode(top(), jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
3908   Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3909 
3910   // Load the current thread id from the event writer object.
3911   Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
3912   // Get the field offset to, conditionally, store an updated tid value later.
3913   Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
3914   // Get the field offset to, conditionally, store an updated exclusion value later.
3915   Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
3916   // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
3917   Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
3918 
3919   RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
3920   record_for_igvn(event_writer_tid_compare_rgn);
3921   PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3922   record_for_igvn(event_writer_tid_compare_mem);
3923   PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
3924   record_for_igvn(event_writer_tid_compare_io);
3925 
3926   // Compare the current tid from the thread object to what is currently stored in the event writer object.
3927   Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
3928   Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
3929   IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3930 
3931   // False path, tids are the same.
3932   Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
3933 
3934   // True path, tid is not equal, need to update the tid in the event writer.
3935   Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
3936   record_for_igvn(tid_is_not_equal);
3937 
3938   // Store the pin state to the event writer.
3939   store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
3940 
3941   // Store the exclusion state to the event writer.
3942   Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
3943   store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
3944 
3945   // Store the tid to the event writer.
3946   store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
3947 
3948   // Update control and phi nodes.
3949   event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
3950   event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
3951   event_writer_tid_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3952   event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
3953   event_writer_tid_compare_io->init_req(_true_path, _gvn.transform(i_o()));
3954   event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
3955 
3956   // Result of top level CFG, Memory, IO and Value.
3957   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3958   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3959   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3960   PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
3961 
3962   // Result control.
3963   result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
3964   result_rgn->init_req(_false_path, jobj_is_null);
3965 
3966   // Result memory.
3967   result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
3968   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
3969 
3970   // Result IO.
3971   result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
3972   result_io->init_req(_false_path, _gvn.transform(input_io_state));
3973 
3974   // Result value.
3975   result_value->init_req(_true_path, _gvn.transform(event_writer)); // return event writer oop
3976   result_value->init_req(_false_path, null()); // return null
3977 
3978   // Set output state.
3979   set_control(_gvn.transform(result_rgn));
3980   set_all_memory(_gvn.transform(result_mem));
3981   set_i_o(_gvn.transform(result_io));
3982   set_result(result_rgn, result_value);
3983   return true;
3984 }
3985 
3986 /*
3987  * The intrinsic is a model of this pseudo-code:
3988  *
3989  * JfrThreadLocal* const tl = thread->jfr_thread_local();
3990  * if (carrierThread != thread) { // is virtual thread
3991  *   const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
3992  *   bool excluded = vthread_epoch_raw & excluded_mask;
3993  *   Atomic::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
3994  *   Atomic::store(&tl->_contextual_thread_excluded, is_excluded);
3995  *   if (!excluded) {
3996  *     const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3997  *     Atomic::store(&tl->_vthread_epoch, vthread_epoch);
3998  *   }
3999  *   Atomic::release_store(&tl->_vthread, true);
4000  *   return;
4001  * }
4002  * Atomic::release_store(&tl->_vthread, false);
4003  */
4004 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
4005   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4006 
4007   Node* input_memory_state = reset_memory();
4008   set_all_memory(input_memory_state);
4009 
4010   // The most significant bit of the u2 is used to denote thread exclusion
4011   Node* excluded_mask = _gvn.intcon(1 << 15);
4012   // The epoch generation is the range [1-32767]
4013   Node* epoch_mask = _gvn.intcon(32767);
4014 
4015   Node* const carrierThread = generate_current_thread(jt);
4016   // If thread != carrierThread, this is a virtual thread.
4017   Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
4018   Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
4019   IfNode* iff_thread_not_equal_carrierThread =
4020     create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
4021 
4022   Node* vthread_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
4023 
4024   // False branch, is carrierThread.
4025   Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
4026   // Store release
4027   Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
4028 
4029   set_all_memory(input_memory_state);
4030 
4031   // True branch, is virtual thread.
4032   Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
4033   set_control(thread_not_equal_carrierThread);
4034 
4035   // Load the raw epoch value from the vthread.
4036   Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
4037   Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
4038                                    IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
4039 
4040   // Mask off the excluded information from the epoch.
4041   Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(excluded_mask)));
4042 
4043   // Load the tid field from the thread.
4044   Node* tid = load_field_from_object(thread, "tid", "J");
4045 
4046   // Store the vthread tid to the jfr thread local.
4047   Node* thread_id_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
4048   Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
4049 
4050   // Branch is_excluded to conditionalize updating the epoch .
4051   Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, _gvn.transform(excluded_mask)));
4052   Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
4053   IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
4054 
4055   // True branch, vthread is excluded, no need to write epoch info.
4056   Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
4057   set_control(excluded);
4058   Node* vthread_is_excluded = _gvn.intcon(1);
4059 
4060   // False branch, vthread is included, update epoch info.
4061   Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
4062   set_control(included);
4063   Node* vthread_is_included = _gvn.intcon(0);
4064 
4065   // Get epoch value.
4066   Node* epoch = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(epoch_mask)));
4067 
4068   // Store the vthread epoch to the jfr thread local.
4069   Node* vthread_epoch_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
4070   Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
4071 
4072   RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
4073   record_for_igvn(excluded_rgn);
4074   PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
4075   record_for_igvn(excluded_mem);
4076   PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
4077   record_for_igvn(exclusion);
4078 
4079   // Merge the excluded control and memory.
4080   excluded_rgn->init_req(_true_path, excluded);
4081   excluded_rgn->init_req(_false_path, included);
4082   excluded_mem->init_req(_true_path, tid_memory);
4083   excluded_mem->init_req(_false_path, included_memory);
4084   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
4085   exclusion->init_req(_false_path, _gvn.transform(vthread_is_included));
4086 
4087   // Set intermediate state.
4088   set_control(_gvn.transform(excluded_rgn));
4089   set_all_memory(excluded_mem);
4090 
4091   // Store the vthread exclusion state to the jfr thread local.
4092   Node* thread_local_excluded_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
4093   store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
4094 
4095   // Store release
4096   Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
4097 
4098   RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
4099   record_for_igvn(thread_compare_rgn);
4100   PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4101   record_for_igvn(thread_compare_mem);
4102   PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
4103   record_for_igvn(vthread);
4104 
4105   // Merge the thread_compare control and memory.
4106   thread_compare_rgn->init_req(_true_path, control());
4107   thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
4108   thread_compare_mem->init_req(_true_path, vthread_true_memory);
4109   thread_compare_mem->init_req(_false_path, vthread_false_memory);
4110 
4111   // Set output state.
4112   set_control(_gvn.transform(thread_compare_rgn));
4113   set_all_memory(_gvn.transform(thread_compare_mem));
4114 }
4115 
4116 #endif // JFR_HAVE_INTRINSICS
4117 
4118 //------------------------inline_native_currentCarrierThread------------------
4119 bool LibraryCallKit::inline_native_currentCarrierThread() {
4120   Node* junk = nullptr;
4121   set_result(generate_current_thread(junk));
4122   return true;
4123 }
4124 
4125 //------------------------inline_native_currentThread------------------
4126 bool LibraryCallKit::inline_native_currentThread() {
4127   Node* junk = nullptr;
4128   set_result(generate_virtual_thread(junk));
4129   return true;
4130 }
4131 
4132 //------------------------inline_native_setVthread------------------
4133 bool LibraryCallKit::inline_native_setCurrentThread() {
4134   assert(C->method()->changes_current_thread(),
4135          "method changes current Thread but is not annotated ChangesCurrentThread");
4136   Node* arr = argument(1);
4137   Node* thread = _gvn.transform(new ThreadLocalNode());
4138   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
4139   Node* thread_obj_handle
4140     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4141   thread_obj_handle = _gvn.transform(thread_obj_handle);
4142   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4143   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4144 
4145   // Change the _monitor_owner_id of the JavaThread
4146   Node* tid = load_field_from_object(arr, "tid", "J");
4147   Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4148   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4149 
4150   JFR_ONLY(extend_setCurrentThread(thread, arr);)
4151   return true;
4152 }
4153 
4154 const Type* LibraryCallKit::scopedValueCache_type() {
4155   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4156   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4157   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true);
4158 
4159   // Because we create the scopedValue cache lazily we have to make the
4160   // type of the result BotPTR.
4161   bool xk = etype->klass_is_exact();
4162   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4163   return objects_type;
4164 }
4165 
4166 Node* LibraryCallKit::scopedValueCache_helper() {
4167   Node* thread = _gvn.transform(new ThreadLocalNode());
4168   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
4169   // We cannot use immutable_memory() because we might flip onto a
4170   // different carrier thread, at which point we'll need to use that
4171   // carrier thread's cache.
4172   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4173   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4174   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4175 }
4176 
4177 //------------------------inline_native_scopedValueCache------------------
4178 bool LibraryCallKit::inline_native_scopedValueCache() {
4179   Node* cache_obj_handle = scopedValueCache_helper();
4180   const Type* objects_type = scopedValueCache_type();
4181   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4182 
4183   return true;
4184 }
4185 
4186 //------------------------inline_native_setScopedValueCache------------------
4187 bool LibraryCallKit::inline_native_setScopedValueCache() {
4188   Node* arr = argument(0);
4189   Node* cache_obj_handle = scopedValueCache_helper();
4190   const Type* objects_type = scopedValueCache_type();
4191 
4192   const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4193   access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4194 
4195   return true;
4196 }
4197 
4198 //------------------------inline_native_Continuation_pin and unpin-----------
4199 
4200 // Shared implementation routine for both pin and unpin.
4201 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4202   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4203 
4204   // Save input memory.
4205   Node* input_memory_state = reset_memory();
4206   set_all_memory(input_memory_state);
4207 
4208   // TLS
4209   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4210   Node* last_continuation_offset = basic_plus_adr(top(), tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4211   Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4212 
4213   // Null check the last continuation object.
4214   Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4215   Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4216   IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4217 
4218   // False path, last continuation is null.
4219   Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4220 
4221   // True path, last continuation is not null.
4222   Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4223 
4224   set_control(continuation_is_not_null);
4225 
4226   // Load the pin count from the last continuation.
4227   Node* pin_count_offset = basic_plus_adr(top(), last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4228   Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4229 
4230   // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4231   Node* pin_count_rhs;
4232   if (unpin) {
4233     pin_count_rhs = _gvn.intcon(0);
4234   } else {
4235     pin_count_rhs = _gvn.intcon(UINT32_MAX);
4236   }
4237   Node* pin_count_cmp = _gvn.transform(new CmpUNode(_gvn.transform(pin_count), pin_count_rhs));
4238   Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4239   IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4240 
4241   // True branch, pin count over/underflow.
4242   Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4243   {
4244     // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4245     // which will throw IllegalStateException for pin count over/underflow.
4246     // No memory changed so far - we can use memory create by reset_memory()
4247     // at the beginning of this intrinsic. No need to call reset_memory() again.
4248     PreserveJVMState pjvms(this);
4249     set_control(pin_count_over_underflow);
4250     uncommon_trap(Deoptimization::Reason_intrinsic,
4251                   Deoptimization::Action_none);
4252     assert(stopped(), "invariant");
4253   }
4254 
4255   // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4256   Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4257   set_control(valid_pin_count);
4258 
4259   Node* next_pin_count;
4260   if (unpin) {
4261     next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4262   } else {
4263     next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4264   }
4265 
4266   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4267 
4268   // Result of top level CFG and Memory.
4269   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4270   record_for_igvn(result_rgn);
4271   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4272   record_for_igvn(result_mem);
4273 
4274   result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
4275   result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
4276   result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4277   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4278 
4279   // Set output state.
4280   set_control(_gvn.transform(result_rgn));
4281   set_all_memory(_gvn.transform(result_mem));
4282 
4283   return true;
4284 }
4285 
4286 //-----------------------load_klass_from_mirror_common-------------------------
4287 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4288 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4289 // and branch to the given path on the region.
4290 // If never_see_null, take an uncommon trap on null, so we can optimistically
4291 // compile for the non-null case.
4292 // If the region is null, force never_see_null = true.
4293 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4294                                                     bool never_see_null,
4295                                                     RegionNode* region,
4296                                                     int null_path,
4297                                                     int offset) {
4298   if (region == nullptr)  never_see_null = true;
4299   Node* p = basic_plus_adr(mirror, offset);
4300   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4301   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4302   Node* null_ctl = top();
4303   kls = null_check_oop(kls, &null_ctl, never_see_null);
4304   if (region != nullptr) {
4305     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4306     region->init_req(null_path, null_ctl);
4307   } else {
4308     assert(null_ctl == top(), "no loose ends");
4309   }
4310   return kls;
4311 }
4312 
4313 //--------------------(inline_native_Class_query helpers)---------------------
4314 // Use this for JVM_ACC_INTERFACE.
4315 // Fall through if (mods & mask) == bits, take the guard otherwise.
4316 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4317                                                  ByteSize offset, const Type* type, BasicType bt) {
4318   // Branch around if the given klass has the given modifier bit set.
4319   // Like generate_guard, adds a new path onto the region.
4320   Node* modp = basic_plus_adr(kls, in_bytes(offset));
4321   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4322   Node* mask = intcon(modifier_mask);
4323   Node* bits = intcon(modifier_bits);
4324   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4325   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4326   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4327   return generate_fair_guard(bol, region);
4328 }
4329 
4330 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4331   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4332                                     Klass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4333 }
4334 
4335 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4336 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4337   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4338                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4339 }
4340 
4341 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4342   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4343 }
4344 
4345 //-------------------------inline_native_Class_query-------------------
4346 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4347   const Type* return_type = TypeInt::BOOL;
4348   Node* prim_return_value = top();  // what happens if it's a primitive class?
4349   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4350   bool expect_prim = false;     // most of these guys expect to work on refs
4351 
4352   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4353 
4354   Node* mirror = argument(0);
4355   Node* obj    = top();
4356 
4357   switch (id) {
4358   case vmIntrinsics::_isInstance:
4359     // nothing is an instance of a primitive type
4360     prim_return_value = intcon(0);
4361     obj = argument(1);
4362     break;
4363   case vmIntrinsics::_isHidden:
4364     prim_return_value = intcon(0);
4365     break;
4366   case vmIntrinsics::_getSuperclass:
4367     prim_return_value = null();
4368     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4369     break;
4370   case vmIntrinsics::_getClassAccessFlags:
4371     prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
4372     return_type = TypeInt::CHAR;
4373     break;
4374   default:
4375     fatal_unexpected_iid(id);
4376     break;
4377   }
4378 
4379   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4380   if (mirror_con == nullptr)  return false;  // cannot happen?
4381 
4382 #ifndef PRODUCT
4383   if (C->print_intrinsics() || C->print_inlining()) {
4384     ciType* k = mirror_con->java_mirror_type();
4385     if (k) {
4386       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4387       k->print_name();
4388       tty->cr();
4389     }
4390   }
4391 #endif
4392 
4393   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4394   RegionNode* region = new RegionNode(PATH_LIMIT);
4395   record_for_igvn(region);
4396   PhiNode* phi = new PhiNode(region, return_type);
4397 
4398   // The mirror will never be null of Reflection.getClassAccessFlags, however
4399   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4400   // if it is. See bug 4774291.
4401 
4402   // For Reflection.getClassAccessFlags(), the null check occurs in
4403   // the wrong place; see inline_unsafe_access(), above, for a similar
4404   // situation.
4405   mirror = null_check(mirror);
4406   // If mirror or obj is dead, only null-path is taken.
4407   if (stopped())  return true;
4408 
4409   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
4410 
4411   // Now load the mirror's klass metaobject, and null-check it.
4412   // Side-effects region with the control path if the klass is null.
4413   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4414   // If kls is null, we have a primitive mirror.
4415   phi->init_req(_prim_path, prim_return_value);
4416   if (stopped()) { set_result(region, phi); return true; }
4417   bool safe_for_replace = (region->in(_prim_path) == top());
4418 
4419   Node* p;  // handy temp
4420   Node* null_ctl;
4421 
4422   // Now that we have the non-null klass, we can perform the real query.
4423   // For constant classes, the query will constant-fold in LoadNode::Value.
4424   Node* query_value = top();
4425   switch (id) {
4426   case vmIntrinsics::_isInstance:
4427     // nothing is an instance of a primitive type
4428     query_value = gen_instanceof(obj, kls, safe_for_replace);
4429     break;
4430 
4431   case vmIntrinsics::_isHidden:
4432     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4433     if (generate_hidden_class_guard(kls, region) != nullptr)
4434       // A guard was added.  If the guard is taken, it was an hidden class.
4435       phi->add_req(intcon(1));
4436     // If we fall through, it's a plain class.
4437     query_value = intcon(0);
4438     break;
4439 
4440 
4441   case vmIntrinsics::_getSuperclass:
4442     // The rules here are somewhat unfortunate, but we can still do better
4443     // with random logic than with a JNI call.
4444     // Interfaces store null or Object as _super, but must report null.
4445     // Arrays store an intermediate super as _super, but must report Object.
4446     // Other types can report the actual _super.
4447     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4448     if (generate_interface_guard(kls, region) != nullptr)
4449       // A guard was added.  If the guard is taken, it was an interface.
4450       phi->add_req(null());
4451     if (generate_array_guard(kls, region) != nullptr)
4452       // A guard was added.  If the guard is taken, it was an array.
4453       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4454     // If we fall through, it's a plain class.  Get its _super.
4455     p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
4456     kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4457     null_ctl = top();
4458     kls = null_check_oop(kls, &null_ctl);
4459     if (null_ctl != top()) {
4460       // If the guard is taken, Object.superClass is null (both klass and mirror).
4461       region->add_req(null_ctl);
4462       phi   ->add_req(null());
4463     }
4464     if (!stopped()) {
4465       query_value = load_mirror_from_klass(kls);
4466     }
4467     break;
4468 
4469   case vmIntrinsics::_getClassAccessFlags:
4470     p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
4471     query_value = make_load(nullptr, p, TypeInt::CHAR, T_CHAR, MemNode::unordered);
4472     break;
4473 
4474   default:
4475     fatal_unexpected_iid(id);
4476     break;
4477   }
4478 
4479   // Fall-through is the normal case of a query to a real class.
4480   phi->init_req(1, query_value);
4481   region->init_req(1, control());
4482 
4483   C->set_has_split_ifs(true); // Has chance for split-if optimization
4484   set_result(region, phi);
4485   return true;
4486 }
4487 
4488 
4489 //-------------------------inline_Class_cast-------------------
4490 bool LibraryCallKit::inline_Class_cast() {
4491   Node* mirror = argument(0); // Class
4492   Node* obj    = argument(1);
4493   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4494   if (mirror_con == nullptr) {
4495     return false;  // dead path (mirror->is_top()).
4496   }
4497   if (obj == nullptr || obj->is_top()) {
4498     return false;  // dead path
4499   }
4500   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4501 
4502   // First, see if Class.cast() can be folded statically.
4503   // java_mirror_type() returns non-null for compile-time Class constants.
4504   ciType* tm = mirror_con->java_mirror_type();
4505   if (tm != nullptr && tm->is_klass() &&
4506       tp != nullptr) {
4507     if (!tp->is_loaded()) {
4508       // Don't use intrinsic when class is not loaded.
4509       return false;
4510     } else {
4511       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4512       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4513       if (static_res == Compile::SSC_always_true) {
4514         // isInstance() is true - fold the code.
4515         set_result(obj);
4516         return true;
4517       } else if (static_res == Compile::SSC_always_false) {
4518         // Don't use intrinsic, have to throw ClassCastException.
4519         // If the reference is null, the non-intrinsic bytecode will
4520         // be optimized appropriately.
4521         return false;
4522       }
4523     }
4524   }
4525 
4526   // Bailout intrinsic and do normal inlining if exception path is frequent.
4527   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4528     return false;
4529   }
4530 
4531   // Generate dynamic checks.
4532   // Class.cast() is java implementation of _checkcast bytecode.
4533   // Do checkcast (Parse::do_checkcast()) optimizations here.
4534 
4535   mirror = null_check(mirror);
4536   // If mirror is dead, only null-path is taken.
4537   if (stopped()) {
4538     return true;
4539   }
4540 
4541   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4542   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4543   RegionNode* region = new RegionNode(PATH_LIMIT);
4544   record_for_igvn(region);
4545 
4546   // Now load the mirror's klass metaobject, and null-check it.
4547   // If kls is null, we have a primitive mirror and
4548   // nothing is an instance of a primitive type.
4549   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4550 
4551   Node* res = top();
4552   Node* io = i_o();
4553   Node* mem = merged_memory();
4554   if (!stopped()) {
4555 
4556     Node* bad_type_ctrl = top();
4557     // Do checkcast optimizations.
4558     res = gen_checkcast(obj, kls, &bad_type_ctrl);
4559     region->init_req(_bad_type_path, bad_type_ctrl);
4560   }
4561   if (region->in(_prim_path) != top() ||
4562       region->in(_bad_type_path) != top() ||
4563       region->in(_npe_path) != top()) {
4564     // Let Interpreter throw ClassCastException.
4565     PreserveJVMState pjvms(this);
4566     set_control(_gvn.transform(region));
4567     // Set IO and memory because gen_checkcast may override them when buffering inline types
4568     set_i_o(io);
4569     set_all_memory(mem);
4570     uncommon_trap(Deoptimization::Reason_intrinsic,
4571                   Deoptimization::Action_maybe_recompile);
4572   }
4573   if (!stopped()) {
4574     set_result(res);
4575   }
4576   return true;
4577 }
4578 
4579 
4580 //--------------------------inline_native_subtype_check------------------------
4581 // This intrinsic takes the JNI calls out of the heart of
4582 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4583 bool LibraryCallKit::inline_native_subtype_check() {
4584   // Pull both arguments off the stack.
4585   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4586   args[0] = argument(0);
4587   args[1] = argument(1);
4588   Node* klasses[2];             // corresponding Klasses: superk, subk
4589   klasses[0] = klasses[1] = top();
4590 
4591   enum {
4592     // A full decision tree on {superc is prim, subc is prim}:
4593     _prim_0_path = 1,           // {P,N} => false
4594                                 // {P,P} & superc!=subc => false
4595     _prim_same_path,            // {P,P} & superc==subc => true
4596     _prim_1_path,               // {N,P} => false
4597     _ref_subtype_path,          // {N,N} & subtype check wins => true
4598     _both_ref_path,             // {N,N} & subtype check loses => false
4599     PATH_LIMIT
4600   };
4601 
4602   RegionNode* region = new RegionNode(PATH_LIMIT);
4603   RegionNode* prim_region = new RegionNode(2);
4604   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4605   record_for_igvn(region);
4606   record_for_igvn(prim_region);
4607 
4608   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4609   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4610   int class_klass_offset = java_lang_Class::klass_offset();
4611 
4612   // First null-check both mirrors and load each mirror's klass metaobject.
4613   int which_arg;
4614   for (which_arg = 0; which_arg <= 1; which_arg++) {
4615     Node* arg = args[which_arg];
4616     arg = null_check(arg);
4617     if (stopped())  break;
4618     args[which_arg] = arg;
4619 
4620     Node* p = basic_plus_adr(arg, class_klass_offset);
4621     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4622     klasses[which_arg] = _gvn.transform(kls);
4623   }
4624 
4625   // Having loaded both klasses, test each for null.
4626   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4627   for (which_arg = 0; which_arg <= 1; which_arg++) {
4628     Node* kls = klasses[which_arg];
4629     Node* null_ctl = top();
4630     kls = null_check_oop(kls, &null_ctl, never_see_null);
4631     if (which_arg == 0) {
4632       prim_region->init_req(1, null_ctl);
4633     } else {
4634       region->init_req(_prim_1_path, null_ctl);
4635     }
4636     if (stopped())  break;
4637     klasses[which_arg] = kls;
4638   }
4639 
4640   if (!stopped()) {
4641     // now we have two reference types, in klasses[0..1]
4642     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4643     Node* superk = klasses[0];  // the receiver
4644     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4645     region->set_req(_ref_subtype_path, control());
4646   }
4647 
4648   // If both operands are primitive (both klasses null), then
4649   // we must return true when they are identical primitives.
4650   // It is convenient to test this after the first null klass check.
4651   // This path is also used if superc is a value mirror.
4652   set_control(_gvn.transform(prim_region));
4653   if (!stopped()) {
4654     // Since superc is primitive, make a guard for the superc==subc case.
4655     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4656     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4657     generate_fair_guard(bol_eq, region);
4658     if (region->req() == PATH_LIMIT+1) {
4659       // A guard was added.  If the added guard is taken, superc==subc.
4660       region->swap_edges(PATH_LIMIT, _prim_same_path);
4661       region->del_req(PATH_LIMIT);
4662     }
4663     region->set_req(_prim_0_path, control()); // Not equal after all.
4664   }
4665 
4666   // these are the only paths that produce 'true':
4667   phi->set_req(_prim_same_path,   intcon(1));
4668   phi->set_req(_ref_subtype_path, intcon(1));
4669 
4670   // pull together the cases:
4671   assert(region->req() == PATH_LIMIT, "sane region");
4672   for (uint i = 1; i < region->req(); i++) {
4673     Node* ctl = region->in(i);
4674     if (ctl == nullptr || ctl == top()) {
4675       region->set_req(i, top());
4676       phi   ->set_req(i, top());
4677     } else if (phi->in(i) == nullptr) {
4678       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4679     }
4680   }
4681 
4682   set_control(_gvn.transform(region));
4683   set_result(_gvn.transform(phi));
4684   return true;
4685 }
4686 
4687 //---------------------generate_array_guard_common------------------------
4688 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4689 
4690   if (stopped()) {
4691     return nullptr;
4692   }
4693 
4694   // Like generate_guard, adds a new path onto the region.
4695   jint  layout_con = 0;
4696   Node* layout_val = get_layout_helper(kls, layout_con);
4697   if (layout_val == nullptr) {
4698     bool query = 0;
4699     switch(kind) {
4700       case RefArray:       query = Klass::layout_helper_is_refArray(layout_con); break;
4701       case NonRefArray:    query = !Klass::layout_helper_is_refArray(layout_con); break;
4702       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
4703       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
4704       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
4705       default:
4706         ShouldNotReachHere();
4707     }
4708     if (!query) {
4709       return nullptr;                       // never a branch
4710     } else {                             // always a branch
4711       Node* always_branch = control();
4712       if (region != nullptr)
4713         region->add_req(always_branch);
4714       set_control(top());
4715       return always_branch;
4716     }
4717   }
4718   unsigned int value = 0;
4719   BoolTest::mask btest = BoolTest::illegal;
4720   switch(kind) {
4721     case RefArray:
4722     case NonRefArray: {
4723       value = Klass::_lh_array_tag_ref_value;
4724       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4725       btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4726       break;
4727     }
4728     case TypeArray: {
4729       value = Klass::_lh_array_tag_type_value;
4730       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4731       btest = BoolTest::eq;
4732       break;
4733     }
4734     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4735     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4736     default:
4737       ShouldNotReachHere();
4738   }
4739   // Now test the correct condition.
4740   jint nval = (jint)value;
4741   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4742   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4743   Node* ctrl = generate_fair_guard(bol, region);
4744   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4745   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4746     // Keep track of the fact that 'obj' is an array to prevent
4747     // array specific accesses from floating above the guard.
4748     *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4749   }
4750   return ctrl;
4751 }
4752 
4753 // public static native Object[] newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4754 // public static native Object[] newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4755 // public static native Object[] newNullableAtomicArray(Class<?> componentType, int length);
4756 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4757   assert(null_free || atomic, "nullable implies atomic");
4758   Node* componentType = argument(0);
4759   Node* length = argument(1);
4760   Node* init_val = null_free ? argument(2) : nullptr;
4761 
4762   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4763   if (tp != nullptr) {
4764     ciInstanceKlass* ik = tp->instance_klass();
4765     if (ik == C->env()->Class_klass()) {
4766       ciType* t = tp->java_mirror_type();
4767       if (t != nullptr && t->is_inlinetype()) {
4768 
4769         ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4770         assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4771         assert(array_klass->is_elem_atomic() == atomic, "inconsistency");
4772 
4773         // TOOD 8350865 ZGC needs card marks on initializing oop stores
4774         if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4775           return false;
4776         }
4777 
4778         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4779           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces, true);
4780           if (null_free) {
4781             if (init_val->is_InlineType()) {
4782               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4783                 // Zeroing is enough because the init value is the all-zero value
4784                 init_val = nullptr;
4785               } else {
4786                 init_val = init_val->as_InlineType()->buffer(this);
4787               }
4788             }
4789             // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4790           }
4791           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4792           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4793           assert(arytype->is_null_free() == null_free, "inconsistency");
4794           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4795           assert(arytype->is_atomic() == atomic, "inconsistency");
4796           set_result(obj);
4797           return true;
4798         }
4799       }
4800     }
4801   }
4802   return false;
4803 }
4804 
4805 Node* LibraryCallKit::load_default_array_klass(Node* klass_node) {
4806   // TODO 8366668
4807   // - Fred suggested that we could just have the first entry in the refined list point to the array with ArrayKlass::ArrayProperties::DEFAULT property
4808   //   For now, we just load from ObjArrayKlass::_next_refined_array_klass, which would always be the refKlass for non-values, and deopt if it's not
4809   // - Convert this to an IGVN optimization, so it's also folded after parsing
4810   // - The generate_typeArray_guard is not needed by all callers, double-check that it's folded
4811 
4812   const Type* klass_t = _gvn.type(klass_node);
4813   const TypeAryKlassPtr* ary_klass_t = klass_t->isa_aryklassptr();
4814   if (ary_klass_t && ary_klass_t->klass_is_exact()) {
4815     if (ary_klass_t->exact_klass()->is_obj_array_klass()) {
4816       ary_klass_t = ary_klass_t->get_vm_type(false);
4817       return makecon(ary_klass_t);
4818     } else {
4819       return klass_node;
4820     }
4821   }
4822 
4823   // Load next refined array klass if klass is an ObjArrayKlass
4824   RegionNode* refined_region = new RegionNode(2);
4825   Node* refined_phi = new PhiNode(refined_region, klass_t);
4826 
4827   generate_typeArray_guard(klass_node, refined_region);
4828   if (refined_region->req() == 3) {
4829     refined_phi->add_req(klass_node);
4830   }
4831 
4832   Node* adr_refined_klass = basic_plus_adr(klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4833   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4834 
4835   RegionNode* refined_region2 = new RegionNode(3);
4836   Node* refined_phi2 = new PhiNode(refined_region2, klass_t);
4837 
4838   Node* null_ctl = top();
4839   Node* null_free_klass = null_check_common(refined_klass, T_OBJECT, false, &null_ctl);
4840   refined_region2->init_req(1, null_ctl);
4841   refined_phi2->init_req(1, klass_node);
4842 
4843   refined_region2->init_req(2, control());
4844   refined_phi2->init_req(2, null_free_klass);
4845 
4846   set_control(_gvn.transform(refined_region2));
4847   refined_klass = _gvn.transform(refined_phi2);
4848 
4849   Node* adr_properties = basic_plus_adr(refined_klass, in_bytes(ObjArrayKlass::properties_offset()));
4850 
4851   Node* properties = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_properties, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
4852   Node* default_val = makecon(TypeInt::make(ArrayKlass::ArrayProperties::DEFAULT));
4853   Node* chk = _gvn.transform(new CmpINode(properties, default_val));
4854   Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
4855 
4856   { // Deoptimize if not the default property
4857     BuildCutout unless(this, tst, PROB_MAX);
4858     uncommon_trap_exact(Deoptimization::Reason_class_check, Deoptimization::Action_none);
4859   }
4860 
4861   refined_region->init_req(1, control());
4862   refined_phi->init_req(1, refined_klass);
4863 
4864   set_control(_gvn.transform(refined_region));
4865   klass_node = _gvn.transform(refined_phi);
4866 
4867   return klass_node;
4868 }
4869 
4870 //-----------------------inline_native_newArray--------------------------
4871 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
4872 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4873 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4874   Node* mirror;
4875   Node* count_val;
4876   if (uninitialized) {
4877     null_check_receiver();
4878     mirror    = argument(1);
4879     count_val = argument(2);
4880   } else {
4881     mirror    = argument(0);
4882     count_val = argument(1);
4883   }
4884 
4885   mirror = null_check(mirror);
4886   // If mirror or obj is dead, only null-path is taken.
4887   if (stopped())  return true;
4888 
4889   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4890   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4891   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4892   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4893   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4894 
4895   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4896   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
4897                                                   result_reg, _slow_path);
4898   Node* normal_ctl   = control();
4899   Node* no_array_ctl = result_reg->in(_slow_path);
4900 
4901   // Generate code for the slow case.  We make a call to newArray().
4902   set_control(no_array_ctl);
4903   if (!stopped()) {
4904     // Either the input type is void.class, or else the
4905     // array klass has not yet been cached.  Either the
4906     // ensuing call will throw an exception, or else it
4907     // will cache the array klass for next time.
4908     PreserveJVMState pjvms(this);
4909     CallJavaNode* slow_call = nullptr;
4910     if (uninitialized) {
4911       // Generate optimized virtual call (holder class 'Unsafe' is final)
4912       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4913     } else {
4914       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4915     }
4916     Node* slow_result = set_results_for_java_call(slow_call);
4917     // this->control() comes from set_results_for_java_call
4918     result_reg->set_req(_slow_path, control());
4919     result_val->set_req(_slow_path, slow_result);
4920     result_io ->set_req(_slow_path, i_o());
4921     result_mem->set_req(_slow_path, reset_memory());
4922   }
4923 
4924   set_control(normal_ctl);
4925   if (!stopped()) {
4926     // Normal case:  The array type has been cached in the java.lang.Class.
4927     // The following call works fine even if the array type is polymorphic.
4928     // It could be a dynamic mix of int[], boolean[], Object[], etc.
4929 
4930     klass_node = load_default_array_klass(klass_node);
4931 
4932     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
4933     result_reg->init_req(_normal_path, control());
4934     result_val->init_req(_normal_path, obj);
4935     result_io ->init_req(_normal_path, i_o());
4936     result_mem->init_req(_normal_path, reset_memory());
4937 
4938     if (uninitialized) {
4939       // Mark the allocation so that zeroing is skipped
4940       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4941       alloc->maybe_set_complete(&_gvn);
4942     }
4943   }
4944 
4945   // Return the combined state.
4946   set_i_o(        _gvn.transform(result_io)  );
4947   set_all_memory( _gvn.transform(result_mem));
4948 
4949   C->set_has_split_ifs(true); // Has chance for split-if optimization
4950   set_result(result_reg, result_val);
4951   return true;
4952 }
4953 
4954 //----------------------inline_native_getLength--------------------------
4955 // public static native int java.lang.reflect.Array.getLength(Object array);
4956 bool LibraryCallKit::inline_native_getLength() {
4957   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
4958 
4959   Node* array = null_check(argument(0));
4960   // If array is dead, only null-path is taken.
4961   if (stopped())  return true;
4962 
4963   // Deoptimize if it is a non-array.
4964   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
4965 
4966   if (non_array != nullptr) {
4967     PreserveJVMState pjvms(this);
4968     set_control(non_array);
4969     uncommon_trap(Deoptimization::Reason_intrinsic,
4970                   Deoptimization::Action_maybe_recompile);
4971   }
4972 
4973   // If control is dead, only non-array-path is taken.
4974   if (stopped())  return true;
4975 
4976   // The works fine even if the array type is polymorphic.
4977   // It could be a dynamic mix of int[], boolean[], Object[], etc.
4978   Node* result = load_array_length(array);
4979 
4980   C->set_has_split_ifs(true);  // Has chance for split-if optimization
4981   set_result(result);
4982   return true;
4983 }
4984 
4985 //------------------------inline_array_copyOf----------------------------
4986 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
4987 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
4988 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
4989   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
4990 
4991   // Get the arguments.
4992   Node* original          = argument(0);
4993   Node* start             = is_copyOfRange? argument(1): intcon(0);
4994   Node* end               = is_copyOfRange? argument(2): argument(1);
4995   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
4996 
4997   Node* newcopy = nullptr;
4998 
4999   // Set the original stack and the reexecute bit for the interpreter to reexecute
5000   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5001   { PreserveReexecuteState preexecs(this);
5002     jvms()->set_should_reexecute(true);
5003 
5004     array_type_mirror = null_check(array_type_mirror);
5005     original          = null_check(original);
5006 
5007     // Check if a null path was taken unconditionally.
5008     if (stopped())  return true;
5009 
5010     Node* orig_length = load_array_length(original);
5011 
5012     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5013     klass_node = null_check(klass_node);
5014 
5015     RegionNode* bailout = new RegionNode(1);
5016     record_for_igvn(bailout);
5017 
5018     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5019     // Bail out if that is so.
5020     // Inline type array may have object field that would require a
5021     // write barrier. Conservatively, go to slow path.
5022     // TODO 8251971: Optimize for the case when flat src/dst are later found
5023     // to not contain oops (i.e., move this check to the macro expansion phase).
5024     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5025     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5026     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5027     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5028                         // Can src array be flat and contain oops?
5029                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5030                         // Can dest array be flat and contain oops?
5031                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5032     // TODO 8366668 generate_non_refArray_guard also passed for ref arrays??
5033     Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5034 
5035     klass_node = load_default_array_klass(klass_node);
5036 
5037     if (not_objArray != nullptr) {
5038       // Improve the klass node's type from the new optimistic assumption:
5039       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5040       const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0));
5041       Node* cast = new CastPPNode(control(), klass_node, akls);
5042       klass_node = _gvn.transform(cast);
5043     }
5044 
5045     // Bail out if either start or end is negative.
5046     generate_negative_guard(start, bailout, &start);
5047     generate_negative_guard(end,   bailout, &end);
5048 
5049     Node* length = end;
5050     if (_gvn.type(start) != TypeInt::ZERO) {
5051       length = _gvn.transform(new SubINode(end, start));
5052     }
5053 
5054     // Bail out if length is negative (i.e., if start > end).
5055     // Without this the new_array would throw
5056     // NegativeArraySizeException but IllegalArgumentException is what
5057     // should be thrown
5058     generate_negative_guard(length, bailout, &length);
5059 
5060     // Handle inline type arrays
5061     bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5062     if (!stopped()) {
5063       // TODO JDK-8329224
5064       if (!orig_t->is_null_free()) {
5065         // Not statically known to be null free, add a check
5066         generate_fair_guard(null_free_array_test(original), bailout);
5067       }
5068       orig_t = _gvn.type(original)->isa_aryptr();
5069       if (orig_t != nullptr && orig_t->is_flat()) {
5070         // Src is flat, check that dest is flat as well
5071         if (exclude_flat) {
5072           // Dest can't be flat, bail out
5073           bailout->add_req(control());
5074           set_control(top());
5075         } else {
5076           generate_fair_guard(flat_array_test(klass_node, /* flat = */ false), bailout);
5077         }
5078         // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5079       } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5080                  // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5081                  ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5082         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5083         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5084         generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5085         if (orig_t != nullptr) {
5086           orig_t = orig_t->cast_to_not_flat();
5087           original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5088         }
5089       }
5090       if (!can_validate) {
5091         // No validation. The subtype check emitted at macro expansion time will not go to the slow
5092         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5093         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5094         generate_fair_guard(flat_array_test(klass_node), bailout);
5095         generate_fair_guard(null_free_array_test(original), bailout);
5096       }
5097     }
5098 
5099     // Bail out if start is larger than the original length
5100     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5101     generate_negative_guard(orig_tail, bailout, &orig_tail);
5102 
5103     if (bailout->req() > 1) {
5104       PreserveJVMState pjvms(this);
5105       set_control(_gvn.transform(bailout));
5106       uncommon_trap(Deoptimization::Reason_intrinsic,
5107                     Deoptimization::Action_maybe_recompile);
5108     }
5109 
5110     if (!stopped()) {
5111       // How many elements will we copy from the original?
5112       // The answer is MinI(orig_tail, length).
5113       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5114 
5115       // Generate a direct call to the right arraycopy function(s).
5116       // We know the copy is disjoint but we might not know if the
5117       // oop stores need checking.
5118       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
5119       // This will fail a store-check if x contains any non-nulls.
5120 
5121       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5122       // loads/stores but it is legal only if we're sure the
5123       // Arrays.copyOf would succeed. So we need all input arguments
5124       // to the copyOf to be validated, including that the copy to the
5125       // new array won't trigger an ArrayStoreException. That subtype
5126       // check can be optimized if we know something on the type of
5127       // the input array from type speculation.
5128       if (_gvn.type(klass_node)->singleton()) {
5129         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5130         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5131 
5132         int test = C->static_subtype_check(superk, subk);
5133         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5134           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5135           if (t_original->speculative_type() != nullptr) {
5136             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5137           }
5138         }
5139       }
5140 
5141       bool validated = false;
5142       // Reason_class_check rather than Reason_intrinsic because we
5143       // want to intrinsify even if this traps.
5144       if (can_validate) {
5145         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5146 
5147         if (not_subtype_ctrl != top()) {
5148           PreserveJVMState pjvms(this);
5149           set_control(not_subtype_ctrl);
5150           uncommon_trap(Deoptimization::Reason_class_check,
5151                         Deoptimization::Action_make_not_entrant);
5152           assert(stopped(), "Should be stopped");
5153         }
5154         validated = true;
5155       }
5156 
5157       if (!stopped()) {
5158         newcopy = new_array(klass_node, length, 0);  // no arguments to push
5159 
5160         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5161                                                 load_object_klass(original), klass_node);
5162         if (!is_copyOfRange) {
5163           ac->set_copyof(validated);
5164         } else {
5165           ac->set_copyofrange(validated);
5166         }
5167         Node* n = _gvn.transform(ac);
5168         if (n == ac) {
5169           ac->connect_outputs(this);
5170         } else {
5171           assert(validated, "shouldn't transform if all arguments not validated");
5172           set_all_memory(n);
5173         }
5174       }
5175     }
5176   } // original reexecute is set back here
5177 
5178   C->set_has_split_ifs(true); // Has chance for split-if optimization
5179   if (!stopped()) {
5180     set_result(newcopy);
5181   }
5182   return true;
5183 }
5184 
5185 
5186 //----------------------generate_virtual_guard---------------------------
5187 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
5188 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5189                                              RegionNode* slow_region) {
5190   ciMethod* method = callee();
5191   int vtable_index = method->vtable_index();
5192   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5193          "bad index %d", vtable_index);
5194   // Get the Method* out of the appropriate vtable entry.
5195   int entry_offset  = in_bytes(Klass::vtable_start_offset()) +
5196                      vtable_index*vtableEntry::size_in_bytes() +
5197                      in_bytes(vtableEntry::method_offset());
5198   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
5199   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5200 
5201   // Compare the target method with the expected method (e.g., Object.hashCode).
5202   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5203 
5204   Node* native_call = makecon(native_call_addr);
5205   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
5206   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5207 
5208   return generate_slow_guard(test_native, slow_region);
5209 }
5210 
5211 //-----------------------generate_method_call----------------------------
5212 // Use generate_method_call to make a slow-call to the real
5213 // method if the fast path fails.  An alternative would be to
5214 // use a stub like OptoRuntime::slow_arraycopy_Java.
5215 // This only works for expanding the current library call,
5216 // not another intrinsic.  (E.g., don't use this for making an
5217 // arraycopy call inside of the copyOf intrinsic.)
5218 CallJavaNode*
5219 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5220   // When compiling the intrinsic method itself, do not use this technique.
5221   guarantee(callee() != C->method(), "cannot make slow-call to self");
5222 
5223   ciMethod* method = callee();
5224   // ensure the JVMS we have will be correct for this call
5225   guarantee(method_id == method->intrinsic_id(), "must match");
5226 
5227   const TypeFunc* tf = TypeFunc::make(method);
5228   if (res_not_null) {
5229     assert(tf->return_type() == T_OBJECT, "");
5230     const TypeTuple* range = tf->range_cc();
5231     const Type** fields = TypeTuple::fields(range->cnt());
5232     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5233     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5234     tf = TypeFunc::make(tf->domain_cc(), new_range);
5235   }
5236   CallJavaNode* slow_call;
5237   if (is_static) {
5238     assert(!is_virtual, "");
5239     slow_call = new CallStaticJavaNode(C, tf,
5240                            SharedRuntime::get_resolve_static_call_stub(), method);
5241   } else if (is_virtual) {
5242     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5243     int vtable_index = Method::invalid_vtable_index;
5244     if (UseInlineCaches) {
5245       // Suppress the vtable call
5246     } else {
5247       // hashCode and clone are not a miranda methods,
5248       // so the vtable index is fixed.
5249       // No need to use the linkResolver to get it.
5250        vtable_index = method->vtable_index();
5251        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5252               "bad index %d", vtable_index);
5253     }
5254     slow_call = new CallDynamicJavaNode(tf,
5255                           SharedRuntime::get_resolve_virtual_call_stub(),
5256                           method, vtable_index);
5257   } else {  // neither virtual nor static:  opt_virtual
5258     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5259     slow_call = new CallStaticJavaNode(C, tf,
5260                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5261     slow_call->set_optimized_virtual(true);
5262   }
5263   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5264     // To be able to issue a direct call (optimized virtual or virtual)
5265     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5266     // about the method being invoked should be attached to the call site to
5267     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5268     slow_call->set_override_symbolic_info(true);
5269   }
5270   set_arguments_for_java_call(slow_call);
5271   set_edges_for_java_call(slow_call);
5272   return slow_call;
5273 }
5274 
5275 
5276 /**
5277  * Build special case code for calls to hashCode on an object. This call may
5278  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5279  * slightly different code.
5280  */
5281 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5282   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5283   assert(!(is_virtual && is_static), "either virtual, special, or static");
5284 
5285   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5286 
5287   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5288   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5289   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5290   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5291   Node* obj = argument(0);
5292 
5293   // Don't intrinsify hashcode on inline types for now.
5294   // The "is locked" runtime check below also serves as inline type check and goes to the slow path.
5295   if (gvn().type(obj)->is_inlinetypeptr()) {
5296     return false;
5297   }
5298 
5299   if (!is_static) {
5300     // Check for hashing null object
5301     obj = null_check_receiver();
5302     if (stopped())  return true;        // unconditionally null
5303     result_reg->init_req(_null_path, top());
5304     result_val->init_req(_null_path, top());
5305   } else {
5306     // Do a null check, and return zero if null.
5307     // System.identityHashCode(null) == 0
5308     Node* null_ctl = top();
5309     obj = null_check_oop(obj, &null_ctl);
5310     result_reg->init_req(_null_path, null_ctl);
5311     result_val->init_req(_null_path, _gvn.intcon(0));
5312   }
5313 
5314   // Unconditionally null?  Then return right away.
5315   if (stopped()) {
5316     set_control( result_reg->in(_null_path));
5317     if (!stopped())
5318       set_result(result_val->in(_null_path));
5319     return true;
5320   }
5321 
5322   // We only go to the fast case code if we pass a number of guards.  The
5323   // paths which do not pass are accumulated in the slow_region.
5324   RegionNode* slow_region = new RegionNode(1);
5325   record_for_igvn(slow_region);
5326 
5327   // If this is a virtual call, we generate a funny guard.  We pull out
5328   // the vtable entry corresponding to hashCode() from the target object.
5329   // If the target method which we are calling happens to be the native
5330   // Object hashCode() method, we pass the guard.  We do not need this
5331   // guard for non-virtual calls -- the caller is known to be the native
5332   // Object hashCode().
5333   if (is_virtual) {
5334     // After null check, get the object's klass.
5335     Node* obj_klass = load_object_klass(obj);
5336     generate_virtual_guard(obj_klass, slow_region);
5337   }
5338 
5339   // Get the header out of the object, use LoadMarkNode when available
5340   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5341   // The control of the load must be null. Otherwise, the load can move before
5342   // the null check after castPP removal.
5343   Node* no_ctrl = nullptr;
5344   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5345 
5346   if (!UseObjectMonitorTable) {
5347     // Test the header to see if it is safe to read w.r.t. locking.
5348   // This also serves as guard against inline types
5349     Node *lock_mask      = _gvn.MakeConX(markWord::inline_type_mask_in_place);
5350     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5351     if (LockingMode == LM_LIGHTWEIGHT) {
5352       Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5353       Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5354       Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5355 
5356       generate_slow_guard(test_monitor, slow_region);
5357     } else {
5358       Node *unlocked_val      = _gvn.MakeConX(markWord::unlocked_value);
5359       Node *chk_unlocked      = _gvn.transform(new CmpXNode(lmasked_header, unlocked_val));
5360       Node *test_not_unlocked = _gvn.transform(new BoolNode(chk_unlocked, BoolTest::ne));
5361 
5362       generate_slow_guard(test_not_unlocked, slow_region);
5363     }
5364   }
5365 
5366   // Get the hash value and check to see that it has been properly assigned.
5367   // We depend on hash_mask being at most 32 bits and avoid the use of
5368   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5369   // vm: see markWord.hpp.
5370   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5371   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5372   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5373   // This hack lets the hash bits live anywhere in the mark object now, as long
5374   // as the shift drops the relevant bits into the low 32 bits.  Note that
5375   // Java spec says that HashCode is an int so there's no point in capturing
5376   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5377   hshifted_header      = ConvX2I(hshifted_header);
5378   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5379 
5380   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
5381   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5382   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5383 
5384   generate_slow_guard(test_assigned, slow_region);
5385 
5386   Node* init_mem = reset_memory();
5387   // fill in the rest of the null path:
5388   result_io ->init_req(_null_path, i_o());
5389   result_mem->init_req(_null_path, init_mem);
5390 
5391   result_val->init_req(_fast_path, hash_val);
5392   result_reg->init_req(_fast_path, control());
5393   result_io ->init_req(_fast_path, i_o());
5394   result_mem->init_req(_fast_path, init_mem);
5395 
5396   // Generate code for the slow case.  We make a call to hashCode().
5397   set_control(_gvn.transform(slow_region));
5398   if (!stopped()) {
5399     // No need for PreserveJVMState, because we're using up the present state.
5400     set_all_memory(init_mem);
5401     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5402     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5403     Node* slow_result = set_results_for_java_call(slow_call);
5404     // this->control() comes from set_results_for_java_call
5405     result_reg->init_req(_slow_path, control());
5406     result_val->init_req(_slow_path, slow_result);
5407     result_io  ->set_req(_slow_path, i_o());
5408     result_mem ->set_req(_slow_path, reset_memory());
5409   }
5410 
5411   // Return the combined state.
5412   set_i_o(        _gvn.transform(result_io)  );
5413   set_all_memory( _gvn.transform(result_mem));
5414 
5415   set_result(result_reg, result_val);
5416   return true;
5417 }
5418 
5419 //---------------------------inline_native_getClass----------------------------
5420 // public final native Class<?> java.lang.Object.getClass();
5421 //
5422 // Build special case code for calls to getClass on an object.
5423 bool LibraryCallKit::inline_native_getClass() {
5424   Node* obj = argument(0);
5425   if (obj->is_InlineType()) {
5426     const Type* t = _gvn.type(obj);
5427     if (t->maybe_null()) {
5428       null_check(obj);
5429     }
5430     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5431     return true;
5432   }
5433   obj = null_check_receiver();
5434   if (stopped())  return true;
5435   set_result(load_mirror_from_klass(load_object_klass(obj)));
5436   return true;
5437 }
5438 
5439 //-----------------inline_native_Reflection_getCallerClass---------------------
5440 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5441 //
5442 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5443 //
5444 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5445 // in that it must skip particular security frames and checks for
5446 // caller sensitive methods.
5447 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5448 #ifndef PRODUCT
5449   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5450     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5451   }
5452 #endif
5453 
5454   if (!jvms()->has_method()) {
5455 #ifndef PRODUCT
5456     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5457       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
5458     }
5459 #endif
5460     return false;
5461   }
5462 
5463   // Walk back up the JVM state to find the caller at the required
5464   // depth.
5465   JVMState* caller_jvms = jvms();
5466 
5467   // Cf. JVM_GetCallerClass
5468   // NOTE: Start the loop at depth 1 because the current JVM state does
5469   // not include the Reflection.getCallerClass() frame.
5470   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5471     ciMethod* m = caller_jvms->method();
5472     switch (n) {
5473     case 0:
5474       fatal("current JVM state does not include the Reflection.getCallerClass frame");
5475       break;
5476     case 1:
5477       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5478       if (!m->caller_sensitive()) {
5479 #ifndef PRODUCT
5480         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5481           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
5482         }
5483 #endif
5484         return false;  // bail-out; let JVM_GetCallerClass do the work
5485       }
5486       break;
5487     default:
5488       if (!m->is_ignored_by_security_stack_walk()) {
5489         // We have reached the desired frame; return the holder class.
5490         // Acquire method holder as java.lang.Class and push as constant.
5491         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5492         ciInstance* caller_mirror = caller_klass->java_mirror();
5493         set_result(makecon(TypeInstPtr::make(caller_mirror)));
5494 
5495 #ifndef PRODUCT
5496         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5497           tty->print_cr("  Succeeded: caller = %d) %s.%s, JVMS depth = %d", n, caller_klass->name()->as_utf8(), caller_jvms->method()->name()->as_utf8(), jvms()->depth());
5498           tty->print_cr("  JVM state at this point:");
5499           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5500             ciMethod* m = jvms()->of_depth(i)->method();
5501             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5502           }
5503         }
5504 #endif
5505         return true;
5506       }
5507       break;
5508     }
5509   }
5510 
5511 #ifndef PRODUCT
5512   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5513     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5514     tty->print_cr("  JVM state at this point:");
5515     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5516       ciMethod* m = jvms()->of_depth(i)->method();
5517       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5518     }
5519   }
5520 #endif
5521 
5522   return false;  // bail-out; let JVM_GetCallerClass do the work
5523 }
5524 
5525 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5526   Node* arg = argument(0);
5527   Node* result = nullptr;
5528 
5529   switch (id) {
5530   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
5531   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
5532   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
5533   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
5534   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
5535   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
5536 
5537   case vmIntrinsics::_doubleToLongBits: {
5538     // two paths (plus control) merge in a wood
5539     RegionNode *r = new RegionNode(3);
5540     Node *phi = new PhiNode(r, TypeLong::LONG);
5541 
5542     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5543     // Build the boolean node
5544     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5545 
5546     // Branch either way.
5547     // NaN case is less traveled, which makes all the difference.
5548     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5549     Node *opt_isnan = _gvn.transform(ifisnan);
5550     assert( opt_isnan->is_If(), "Expect an IfNode");
5551     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5552     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5553 
5554     set_control(iftrue);
5555 
5556     static const jlong nan_bits = CONST64(0x7ff8000000000000);
5557     Node *slow_result = longcon(nan_bits); // return NaN
5558     phi->init_req(1, _gvn.transform( slow_result ));
5559     r->init_req(1, iftrue);
5560 
5561     // Else fall through
5562     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5563     set_control(iffalse);
5564 
5565     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5566     r->init_req(2, iffalse);
5567 
5568     // Post merge
5569     set_control(_gvn.transform(r));
5570     record_for_igvn(r);
5571 
5572     C->set_has_split_ifs(true); // Has chance for split-if optimization
5573     result = phi;
5574     assert(result->bottom_type()->isa_long(), "must be");
5575     break;
5576   }
5577 
5578   case vmIntrinsics::_floatToIntBits: {
5579     // two paths (plus control) merge in a wood
5580     RegionNode *r = new RegionNode(3);
5581     Node *phi = new PhiNode(r, TypeInt::INT);
5582 
5583     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5584     // Build the boolean node
5585     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5586 
5587     // Branch either way.
5588     // NaN case is less traveled, which makes all the difference.
5589     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5590     Node *opt_isnan = _gvn.transform(ifisnan);
5591     assert( opt_isnan->is_If(), "Expect an IfNode");
5592     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5593     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5594 
5595     set_control(iftrue);
5596 
5597     static const jint nan_bits = 0x7fc00000;
5598     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5599     phi->init_req(1, _gvn.transform( slow_result ));
5600     r->init_req(1, iftrue);
5601 
5602     // Else fall through
5603     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5604     set_control(iffalse);
5605 
5606     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5607     r->init_req(2, iffalse);
5608 
5609     // Post merge
5610     set_control(_gvn.transform(r));
5611     record_for_igvn(r);
5612 
5613     C->set_has_split_ifs(true); // Has chance for split-if optimization
5614     result = phi;
5615     assert(result->bottom_type()->isa_int(), "must be");
5616     break;
5617   }
5618 
5619   default:
5620     fatal_unexpected_iid(id);
5621     break;
5622   }
5623   set_result(_gvn.transform(result));
5624   return true;
5625 }
5626 
5627 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5628   Node* arg = argument(0);
5629   Node* result = nullptr;
5630 
5631   switch (id) {
5632   case vmIntrinsics::_floatIsInfinite:
5633     result = new IsInfiniteFNode(arg);
5634     break;
5635   case vmIntrinsics::_floatIsFinite:
5636     result = new IsFiniteFNode(arg);
5637     break;
5638   case vmIntrinsics::_doubleIsInfinite:
5639     result = new IsInfiniteDNode(arg);
5640     break;
5641   case vmIntrinsics::_doubleIsFinite:
5642     result = new IsFiniteDNode(arg);
5643     break;
5644   default:
5645     fatal_unexpected_iid(id);
5646     break;
5647   }
5648   set_result(_gvn.transform(result));
5649   return true;
5650 }
5651 
5652 //----------------------inline_unsafe_copyMemory-------------------------
5653 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5654 
5655 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5656   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5657   const Type*       base_t = gvn.type(base);
5658 
5659   bool in_native = (base_t == TypePtr::NULL_PTR);
5660   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
5661   bool is_mixed  = !in_heap && !in_native;
5662 
5663   if (is_mixed) {
5664     return true; // mixed accesses can touch both on-heap and off-heap memory
5665   }
5666   if (in_heap) {
5667     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5668     if (!is_prim_array) {
5669       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5670       // there's not enough type information available to determine proper memory slice for it.
5671       return true;
5672     }
5673   }
5674   return false;
5675 }
5676 
5677 bool LibraryCallKit::inline_unsafe_copyMemory() {
5678   if (callee()->is_static())  return false;  // caller must have the capability!
5679   null_check_receiver();  // null-check receiver
5680   if (stopped())  return true;
5681 
5682   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5683 
5684   Node* src_base =         argument(1);  // type: oop
5685   Node* src_off  = ConvL2X(argument(2)); // type: long
5686   Node* dst_base =         argument(4);  // type: oop
5687   Node* dst_off  = ConvL2X(argument(5)); // type: long
5688   Node* size     = ConvL2X(argument(7)); // type: long
5689 
5690   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5691          "fieldOffset must be byte-scaled");
5692 
5693   Node* src_addr = make_unsafe_address(src_base, src_off);
5694   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5695 
5696   Node* thread = _gvn.transform(new ThreadLocalNode());
5697   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5698   BasicType doing_unsafe_access_bt = T_BYTE;
5699   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5700 
5701   // update volatile field
5702   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5703 
5704   int flags = RC_LEAF | RC_NO_FP;
5705 
5706   const TypePtr* dst_type = TypePtr::BOTTOM;
5707 
5708   // Adjust memory effects of the runtime call based on input values.
5709   if (!has_wide_mem(_gvn, src_addr, src_base) &&
5710       !has_wide_mem(_gvn, dst_addr, dst_base)) {
5711     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5712 
5713     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5714     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5715       flags |= RC_NARROW_MEM; // narrow in memory
5716     }
5717   }
5718 
5719   // Call it.  Note that the length argument is not scaled.
5720   make_runtime_call(flags,
5721                     OptoRuntime::fast_arraycopy_Type(),
5722                     StubRoutines::unsafe_arraycopy(),
5723                     "unsafe_arraycopy",
5724                     dst_type,
5725                     src_addr, dst_addr, size XTOP);
5726 
5727   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5728 
5729   return true;
5730 }
5731 
5732 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5733 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5734 bool LibraryCallKit::inline_unsafe_setMemory() {
5735   if (callee()->is_static())  return false;  // caller must have the capability!
5736   null_check_receiver();  // null-check receiver
5737   if (stopped())  return true;
5738 
5739   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5740 
5741   Node* dst_base =         argument(1);  // type: oop
5742   Node* dst_off  = ConvL2X(argument(2)); // type: long
5743   Node* size     = ConvL2X(argument(4)); // type: long
5744   Node* byte     =         argument(6);  // type: byte
5745 
5746   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5747          "fieldOffset must be byte-scaled");
5748 
5749   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5750 
5751   Node* thread = _gvn.transform(new ThreadLocalNode());
5752   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5753   BasicType doing_unsafe_access_bt = T_BYTE;
5754   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5755 
5756   // update volatile field
5757   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5758 
5759   int flags = RC_LEAF | RC_NO_FP;
5760 
5761   const TypePtr* dst_type = TypePtr::BOTTOM;
5762 
5763   // Adjust memory effects of the runtime call based on input values.
5764   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5765     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5766 
5767     flags |= RC_NARROW_MEM; // narrow in memory
5768   }
5769 
5770   // Call it.  Note that the length argument is not scaled.
5771   make_runtime_call(flags,
5772                     OptoRuntime::unsafe_setmemory_Type(),
5773                     StubRoutines::unsafe_setmemory(),
5774                     "unsafe_setmemory",
5775                     dst_type,
5776                     dst_addr, size XTOP, byte);
5777 
5778   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5779 
5780   return true;
5781 }
5782 
5783 #undef XTOP
5784 
5785 //------------------------clone_coping-----------------------------------
5786 // Helper function for inline_native_clone.
5787 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5788   assert(obj_size != nullptr, "");
5789   Node* raw_obj = alloc_obj->in(1);
5790   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5791 
5792   AllocateNode* alloc = nullptr;
5793   if (ReduceBulkZeroing &&
5794       // If we are implementing an array clone without knowing its source type
5795       // (can happen when compiling the array-guarded branch of a reflective
5796       // Object.clone() invocation), initialize the array within the allocation.
5797       // This is needed because some GCs (e.g. ZGC) might fall back in this case
5798       // to a runtime clone call that assumes fully initialized source arrays.
5799       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5800     // We will be completely responsible for initializing this object -
5801     // mark Initialize node as complete.
5802     alloc = AllocateNode::Ideal_allocation(alloc_obj);
5803     // The object was just allocated - there should be no any stores!
5804     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5805     // Mark as complete_with_arraycopy so that on AllocateNode
5806     // expansion, we know this AllocateNode is initialized by an array
5807     // copy and a StoreStore barrier exists after the array copy.
5808     alloc->initialization()->set_complete_with_arraycopy();
5809   }
5810 
5811   Node* size = _gvn.transform(obj_size);
5812   access_clone(obj, alloc_obj, size, is_array);
5813 
5814   // Do not let reads from the cloned object float above the arraycopy.
5815   if (alloc != nullptr) {
5816     // Do not let stores that initialize this object be reordered with
5817     // a subsequent store that would make this object accessible by
5818     // other threads.
5819     // Record what AllocateNode this StoreStore protects so that
5820     // escape analysis can go from the MemBarStoreStoreNode to the
5821     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5822     // based on the escape status of the AllocateNode.
5823     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5824   } else {
5825     insert_mem_bar(Op_MemBarCPUOrder);
5826   }
5827 }
5828 
5829 //------------------------inline_native_clone----------------------------
5830 // protected native Object java.lang.Object.clone();
5831 //
5832 // Here are the simple edge cases:
5833 //  null receiver => normal trap
5834 //  virtual and clone was overridden => slow path to out-of-line clone
5835 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5836 //
5837 // The general case has two steps, allocation and copying.
5838 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5839 //
5840 // Copying also has two cases, oop arrays and everything else.
5841 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5842 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5843 //
5844 // These steps fold up nicely if and when the cloned object's klass
5845 // can be sharply typed as an object array, a type array, or an instance.
5846 //
5847 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5848   PhiNode* result_val;
5849 
5850   // Set the reexecute bit for the interpreter to reexecute
5851   // the bytecode that invokes Object.clone if deoptimization happens.
5852   { PreserveReexecuteState preexecs(this);
5853     jvms()->set_should_reexecute(true);
5854 
5855     Node* obj = argument(0);
5856     obj = null_check_receiver();
5857     if (stopped())  return true;
5858 
5859     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5860     if (obj_type->is_inlinetypeptr()) {
5861       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5862       // no identity.
5863       set_result(obj);
5864       return true;
5865     }
5866 
5867     // If we are going to clone an instance, we need its exact type to
5868     // know the number and types of fields to convert the clone to
5869     // loads/stores. Maybe a speculative type can help us.
5870     if (!obj_type->klass_is_exact() &&
5871         obj_type->speculative_type() != nullptr &&
5872         obj_type->speculative_type()->is_instance_klass() &&
5873         !obj_type->speculative_type()->is_inlinetype()) {
5874       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5875       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5876           !spec_ik->has_injected_fields()) {
5877         if (!obj_type->isa_instptr() ||
5878             obj_type->is_instptr()->instance_klass()->has_subklass()) {
5879           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5880         }
5881       }
5882     }
5883 
5884     // Conservatively insert a memory barrier on all memory slices.
5885     // Do not let writes into the original float below the clone.
5886     insert_mem_bar(Op_MemBarCPUOrder);
5887 
5888     // paths into result_reg:
5889     enum {
5890       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
5891       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
5892       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
5893       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
5894       PATH_LIMIT
5895     };
5896     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5897     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5898     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
5899     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5900     record_for_igvn(result_reg);
5901 
5902     Node* obj_klass = load_object_klass(obj);
5903     // We only go to the fast case code if we pass a number of guards.
5904     // The paths which do not pass are accumulated in the slow_region.
5905     RegionNode* slow_region = new RegionNode(1);
5906     record_for_igvn(slow_region);
5907 
5908     Node* array_obj = obj;
5909     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5910     if (array_ctl != nullptr) {
5911       // It's an array.
5912       PreserveJVMState pjvms(this);
5913       set_control(array_ctl);
5914 
5915       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5916       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
5917       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
5918           obj_type->can_be_inline_array() &&
5919           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
5920         // Flat inline type array may have object field that would require a
5921         // write barrier. Conservatively, go to slow path.
5922         generate_fair_guard(flat_array_test(obj_klass), slow_region);
5923       }
5924 
5925       if (!stopped()) {
5926         Node* obj_length = load_array_length(array_obj);
5927         Node* array_size = nullptr; // Size of the array without object alignment padding.
5928         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5929 
5930         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5931         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5932           // If it is an oop array, it requires very special treatment,
5933           // because gc barriers are required when accessing the array.
5934           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
5935           if (is_obja != nullptr) {
5936             PreserveJVMState pjvms2(this);
5937             set_control(is_obja);
5938             // Generate a direct call to the right arraycopy function(s).
5939             // Clones are always tightly coupled.
5940             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5941             ac->set_clone_oop_array();
5942             Node* n = _gvn.transform(ac);
5943             assert(n == ac, "cannot disappear");
5944             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5945 
5946             result_reg->init_req(_objArray_path, control());
5947             result_val->init_req(_objArray_path, alloc_obj);
5948             result_i_o ->set_req(_objArray_path, i_o());
5949             result_mem ->set_req(_objArray_path, reset_memory());
5950           }
5951         }
5952         // Otherwise, there are no barriers to worry about.
5953         // (We can dispense with card marks if we know the allocation
5954         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
5955         //  causes the non-eden paths to take compensating steps to
5956         //  simulate a fresh allocation, so that no further
5957         //  card marks are required in compiled code to initialize
5958         //  the object.)
5959 
5960         if (!stopped()) {
5961           copy_to_clone(obj, alloc_obj, array_size, true);
5962 
5963           // Present the results of the copy.
5964           result_reg->init_req(_array_path, control());
5965           result_val->init_req(_array_path, alloc_obj);
5966           result_i_o ->set_req(_array_path, i_o());
5967           result_mem ->set_req(_array_path, reset_memory());
5968         }
5969       }
5970     }
5971 
5972     if (!stopped()) {
5973       // It's an instance (we did array above).  Make the slow-path tests.
5974       // If this is a virtual call, we generate a funny guard.  We grab
5975       // the vtable entry corresponding to clone() from the target object.
5976       // If the target method which we are calling happens to be the
5977       // Object clone() method, we pass the guard.  We do not need this
5978       // guard for non-virtual calls; the caller is known to be the native
5979       // Object clone().
5980       if (is_virtual) {
5981         generate_virtual_guard(obj_klass, slow_region);
5982       }
5983 
5984       // The object must be easily cloneable and must not have a finalizer.
5985       // Both of these conditions may be checked in a single test.
5986       // We could optimize the test further, but we don't care.
5987       generate_misc_flags_guard(obj_klass,
5988                                 // Test both conditions:
5989                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5990                                 // Must be cloneable but not finalizer:
5991                                 KlassFlags::_misc_is_cloneable_fast,
5992                                 slow_region);
5993     }
5994 
5995     if (!stopped()) {
5996       // It's an instance, and it passed the slow-path tests.
5997       PreserveJVMState pjvms(this);
5998       Node* obj_size = nullptr; // Total object size, including object alignment padding.
5999       // Need to deoptimize on exception from allocation since Object.clone intrinsic
6000       // is reexecuted if deoptimization occurs and there could be problems when merging
6001       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
6002       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
6003 
6004       copy_to_clone(obj, alloc_obj, obj_size, false);
6005 
6006       // Present the results of the slow call.
6007       result_reg->init_req(_instance_path, control());
6008       result_val->init_req(_instance_path, alloc_obj);
6009       result_i_o ->set_req(_instance_path, i_o());
6010       result_mem ->set_req(_instance_path, reset_memory());
6011     }
6012 
6013     // Generate code for the slow case.  We make a call to clone().
6014     set_control(_gvn.transform(slow_region));
6015     if (!stopped()) {
6016       PreserveJVMState pjvms(this);
6017       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
6018       // We need to deoptimize on exception (see comment above)
6019       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
6020       // this->control() comes from set_results_for_java_call
6021       result_reg->init_req(_slow_path, control());
6022       result_val->init_req(_slow_path, slow_result);
6023       result_i_o ->set_req(_slow_path, i_o());
6024       result_mem ->set_req(_slow_path, reset_memory());
6025     }
6026 
6027     // Return the combined state.
6028     set_control(    _gvn.transform(result_reg));
6029     set_i_o(        _gvn.transform(result_i_o));
6030     set_all_memory( _gvn.transform(result_mem));
6031   } // original reexecute is set back here
6032 
6033   set_result(_gvn.transform(result_val));
6034   return true;
6035 }
6036 
6037 // If we have a tightly coupled allocation, the arraycopy may take care
6038 // of the array initialization. If one of the guards we insert between
6039 // the allocation and the arraycopy causes a deoptimization, an
6040 // uninitialized array will escape the compiled method. To prevent that
6041 // we set the JVM state for uncommon traps between the allocation and
6042 // the arraycopy to the state before the allocation so, in case of
6043 // deoptimization, we'll reexecute the allocation and the
6044 // initialization.
6045 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6046   if (alloc != nullptr) {
6047     ciMethod* trap_method = alloc->jvms()->method();
6048     int trap_bci = alloc->jvms()->bci();
6049 
6050     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6051         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6052       // Make sure there's no store between the allocation and the
6053       // arraycopy otherwise visible side effects could be rexecuted
6054       // in case of deoptimization and cause incorrect execution.
6055       bool no_interfering_store = true;
6056       Node* mem = alloc->in(TypeFunc::Memory);
6057       if (mem->is_MergeMem()) {
6058         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6059           Node* n = mms.memory();
6060           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6061             assert(n->is_Store(), "what else?");
6062             no_interfering_store = false;
6063             break;
6064           }
6065         }
6066       } else {
6067         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6068           Node* n = mms.memory();
6069           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6070             assert(n->is_Store(), "what else?");
6071             no_interfering_store = false;
6072             break;
6073           }
6074         }
6075       }
6076 
6077       if (no_interfering_store) {
6078         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6079 
6080         JVMState* saved_jvms = jvms();
6081         saved_reexecute_sp = _reexecute_sp;
6082 
6083         set_jvms(sfpt->jvms());
6084         _reexecute_sp = jvms()->sp();
6085 
6086         return saved_jvms;
6087       }
6088     }
6089   }
6090   return nullptr;
6091 }
6092 
6093 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6094 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6095 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6096   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6097   uint size = alloc->req();
6098   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6099   old_jvms->set_map(sfpt);
6100   for (uint i = 0; i < size; i++) {
6101     sfpt->init_req(i, alloc->in(i));
6102   }
6103   int adjustment = 1;
6104   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6105   if (ary_klass_ptr->is_null_free()) {
6106     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6107     // also requires the componentType and initVal on stack for re-execution.
6108     // Re-create and push the componentType.
6109     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6110     ciInstance* instance = klass->component_mirror_instance();
6111     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6112     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6113     adjustment++;
6114   }
6115   // re-push array length for deoptimization
6116   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6117   if (ary_klass_ptr->is_null_free()) {
6118     // Re-create and push the initVal.
6119     Node* init_val = alloc->in(AllocateNode::InitValue);
6120     if (init_val == nullptr) {
6121       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6122     } else if (UseCompressedOops) {
6123       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6124     }
6125     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6126     adjustment++;
6127   }
6128   old_jvms->set_sp(old_jvms->sp() + adjustment);
6129   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6130   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6131   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6132   old_jvms->set_should_reexecute(true);
6133 
6134   sfpt->set_i_o(map()->i_o());
6135   sfpt->set_memory(map()->memory());
6136   sfpt->set_control(map()->control());
6137   return sfpt;
6138 }
6139 
6140 // In case of a deoptimization, we restart execution at the
6141 // allocation, allocating a new array. We would leave an uninitialized
6142 // array in the heap that GCs wouldn't expect. Move the allocation
6143 // after the traps so we don't allocate the array if we
6144 // deoptimize. This is possible because tightly_coupled_allocation()
6145 // guarantees there's no observer of the allocated array at this point
6146 // and the control flow is simple enough.
6147 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6148                                                     int saved_reexecute_sp, uint new_idx) {
6149   if (saved_jvms_before_guards != nullptr && !stopped()) {
6150     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6151 
6152     assert(alloc != nullptr, "only with a tightly coupled allocation");
6153     // restore JVM state to the state at the arraycopy
6154     saved_jvms_before_guards->map()->set_control(map()->control());
6155     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6156     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6157     // If we've improved the types of some nodes (null check) while
6158     // emitting the guards, propagate them to the current state
6159     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6160     set_jvms(saved_jvms_before_guards);
6161     _reexecute_sp = saved_reexecute_sp;
6162 
6163     // Remove the allocation from above the guards
6164     CallProjections* callprojs = alloc->extract_projections(true);
6165     InitializeNode* init = alloc->initialization();
6166     Node* alloc_mem = alloc->in(TypeFunc::Memory);
6167     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6168     C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
6169 
6170     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6171     // the allocation (i.e. is only valid if the allocation succeeds):
6172     // 1) replace CastIINode with AllocateArrayNode's length here
6173     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6174     //
6175     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6176     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6177     Node* init_control = init->proj_out(TypeFunc::Control);
6178     Node* alloc_length = alloc->Ideal_length();
6179 #ifdef ASSERT
6180     Node* prev_cast = nullptr;
6181 #endif
6182     for (uint i = 0; i < init_control->outcnt(); i++) {
6183       Node* init_out = init_control->raw_out(i);
6184       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6185 #ifdef ASSERT
6186         if (prev_cast == nullptr) {
6187           prev_cast = init_out;
6188         } else {
6189           if (prev_cast->cmp(*init_out) == false) {
6190             prev_cast->dump();
6191             init_out->dump();
6192             assert(false, "not equal CastIINode");
6193           }
6194         }
6195 #endif
6196         C->gvn_replace_by(init_out, alloc_length);
6197       }
6198     }
6199     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6200 
6201     // move the allocation here (after the guards)
6202     _gvn.hash_delete(alloc);
6203     alloc->set_req(TypeFunc::Control, control());
6204     alloc->set_req(TypeFunc::I_O, i_o());
6205     Node *mem = reset_memory();
6206     set_all_memory(mem);
6207     alloc->set_req(TypeFunc::Memory, mem);
6208     set_control(init->proj_out_or_null(TypeFunc::Control));
6209     set_i_o(callprojs->fallthrough_ioproj);
6210 
6211     // Update memory as done in GraphKit::set_output_for_allocation()
6212     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6213     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6214     if (ary_type->isa_aryptr() && length_type != nullptr) {
6215       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6216     }
6217     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6218     int            elemidx  = C->get_alias_index(telemref);
6219     set_memory(init->proj_out_or_null(TypeFunc::Memory), Compile::AliasIdxRaw);
6220     set_memory(init->proj_out_or_null(TypeFunc::Memory), elemidx);
6221 
6222     Node* allocx = _gvn.transform(alloc);
6223     assert(allocx == alloc, "where has the allocation gone?");
6224     assert(dest->is_CheckCastPP(), "not an allocation result?");
6225 
6226     _gvn.hash_delete(dest);
6227     dest->set_req(0, control());
6228     Node* destx = _gvn.transform(dest);
6229     assert(destx == dest, "where has the allocation result gone?");
6230 
6231     array_ideal_length(alloc, ary_type, true);
6232   }
6233 }
6234 
6235 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6236 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6237 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6238 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6239 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6240 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6241 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6242                                                                        JVMState* saved_jvms_before_guards) {
6243   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6244     // There is at least one unrelated uncommon trap which needs to be replaced.
6245     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6246 
6247     JVMState* saved_jvms = jvms();
6248     const int saved_reexecute_sp = _reexecute_sp;
6249     set_jvms(sfpt->jvms());
6250     _reexecute_sp = jvms()->sp();
6251 
6252     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6253 
6254     // Restore state
6255     set_jvms(saved_jvms);
6256     _reexecute_sp = saved_reexecute_sp;
6257   }
6258 }
6259 
6260 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6261 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6262 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6263   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6264   while (if_proj->is_IfProj()) {
6265     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6266     if (uncommon_trap != nullptr) {
6267       create_new_uncommon_trap(uncommon_trap);
6268     }
6269     assert(if_proj->in(0)->is_If(), "must be If");
6270     if_proj = if_proj->in(0)->in(0);
6271   }
6272   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6273          "must have reached control projection of init node");
6274 }
6275 
6276 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6277   const int trap_request = uncommon_trap_call->uncommon_trap_request();
6278   assert(trap_request != 0, "no valid UCT trap request");
6279   PreserveJVMState pjvms(this);
6280   set_control(uncommon_trap_call->in(0));
6281   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6282                 Deoptimization::trap_request_action(trap_request));
6283   assert(stopped(), "Should be stopped");
6284   _gvn.hash_delete(uncommon_trap_call);
6285   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6286 }
6287 
6288 // Common checks for array sorting intrinsics arguments.
6289 // Returns `true` if checks passed.
6290 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6291   // check address of the class
6292   if (elementType == nullptr || elementType->is_top()) {
6293     return false;  // dead path
6294   }
6295   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6296   if (elem_klass == nullptr) {
6297     return false;  // dead path
6298   }
6299   // java_mirror_type() returns non-null for compile-time Class constants only
6300   ciType* elem_type = elem_klass->java_mirror_type();
6301   if (elem_type == nullptr) {
6302     return false;
6303   }
6304   bt = elem_type->basic_type();
6305   // Disable the intrinsic if the CPU does not support SIMD sort
6306   if (!Matcher::supports_simd_sort(bt)) {
6307     return false;
6308   }
6309   // check address of the array
6310   if (obj == nullptr || obj->is_top()) {
6311     return false;  // dead path
6312   }
6313   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6314   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6315     return false; // failed input validation
6316   }
6317   return true;
6318 }
6319 
6320 //------------------------------inline_array_partition-----------------------
6321 bool LibraryCallKit::inline_array_partition() {
6322   address stubAddr = StubRoutines::select_array_partition_function();
6323   if (stubAddr == nullptr) {
6324     return false; // Intrinsic's stub is not implemented on this platform
6325   }
6326   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6327 
6328   // no receiver because it is a static method
6329   Node* elementType     = argument(0);
6330   Node* obj             = argument(1);
6331   Node* offset          = argument(2); // long
6332   Node* fromIndex       = argument(4);
6333   Node* toIndex         = argument(5);
6334   Node* indexPivot1     = argument(6);
6335   Node* indexPivot2     = argument(7);
6336   // PartitionOperation:  argument(8) is ignored
6337 
6338   Node* pivotIndices = nullptr;
6339   BasicType bt = T_ILLEGAL;
6340 
6341   if (!check_array_sort_arguments(elementType, obj, bt)) {
6342     return false;
6343   }
6344   null_check(obj);
6345   // If obj is dead, only null-path is taken.
6346   if (stopped()) {
6347     return true;
6348   }
6349   // Set the original stack and the reexecute bit for the interpreter to reexecute
6350   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6351   { PreserveReexecuteState preexecs(this);
6352     jvms()->set_should_reexecute(true);
6353 
6354     Node* obj_adr = make_unsafe_address(obj, offset);
6355 
6356     // create the pivotIndices array of type int and size = 2
6357     Node* size = intcon(2);
6358     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6359     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
6360     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6361     guarantee(alloc != nullptr, "created above");
6362     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6363 
6364     // pass the basic type enum to the stub
6365     Node* elemType = intcon(bt);
6366 
6367     // Call the stub
6368     const char *stubName = "array_partition_stub";
6369     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6370                       stubAddr, stubName, TypePtr::BOTTOM,
6371                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6372                       indexPivot1, indexPivot2);
6373 
6374   } // original reexecute is set back here
6375 
6376   if (!stopped()) {
6377     set_result(pivotIndices);
6378   }
6379 
6380   return true;
6381 }
6382 
6383 
6384 //------------------------------inline_array_sort-----------------------
6385 bool LibraryCallKit::inline_array_sort() {
6386   address stubAddr = StubRoutines::select_arraysort_function();
6387   if (stubAddr == nullptr) {
6388     return false; // Intrinsic's stub is not implemented on this platform
6389   }
6390   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6391 
6392   // no receiver because it is a static method
6393   Node* elementType     = argument(0);
6394   Node* obj             = argument(1);
6395   Node* offset          = argument(2); // long
6396   Node* fromIndex       = argument(4);
6397   Node* toIndex         = argument(5);
6398   // SortOperation:       argument(6) is ignored
6399 
6400   BasicType bt = T_ILLEGAL;
6401 
6402   if (!check_array_sort_arguments(elementType, obj, bt)) {
6403     return false;
6404   }
6405   null_check(obj);
6406   // If obj is dead, only null-path is taken.
6407   if (stopped()) {
6408     return true;
6409   }
6410   Node* obj_adr = make_unsafe_address(obj, offset);
6411 
6412   // pass the basic type enum to the stub
6413   Node* elemType = intcon(bt);
6414 
6415   // Call the stub.
6416   const char *stubName = "arraysort_stub";
6417   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6418                     stubAddr, stubName, TypePtr::BOTTOM,
6419                     obj_adr, elemType, fromIndex, toIndex);
6420 
6421   return true;
6422 }
6423 
6424 
6425 //------------------------------inline_arraycopy-----------------------
6426 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
6427 //                                                      Object dest, int destPos,
6428 //                                                      int length);
6429 bool LibraryCallKit::inline_arraycopy() {
6430   // Get the arguments.
6431   Node* src         = argument(0);  // type: oop
6432   Node* src_offset  = argument(1);  // type: int
6433   Node* dest        = argument(2);  // type: oop
6434   Node* dest_offset = argument(3);  // type: int
6435   Node* length      = argument(4);  // type: int
6436 
6437   uint new_idx = C->unique();
6438 
6439   // Check for allocation before we add nodes that would confuse
6440   // tightly_coupled_allocation()
6441   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6442 
6443   int saved_reexecute_sp = -1;
6444   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6445   // See arraycopy_restore_alloc_state() comment
6446   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6447   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6448   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6449   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6450 
6451   // The following tests must be performed
6452   // (1) src and dest are arrays.
6453   // (2) src and dest arrays must have elements of the same BasicType
6454   // (3) src and dest must not be null.
6455   // (4) src_offset must not be negative.
6456   // (5) dest_offset must not be negative.
6457   // (6) length must not be negative.
6458   // (7) src_offset + length must not exceed length of src.
6459   // (8) dest_offset + length must not exceed length of dest.
6460   // (9) each element of an oop array must be assignable
6461 
6462   // (3) src and dest must not be null.
6463   // always do this here because we need the JVM state for uncommon traps
6464   Node* null_ctl = top();
6465   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6466   assert(null_ctl->is_top(), "no null control here");
6467   dest = null_check(dest, T_ARRAY);
6468 
6469   if (!can_emit_guards) {
6470     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6471     // guards but the arraycopy node could still take advantage of a
6472     // tightly allocated allocation. tightly_coupled_allocation() is
6473     // called again to make sure it takes the null check above into
6474     // account: the null check is mandatory and if it caused an
6475     // uncommon trap to be emitted then the allocation can't be
6476     // considered tightly coupled in this context.
6477     alloc = tightly_coupled_allocation(dest);
6478   }
6479 
6480   bool validated = false;
6481 
6482   const Type* src_type  = _gvn.type(src);
6483   const Type* dest_type = _gvn.type(dest);
6484   const TypeAryPtr* top_src  = src_type->isa_aryptr();
6485   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6486 
6487   // Do we have the type of src?
6488   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6489   // Do we have the type of dest?
6490   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6491   // Is the type for src from speculation?
6492   bool src_spec = false;
6493   // Is the type for dest from speculation?
6494   bool dest_spec = false;
6495 
6496   if ((!has_src || !has_dest) && can_emit_guards) {
6497     // We don't have sufficient type information, let's see if
6498     // speculative types can help. We need to have types for both src
6499     // and dest so that it pays off.
6500 
6501     // Do we already have or could we have type information for src
6502     bool could_have_src = has_src;
6503     // Do we already have or could we have type information for dest
6504     bool could_have_dest = has_dest;
6505 
6506     ciKlass* src_k = nullptr;
6507     if (!has_src) {
6508       src_k = src_type->speculative_type_not_null();
6509       if (src_k != nullptr && src_k->is_array_klass()) {
6510         could_have_src = true;
6511       }
6512     }
6513 
6514     ciKlass* dest_k = nullptr;
6515     if (!has_dest) {
6516       dest_k = dest_type->speculative_type_not_null();
6517       if (dest_k != nullptr && dest_k->is_array_klass()) {
6518         could_have_dest = true;
6519       }
6520     }
6521 
6522     if (could_have_src && could_have_dest) {
6523       // This is going to pay off so emit the required guards
6524       if (!has_src) {
6525         src = maybe_cast_profiled_obj(src, src_k, true);
6526         src_type  = _gvn.type(src);
6527         top_src  = src_type->isa_aryptr();
6528         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6529         src_spec = true;
6530       }
6531       if (!has_dest) {
6532         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6533         dest_type  = _gvn.type(dest);
6534         top_dest  = dest_type->isa_aryptr();
6535         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6536         dest_spec = true;
6537       }
6538     }
6539   }
6540 
6541   if (has_src && has_dest && can_emit_guards) {
6542     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6543     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6544     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6545     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6546 
6547     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6548       // If both arrays are object arrays then having the exact types
6549       // for both will remove the need for a subtype check at runtime
6550       // before the call and may make it possible to pick a faster copy
6551       // routine (without a subtype check on every element)
6552       // Do we have the exact type of src?
6553       bool could_have_src = src_spec;
6554       // Do we have the exact type of dest?
6555       bool could_have_dest = dest_spec;
6556       ciKlass* src_k = nullptr;
6557       ciKlass* dest_k = nullptr;
6558       if (!src_spec) {
6559         src_k = src_type->speculative_type_not_null();
6560         if (src_k != nullptr && src_k->is_array_klass()) {
6561           could_have_src = true;
6562         }
6563       }
6564       if (!dest_spec) {
6565         dest_k = dest_type->speculative_type_not_null();
6566         if (dest_k != nullptr && dest_k->is_array_klass()) {
6567           could_have_dest = true;
6568         }
6569       }
6570       if (could_have_src && could_have_dest) {
6571         // If we can have both exact types, emit the missing guards
6572         if (could_have_src && !src_spec) {
6573           src = maybe_cast_profiled_obj(src, src_k, true);
6574           src_type = _gvn.type(src);
6575           top_src = src_type->isa_aryptr();
6576         }
6577         if (could_have_dest && !dest_spec) {
6578           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6579           dest_type = _gvn.type(dest);
6580           top_dest = dest_type->isa_aryptr();
6581         }
6582       }
6583     }
6584   }
6585 
6586   ciMethod* trap_method = method();
6587   int trap_bci = bci();
6588   if (saved_jvms_before_guards != nullptr) {
6589     trap_method = alloc->jvms()->method();
6590     trap_bci = alloc->jvms()->bci();
6591   }
6592 
6593   bool negative_length_guard_generated = false;
6594 
6595   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6596       can_emit_guards && !src->is_top() && !dest->is_top()) {
6597     // validate arguments: enables transformation the ArrayCopyNode
6598     validated = true;
6599 
6600     RegionNode* slow_region = new RegionNode(1);
6601     record_for_igvn(slow_region);
6602 
6603     // (1) src and dest are arrays.
6604     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6605     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6606 
6607     // (2) src and dest arrays must have elements of the same BasicType
6608     // done at macro expansion or at Ideal transformation time
6609 
6610     // (4) src_offset must not be negative.
6611     generate_negative_guard(src_offset, slow_region);
6612 
6613     // (5) dest_offset must not be negative.
6614     generate_negative_guard(dest_offset, slow_region);
6615 
6616     // (7) src_offset + length must not exceed length of src.
6617     generate_limit_guard(src_offset, length,
6618                          load_array_length(src),
6619                          slow_region);
6620 
6621     // (8) dest_offset + length must not exceed length of dest.
6622     generate_limit_guard(dest_offset, length,
6623                          load_array_length(dest),
6624                          slow_region);
6625 
6626     // (6) length must not be negative.
6627     // This is also checked in generate_arraycopy() during macro expansion, but
6628     // we also have to check it here for the case where the ArrayCopyNode will
6629     // be eliminated by Escape Analysis.
6630     if (EliminateAllocations) {
6631       generate_negative_guard(length, slow_region);
6632       negative_length_guard_generated = true;
6633     }
6634 
6635     // (9) each element of an oop array must be assignable
6636     Node* dest_klass = load_object_klass(dest);
6637     if (src != dest) {
6638       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6639       slow_region->add_req(not_subtype_ctrl);
6640     }
6641 
6642     // TODO 8350865 Fix below logic. Also handle atomicity.
6643     generate_fair_guard(flat_array_test(src), slow_region);
6644     generate_fair_guard(flat_array_test(dest), slow_region);
6645 
6646     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
6647     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6648     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6649     src_type = _gvn.type(src);
6650     top_src  = src_type->isa_aryptr();
6651 
6652     // Handle flat inline type arrays (null-free arrays are handled by the subtype check above)
6653     if (!stopped() && UseArrayFlattening) {
6654       // If dest is flat, src must be flat as well (guaranteed by src <: dest check). Handle flat src here.
6655       assert(top_dest == nullptr || !top_dest->is_flat() || top_src->is_flat(), "src array must be flat");
6656       if (top_src != nullptr && top_src->is_flat()) {
6657         // Src is flat, check that dest is flat as well
6658         if (top_dest != nullptr && !top_dest->is_flat()) {
6659           generate_fair_guard(flat_array_test(dest_klass, /* flat = */ false), slow_region);
6660           // Since dest is flat and src <: dest, dest must have the same type as src.
6661           top_dest = top_src->cast_to_exactness(false);
6662           assert(top_dest->is_flat(), "dest must be flat");
6663           dest = _gvn.transform(new CheckCastPPNode(control(), dest, top_dest));
6664         }
6665       } else if (top_src == nullptr || !top_src->is_not_flat()) {
6666         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
6667         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
6668         assert(top_dest == nullptr || !top_dest->is_flat(), "dest array must not be flat");
6669         generate_fair_guard(flat_array_test(src), slow_region);
6670         if (top_src != nullptr) {
6671           top_src = top_src->cast_to_not_flat();
6672           src = _gvn.transform(new CheckCastPPNode(control(), src, top_src));
6673         }
6674       }
6675     }
6676 
6677     {
6678       PreserveJVMState pjvms(this);
6679       set_control(_gvn.transform(slow_region));
6680       uncommon_trap(Deoptimization::Reason_intrinsic,
6681                     Deoptimization::Action_make_not_entrant);
6682       assert(stopped(), "Should be stopped");
6683     }
6684     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6685   }
6686 
6687   if (stopped()) {
6688     return true;
6689   }
6690 
6691   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6692                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6693                                           // so the compiler has a chance to eliminate them: during macro expansion,
6694                                           // we have to set their control (CastPP nodes are eliminated).
6695                                           load_object_klass(src), load_object_klass(dest),
6696                                           load_array_length(src), load_array_length(dest));
6697 
6698   ac->set_arraycopy(validated);
6699 
6700   Node* n = _gvn.transform(ac);
6701   if (n == ac) {
6702     ac->connect_outputs(this);
6703   } else {
6704     assert(validated, "shouldn't transform if all arguments not validated");
6705     set_all_memory(n);
6706   }
6707   clear_upper_avx();
6708 
6709 
6710   return true;
6711 }
6712 
6713 
6714 // Helper function which determines if an arraycopy immediately follows
6715 // an allocation, with no intervening tests or other escapes for the object.
6716 AllocateArrayNode*
6717 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6718   if (stopped())             return nullptr;  // no fast path
6719   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
6720 
6721   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6722   if (alloc == nullptr)  return nullptr;
6723 
6724   Node* rawmem = memory(Compile::AliasIdxRaw);
6725   // Is the allocation's memory state untouched?
6726   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6727     // Bail out if there have been raw-memory effects since the allocation.
6728     // (Example:  There might have been a call or safepoint.)
6729     return nullptr;
6730   }
6731   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6732   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6733     return nullptr;
6734   }
6735 
6736   // There must be no unexpected observers of this allocation.
6737   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6738     Node* obs = ptr->fast_out(i);
6739     if (obs != this->map()) {
6740       return nullptr;
6741     }
6742   }
6743 
6744   // This arraycopy must unconditionally follow the allocation of the ptr.
6745   Node* alloc_ctl = ptr->in(0);
6746   Node* ctl = control();
6747   while (ctl != alloc_ctl) {
6748     // There may be guards which feed into the slow_region.
6749     // Any other control flow means that we might not get a chance
6750     // to finish initializing the allocated object.
6751     // Various low-level checks bottom out in uncommon traps. These
6752     // are considered safe since we've already checked above that
6753     // there is no unexpected observer of this allocation.
6754     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6755       assert(ctl->in(0)->is_If(), "must be If");
6756       ctl = ctl->in(0)->in(0);
6757     } else {
6758       return nullptr;
6759     }
6760   }
6761 
6762   // If we get this far, we have an allocation which immediately
6763   // precedes the arraycopy, and we can take over zeroing the new object.
6764   // The arraycopy will finish the initialization, and provide
6765   // a new control state to which we will anchor the destination pointer.
6766 
6767   return alloc;
6768 }
6769 
6770 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6771   if (node->is_IfProj()) {
6772     Node* other_proj = node->as_IfProj()->other_if_proj();
6773     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6774       Node* obs = other_proj->fast_out(j);
6775       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6776           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6777         return obs->as_CallStaticJava();
6778       }
6779     }
6780   }
6781   return nullptr;
6782 }
6783 
6784 //-------------inline_encodeISOArray-----------------------------------
6785 // encode char[] to byte[] in ISO_8859_1 or ASCII
6786 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6787   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6788   // no receiver since it is static method
6789   Node *src         = argument(0);
6790   Node *src_offset  = argument(1);
6791   Node *dst         = argument(2);
6792   Node *dst_offset  = argument(3);
6793   Node *length      = argument(4);
6794 
6795   src = must_be_not_null(src, true);
6796   dst = must_be_not_null(dst, true);
6797 
6798   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6799   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6800   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6801       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6802     // failed array check
6803     return false;
6804   }
6805 
6806   // Figure out the size and type of the elements we will be copying.
6807   BasicType src_elem = src_type->elem()->array_element_basic_type();
6808   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6809   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6810     return false;
6811   }
6812 
6813   Node* src_start = array_element_address(src, src_offset, T_CHAR);
6814   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6815   // 'src_start' points to src array + scaled offset
6816   // 'dst_start' points to dst array + scaled offset
6817 
6818   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
6819   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
6820   enc = _gvn.transform(enc);
6821   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6822   set_memory(res_mem, mtype);
6823   set_result(enc);
6824   clear_upper_avx();
6825 
6826   return true;
6827 }
6828 
6829 //-------------inline_multiplyToLen-----------------------------------
6830 bool LibraryCallKit::inline_multiplyToLen() {
6831   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
6832 
6833   address stubAddr = StubRoutines::multiplyToLen();
6834   if (stubAddr == nullptr) {
6835     return false; // Intrinsic's stub is not implemented on this platform
6836   }
6837   const char* stubName = "multiplyToLen";
6838 
6839   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
6840 
6841   // no receiver because it is a static method
6842   Node* x    = argument(0);
6843   Node* xlen = argument(1);
6844   Node* y    = argument(2);
6845   Node* ylen = argument(3);
6846   Node* z    = argument(4);
6847 
6848   x = must_be_not_null(x, true);
6849   y = must_be_not_null(y, true);
6850 
6851   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6852   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
6853   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6854       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
6855     // failed array check
6856     return false;
6857   }
6858 
6859   BasicType x_elem = x_type->elem()->array_element_basic_type();
6860   BasicType y_elem = y_type->elem()->array_element_basic_type();
6861   if (x_elem != T_INT || y_elem != T_INT) {
6862     return false;
6863   }
6864 
6865   Node* x_start = array_element_address(x, intcon(0), x_elem);
6866   Node* y_start = array_element_address(y, intcon(0), y_elem);
6867   // 'x_start' points to x array + scaled xlen
6868   // 'y_start' points to y array + scaled ylen
6869 
6870   Node* z_start = array_element_address(z, intcon(0), T_INT);
6871 
6872   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6873                                  OptoRuntime::multiplyToLen_Type(),
6874                                  stubAddr, stubName, TypePtr::BOTTOM,
6875                                  x_start, xlen, y_start, ylen, z_start);
6876 
6877   C->set_has_split_ifs(true); // Has chance for split-if optimization
6878   set_result(z);
6879   return true;
6880 }
6881 
6882 //-------------inline_squareToLen------------------------------------
6883 bool LibraryCallKit::inline_squareToLen() {
6884   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
6885 
6886   address stubAddr = StubRoutines::squareToLen();
6887   if (stubAddr == nullptr) {
6888     return false; // Intrinsic's stub is not implemented on this platform
6889   }
6890   const char* stubName = "squareToLen";
6891 
6892   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
6893 
6894   Node* x    = argument(0);
6895   Node* len  = argument(1);
6896   Node* z    = argument(2);
6897   Node* zlen = argument(3);
6898 
6899   x = must_be_not_null(x, true);
6900   z = must_be_not_null(z, true);
6901 
6902   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6903   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
6904   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6905       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
6906     // failed array check
6907     return false;
6908   }
6909 
6910   BasicType x_elem = x_type->elem()->array_element_basic_type();
6911   BasicType z_elem = z_type->elem()->array_element_basic_type();
6912   if (x_elem != T_INT || z_elem != T_INT) {
6913     return false;
6914   }
6915 
6916 
6917   Node* x_start = array_element_address(x, intcon(0), x_elem);
6918   Node* z_start = array_element_address(z, intcon(0), z_elem);
6919 
6920   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
6921                                   OptoRuntime::squareToLen_Type(),
6922                                   stubAddr, stubName, TypePtr::BOTTOM,
6923                                   x_start, len, z_start, zlen);
6924 
6925   set_result(z);
6926   return true;
6927 }
6928 
6929 //-------------inline_mulAdd------------------------------------------
6930 bool LibraryCallKit::inline_mulAdd() {
6931   assert(UseMulAddIntrinsic, "not implemented on this platform");
6932 
6933   address stubAddr = StubRoutines::mulAdd();
6934   if (stubAddr == nullptr) {
6935     return false; // Intrinsic's stub is not implemented on this platform
6936   }
6937   const char* stubName = "mulAdd";
6938 
6939   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
6940 
6941   Node* out      = argument(0);
6942   Node* in       = argument(1);
6943   Node* offset   = argument(2);
6944   Node* len      = argument(3);
6945   Node* k        = argument(4);
6946 
6947   in = must_be_not_null(in, true);
6948   out = must_be_not_null(out, true);
6949 
6950   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
6951   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
6952   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
6953        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
6954     // failed array check
6955     return false;
6956   }
6957 
6958   BasicType out_elem = out_type->elem()->array_element_basic_type();
6959   BasicType in_elem = in_type->elem()->array_element_basic_type();
6960   if (out_elem != T_INT || in_elem != T_INT) {
6961     return false;
6962   }
6963 
6964   Node* outlen = load_array_length(out);
6965   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
6966   Node* out_start = array_element_address(out, intcon(0), out_elem);
6967   Node* in_start = array_element_address(in, intcon(0), in_elem);
6968 
6969   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
6970                                   OptoRuntime::mulAdd_Type(),
6971                                   stubAddr, stubName, TypePtr::BOTTOM,
6972                                   out_start,in_start, new_offset, len, k);
6973   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6974   set_result(result);
6975   return true;
6976 }
6977 
6978 //-------------inline_montgomeryMultiply-----------------------------------
6979 bool LibraryCallKit::inline_montgomeryMultiply() {
6980   address stubAddr = StubRoutines::montgomeryMultiply();
6981   if (stubAddr == nullptr) {
6982     return false; // Intrinsic's stub is not implemented on this platform
6983   }
6984 
6985   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
6986   const char* stubName = "montgomery_multiply";
6987 
6988   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
6989 
6990   Node* a    = argument(0);
6991   Node* b    = argument(1);
6992   Node* n    = argument(2);
6993   Node* len  = argument(3);
6994   Node* inv  = argument(4);
6995   Node* m    = argument(6);
6996 
6997   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
6998   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
6999   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7000   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7001   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7002       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
7003       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7004       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7005     // failed array check
7006     return false;
7007   }
7008 
7009   BasicType a_elem = a_type->elem()->array_element_basic_type();
7010   BasicType b_elem = b_type->elem()->array_element_basic_type();
7011   BasicType n_elem = n_type->elem()->array_element_basic_type();
7012   BasicType m_elem = m_type->elem()->array_element_basic_type();
7013   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7014     return false;
7015   }
7016 
7017   // Make the call
7018   {
7019     Node* a_start = array_element_address(a, intcon(0), a_elem);
7020     Node* b_start = array_element_address(b, intcon(0), b_elem);
7021     Node* n_start = array_element_address(n, intcon(0), n_elem);
7022     Node* m_start = array_element_address(m, intcon(0), m_elem);
7023 
7024     Node* call = make_runtime_call(RC_LEAF,
7025                                    OptoRuntime::montgomeryMultiply_Type(),
7026                                    stubAddr, stubName, TypePtr::BOTTOM,
7027                                    a_start, b_start, n_start, len, inv, top(),
7028                                    m_start);
7029     set_result(m);
7030   }
7031 
7032   return true;
7033 }
7034 
7035 bool LibraryCallKit::inline_montgomerySquare() {
7036   address stubAddr = StubRoutines::montgomerySquare();
7037   if (stubAddr == nullptr) {
7038     return false; // Intrinsic's stub is not implemented on this platform
7039   }
7040 
7041   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7042   const char* stubName = "montgomery_square";
7043 
7044   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7045 
7046   Node* a    = argument(0);
7047   Node* n    = argument(1);
7048   Node* len  = argument(2);
7049   Node* inv  = argument(3);
7050   Node* m    = argument(5);
7051 
7052   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7053   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7054   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7055   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7056       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7057       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7058     // failed array check
7059     return false;
7060   }
7061 
7062   BasicType a_elem = a_type->elem()->array_element_basic_type();
7063   BasicType n_elem = n_type->elem()->array_element_basic_type();
7064   BasicType m_elem = m_type->elem()->array_element_basic_type();
7065   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7066     return false;
7067   }
7068 
7069   // Make the call
7070   {
7071     Node* a_start = array_element_address(a, intcon(0), a_elem);
7072     Node* n_start = array_element_address(n, intcon(0), n_elem);
7073     Node* m_start = array_element_address(m, intcon(0), m_elem);
7074 
7075     Node* call = make_runtime_call(RC_LEAF,
7076                                    OptoRuntime::montgomerySquare_Type(),
7077                                    stubAddr, stubName, TypePtr::BOTTOM,
7078                                    a_start, n_start, len, inv, top(),
7079                                    m_start);
7080     set_result(m);
7081   }
7082 
7083   return true;
7084 }
7085 
7086 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7087   address stubAddr = nullptr;
7088   const char* stubName = nullptr;
7089 
7090   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7091   if (stubAddr == nullptr) {
7092     return false; // Intrinsic's stub is not implemented on this platform
7093   }
7094 
7095   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7096 
7097   assert(callee()->signature()->size() == 5, "expected 5 arguments");
7098 
7099   Node* newArr = argument(0);
7100   Node* oldArr = argument(1);
7101   Node* newIdx = argument(2);
7102   Node* shiftCount = argument(3);
7103   Node* numIter = argument(4);
7104 
7105   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7106   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7107   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7108       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7109     return false;
7110   }
7111 
7112   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7113   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7114   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7115     return false;
7116   }
7117 
7118   // Make the call
7119   {
7120     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7121     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7122 
7123     Node* call = make_runtime_call(RC_LEAF,
7124                                    OptoRuntime::bigIntegerShift_Type(),
7125                                    stubAddr,
7126                                    stubName,
7127                                    TypePtr::BOTTOM,
7128                                    newArr_start,
7129                                    oldArr_start,
7130                                    newIdx,
7131                                    shiftCount,
7132                                    numIter);
7133   }
7134 
7135   return true;
7136 }
7137 
7138 //-------------inline_vectorizedMismatch------------------------------
7139 bool LibraryCallKit::inline_vectorizedMismatch() {
7140   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7141 
7142   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7143   Node* obja    = argument(0); // Object
7144   Node* aoffset = argument(1); // long
7145   Node* objb    = argument(3); // Object
7146   Node* boffset = argument(4); // long
7147   Node* length  = argument(6); // int
7148   Node* scale   = argument(7); // int
7149 
7150   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7151   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7152   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7153       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7154       scale == top()) {
7155     return false; // failed input validation
7156   }
7157 
7158   Node* obja_adr = make_unsafe_address(obja, aoffset);
7159   Node* objb_adr = make_unsafe_address(objb, boffset);
7160 
7161   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7162   //
7163   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
7164   //    if (length <= inline_limit) {
7165   //      inline_path:
7166   //        vmask   = VectorMaskGen length
7167   //        vload1  = LoadVectorMasked obja, vmask
7168   //        vload2  = LoadVectorMasked objb, vmask
7169   //        result1 = VectorCmpMasked vload1, vload2, vmask
7170   //    } else {
7171   //      call_stub_path:
7172   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7173   //    }
7174   //    exit_block:
7175   //      return Phi(result1, result2);
7176   //
7177   enum { inline_path = 1,  // input is small enough to process it all at once
7178          stub_path   = 2,  // input is too large; call into the VM
7179          PATH_LIMIT  = 3
7180   };
7181 
7182   Node* exit_block = new RegionNode(PATH_LIMIT);
7183   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7184   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7185 
7186   Node* call_stub_path = control();
7187 
7188   BasicType elem_bt = T_ILLEGAL;
7189 
7190   const TypeInt* scale_t = _gvn.type(scale)->is_int();
7191   if (scale_t->is_con()) {
7192     switch (scale_t->get_con()) {
7193       case 0: elem_bt = T_BYTE;  break;
7194       case 1: elem_bt = T_SHORT; break;
7195       case 2: elem_bt = T_INT;   break;
7196       case 3: elem_bt = T_LONG;  break;
7197 
7198       default: elem_bt = T_ILLEGAL; break; // not supported
7199     }
7200   }
7201 
7202   int inline_limit = 0;
7203   bool do_partial_inline = false;
7204 
7205   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7206     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7207     do_partial_inline = inline_limit >= 16;
7208   }
7209 
7210   if (do_partial_inline) {
7211     assert(elem_bt != T_ILLEGAL, "sanity");
7212 
7213     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
7214         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7215         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
7216 
7217       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7218       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7219       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7220 
7221       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7222 
7223       if (!stopped()) {
7224         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7225 
7226         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7227         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7228         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7229         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7230 
7231         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7232         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7233         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7234         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7235 
7236         exit_block->init_req(inline_path, control());
7237         memory_phi->init_req(inline_path, map()->memory());
7238         result_phi->init_req(inline_path, result);
7239 
7240         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7241         clear_upper_avx();
7242       }
7243     }
7244   }
7245 
7246   if (call_stub_path != nullptr) {
7247     set_control(call_stub_path);
7248 
7249     Node* call = make_runtime_call(RC_LEAF,
7250                                    OptoRuntime::vectorizedMismatch_Type(),
7251                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7252                                    obja_adr, objb_adr, length, scale);
7253 
7254     exit_block->init_req(stub_path, control());
7255     memory_phi->init_req(stub_path, map()->memory());
7256     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7257   }
7258 
7259   exit_block = _gvn.transform(exit_block);
7260   memory_phi = _gvn.transform(memory_phi);
7261   result_phi = _gvn.transform(result_phi);
7262 
7263   record_for_igvn(exit_block);
7264   record_for_igvn(memory_phi);
7265   record_for_igvn(result_phi);
7266 
7267   set_control(exit_block);
7268   set_all_memory(memory_phi);
7269   set_result(result_phi);
7270 
7271   return true;
7272 }
7273 
7274 //------------------------------inline_vectorizedHashcode----------------------------
7275 bool LibraryCallKit::inline_vectorizedHashCode() {
7276   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7277 
7278   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7279   Node* array          = argument(0);
7280   Node* offset         = argument(1);
7281   Node* length         = argument(2);
7282   Node* initialValue   = argument(3);
7283   Node* basic_type     = argument(4);
7284 
7285   if (basic_type == top()) {
7286     return false; // failed input validation
7287   }
7288 
7289   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7290   if (!basic_type_t->is_con()) {
7291     return false; // Only intrinsify if mode argument is constant
7292   }
7293 
7294   array = must_be_not_null(array, true);
7295 
7296   BasicType bt = (BasicType)basic_type_t->get_con();
7297 
7298   // Resolve address of first element
7299   Node* array_start = array_element_address(array, offset, bt);
7300 
7301   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
7302     array_start, length, initialValue, basic_type)));
7303   clear_upper_avx();
7304 
7305   return true;
7306 }
7307 
7308 /**
7309  * Calculate CRC32 for byte.
7310  * int java.util.zip.CRC32.update(int crc, int b)
7311  */
7312 bool LibraryCallKit::inline_updateCRC32() {
7313   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7314   assert(callee()->signature()->size() == 2, "update has 2 parameters");
7315   // no receiver since it is static method
7316   Node* crc  = argument(0); // type: int
7317   Node* b    = argument(1); // type: int
7318 
7319   /*
7320    *    int c = ~ crc;
7321    *    b = timesXtoThe32[(b ^ c) & 0xFF];
7322    *    b = b ^ (c >>> 8);
7323    *    crc = ~b;
7324    */
7325 
7326   Node* M1 = intcon(-1);
7327   crc = _gvn.transform(new XorINode(crc, M1));
7328   Node* result = _gvn.transform(new XorINode(crc, b));
7329   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7330 
7331   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7332   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7333   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
7334   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7335 
7336   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7337   result = _gvn.transform(new XorINode(crc, result));
7338   result = _gvn.transform(new XorINode(result, M1));
7339   set_result(result);
7340   return true;
7341 }
7342 
7343 /**
7344  * Calculate CRC32 for byte[] array.
7345  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7346  */
7347 bool LibraryCallKit::inline_updateBytesCRC32() {
7348   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7349   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7350   // no receiver since it is static method
7351   Node* crc     = argument(0); // type: int
7352   Node* src     = argument(1); // type: oop
7353   Node* offset  = argument(2); // type: int
7354   Node* length  = argument(3); // type: int
7355 
7356   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7357   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7358     // failed array check
7359     return false;
7360   }
7361 
7362   // Figure out the size and type of the elements we will be copying.
7363   BasicType src_elem = src_type->elem()->array_element_basic_type();
7364   if (src_elem != T_BYTE) {
7365     return false;
7366   }
7367 
7368   // 'src_start' points to src array + scaled offset
7369   src = must_be_not_null(src, true);
7370   Node* src_start = array_element_address(src, offset, src_elem);
7371 
7372   // We assume that range check is done by caller.
7373   // TODO: generate range check (offset+length < src.length) in debug VM.
7374 
7375   // Call the stub.
7376   address stubAddr = StubRoutines::updateBytesCRC32();
7377   const char *stubName = "updateBytesCRC32";
7378 
7379   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7380                                  stubAddr, stubName, TypePtr::BOTTOM,
7381                                  crc, src_start, length);
7382   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7383   set_result(result);
7384   return true;
7385 }
7386 
7387 /**
7388  * Calculate CRC32 for ByteBuffer.
7389  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7390  */
7391 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7392   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7393   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7394   // no receiver since it is static method
7395   Node* crc     = argument(0); // type: int
7396   Node* src     = argument(1); // type: long
7397   Node* offset  = argument(3); // type: int
7398   Node* length  = argument(4); // type: int
7399 
7400   src = ConvL2X(src);  // adjust Java long to machine word
7401   Node* base = _gvn.transform(new CastX2PNode(src));
7402   offset = ConvI2X(offset);
7403 
7404   // 'src_start' points to src array + scaled offset
7405   Node* src_start = basic_plus_adr(top(), base, offset);
7406 
7407   // Call the stub.
7408   address stubAddr = StubRoutines::updateBytesCRC32();
7409   const char *stubName = "updateBytesCRC32";
7410 
7411   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7412                                  stubAddr, stubName, TypePtr::BOTTOM,
7413                                  crc, src_start, length);
7414   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7415   set_result(result);
7416   return true;
7417 }
7418 
7419 //------------------------------get_table_from_crc32c_class-----------------------
7420 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7421   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7422   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7423 
7424   return table;
7425 }
7426 
7427 //------------------------------inline_updateBytesCRC32C-----------------------
7428 //
7429 // Calculate CRC32C for byte[] array.
7430 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7431 //
7432 bool LibraryCallKit::inline_updateBytesCRC32C() {
7433   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7434   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7435   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7436   // no receiver since it is a static method
7437   Node* crc     = argument(0); // type: int
7438   Node* src     = argument(1); // type: oop
7439   Node* offset  = argument(2); // type: int
7440   Node* end     = argument(3); // type: int
7441 
7442   Node* length = _gvn.transform(new SubINode(end, offset));
7443 
7444   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7445   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7446     // failed array check
7447     return false;
7448   }
7449 
7450   // Figure out the size and type of the elements we will be copying.
7451   BasicType src_elem = src_type->elem()->array_element_basic_type();
7452   if (src_elem != T_BYTE) {
7453     return false;
7454   }
7455 
7456   // 'src_start' points to src array + scaled offset
7457   src = must_be_not_null(src, true);
7458   Node* src_start = array_element_address(src, offset, src_elem);
7459 
7460   // static final int[] byteTable in class CRC32C
7461   Node* table = get_table_from_crc32c_class(callee()->holder());
7462   table = must_be_not_null(table, true);
7463   Node* table_start = array_element_address(table, intcon(0), T_INT);
7464 
7465   // We assume that range check is done by caller.
7466   // TODO: generate range check (offset+length < src.length) in debug VM.
7467 
7468   // Call the stub.
7469   address stubAddr = StubRoutines::updateBytesCRC32C();
7470   const char *stubName = "updateBytesCRC32C";
7471 
7472   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7473                                  stubAddr, stubName, TypePtr::BOTTOM,
7474                                  crc, src_start, length, table_start);
7475   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7476   set_result(result);
7477   return true;
7478 }
7479 
7480 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7481 //
7482 // Calculate CRC32C for DirectByteBuffer.
7483 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7484 //
7485 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7486   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7487   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7488   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7489   // no receiver since it is a static method
7490   Node* crc     = argument(0); // type: int
7491   Node* src     = argument(1); // type: long
7492   Node* offset  = argument(3); // type: int
7493   Node* end     = argument(4); // type: int
7494 
7495   Node* length = _gvn.transform(new SubINode(end, offset));
7496 
7497   src = ConvL2X(src);  // adjust Java long to machine word
7498   Node* base = _gvn.transform(new CastX2PNode(src));
7499   offset = ConvI2X(offset);
7500 
7501   // 'src_start' points to src array + scaled offset
7502   Node* src_start = basic_plus_adr(top(), base, offset);
7503 
7504   // static final int[] byteTable in class CRC32C
7505   Node* table = get_table_from_crc32c_class(callee()->holder());
7506   table = must_be_not_null(table, true);
7507   Node* table_start = array_element_address(table, intcon(0), T_INT);
7508 
7509   // Call the stub.
7510   address stubAddr = StubRoutines::updateBytesCRC32C();
7511   const char *stubName = "updateBytesCRC32C";
7512 
7513   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7514                                  stubAddr, stubName, TypePtr::BOTTOM,
7515                                  crc, src_start, length, table_start);
7516   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7517   set_result(result);
7518   return true;
7519 }
7520 
7521 //------------------------------inline_updateBytesAdler32----------------------
7522 //
7523 // Calculate Adler32 checksum for byte[] array.
7524 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7525 //
7526 bool LibraryCallKit::inline_updateBytesAdler32() {
7527   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7528   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7529   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7530   // no receiver since it is static method
7531   Node* crc     = argument(0); // type: int
7532   Node* src     = argument(1); // type: oop
7533   Node* offset  = argument(2); // type: int
7534   Node* length  = argument(3); // type: int
7535 
7536   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7537   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7538     // failed array check
7539     return false;
7540   }
7541 
7542   // Figure out the size and type of the elements we will be copying.
7543   BasicType src_elem = src_type->elem()->array_element_basic_type();
7544   if (src_elem != T_BYTE) {
7545     return false;
7546   }
7547 
7548   // 'src_start' points to src array + scaled offset
7549   Node* src_start = array_element_address(src, offset, src_elem);
7550 
7551   // We assume that range check is done by caller.
7552   // TODO: generate range check (offset+length < src.length) in debug VM.
7553 
7554   // Call the stub.
7555   address stubAddr = StubRoutines::updateBytesAdler32();
7556   const char *stubName = "updateBytesAdler32";
7557 
7558   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7559                                  stubAddr, stubName, TypePtr::BOTTOM,
7560                                  crc, src_start, length);
7561   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7562   set_result(result);
7563   return true;
7564 }
7565 
7566 //------------------------------inline_updateByteBufferAdler32---------------
7567 //
7568 // Calculate Adler32 checksum for DirectByteBuffer.
7569 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7570 //
7571 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7572   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7573   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7574   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7575   // no receiver since it is static method
7576   Node* crc     = argument(0); // type: int
7577   Node* src     = argument(1); // type: long
7578   Node* offset  = argument(3); // type: int
7579   Node* length  = argument(4); // type: int
7580 
7581   src = ConvL2X(src);  // adjust Java long to machine word
7582   Node* base = _gvn.transform(new CastX2PNode(src));
7583   offset = ConvI2X(offset);
7584 
7585   // 'src_start' points to src array + scaled offset
7586   Node* src_start = basic_plus_adr(top(), base, offset);
7587 
7588   // Call the stub.
7589   address stubAddr = StubRoutines::updateBytesAdler32();
7590   const char *stubName = "updateBytesAdler32";
7591 
7592   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7593                                  stubAddr, stubName, TypePtr::BOTTOM,
7594                                  crc, src_start, length);
7595 
7596   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7597   set_result(result);
7598   return true;
7599 }
7600 
7601 //----------------------------inline_reference_get0----------------------------
7602 // public T java.lang.ref.Reference.get();
7603 bool LibraryCallKit::inline_reference_get0() {
7604   const int referent_offset = java_lang_ref_Reference::referent_offset();
7605 
7606   // Get the argument:
7607   Node* reference_obj = null_check_receiver();
7608   if (stopped()) return true;
7609 
7610   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7611   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7612                                         decorators, /*is_static*/ false, nullptr);
7613   if (result == nullptr) return false;
7614 
7615   // Add memory barrier to prevent commoning reads from this field
7616   // across safepoint since GC can change its value.
7617   insert_mem_bar(Op_MemBarCPUOrder);
7618 
7619   set_result(result);
7620   return true;
7621 }
7622 
7623 //----------------------------inline_reference_refersTo0----------------------------
7624 // bool java.lang.ref.Reference.refersTo0();
7625 // bool java.lang.ref.PhantomReference.refersTo0();
7626 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7627   // Get arguments:
7628   Node* reference_obj = null_check_receiver();
7629   Node* other_obj = argument(1);
7630   if (stopped()) return true;
7631 
7632   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7633   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7634   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7635                                           decorators, /*is_static*/ false, nullptr);
7636   if (referent == nullptr) return false;
7637 
7638   // Add memory barrier to prevent commoning reads from this field
7639   // across safepoint since GC can change its value.
7640   insert_mem_bar(Op_MemBarCPUOrder);
7641 
7642   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7643   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7644   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7645 
7646   RegionNode* region = new RegionNode(3);
7647   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7648 
7649   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7650   region->init_req(1, if_true);
7651   phi->init_req(1, intcon(1));
7652 
7653   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7654   region->init_req(2, if_false);
7655   phi->init_req(2, intcon(0));
7656 
7657   set_control(_gvn.transform(region));
7658   record_for_igvn(region);
7659   set_result(_gvn.transform(phi));
7660   return true;
7661 }
7662 
7663 //----------------------------inline_reference_clear0----------------------------
7664 // void java.lang.ref.Reference.clear0();
7665 // void java.lang.ref.PhantomReference.clear0();
7666 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7667   // This matches the implementation in JVM_ReferenceClear, see the comments there.
7668 
7669   // Get arguments
7670   Node* reference_obj = null_check_receiver();
7671   if (stopped()) return true;
7672 
7673   // Common access parameters
7674   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7675   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7676   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7677   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7678   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7679 
7680   Node* referent = access_load_at(reference_obj,
7681                                   referent_field_addr,
7682                                   referent_field_addr_type,
7683                                   val_type,
7684                                   T_OBJECT,
7685                                   decorators);
7686 
7687   IdealKit ideal(this);
7688 #define __ ideal.
7689   __ if_then(referent, BoolTest::ne, null());
7690     sync_kit(ideal);
7691     access_store_at(reference_obj,
7692                     referent_field_addr,
7693                     referent_field_addr_type,
7694                     null(),
7695                     val_type,
7696                     T_OBJECT,
7697                     decorators);
7698     __ sync_kit(this);
7699   __ end_if();
7700   final_sync(ideal);
7701 #undef __
7702 
7703   return true;
7704 }
7705 
7706 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7707                                              DecoratorSet decorators, bool is_static,
7708                                              ciInstanceKlass* fromKls) {
7709   if (fromKls == nullptr) {
7710     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7711     assert(tinst != nullptr, "obj is null");
7712     assert(tinst->is_loaded(), "obj is not loaded");
7713     fromKls = tinst->instance_klass();
7714   } else {
7715     assert(is_static, "only for static field access");
7716   }
7717   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7718                                               ciSymbol::make(fieldTypeString),
7719                                               is_static);
7720 
7721   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7722   if (field == nullptr) return (Node *) nullptr;
7723 
7724   if (is_static) {
7725     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7726     fromObj = makecon(tip);
7727   }
7728 
7729   // Next code  copied from Parse::do_get_xxx():
7730 
7731   // Compute address and memory type.
7732   int offset  = field->offset_in_bytes();
7733   bool is_vol = field->is_volatile();
7734   ciType* field_klass = field->type();
7735   assert(field_klass->is_loaded(), "should be loaded");
7736   const TypePtr* adr_type = C->alias_type(field)->adr_type();
7737   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7738   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7739     "slice of address and input slice don't match");
7740   BasicType bt = field->layout_type();
7741 
7742   // Build the resultant type of the load
7743   const Type *type;
7744   if (bt == T_OBJECT) {
7745     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7746   } else {
7747     type = Type::get_const_basic_type(bt);
7748   }
7749 
7750   if (is_vol) {
7751     decorators |= MO_SEQ_CST;
7752   }
7753 
7754   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7755 }
7756 
7757 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7758                                                  bool is_exact /* true */, bool is_static /* false */,
7759                                                  ciInstanceKlass * fromKls /* nullptr */) {
7760   if (fromKls == nullptr) {
7761     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7762     assert(tinst != nullptr, "obj is null");
7763     assert(tinst->is_loaded(), "obj is not loaded");
7764     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7765     fromKls = tinst->instance_klass();
7766   }
7767   else {
7768     assert(is_static, "only for static field access");
7769   }
7770   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7771     ciSymbol::make(fieldTypeString),
7772     is_static);
7773 
7774   assert(field != nullptr, "undefined field");
7775   assert(!field->is_volatile(), "not defined for volatile fields");
7776 
7777   if (is_static) {
7778     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7779     fromObj = makecon(tip);
7780   }
7781 
7782   // Next code  copied from Parse::do_get_xxx():
7783 
7784   // Compute address and memory type.
7785   int offset = field->offset_in_bytes();
7786   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7787 
7788   return adr;
7789 }
7790 
7791 //------------------------------inline_aescrypt_Block-----------------------
7792 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7793   address stubAddr = nullptr;
7794   const char *stubName;
7795   assert(UseAES, "need AES instruction support");
7796 
7797   switch(id) {
7798   case vmIntrinsics::_aescrypt_encryptBlock:
7799     stubAddr = StubRoutines::aescrypt_encryptBlock();
7800     stubName = "aescrypt_encryptBlock";
7801     break;
7802   case vmIntrinsics::_aescrypt_decryptBlock:
7803     stubAddr = StubRoutines::aescrypt_decryptBlock();
7804     stubName = "aescrypt_decryptBlock";
7805     break;
7806   default:
7807     break;
7808   }
7809   if (stubAddr == nullptr) return false;
7810 
7811   Node* aescrypt_object = argument(0);
7812   Node* src             = argument(1);
7813   Node* src_offset      = argument(2);
7814   Node* dest            = argument(3);
7815   Node* dest_offset     = argument(4);
7816 
7817   src = must_be_not_null(src, true);
7818   dest = must_be_not_null(dest, true);
7819 
7820   // (1) src and dest are arrays.
7821   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7822   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7823   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7824          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7825 
7826   // for the quick and dirty code we will skip all the checks.
7827   // we are just trying to get the call to be generated.
7828   Node* src_start  = src;
7829   Node* dest_start = dest;
7830   if (src_offset != nullptr || dest_offset != nullptr) {
7831     assert(src_offset != nullptr && dest_offset != nullptr, "");
7832     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7833     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7834   }
7835 
7836   // now need to get the start of its expanded key array
7837   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7838   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
7839   if (k_start == nullptr) return false;
7840 
7841   // Call the stub.
7842   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
7843                     stubAddr, stubName, TypePtr::BOTTOM,
7844                     src_start, dest_start, k_start);
7845 
7846   return true;
7847 }
7848 
7849 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
7850 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
7851   address stubAddr = nullptr;
7852   const char *stubName = nullptr;
7853 
7854   assert(UseAES, "need AES instruction support");
7855 
7856   switch(id) {
7857   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
7858     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
7859     stubName = "cipherBlockChaining_encryptAESCrypt";
7860     break;
7861   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
7862     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
7863     stubName = "cipherBlockChaining_decryptAESCrypt";
7864     break;
7865   default:
7866     break;
7867   }
7868   if (stubAddr == nullptr) return false;
7869 
7870   Node* cipherBlockChaining_object = argument(0);
7871   Node* src                        = argument(1);
7872   Node* src_offset                 = argument(2);
7873   Node* len                        = argument(3);
7874   Node* dest                       = argument(4);
7875   Node* dest_offset                = argument(5);
7876 
7877   src = must_be_not_null(src, false);
7878   dest = must_be_not_null(dest, false);
7879 
7880   // (1) src and dest are arrays.
7881   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7882   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7883   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7884          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7885 
7886   // checks are the responsibility of the caller
7887   Node* src_start  = src;
7888   Node* dest_start = dest;
7889   if (src_offset != nullptr || dest_offset != nullptr) {
7890     assert(src_offset != nullptr && dest_offset != nullptr, "");
7891     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7892     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7893   }
7894 
7895   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7896   // (because of the predicated logic executed earlier).
7897   // so we cast it here safely.
7898   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7899 
7900   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7901   if (embeddedCipherObj == nullptr) return false;
7902 
7903   // cast it to what we know it will be at runtime
7904   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
7905   assert(tinst != nullptr, "CBC obj is null");
7906   assert(tinst->is_loaded(), "CBC obj is not loaded");
7907   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
7908   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7909 
7910   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7911   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7912   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7913   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7914   aescrypt_object = _gvn.transform(aescrypt_object);
7915 
7916   // we need to get the start of the aescrypt_object's expanded key array
7917   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
7918   if (k_start == nullptr) return false;
7919 
7920   // similarly, get the start address of the r vector
7921   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
7922   if (objRvec == nullptr) return false;
7923   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
7924 
7925   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7926   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
7927                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
7928                                      stubAddr, stubName, TypePtr::BOTTOM,
7929                                      src_start, dest_start, k_start, r_start, len);
7930 
7931   // return cipher length (int)
7932   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
7933   set_result(retvalue);
7934   return true;
7935 }
7936 
7937 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
7938 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
7939   address stubAddr = nullptr;
7940   const char *stubName = nullptr;
7941 
7942   assert(UseAES, "need AES instruction support");
7943 
7944   switch (id) {
7945   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
7946     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
7947     stubName = "electronicCodeBook_encryptAESCrypt";
7948     break;
7949   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
7950     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
7951     stubName = "electronicCodeBook_decryptAESCrypt";
7952     break;
7953   default:
7954     break;
7955   }
7956 
7957   if (stubAddr == nullptr) return false;
7958 
7959   Node* electronicCodeBook_object = argument(0);
7960   Node* src                       = argument(1);
7961   Node* src_offset                = argument(2);
7962   Node* len                       = argument(3);
7963   Node* dest                      = argument(4);
7964   Node* dest_offset               = argument(5);
7965 
7966   // (1) src and dest are arrays.
7967   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7968   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7969   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7970          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7971 
7972   // checks are the responsibility of the caller
7973   Node* src_start = src;
7974   Node* dest_start = dest;
7975   if (src_offset != nullptr || dest_offset != nullptr) {
7976     assert(src_offset != nullptr && dest_offset != nullptr, "");
7977     src_start = array_element_address(src, src_offset, T_BYTE);
7978     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7979   }
7980 
7981   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7982   // (because of the predicated logic executed earlier).
7983   // so we cast it here safely.
7984   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7985 
7986   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7987   if (embeddedCipherObj == nullptr) return false;
7988 
7989   // cast it to what we know it will be at runtime
7990   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
7991   assert(tinst != nullptr, "ECB obj is null");
7992   assert(tinst->is_loaded(), "ECB obj is not loaded");
7993   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
7994   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7995 
7996   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7997   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7998   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7999   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8000   aescrypt_object = _gvn.transform(aescrypt_object);
8001 
8002   // we need to get the start of the aescrypt_object's expanded key array
8003   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
8004   if (k_start == nullptr) return false;
8005 
8006   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8007   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8008                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
8009                                      stubAddr, stubName, TypePtr::BOTTOM,
8010                                      src_start, dest_start, k_start, len);
8011 
8012   // return cipher length (int)
8013   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8014   set_result(retvalue);
8015   return true;
8016 }
8017 
8018 //------------------------------inline_counterMode_AESCrypt-----------------------
8019 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8020   assert(UseAES, "need AES instruction support");
8021   if (!UseAESCTRIntrinsics) return false;
8022 
8023   address stubAddr = nullptr;
8024   const char *stubName = nullptr;
8025   if (id == vmIntrinsics::_counterMode_AESCrypt) {
8026     stubAddr = StubRoutines::counterMode_AESCrypt();
8027     stubName = "counterMode_AESCrypt";
8028   }
8029   if (stubAddr == nullptr) return false;
8030 
8031   Node* counterMode_object = argument(0);
8032   Node* src = argument(1);
8033   Node* src_offset = argument(2);
8034   Node* len = argument(3);
8035   Node* dest = argument(4);
8036   Node* dest_offset = argument(5);
8037 
8038   // (1) src and dest are arrays.
8039   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8040   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8041   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8042          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8043 
8044   // checks are the responsibility of the caller
8045   Node* src_start = src;
8046   Node* dest_start = dest;
8047   if (src_offset != nullptr || dest_offset != nullptr) {
8048     assert(src_offset != nullptr && dest_offset != nullptr, "");
8049     src_start = array_element_address(src, src_offset, T_BYTE);
8050     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8051   }
8052 
8053   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8054   // (because of the predicated logic executed earlier).
8055   // so we cast it here safely.
8056   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8057   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8058   if (embeddedCipherObj == nullptr) return false;
8059   // cast it to what we know it will be at runtime
8060   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8061   assert(tinst != nullptr, "CTR obj is null");
8062   assert(tinst->is_loaded(), "CTR obj is not loaded");
8063   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
8064   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8065   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8066   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8067   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8068   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8069   aescrypt_object = _gvn.transform(aescrypt_object);
8070   // we need to get the start of the aescrypt_object's expanded key array
8071   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
8072   if (k_start == nullptr) return false;
8073   // similarly, get the start address of the r vector
8074   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8075   if (obj_counter == nullptr) return false;
8076   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8077 
8078   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8079   if (saved_encCounter == nullptr) return false;
8080   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8081   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8082 
8083   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8084   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8085                                      OptoRuntime::counterMode_aescrypt_Type(),
8086                                      stubAddr, stubName, TypePtr::BOTTOM,
8087                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8088 
8089   // return cipher length (int)
8090   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8091   set_result(retvalue);
8092   return true;
8093 }
8094 
8095 //------------------------------get_key_start_from_aescrypt_object-----------------------
8096 Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
8097 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8098   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8099   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8100   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8101   // The ppc64 and riscv64 stubs of encryption and decryption use the same round keys (sessionK[0]).
8102   Node* objSessionK = load_field_from_object(aescrypt_object, "sessionK", "[[I");
8103   assert (objSessionK != nullptr, "wrong version of com.sun.crypto.provider.AESCrypt");
8104   if (objSessionK == nullptr) {
8105     return (Node *) nullptr;
8106   }
8107   Node* objAESCryptKey = load_array_element(objSessionK, intcon(0), TypeAryPtr::OOPS, /* set_ctrl */ true);
8108 #else
8109   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I");
8110 #endif // PPC64
8111   assert (objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AESCrypt");
8112   if (objAESCryptKey == nullptr) return (Node *) nullptr;
8113 
8114   // now have the array, need to get the start address of the K array
8115   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8116   return k_start;
8117 }
8118 
8119 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8120 // Return node representing slow path of predicate check.
8121 // the pseudo code we want to emulate with this predicate is:
8122 // for encryption:
8123 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8124 // for decryption:
8125 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8126 //    note cipher==plain is more conservative than the original java code but that's OK
8127 //
8128 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8129   // The receiver was checked for null already.
8130   Node* objCBC = argument(0);
8131 
8132   Node* src = argument(1);
8133   Node* dest = argument(4);
8134 
8135   // Load embeddedCipher field of CipherBlockChaining object.
8136   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8137 
8138   // get AESCrypt klass for instanceOf check
8139   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8140   // will have same classloader as CipherBlockChaining object
8141   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8142   assert(tinst != nullptr, "CBCobj is null");
8143   assert(tinst->is_loaded(), "CBCobj is not loaded");
8144 
8145   // we want to do an instanceof comparison against the AESCrypt class
8146   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
8147   if (!klass_AESCrypt->is_loaded()) {
8148     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8149     Node* ctrl = control();
8150     set_control(top()); // no regular fast path
8151     return ctrl;
8152   }
8153 
8154   src = must_be_not_null(src, true);
8155   dest = must_be_not_null(dest, true);
8156 
8157   // Resolve oops to stable for CmpP below.
8158   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8159 
8160   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8161   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
8162   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8163 
8164   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8165 
8166   // for encryption, we are done
8167   if (!decrypting)
8168     return instof_false;  // even if it is null
8169 
8170   // for decryption, we need to add a further check to avoid
8171   // taking the intrinsic path when cipher and plain are the same
8172   // see the original java code for why.
8173   RegionNode* region = new RegionNode(3);
8174   region->init_req(1, instof_false);
8175 
8176   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8177   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8178   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8179   region->init_req(2, src_dest_conjoint);
8180 
8181   record_for_igvn(region);
8182   return _gvn.transform(region);
8183 }
8184 
8185 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8186 // Return node representing slow path of predicate check.
8187 // the pseudo code we want to emulate with this predicate is:
8188 // for encryption:
8189 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8190 // for decryption:
8191 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8192 //    note cipher==plain is more conservative than the original java code but that's OK
8193 //
8194 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8195   // The receiver was checked for null already.
8196   Node* objECB = argument(0);
8197 
8198   // Load embeddedCipher field of ElectronicCodeBook object.
8199   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8200 
8201   // get AESCrypt klass for instanceOf check
8202   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8203   // will have same classloader as ElectronicCodeBook object
8204   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8205   assert(tinst != nullptr, "ECBobj is null");
8206   assert(tinst->is_loaded(), "ECBobj is not loaded");
8207 
8208   // we want to do an instanceof comparison against the AESCrypt class
8209   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
8210   if (!klass_AESCrypt->is_loaded()) {
8211     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8212     Node* ctrl = control();
8213     set_control(top()); // no regular fast path
8214     return ctrl;
8215   }
8216   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8217 
8218   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8219   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8220   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8221 
8222   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8223 
8224   // for encryption, we are done
8225   if (!decrypting)
8226     return instof_false;  // even if it is null
8227 
8228   // for decryption, we need to add a further check to avoid
8229   // taking the intrinsic path when cipher and plain are the same
8230   // see the original java code for why.
8231   RegionNode* region = new RegionNode(3);
8232   region->init_req(1, instof_false);
8233   Node* src = argument(1);
8234   Node* dest = argument(4);
8235   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8236   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8237   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8238   region->init_req(2, src_dest_conjoint);
8239 
8240   record_for_igvn(region);
8241   return _gvn.transform(region);
8242 }
8243 
8244 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8245 // Return node representing slow path of predicate check.
8246 // the pseudo code we want to emulate with this predicate is:
8247 // for encryption:
8248 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8249 // for decryption:
8250 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8251 //    note cipher==plain is more conservative than the original java code but that's OK
8252 //
8253 
8254 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8255   // The receiver was checked for null already.
8256   Node* objCTR = argument(0);
8257 
8258   // Load embeddedCipher field of CipherBlockChaining object.
8259   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8260 
8261   // get AESCrypt klass for instanceOf check
8262   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8263   // will have same classloader as CipherBlockChaining object
8264   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8265   assert(tinst != nullptr, "CTRobj is null");
8266   assert(tinst->is_loaded(), "CTRobj is not loaded");
8267 
8268   // we want to do an instanceof comparison against the AESCrypt class
8269   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
8270   if (!klass_AESCrypt->is_loaded()) {
8271     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8272     Node* ctrl = control();
8273     set_control(top()); // no regular fast path
8274     return ctrl;
8275   }
8276 
8277   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8278   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8279   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8280   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8281   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8282 
8283   return instof_false; // even if it is null
8284 }
8285 
8286 //------------------------------inline_ghash_processBlocks
8287 bool LibraryCallKit::inline_ghash_processBlocks() {
8288   address stubAddr;
8289   const char *stubName;
8290   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8291 
8292   stubAddr = StubRoutines::ghash_processBlocks();
8293   stubName = "ghash_processBlocks";
8294 
8295   Node* data           = argument(0);
8296   Node* offset         = argument(1);
8297   Node* len            = argument(2);
8298   Node* state          = argument(3);
8299   Node* subkeyH        = argument(4);
8300 
8301   state = must_be_not_null(state, true);
8302   subkeyH = must_be_not_null(subkeyH, true);
8303   data = must_be_not_null(data, true);
8304 
8305   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
8306   assert(state_start, "state is null");
8307   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
8308   assert(subkeyH_start, "subkeyH is null");
8309   Node* data_start  = array_element_address(data, offset, T_BYTE);
8310   assert(data_start, "data is null");
8311 
8312   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8313                                   OptoRuntime::ghash_processBlocks_Type(),
8314                                   stubAddr, stubName, TypePtr::BOTTOM,
8315                                   state_start, subkeyH_start, data_start, len);
8316   return true;
8317 }
8318 
8319 //------------------------------inline_chacha20Block
8320 bool LibraryCallKit::inline_chacha20Block() {
8321   address stubAddr;
8322   const char *stubName;
8323   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8324 
8325   stubAddr = StubRoutines::chacha20Block();
8326   stubName = "chacha20Block";
8327 
8328   Node* state          = argument(0);
8329   Node* result         = argument(1);
8330 
8331   state = must_be_not_null(state, true);
8332   result = must_be_not_null(result, true);
8333 
8334   Node* state_start  = array_element_address(state, intcon(0), T_INT);
8335   assert(state_start, "state is null");
8336   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
8337   assert(result_start, "result is null");
8338 
8339   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8340                                   OptoRuntime::chacha20Block_Type(),
8341                                   stubAddr, stubName, TypePtr::BOTTOM,
8342                                   state_start, result_start);
8343   // return key stream length (int)
8344   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8345   set_result(retvalue);
8346   return true;
8347 }
8348 
8349 //------------------------------inline_kyberNtt
8350 bool LibraryCallKit::inline_kyberNtt() {
8351   address stubAddr;
8352   const char *stubName;
8353   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8354   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8355 
8356   stubAddr = StubRoutines::kyberNtt();
8357   stubName = "kyberNtt";
8358   if (!stubAddr) return false;
8359 
8360   Node* coeffs          = argument(0);
8361   Node* ntt_zetas        = argument(1);
8362 
8363   coeffs = must_be_not_null(coeffs, true);
8364   ntt_zetas = must_be_not_null(ntt_zetas, true);
8365 
8366   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8367   assert(coeffs_start, "coeffs is null");
8368   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8369   assert(ntt_zetas_start, "ntt_zetas is null");
8370   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8371                                   OptoRuntime::kyberNtt_Type(),
8372                                   stubAddr, stubName, TypePtr::BOTTOM,
8373                                   coeffs_start, ntt_zetas_start);
8374   // return an int
8375   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8376   set_result(retvalue);
8377   return true;
8378 }
8379 
8380 //------------------------------inline_kyberInverseNtt
8381 bool LibraryCallKit::inline_kyberInverseNtt() {
8382   address stubAddr;
8383   const char *stubName;
8384   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8385   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8386 
8387   stubAddr = StubRoutines::kyberInverseNtt();
8388   stubName = "kyberInverseNtt";
8389   if (!stubAddr) return false;
8390 
8391   Node* coeffs          = argument(0);
8392   Node* zetas           = argument(1);
8393 
8394   coeffs = must_be_not_null(coeffs, true);
8395   zetas = must_be_not_null(zetas, true);
8396 
8397   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8398   assert(coeffs_start, "coeffs is null");
8399   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8400   assert(zetas_start, "inverseNtt_zetas is null");
8401   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8402                                   OptoRuntime::kyberInverseNtt_Type(),
8403                                   stubAddr, stubName, TypePtr::BOTTOM,
8404                                   coeffs_start, zetas_start);
8405 
8406   // return an int
8407   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8408   set_result(retvalue);
8409   return true;
8410 }
8411 
8412 //------------------------------inline_kyberNttMult
8413 bool LibraryCallKit::inline_kyberNttMult() {
8414   address stubAddr;
8415   const char *stubName;
8416   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8417   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8418 
8419   stubAddr = StubRoutines::kyberNttMult();
8420   stubName = "kyberNttMult";
8421   if (!stubAddr) return false;
8422 
8423   Node* result          = argument(0);
8424   Node* ntta            = argument(1);
8425   Node* nttb            = argument(2);
8426   Node* zetas           = argument(3);
8427 
8428   result = must_be_not_null(result, true);
8429   ntta = must_be_not_null(ntta, true);
8430   nttb = must_be_not_null(nttb, true);
8431   zetas = must_be_not_null(zetas, true);
8432 
8433   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8434   assert(result_start, "result is null");
8435   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
8436   assert(ntta_start, "ntta is null");
8437   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
8438   assert(nttb_start, "nttb is null");
8439   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8440   assert(zetas_start, "nttMult_zetas is null");
8441   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8442                                   OptoRuntime::kyberNttMult_Type(),
8443                                   stubAddr, stubName, TypePtr::BOTTOM,
8444                                   result_start, ntta_start, nttb_start,
8445                                   zetas_start);
8446 
8447   // return an int
8448   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8449   set_result(retvalue);
8450 
8451   return true;
8452 }
8453 
8454 //------------------------------inline_kyberAddPoly_2
8455 bool LibraryCallKit::inline_kyberAddPoly_2() {
8456   address stubAddr;
8457   const char *stubName;
8458   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8459   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8460 
8461   stubAddr = StubRoutines::kyberAddPoly_2();
8462   stubName = "kyberAddPoly_2";
8463   if (!stubAddr) return false;
8464 
8465   Node* result          = argument(0);
8466   Node* a               = argument(1);
8467   Node* b               = argument(2);
8468 
8469   result = must_be_not_null(result, true);
8470   a = must_be_not_null(a, true);
8471   b = must_be_not_null(b, true);
8472 
8473   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8474   assert(result_start, "result is null");
8475   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8476   assert(a_start, "a is null");
8477   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8478   assert(b_start, "b is null");
8479   Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8480                                   OptoRuntime::kyberAddPoly_2_Type(),
8481                                   stubAddr, stubName, TypePtr::BOTTOM,
8482                                   result_start, a_start, b_start);
8483   // return an int
8484   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8485   set_result(retvalue);
8486   return true;
8487 }
8488 
8489 //------------------------------inline_kyberAddPoly_3
8490 bool LibraryCallKit::inline_kyberAddPoly_3() {
8491   address stubAddr;
8492   const char *stubName;
8493   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8494   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8495 
8496   stubAddr = StubRoutines::kyberAddPoly_3();
8497   stubName = "kyberAddPoly_3";
8498   if (!stubAddr) return false;
8499 
8500   Node* result          = argument(0);
8501   Node* a               = argument(1);
8502   Node* b               = argument(2);
8503   Node* c               = argument(3);
8504 
8505   result = must_be_not_null(result, true);
8506   a = must_be_not_null(a, true);
8507   b = must_be_not_null(b, true);
8508   c = must_be_not_null(c, true);
8509 
8510   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8511   assert(result_start, "result is null");
8512   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8513   assert(a_start, "a is null");
8514   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8515   assert(b_start, "b is null");
8516   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
8517   assert(c_start, "c is null");
8518   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8519                                   OptoRuntime::kyberAddPoly_3_Type(),
8520                                   stubAddr, stubName, TypePtr::BOTTOM,
8521                                   result_start, a_start, b_start, c_start);
8522   // return an int
8523   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8524   set_result(retvalue);
8525   return true;
8526 }
8527 
8528 //------------------------------inline_kyber12To16
8529 bool LibraryCallKit::inline_kyber12To16() {
8530   address stubAddr;
8531   const char *stubName;
8532   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8533   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8534 
8535   stubAddr = StubRoutines::kyber12To16();
8536   stubName = "kyber12To16";
8537   if (!stubAddr) return false;
8538 
8539   Node* condensed       = argument(0);
8540   Node* condensedOffs   = argument(1);
8541   Node* parsed          = argument(2);
8542   Node* parsedLength    = argument(3);
8543 
8544   condensed = must_be_not_null(condensed, true);
8545   parsed = must_be_not_null(parsed, true);
8546 
8547   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
8548   assert(condensed_start, "condensed is null");
8549   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
8550   assert(parsed_start, "parsed is null");
8551   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8552                                   OptoRuntime::kyber12To16_Type(),
8553                                   stubAddr, stubName, TypePtr::BOTTOM,
8554                                   condensed_start, condensedOffs, parsed_start, parsedLength);
8555   // return an int
8556   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8557   set_result(retvalue);
8558   return true;
8559 
8560 }
8561 
8562 //------------------------------inline_kyberBarrettReduce
8563 bool LibraryCallKit::inline_kyberBarrettReduce() {
8564   address stubAddr;
8565   const char *stubName;
8566   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8567   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8568 
8569   stubAddr = StubRoutines::kyberBarrettReduce();
8570   stubName = "kyberBarrettReduce";
8571   if (!stubAddr) return false;
8572 
8573   Node* coeffs          = argument(0);
8574 
8575   coeffs = must_be_not_null(coeffs, true);
8576 
8577   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8578   assert(coeffs_start, "coeffs is null");
8579   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8580                                   OptoRuntime::kyberBarrettReduce_Type(),
8581                                   stubAddr, stubName, TypePtr::BOTTOM,
8582                                   coeffs_start);
8583   // return an int
8584   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8585   set_result(retvalue);
8586   return true;
8587 }
8588 
8589 //------------------------------inline_dilithiumAlmostNtt
8590 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8591   address stubAddr;
8592   const char *stubName;
8593   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8594   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8595 
8596   stubAddr = StubRoutines::dilithiumAlmostNtt();
8597   stubName = "dilithiumAlmostNtt";
8598   if (!stubAddr) return false;
8599 
8600   Node* coeffs          = argument(0);
8601   Node* ntt_zetas        = argument(1);
8602 
8603   coeffs = must_be_not_null(coeffs, true);
8604   ntt_zetas = must_be_not_null(ntt_zetas, true);
8605 
8606   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8607   assert(coeffs_start, "coeffs is null");
8608   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
8609   assert(ntt_zetas_start, "ntt_zetas is null");
8610   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8611                                   OptoRuntime::dilithiumAlmostNtt_Type(),
8612                                   stubAddr, stubName, TypePtr::BOTTOM,
8613                                   coeffs_start, ntt_zetas_start);
8614   // return an int
8615   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8616   set_result(retvalue);
8617   return true;
8618 }
8619 
8620 //------------------------------inline_dilithiumAlmostInverseNtt
8621 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8622   address stubAddr;
8623   const char *stubName;
8624   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8625   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8626 
8627   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8628   stubName = "dilithiumAlmostInverseNtt";
8629   if (!stubAddr) return false;
8630 
8631   Node* coeffs          = argument(0);
8632   Node* zetas           = argument(1);
8633 
8634   coeffs = must_be_not_null(coeffs, true);
8635   zetas = must_be_not_null(zetas, true);
8636 
8637   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8638   assert(coeffs_start, "coeffs is null");
8639   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
8640   assert(zetas_start, "inverseNtt_zetas is null");
8641   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8642                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8643                                   stubAddr, stubName, TypePtr::BOTTOM,
8644                                   coeffs_start, zetas_start);
8645   // return an int
8646   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8647   set_result(retvalue);
8648   return true;
8649 }
8650 
8651 //------------------------------inline_dilithiumNttMult
8652 bool LibraryCallKit::inline_dilithiumNttMult() {
8653   address stubAddr;
8654   const char *stubName;
8655   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8656   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8657 
8658   stubAddr = StubRoutines::dilithiumNttMult();
8659   stubName = "dilithiumNttMult";
8660   if (!stubAddr) return false;
8661 
8662   Node* result          = argument(0);
8663   Node* ntta            = argument(1);
8664   Node* nttb            = argument(2);
8665   Node* zetas           = argument(3);
8666 
8667   result = must_be_not_null(result, true);
8668   ntta = must_be_not_null(ntta, true);
8669   nttb = must_be_not_null(nttb, true);
8670   zetas = must_be_not_null(zetas, true);
8671 
8672   Node* result_start  = array_element_address(result, intcon(0), T_INT);
8673   assert(result_start, "result is null");
8674   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
8675   assert(ntta_start, "ntta is null");
8676   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
8677   assert(nttb_start, "nttb is null");
8678   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8679                                   OptoRuntime::dilithiumNttMult_Type(),
8680                                   stubAddr, stubName, TypePtr::BOTTOM,
8681                                   result_start, ntta_start, nttb_start);
8682 
8683   // return an int
8684   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8685   set_result(retvalue);
8686 
8687   return true;
8688 }
8689 
8690 //------------------------------inline_dilithiumMontMulByConstant
8691 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8692   address stubAddr;
8693   const char *stubName;
8694   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8695   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8696 
8697   stubAddr = StubRoutines::dilithiumMontMulByConstant();
8698   stubName = "dilithiumMontMulByConstant";
8699   if (!stubAddr) return false;
8700 
8701   Node* coeffs          = argument(0);
8702   Node* constant        = argument(1);
8703 
8704   coeffs = must_be_not_null(coeffs, true);
8705 
8706   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8707   assert(coeffs_start, "coeffs is null");
8708   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8709                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
8710                                   stubAddr, stubName, TypePtr::BOTTOM,
8711                                   coeffs_start, constant);
8712 
8713   // return an int
8714   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8715   set_result(retvalue);
8716   return true;
8717 }
8718 
8719 
8720 //------------------------------inline_dilithiumDecomposePoly
8721 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8722   address stubAddr;
8723   const char *stubName;
8724   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8725   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8726 
8727   stubAddr = StubRoutines::dilithiumDecomposePoly();
8728   stubName = "dilithiumDecomposePoly";
8729   if (!stubAddr) return false;
8730 
8731   Node* input          = argument(0);
8732   Node* lowPart        = argument(1);
8733   Node* highPart       = argument(2);
8734   Node* twoGamma2      = argument(3);
8735   Node* multiplier     = argument(4);
8736 
8737   input = must_be_not_null(input, true);
8738   lowPart = must_be_not_null(lowPart, true);
8739   highPart = must_be_not_null(highPart, true);
8740 
8741   Node* input_start  = array_element_address(input, intcon(0), T_INT);
8742   assert(input_start, "input is null");
8743   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
8744   assert(lowPart_start, "lowPart is null");
8745   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
8746   assert(highPart_start, "highPart is null");
8747 
8748   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8749                                   OptoRuntime::dilithiumDecomposePoly_Type(),
8750                                   stubAddr, stubName, TypePtr::BOTTOM,
8751                                   input_start, lowPart_start, highPart_start,
8752                                   twoGamma2, multiplier);
8753 
8754   // return an int
8755   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8756   set_result(retvalue);
8757   return true;
8758 }
8759 
8760 bool LibraryCallKit::inline_base64_encodeBlock() {
8761   address stubAddr;
8762   const char *stubName;
8763   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8764   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8765   stubAddr = StubRoutines::base64_encodeBlock();
8766   stubName = "encodeBlock";
8767 
8768   if (!stubAddr) return false;
8769   Node* base64obj = argument(0);
8770   Node* src = argument(1);
8771   Node* offset = argument(2);
8772   Node* len = argument(3);
8773   Node* dest = argument(4);
8774   Node* dp = argument(5);
8775   Node* isURL = argument(6);
8776 
8777   src = must_be_not_null(src, true);
8778   dest = must_be_not_null(dest, true);
8779 
8780   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8781   assert(src_start, "source array is null");
8782   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8783   assert(dest_start, "destination array is null");
8784 
8785   Node* base64 = make_runtime_call(RC_LEAF,
8786                                    OptoRuntime::base64_encodeBlock_Type(),
8787                                    stubAddr, stubName, TypePtr::BOTTOM,
8788                                    src_start, offset, len, dest_start, dp, isURL);
8789   return true;
8790 }
8791 
8792 bool LibraryCallKit::inline_base64_decodeBlock() {
8793   address stubAddr;
8794   const char *stubName;
8795   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8796   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8797   stubAddr = StubRoutines::base64_decodeBlock();
8798   stubName = "decodeBlock";
8799 
8800   if (!stubAddr) return false;
8801   Node* base64obj = argument(0);
8802   Node* src = argument(1);
8803   Node* src_offset = argument(2);
8804   Node* len = argument(3);
8805   Node* dest = argument(4);
8806   Node* dest_offset = argument(5);
8807   Node* isURL = argument(6);
8808   Node* isMIME = argument(7);
8809 
8810   src = must_be_not_null(src, true);
8811   dest = must_be_not_null(dest, true);
8812 
8813   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8814   assert(src_start, "source array is null");
8815   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8816   assert(dest_start, "destination array is null");
8817 
8818   Node* call = make_runtime_call(RC_LEAF,
8819                                  OptoRuntime::base64_decodeBlock_Type(),
8820                                  stubAddr, stubName, TypePtr::BOTTOM,
8821                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
8822   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8823   set_result(result);
8824   return true;
8825 }
8826 
8827 bool LibraryCallKit::inline_poly1305_processBlocks() {
8828   address stubAddr;
8829   const char *stubName;
8830   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
8831   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
8832   stubAddr = StubRoutines::poly1305_processBlocks();
8833   stubName = "poly1305_processBlocks";
8834 
8835   if (!stubAddr) return false;
8836   null_check_receiver();  // null-check receiver
8837   if (stopped())  return true;
8838 
8839   Node* input = argument(1);
8840   Node* input_offset = argument(2);
8841   Node* len = argument(3);
8842   Node* alimbs = argument(4);
8843   Node* rlimbs = argument(5);
8844 
8845   input = must_be_not_null(input, true);
8846   alimbs = must_be_not_null(alimbs, true);
8847   rlimbs = must_be_not_null(rlimbs, true);
8848 
8849   Node* input_start = array_element_address(input, input_offset, T_BYTE);
8850   assert(input_start, "input array is null");
8851   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
8852   assert(acc_start, "acc array is null");
8853   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
8854   assert(r_start, "r array is null");
8855 
8856   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8857                                  OptoRuntime::poly1305_processBlocks_Type(),
8858                                  stubAddr, stubName, TypePtr::BOTTOM,
8859                                  input_start, len, acc_start, r_start);
8860   return true;
8861 }
8862 
8863 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
8864   address stubAddr;
8865   const char *stubName;
8866   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8867   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
8868   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
8869   stubName = "intpoly_montgomeryMult_P256";
8870 
8871   if (!stubAddr) return false;
8872   null_check_receiver();  // null-check receiver
8873   if (stopped())  return true;
8874 
8875   Node* a = argument(1);
8876   Node* b = argument(2);
8877   Node* r = argument(3);
8878 
8879   a = must_be_not_null(a, true);
8880   b = must_be_not_null(b, true);
8881   r = must_be_not_null(r, true);
8882 
8883   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8884   assert(a_start, "a array is null");
8885   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8886   assert(b_start, "b array is null");
8887   Node* r_start = array_element_address(r, intcon(0), T_LONG);
8888   assert(r_start, "r array is null");
8889 
8890   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8891                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
8892                                  stubAddr, stubName, TypePtr::BOTTOM,
8893                                  a_start, b_start, r_start);
8894   return true;
8895 }
8896 
8897 bool LibraryCallKit::inline_intpoly_assign() {
8898   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8899   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
8900   const char *stubName = "intpoly_assign";
8901   address stubAddr = StubRoutines::intpoly_assign();
8902   if (!stubAddr) return false;
8903 
8904   Node* set = argument(0);
8905   Node* a = argument(1);
8906   Node* b = argument(2);
8907   Node* arr_length = load_array_length(a);
8908 
8909   a = must_be_not_null(a, true);
8910   b = must_be_not_null(b, true);
8911 
8912   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8913   assert(a_start, "a array is null");
8914   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8915   assert(b_start, "b array is null");
8916 
8917   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8918                                  OptoRuntime::intpoly_assign_Type(),
8919                                  stubAddr, stubName, TypePtr::BOTTOM,
8920                                  set, a_start, b_start, arr_length);
8921   return true;
8922 }
8923 
8924 //------------------------------inline_digestBase_implCompress-----------------------
8925 //
8926 // Calculate MD5 for single-block byte[] array.
8927 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
8928 //
8929 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
8930 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
8931 //
8932 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
8933 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
8934 //
8935 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
8936 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
8937 //
8938 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
8939 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
8940 //
8941 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
8942   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
8943 
8944   Node* digestBase_obj = argument(0);
8945   Node* src            = argument(1); // type oop
8946   Node* ofs            = argument(2); // type int
8947 
8948   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8949   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
8950     // failed array check
8951     return false;
8952   }
8953   // Figure out the size and type of the elements we will be copying.
8954   BasicType src_elem = src_type->elem()->array_element_basic_type();
8955   if (src_elem != T_BYTE) {
8956     return false;
8957   }
8958   // 'src_start' points to src array + offset
8959   src = must_be_not_null(src, true);
8960   Node* src_start = array_element_address(src, ofs, src_elem);
8961   Node* state = nullptr;
8962   Node* block_size = nullptr;
8963   address stubAddr;
8964   const char *stubName;
8965 
8966   switch(id) {
8967   case vmIntrinsics::_md5_implCompress:
8968     assert(UseMD5Intrinsics, "need MD5 instruction support");
8969     state = get_state_from_digest_object(digestBase_obj, T_INT);
8970     stubAddr = StubRoutines::md5_implCompress();
8971     stubName = "md5_implCompress";
8972     break;
8973   case vmIntrinsics::_sha_implCompress:
8974     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
8975     state = get_state_from_digest_object(digestBase_obj, T_INT);
8976     stubAddr = StubRoutines::sha1_implCompress();
8977     stubName = "sha1_implCompress";
8978     break;
8979   case vmIntrinsics::_sha2_implCompress:
8980     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
8981     state = get_state_from_digest_object(digestBase_obj, T_INT);
8982     stubAddr = StubRoutines::sha256_implCompress();
8983     stubName = "sha256_implCompress";
8984     break;
8985   case vmIntrinsics::_sha5_implCompress:
8986     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
8987     state = get_state_from_digest_object(digestBase_obj, T_LONG);
8988     stubAddr = StubRoutines::sha512_implCompress();
8989     stubName = "sha512_implCompress";
8990     break;
8991   case vmIntrinsics::_sha3_implCompress:
8992     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
8993     state = get_state_from_digest_object(digestBase_obj, T_LONG);
8994     stubAddr = StubRoutines::sha3_implCompress();
8995     stubName = "sha3_implCompress";
8996     block_size = get_block_size_from_digest_object(digestBase_obj);
8997     if (block_size == nullptr) return false;
8998     break;
8999   default:
9000     fatal_unexpected_iid(id);
9001     return false;
9002   }
9003   if (state == nullptr) return false;
9004 
9005   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9006   if (stubAddr == nullptr) return false;
9007 
9008   // Call the stub.
9009   Node* call;
9010   if (block_size == nullptr) {
9011     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9012                              stubAddr, stubName, TypePtr::BOTTOM,
9013                              src_start, state);
9014   } else {
9015     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9016                              stubAddr, stubName, TypePtr::BOTTOM,
9017                              src_start, state, block_size);
9018   }
9019 
9020   return true;
9021 }
9022 
9023 //------------------------------inline_double_keccak
9024 bool LibraryCallKit::inline_double_keccak() {
9025   address stubAddr;
9026   const char *stubName;
9027   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9028   assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
9029 
9030   stubAddr = StubRoutines::double_keccak();
9031   stubName = "double_keccak";
9032   if (!stubAddr) return false;
9033 
9034   Node* status0        = argument(0);
9035   Node* status1        = argument(1);
9036 
9037   status0 = must_be_not_null(status0, true);
9038   status1 = must_be_not_null(status1, true);
9039 
9040   Node* status0_start  = array_element_address(status0, intcon(0), T_LONG);
9041   assert(status0_start, "status0 is null");
9042   Node* status1_start  = array_element_address(status1, intcon(0), T_LONG);
9043   assert(status1_start, "status1 is null");
9044   Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9045                                   OptoRuntime::double_keccak_Type(),
9046                                   stubAddr, stubName, TypePtr::BOTTOM,
9047                                   status0_start, status1_start);
9048   // return an int
9049   Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
9050   set_result(retvalue);
9051   return true;
9052 }
9053 
9054 
9055 //------------------------------inline_digestBase_implCompressMB-----------------------
9056 //
9057 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9058 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9059 //
9060 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9061   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9062          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9063   assert((uint)predicate < 5, "sanity");
9064   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9065 
9066   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9067   Node* src            = argument(1); // byte[] array
9068   Node* ofs            = argument(2); // type int
9069   Node* limit          = argument(3); // type int
9070 
9071   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9072   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9073     // failed array check
9074     return false;
9075   }
9076   // Figure out the size and type of the elements we will be copying.
9077   BasicType src_elem = src_type->elem()->array_element_basic_type();
9078   if (src_elem != T_BYTE) {
9079     return false;
9080   }
9081   // 'src_start' points to src array + offset
9082   src = must_be_not_null(src, false);
9083   Node* src_start = array_element_address(src, ofs, src_elem);
9084 
9085   const char* klass_digestBase_name = nullptr;
9086   const char* stub_name = nullptr;
9087   address     stub_addr = nullptr;
9088   BasicType elem_type = T_INT;
9089 
9090   switch (predicate) {
9091   case 0:
9092     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9093       klass_digestBase_name = "sun/security/provider/MD5";
9094       stub_name = "md5_implCompressMB";
9095       stub_addr = StubRoutines::md5_implCompressMB();
9096     }
9097     break;
9098   case 1:
9099     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9100       klass_digestBase_name = "sun/security/provider/SHA";
9101       stub_name = "sha1_implCompressMB";
9102       stub_addr = StubRoutines::sha1_implCompressMB();
9103     }
9104     break;
9105   case 2:
9106     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9107       klass_digestBase_name = "sun/security/provider/SHA2";
9108       stub_name = "sha256_implCompressMB";
9109       stub_addr = StubRoutines::sha256_implCompressMB();
9110     }
9111     break;
9112   case 3:
9113     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9114       klass_digestBase_name = "sun/security/provider/SHA5";
9115       stub_name = "sha512_implCompressMB";
9116       stub_addr = StubRoutines::sha512_implCompressMB();
9117       elem_type = T_LONG;
9118     }
9119     break;
9120   case 4:
9121     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9122       klass_digestBase_name = "sun/security/provider/SHA3";
9123       stub_name = "sha3_implCompressMB";
9124       stub_addr = StubRoutines::sha3_implCompressMB();
9125       elem_type = T_LONG;
9126     }
9127     break;
9128   default:
9129     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9130   }
9131   if (klass_digestBase_name != nullptr) {
9132     assert(stub_addr != nullptr, "Stub is generated");
9133     if (stub_addr == nullptr) return false;
9134 
9135     // get DigestBase klass to lookup for SHA klass
9136     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9137     assert(tinst != nullptr, "digestBase_obj is not instance???");
9138     assert(tinst->is_loaded(), "DigestBase is not loaded");
9139 
9140     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9141     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9142     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9143     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9144   }
9145   return false;
9146 }
9147 
9148 //------------------------------inline_digestBase_implCompressMB-----------------------
9149 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9150                                                       BasicType elem_type, address stubAddr, const char *stubName,
9151                                                       Node* src_start, Node* ofs, Node* limit) {
9152   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9153   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9154   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9155   digest_obj = _gvn.transform(digest_obj);
9156 
9157   Node* state = get_state_from_digest_object(digest_obj, elem_type);
9158   if (state == nullptr) return false;
9159 
9160   Node* block_size = nullptr;
9161   if (strcmp("sha3_implCompressMB", stubName) == 0) {
9162     block_size = get_block_size_from_digest_object(digest_obj);
9163     if (block_size == nullptr) return false;
9164   }
9165 
9166   // Call the stub.
9167   Node* call;
9168   if (block_size == nullptr) {
9169     call = make_runtime_call(RC_LEAF|RC_NO_FP,
9170                              OptoRuntime::digestBase_implCompressMB_Type(false),
9171                              stubAddr, stubName, TypePtr::BOTTOM,
9172                              src_start, state, ofs, limit);
9173   } else {
9174      call = make_runtime_call(RC_LEAF|RC_NO_FP,
9175                              OptoRuntime::digestBase_implCompressMB_Type(true),
9176                              stubAddr, stubName, TypePtr::BOTTOM,
9177                              src_start, state, block_size, ofs, limit);
9178   }
9179 
9180   // return ofs (int)
9181   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9182   set_result(result);
9183 
9184   return true;
9185 }
9186 
9187 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9188 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9189   assert(UseAES, "need AES instruction support");
9190   address stubAddr = nullptr;
9191   const char *stubName = nullptr;
9192   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9193   stubName = "galoisCounterMode_AESCrypt";
9194 
9195   if (stubAddr == nullptr) return false;
9196 
9197   Node* in      = argument(0);
9198   Node* inOfs   = argument(1);
9199   Node* len     = argument(2);
9200   Node* ct      = argument(3);
9201   Node* ctOfs   = argument(4);
9202   Node* out     = argument(5);
9203   Node* outOfs  = argument(6);
9204   Node* gctr_object = argument(7);
9205   Node* ghash_object = argument(8);
9206 
9207   // (1) in, ct and out are arrays.
9208   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9209   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9210   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9211   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
9212           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
9213          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9214 
9215   // checks are the responsibility of the caller
9216   Node* in_start = in;
9217   Node* ct_start = ct;
9218   Node* out_start = out;
9219   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9220     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9221     in_start = array_element_address(in, inOfs, T_BYTE);
9222     ct_start = array_element_address(ct, ctOfs, T_BYTE);
9223     out_start = array_element_address(out, outOfs, T_BYTE);
9224   }
9225 
9226   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9227   // (because of the predicated logic executed earlier).
9228   // so we cast it here safely.
9229   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9230   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9231   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9232   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9233   Node* state = load_field_from_object(ghash_object, "state", "[J");
9234 
9235   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9236     return false;
9237   }
9238   // cast it to what we know it will be at runtime
9239   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9240   assert(tinst != nullptr, "GCTR obj is null");
9241   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9242   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
9243   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9244   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9245   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9246   const TypeOopPtr* xtype = aklass->as_instance_type();
9247   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9248   aescrypt_object = _gvn.transform(aescrypt_object);
9249   // we need to get the start of the aescrypt_object's expanded key array
9250   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
9251   if (k_start == nullptr) return false;
9252   // similarly, get the start address of the r vector
9253   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9254   Node* state_start = array_element_address(state, intcon(0), T_LONG);
9255   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9256 
9257 
9258   // Call the stub, passing params
9259   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9260                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
9261                                stubAddr, stubName, TypePtr::BOTTOM,
9262                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9263 
9264   // return cipher length (int)
9265   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9266   set_result(retvalue);
9267 
9268   return true;
9269 }
9270 
9271 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9272 // Return node representing slow path of predicate check.
9273 // the pseudo code we want to emulate with this predicate is:
9274 // for encryption:
9275 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9276 // for decryption:
9277 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9278 //    note cipher==plain is more conservative than the original java code but that's OK
9279 //
9280 
9281 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9282   // The receiver was checked for null already.
9283   Node* objGCTR = argument(7);
9284   // Load embeddedCipher field of GCTR object.
9285   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9286   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9287 
9288   // get AESCrypt klass for instanceOf check
9289   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9290   // will have same classloader as CipherBlockChaining object
9291   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9292   assert(tinst != nullptr, "GCTR obj is null");
9293   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9294 
9295   // we want to do an instanceof comparison against the AESCrypt class
9296   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
9297   if (!klass_AESCrypt->is_loaded()) {
9298     // if AESCrypt is not even loaded, we never take the intrinsic fast path
9299     Node* ctrl = control();
9300     set_control(top()); // no regular fast path
9301     return ctrl;
9302   }
9303 
9304   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9305   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9306   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9307   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9308   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9309 
9310   return instof_false; // even if it is null
9311 }
9312 
9313 //------------------------------get_state_from_digest_object-----------------------
9314 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9315   const char* state_type;
9316   switch (elem_type) {
9317     case T_BYTE: state_type = "[B"; break;
9318     case T_INT:  state_type = "[I"; break;
9319     case T_LONG: state_type = "[J"; break;
9320     default: ShouldNotReachHere();
9321   }
9322   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9323   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9324   if (digest_state == nullptr) return (Node *) nullptr;
9325 
9326   // now have the array, need to get the start address of the state array
9327   Node* state = array_element_address(digest_state, intcon(0), elem_type);
9328   return state;
9329 }
9330 
9331 //------------------------------get_block_size_from_sha3_object----------------------------------
9332 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9333   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9334   assert (block_size != nullptr, "sanity");
9335   return block_size;
9336 }
9337 
9338 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9339 // Return node representing slow path of predicate check.
9340 // the pseudo code we want to emulate with this predicate is:
9341 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9342 //
9343 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9344   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9345          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9346   assert((uint)predicate < 5, "sanity");
9347 
9348   // The receiver was checked for null already.
9349   Node* digestBaseObj = argument(0);
9350 
9351   // get DigestBase klass for instanceOf check
9352   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9353   assert(tinst != nullptr, "digestBaseObj is null");
9354   assert(tinst->is_loaded(), "DigestBase is not loaded");
9355 
9356   const char* klass_name = nullptr;
9357   switch (predicate) {
9358   case 0:
9359     if (UseMD5Intrinsics) {
9360       // we want to do an instanceof comparison against the MD5 class
9361       klass_name = "sun/security/provider/MD5";
9362     }
9363     break;
9364   case 1:
9365     if (UseSHA1Intrinsics) {
9366       // we want to do an instanceof comparison against the SHA class
9367       klass_name = "sun/security/provider/SHA";
9368     }
9369     break;
9370   case 2:
9371     if (UseSHA256Intrinsics) {
9372       // we want to do an instanceof comparison against the SHA2 class
9373       klass_name = "sun/security/provider/SHA2";
9374     }
9375     break;
9376   case 3:
9377     if (UseSHA512Intrinsics) {
9378       // we want to do an instanceof comparison against the SHA5 class
9379       klass_name = "sun/security/provider/SHA5";
9380     }
9381     break;
9382   case 4:
9383     if (UseSHA3Intrinsics) {
9384       // we want to do an instanceof comparison against the SHA3 class
9385       klass_name = "sun/security/provider/SHA3";
9386     }
9387     break;
9388   default:
9389     fatal("unknown SHA intrinsic predicate: %d", predicate);
9390   }
9391 
9392   ciKlass* klass = nullptr;
9393   if (klass_name != nullptr) {
9394     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9395   }
9396   if ((klass == nullptr) || !klass->is_loaded()) {
9397     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9398     Node* ctrl = control();
9399     set_control(top()); // no intrinsic path
9400     return ctrl;
9401   }
9402   ciInstanceKlass* instklass = klass->as_instance_klass();
9403 
9404   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9405   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9406   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9407   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9408 
9409   return instof_false;  // even if it is null
9410 }
9411 
9412 //-------------inline_fma-----------------------------------
9413 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9414   Node *a = nullptr;
9415   Node *b = nullptr;
9416   Node *c = nullptr;
9417   Node* result = nullptr;
9418   switch (id) {
9419   case vmIntrinsics::_fmaD:
9420     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9421     // no receiver since it is static method
9422     a = argument(0);
9423     b = argument(2);
9424     c = argument(4);
9425     result = _gvn.transform(new FmaDNode(a, b, c));
9426     break;
9427   case vmIntrinsics::_fmaF:
9428     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9429     a = argument(0);
9430     b = argument(1);
9431     c = argument(2);
9432     result = _gvn.transform(new FmaFNode(a, b, c));
9433     break;
9434   default:
9435     fatal_unexpected_iid(id);  break;
9436   }
9437   set_result(result);
9438   return true;
9439 }
9440 
9441 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9442   // argument(0) is receiver
9443   Node* codePoint = argument(1);
9444   Node* n = nullptr;
9445 
9446   switch (id) {
9447     case vmIntrinsics::_isDigit :
9448       n = new DigitNode(control(), codePoint);
9449       break;
9450     case vmIntrinsics::_isLowerCase :
9451       n = new LowerCaseNode(control(), codePoint);
9452       break;
9453     case vmIntrinsics::_isUpperCase :
9454       n = new UpperCaseNode(control(), codePoint);
9455       break;
9456     case vmIntrinsics::_isWhitespace :
9457       n = new WhitespaceNode(control(), codePoint);
9458       break;
9459     default:
9460       fatal_unexpected_iid(id);
9461   }
9462 
9463   set_result(_gvn.transform(n));
9464   return true;
9465 }
9466 
9467 bool LibraryCallKit::inline_profileBoolean() {
9468   Node* counts = argument(1);
9469   const TypeAryPtr* ary = nullptr;
9470   ciArray* aobj = nullptr;
9471   if (counts->is_Con()
9472       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9473       && (aobj = ary->const_oop()->as_array()) != nullptr
9474       && (aobj->length() == 2)) {
9475     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9476     jint false_cnt = aobj->element_value(0).as_int();
9477     jint  true_cnt = aobj->element_value(1).as_int();
9478 
9479     if (C->log() != nullptr) {
9480       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9481                      false_cnt, true_cnt);
9482     }
9483 
9484     if (false_cnt + true_cnt == 0) {
9485       // According to profile, never executed.
9486       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9487                           Deoptimization::Action_reinterpret);
9488       return true;
9489     }
9490 
9491     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9492     // is a number of each value occurrences.
9493     Node* result = argument(0);
9494     if (false_cnt == 0 || true_cnt == 0) {
9495       // According to profile, one value has been never seen.
9496       int expected_val = (false_cnt == 0) ? 1 : 0;
9497 
9498       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9499       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9500 
9501       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9502       Node* fast_path = _gvn.transform(new IfTrueNode(check));
9503       Node* slow_path = _gvn.transform(new IfFalseNode(check));
9504 
9505       { // Slow path: uncommon trap for never seen value and then reexecute
9506         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9507         // the value has been seen at least once.
9508         PreserveJVMState pjvms(this);
9509         PreserveReexecuteState preexecs(this);
9510         jvms()->set_should_reexecute(true);
9511 
9512         set_control(slow_path);
9513         set_i_o(i_o());
9514 
9515         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9516                             Deoptimization::Action_reinterpret);
9517       }
9518       // The guard for never seen value enables sharpening of the result and
9519       // returning a constant. It allows to eliminate branches on the same value
9520       // later on.
9521       set_control(fast_path);
9522       result = intcon(expected_val);
9523     }
9524     // Stop profiling.
9525     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9526     // By replacing method body with profile data (represented as ProfileBooleanNode
9527     // on IR level) we effectively disable profiling.
9528     // It enables full speed execution once optimized code is generated.
9529     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9530     C->record_for_igvn(profile);
9531     set_result(profile);
9532     return true;
9533   } else {
9534     // Continue profiling.
9535     // Profile data isn't available at the moment. So, execute method's bytecode version.
9536     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9537     // is compiled and counters aren't available since corresponding MethodHandle
9538     // isn't a compile-time constant.
9539     return false;
9540   }
9541 }
9542 
9543 bool LibraryCallKit::inline_isCompileConstant() {
9544   Node* n = argument(0);
9545   set_result(n->is_Con() ? intcon(1) : intcon(0));
9546   return true;
9547 }
9548 
9549 //------------------------------- inline_getObjectSize --------------------------------------
9550 //
9551 // Calculate the runtime size of the object/array.
9552 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9553 //
9554 bool LibraryCallKit::inline_getObjectSize() {
9555   Node* obj = argument(3);
9556   Node* klass_node = load_object_klass(obj);
9557 
9558   jint  layout_con = Klass::_lh_neutral_value;
9559   Node* layout_val = get_layout_helper(klass_node, layout_con);
9560   int   layout_is_con = (layout_val == nullptr);
9561 
9562   if (layout_is_con) {
9563     // Layout helper is constant, can figure out things at compile time.
9564 
9565     if (Klass::layout_helper_is_instance(layout_con)) {
9566       // Instance case:  layout_con contains the size itself.
9567       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9568       set_result(size);
9569     } else {
9570       // Array case: size is round(header + element_size*arraylength).
9571       // Since arraylength is different for every array instance, we have to
9572       // compute the whole thing at runtime.
9573 
9574       Node* arr_length = load_array_length(obj);
9575 
9576       int round_mask = MinObjAlignmentInBytes - 1;
9577       int hsize  = Klass::layout_helper_header_size(layout_con);
9578       int eshift = Klass::layout_helper_log2_element_size(layout_con);
9579 
9580       if ((round_mask & ~right_n_bits(eshift)) == 0) {
9581         round_mask = 0;  // strength-reduce it if it goes away completely
9582       }
9583       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9584       Node* header_size = intcon(hsize + round_mask);
9585 
9586       Node* lengthx = ConvI2X(arr_length);
9587       Node* headerx = ConvI2X(header_size);
9588 
9589       Node* abody = lengthx;
9590       if (eshift != 0) {
9591         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9592       }
9593       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9594       if (round_mask != 0) {
9595         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9596       }
9597       size = ConvX2L(size);
9598       set_result(size);
9599     }
9600   } else {
9601     // Layout helper is not constant, need to test for array-ness at runtime.
9602 
9603     enum { _instance_path = 1, _array_path, PATH_LIMIT };
9604     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9605     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9606     record_for_igvn(result_reg);
9607 
9608     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9609     if (array_ctl != nullptr) {
9610       // Array case: size is round(header + element_size*arraylength).
9611       // Since arraylength is different for every array instance, we have to
9612       // compute the whole thing at runtime.
9613 
9614       PreserveJVMState pjvms(this);
9615       set_control(array_ctl);
9616       Node* arr_length = load_array_length(obj);
9617 
9618       int round_mask = MinObjAlignmentInBytes - 1;
9619       Node* mask = intcon(round_mask);
9620 
9621       Node* hss = intcon(Klass::_lh_header_size_shift);
9622       Node* hsm = intcon(Klass::_lh_header_size_mask);
9623       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9624       header_size = _gvn.transform(new AndINode(header_size, hsm));
9625       header_size = _gvn.transform(new AddINode(header_size, mask));
9626 
9627       // There is no need to mask or shift this value.
9628       // The semantics of LShiftINode include an implicit mask to 0x1F.
9629       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9630       Node* elem_shift = layout_val;
9631 
9632       Node* lengthx = ConvI2X(arr_length);
9633       Node* headerx = ConvI2X(header_size);
9634 
9635       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9636       Node* size = _gvn.transform(new AddXNode(headerx, abody));
9637       if (round_mask != 0) {
9638         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9639       }
9640       size = ConvX2L(size);
9641 
9642       result_reg->init_req(_array_path, control());
9643       result_val->init_req(_array_path, size);
9644     }
9645 
9646     if (!stopped()) {
9647       // Instance case: the layout helper gives us instance size almost directly,
9648       // but we need to mask out the _lh_instance_slow_path_bit.
9649       Node* size = ConvI2X(layout_val);
9650       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9651       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9652       size = _gvn.transform(new AndXNode(size, mask));
9653       size = ConvX2L(size);
9654 
9655       result_reg->init_req(_instance_path, control());
9656       result_val->init_req(_instance_path, size);
9657     }
9658 
9659     set_result(result_reg, result_val);
9660   }
9661 
9662   return true;
9663 }
9664 
9665 //------------------------------- inline_blackhole --------------------------------------
9666 //
9667 // Make sure all arguments to this node are alive.
9668 // This matches methods that were requested to be blackholed through compile commands.
9669 //
9670 bool LibraryCallKit::inline_blackhole() {
9671   assert(callee()->is_static(), "Should have been checked before: only static methods here");
9672   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9673   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9674 
9675   // Blackhole node pinches only the control, not memory. This allows
9676   // the blackhole to be pinned in the loop that computes blackholed
9677   // values, but have no other side effects, like breaking the optimizations
9678   // across the blackhole.
9679 
9680   Node* bh = _gvn.transform(new BlackholeNode(control()));
9681   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9682 
9683   // Bind call arguments as blackhole arguments to keep them alive
9684   uint nargs = callee()->arg_size();
9685   for (uint i = 0; i < nargs; i++) {
9686     bh->add_req(argument(i));
9687   }
9688 
9689   return true;
9690 }
9691 
9692 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9693   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9694   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9695     return nullptr; // box klass is not Float16
9696   }
9697 
9698   // Null check; get notnull casted pointer
9699   Node* null_ctl = top();
9700   Node* not_null_box = null_check_oop(box, &null_ctl, true);
9701   // If not_null_box is dead, only null-path is taken
9702   if (stopped()) {
9703     set_control(null_ctl);
9704     return nullptr;
9705   }
9706   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9707   const TypePtr* adr_type = C->alias_type(field)->adr_type();
9708   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9709   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9710 }
9711 
9712 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9713   PreserveReexecuteState preexecs(this);
9714   jvms()->set_should_reexecute(true);
9715 
9716   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9717   Node* klass_node = makecon(klass_type);
9718   Node* box = new_instance(klass_node);
9719 
9720   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9721   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9722 
9723   Node* field_store = _gvn.transform(access_store_at(box,
9724                                                      value_field,
9725                                                      value_adr_type,
9726                                                      value,
9727                                                      TypeInt::SHORT,
9728                                                      T_SHORT,
9729                                                      IN_HEAP));
9730   set_memory(field_store, value_adr_type);
9731   return box;
9732 }
9733 
9734 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9735   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9736       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9737     return false;
9738   }
9739 
9740   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9741   if (box_type == nullptr || box_type->const_oop() == nullptr) {
9742     return false;
9743   }
9744 
9745   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9746   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9747   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9748                                                     ciSymbols::short_signature(),
9749                                                     false);
9750   assert(field != nullptr, "");
9751 
9752   // Transformed nodes
9753   Node* fld1 = nullptr;
9754   Node* fld2 = nullptr;
9755   Node* fld3 = nullptr;
9756   switch(num_args) {
9757     case 3:
9758       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9759       if (fld3 == nullptr) {
9760         return false;
9761       }
9762       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9763     // fall-through
9764     case 2:
9765       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9766       if (fld2 == nullptr) {
9767         return false;
9768       }
9769       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9770     // fall-through
9771     case 1:
9772       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9773       if (fld1 == nullptr) {
9774         return false;
9775       }
9776       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9777       break;
9778     default: fatal("Unsupported number of arguments %d", num_args);
9779   }
9780 
9781   Node* result = nullptr;
9782   switch (id) {
9783     // Unary operations
9784     case vmIntrinsics::_sqrt_float16:
9785       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9786       break;
9787     // Ternary operations
9788     case vmIntrinsics::_fma_float16:
9789       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9790       break;
9791     default:
9792       fatal_unexpected_iid(id);
9793       break;
9794   }
9795   result = _gvn.transform(new ReinterpretHF2SNode(result));
9796   set_result(box_fp16_value(float16_box_type, field, result));
9797   return true;
9798 }
9799