1 /*
   2  * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/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/globals.hpp"
  68 #include "runtime/jniHandles.inline.hpp"
  69 #include "runtime/mountUnmountDisabler.hpp"
  70 #include "runtime/objectMonitor.hpp"
  71 #include "runtime/sharedRuntime.hpp"
  72 #include "runtime/stubRoutines.hpp"
  73 #include "utilities/globalDefinitions.hpp"
  74 #include "utilities/macros.hpp"
  75 #include "utilities/powerOfTwo.hpp"
  76 
  77 //---------------------------make_vm_intrinsic----------------------------
  78 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
  79   vmIntrinsicID id = m->intrinsic_id();
  80   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
  81 
  82   if (!m->is_loaded()) {
  83     // Do not attempt to inline unloaded methods.
  84     return nullptr;
  85   }
  86 
  87   C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
  88   bool is_available = false;
  89 
  90   {
  91     // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
  92     // the compiler must transition to '_thread_in_vm' state because both
  93     // methods access VM-internal data.
  94     VM_ENTRY_MARK;
  95     methodHandle mh(THREAD, m->get_Method());
  96     is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
  97     if (is_available && is_virtual) {
  98       is_available = vmIntrinsics::does_virtual_dispatch(id);
  99     }
 100   }
 101 
 102   if (is_available) {
 103     assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
 104     assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
 105     return new LibraryIntrinsic(m, is_virtual,
 106                                 vmIntrinsics::predicates_needed(id),
 107                                 vmIntrinsics::does_virtual_dispatch(id),
 108                                 id);
 109   } else {
 110     return nullptr;
 111   }
 112 }
 113 
 114 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
 115   LibraryCallKit kit(jvms, this);
 116   Compile* C = kit.C;
 117   int nodes = C->unique();
 118 #ifndef PRODUCT
 119   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 120     char buf[1000];
 121     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 122     tty->print_cr("Intrinsic %s", str);
 123   }
 124 #endif
 125   ciMethod* callee = kit.callee();
 126   const int bci    = kit.bci();
 127 #ifdef ASSERT
 128   Node* ctrl = kit.control();
 129 #endif
 130   // Try to inline the intrinsic.
 131   if (callee->check_intrinsic_candidate() &&
 132       kit.try_to_inline(_last_predicate)) {
 133     const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
 134                                           : "(intrinsic)";
 135     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 136     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 137     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 138     if (C->log()) {
 139       C->log()->elem("intrinsic id='%s'%s nodes='%d'",
 140                      vmIntrinsics::name_at(intrinsic_id()),
 141                      (is_virtual() ? " virtual='1'" : ""),
 142                      C->unique() - nodes);
 143     }
 144     // Push the result from the inlined method onto the stack.
 145     kit.push_result();
 146     return kit.transfer_exceptions_into_jvms();
 147   }
 148 
 149   // The intrinsic bailed out
 150   assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
 151   assert(jvms->map() == kit.map(), "Out of sync JVM state");
 152   if (jvms->has_method()) {
 153     // Not a root compile.
 154     const char* msg;
 155     if (callee->intrinsic_candidate()) {
 156       msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
 157     } else {
 158       msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
 159                          : "failed to inline (intrinsic), method not annotated";
 160     }
 161     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 162     C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
 163   } else {
 164     // Root compile
 165     ResourceMark rm;
 166     stringStream msg_stream;
 167     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 168                      vmIntrinsics::name_at(intrinsic_id()),
 169                      is_virtual() ? " (virtual)" : "", bci);
 170     const char *msg = msg_stream.freeze();
 171     log_debug(jit, inlining)("%s", msg);
 172     if (C->print_intrinsics() || C->print_inlining()) {
 173       tty->print("%s", msg);
 174     }
 175   }
 176   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 177 
 178   return nullptr;
 179 }
 180 
 181 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
 182   LibraryCallKit kit(jvms, this);
 183   Compile* C = kit.C;
 184   int nodes = C->unique();
 185   _last_predicate = predicate;
 186 #ifndef PRODUCT
 187   assert(is_predicated() && predicate < predicates_count(), "sanity");
 188   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
 189     char buf[1000];
 190     const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
 191     tty->print_cr("Predicate for intrinsic %s", str);
 192   }
 193 #endif
 194   ciMethod* callee = kit.callee();
 195   const int bci    = kit.bci();
 196 
 197   Node* slow_ctl = kit.try_to_predicate(predicate);
 198   if (!kit.failing()) {
 199     const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
 200                                           : "(intrinsic, predicate)";
 201     CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
 202     C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
 203 
 204     C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
 205     if (C->log()) {
 206       C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
 207                      vmIntrinsics::name_at(intrinsic_id()),
 208                      (is_virtual() ? " virtual='1'" : ""),
 209                      C->unique() - nodes);
 210     }
 211     return slow_ctl; // Could be null if the check folds.
 212   }
 213 
 214   // The intrinsic bailed out
 215   if (jvms->has_method()) {
 216     // Not a root compile.
 217     const char* msg = "failed to generate predicate for intrinsic";
 218     CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
 219     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 220   } else {
 221     // Root compile
 222     ResourceMark rm;
 223     stringStream msg_stream;
 224     msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
 225                      vmIntrinsics::name_at(intrinsic_id()),
 226                      is_virtual() ? " (virtual)" : "", bci);
 227     const char *msg = msg_stream.freeze();
 228     log_debug(jit, inlining)("%s", msg);
 229     C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
 230   }
 231   C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
 232   return nullptr;
 233 }
 234 
 235 bool LibraryCallKit::try_to_inline(int predicate) {
 236   // Handle symbolic names for otherwise undistinguished boolean switches:
 237   const bool is_store       = true;
 238   const bool is_compress    = true;
 239   const bool is_static      = true;
 240   const bool is_volatile    = true;
 241 
 242   if (!jvms()->has_method()) {
 243     // Root JVMState has a null method.
 244     assert(map()->memory()->Opcode() == Op_Parm, "");
 245     // Insert the memory aliasing node
 246     set_all_memory(reset_memory());
 247   }
 248   assert(merged_memory(), "");
 249 
 250   switch (intrinsic_id()) {
 251   case vmIntrinsics::_hashCode:                 return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
 252   case vmIntrinsics::_identityHashCode:         return inline_native_hashcode(/*!virtual*/ false,         is_static);
 253   case vmIntrinsics::_getClass:                 return inline_native_getClass();
 254 
 255   case vmIntrinsics::_ceil:
 256   case vmIntrinsics::_floor:
 257   case vmIntrinsics::_rint:
 258   case vmIntrinsics::_dsin:
 259   case vmIntrinsics::_dcos:
 260   case vmIntrinsics::_dtan:
 261   case vmIntrinsics::_dsinh:
 262   case vmIntrinsics::_dtanh:
 263   case vmIntrinsics::_dcbrt:
 264   case vmIntrinsics::_dabs:
 265   case vmIntrinsics::_fabs:
 266   case vmIntrinsics::_iabs:
 267   case vmIntrinsics::_labs:
 268   case vmIntrinsics::_datan2:
 269   case vmIntrinsics::_dsqrt:
 270   case vmIntrinsics::_dsqrt_strict:
 271   case vmIntrinsics::_dexp:
 272   case vmIntrinsics::_dlog:
 273   case vmIntrinsics::_dlog10:
 274   case vmIntrinsics::_dpow:
 275   case vmIntrinsics::_dcopySign:
 276   case vmIntrinsics::_fcopySign:
 277   case vmIntrinsics::_dsignum:
 278   case vmIntrinsics::_roundF:
 279   case vmIntrinsics::_roundD:
 280   case vmIntrinsics::_fsignum:                  return inline_math_native(intrinsic_id());
 281 
 282   case vmIntrinsics::_notify:
 283   case vmIntrinsics::_notifyAll:
 284     return inline_notify(intrinsic_id());
 285 
 286   case vmIntrinsics::_addExactI:                return inline_math_addExactI(false /* add */);
 287   case vmIntrinsics::_addExactL:                return inline_math_addExactL(false /* add */);
 288   case vmIntrinsics::_decrementExactI:          return inline_math_subtractExactI(true /* decrement */);
 289   case vmIntrinsics::_decrementExactL:          return inline_math_subtractExactL(true /* decrement */);
 290   case vmIntrinsics::_incrementExactI:          return inline_math_addExactI(true /* increment */);
 291   case vmIntrinsics::_incrementExactL:          return inline_math_addExactL(true /* increment */);
 292   case vmIntrinsics::_multiplyExactI:           return inline_math_multiplyExactI();
 293   case vmIntrinsics::_multiplyExactL:           return inline_math_multiplyExactL();
 294   case vmIntrinsics::_multiplyHigh:             return inline_math_multiplyHigh();
 295   case vmIntrinsics::_unsignedMultiplyHigh:     return inline_math_unsignedMultiplyHigh();
 296   case vmIntrinsics::_negateExactI:             return inline_math_negateExactI();
 297   case vmIntrinsics::_negateExactL:             return inline_math_negateExactL();
 298   case vmIntrinsics::_subtractExactI:           return inline_math_subtractExactI(false /* subtract */);
 299   case vmIntrinsics::_subtractExactL:           return inline_math_subtractExactL(false /* subtract */);
 300 
 301   case vmIntrinsics::_arraycopy:                return inline_arraycopy();
 302 
 303   case vmIntrinsics::_arraySort:                return inline_array_sort();
 304   case vmIntrinsics::_arrayPartition:           return inline_array_partition();
 305 
 306   case vmIntrinsics::_compareToL:               return inline_string_compareTo(StrIntrinsicNode::LL);
 307   case vmIntrinsics::_compareToU:               return inline_string_compareTo(StrIntrinsicNode::UU);
 308   case vmIntrinsics::_compareToLU:              return inline_string_compareTo(StrIntrinsicNode::LU);
 309   case vmIntrinsics::_compareToUL:              return inline_string_compareTo(StrIntrinsicNode::UL);
 310 
 311   case vmIntrinsics::_indexOfL:                 return inline_string_indexOf(StrIntrinsicNode::LL);
 312   case vmIntrinsics::_indexOfU:                 return inline_string_indexOf(StrIntrinsicNode::UU);
 313   case vmIntrinsics::_indexOfUL:                return inline_string_indexOf(StrIntrinsicNode::UL);
 314   case vmIntrinsics::_indexOfIL:                return inline_string_indexOfI(StrIntrinsicNode::LL);
 315   case vmIntrinsics::_indexOfIU:                return inline_string_indexOfI(StrIntrinsicNode::UU);
 316   case vmIntrinsics::_indexOfIUL:               return inline_string_indexOfI(StrIntrinsicNode::UL);
 317   case vmIntrinsics::_indexOfU_char:            return inline_string_indexOfChar(StrIntrinsicNode::U);
 318   case vmIntrinsics::_indexOfL_char:            return inline_string_indexOfChar(StrIntrinsicNode::L);
 319 
 320   case vmIntrinsics::_equalsL:                  return inline_string_equals(StrIntrinsicNode::LL);
 321 
 322   case vmIntrinsics::_vectorizedHashCode:       return inline_vectorizedHashCode();
 323 
 324   case vmIntrinsics::_toBytesStringU:           return inline_string_toBytesU();
 325   case vmIntrinsics::_getCharsStringU:          return inline_string_getCharsU();
 326   case vmIntrinsics::_getCharStringU:           return inline_string_char_access(!is_store);
 327   case vmIntrinsics::_putCharStringU:           return inline_string_char_access( is_store);
 328 
 329   case vmIntrinsics::_compressStringC:
 330   case vmIntrinsics::_compressStringB:          return inline_string_copy( is_compress);
 331   case vmIntrinsics::_inflateStringC:
 332   case vmIntrinsics::_inflateStringB:           return inline_string_copy(!is_compress);
 333 
 334   case vmIntrinsics::_getReference:             return inline_unsafe_access(!is_store, T_OBJECT,   Relaxed, false);
 335   case vmIntrinsics::_getBoolean:               return inline_unsafe_access(!is_store, T_BOOLEAN,  Relaxed, false);
 336   case vmIntrinsics::_getByte:                  return inline_unsafe_access(!is_store, T_BYTE,     Relaxed, false);
 337   case vmIntrinsics::_getShort:                 return inline_unsafe_access(!is_store, T_SHORT,    Relaxed, false);
 338   case vmIntrinsics::_getChar:                  return inline_unsafe_access(!is_store, T_CHAR,     Relaxed, false);
 339   case vmIntrinsics::_getInt:                   return inline_unsafe_access(!is_store, T_INT,      Relaxed, false);
 340   case vmIntrinsics::_getLong:                  return inline_unsafe_access(!is_store, T_LONG,     Relaxed, false);
 341   case vmIntrinsics::_getFloat:                 return inline_unsafe_access(!is_store, T_FLOAT,    Relaxed, false);
 342   case vmIntrinsics::_getDouble:                return inline_unsafe_access(!is_store, T_DOUBLE,   Relaxed, false);
 343 
 344   case vmIntrinsics::_putReference:             return inline_unsafe_access( is_store, T_OBJECT,   Relaxed, false);
 345   case vmIntrinsics::_putBoolean:               return inline_unsafe_access( is_store, T_BOOLEAN,  Relaxed, false);
 346   case vmIntrinsics::_putByte:                  return inline_unsafe_access( is_store, T_BYTE,     Relaxed, false);
 347   case vmIntrinsics::_putShort:                 return inline_unsafe_access( is_store, T_SHORT,    Relaxed, false);
 348   case vmIntrinsics::_putChar:                  return inline_unsafe_access( is_store, T_CHAR,     Relaxed, false);
 349   case vmIntrinsics::_putInt:                   return inline_unsafe_access( is_store, T_INT,      Relaxed, false);
 350   case vmIntrinsics::_putLong:                  return inline_unsafe_access( is_store, T_LONG,     Relaxed, false);
 351   case vmIntrinsics::_putFloat:                 return inline_unsafe_access( is_store, T_FLOAT,    Relaxed, false);
 352   case vmIntrinsics::_putDouble:                return inline_unsafe_access( is_store, T_DOUBLE,   Relaxed, false);
 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::_arrayInstanceBaseOffset:  return inline_arrayInstanceBaseOffset();
 487   case vmIntrinsics::_arrayInstanceIndexScale:  return inline_arrayInstanceIndexScale();
 488   case vmIntrinsics::_arrayLayout:              return inline_arrayLayout();
 489   case vmIntrinsics::_getFieldMap:              return inline_getFieldMap();
 490 
 491   case vmIntrinsics::_onSpinWait:               return inline_onspinwait();
 492 
 493   case vmIntrinsics::_currentCarrierThread:     return inline_native_currentCarrierThread();
 494   case vmIntrinsics::_currentThread:            return inline_native_currentThread();
 495   case vmIntrinsics::_setCurrentThread:         return inline_native_setCurrentThread();
 496 
 497   case vmIntrinsics::_scopedValueCache:          return inline_native_scopedValueCache();
 498   case vmIntrinsics::_setScopedValueCache:       return inline_native_setScopedValueCache();
 499 
 500   case vmIntrinsics::_Continuation_pin:          return inline_native_Continuation_pinning(false);
 501   case vmIntrinsics::_Continuation_unpin:        return inline_native_Continuation_pinning(true);
 502 
 503   case vmIntrinsics::_vthreadEndFirstTransition:    return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
 504                                                                                                 "endFirstTransition", true);
 505   case vmIntrinsics::_vthreadStartFinalTransition:  return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
 506                                                                                                   "startFinalTransition", true);
 507   case vmIntrinsics::_vthreadStartTransition:       return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
 508                                                                                                   "startTransition", false);
 509   case vmIntrinsics::_vthreadEndTransition:         return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
 510                                                                                                 "endTransition", false);
 511 #if INCLUDE_JVMTI
 512   case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
 513 #endif
 514 
 515 #ifdef JFR_HAVE_INTRINSICS
 516   case vmIntrinsics::_counterTime:              return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
 517   case vmIntrinsics::_getEventWriter:           return inline_native_getEventWriter();
 518   case vmIntrinsics::_jvm_commit:               return inline_native_jvm_commit();
 519 #endif
 520   case vmIntrinsics::_currentTimeMillis:        return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
 521   case vmIntrinsics::_nanoTime:                 return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
 522   case vmIntrinsics::_writeback0:               return inline_unsafe_writeback0();
 523   case vmIntrinsics::_writebackPreSync0:        return inline_unsafe_writebackSync0(true);
 524   case vmIntrinsics::_writebackPostSync0:       return inline_unsafe_writebackSync0(false);
 525   case vmIntrinsics::_allocateInstance:         return inline_unsafe_allocate();
 526   case vmIntrinsics::_copyMemory:               return inline_unsafe_copyMemory();
 527   case vmIntrinsics::_setMemory:                return inline_unsafe_setMemory();
 528   case vmIntrinsics::_getLength:                return inline_native_getLength();
 529   case vmIntrinsics::_copyOf:                   return inline_array_copyOf(false);
 530   case vmIntrinsics::_copyOfRange:              return inline_array_copyOf(true);
 531   case vmIntrinsics::_equalsB:                  return inline_array_equals(StrIntrinsicNode::LL);
 532   case vmIntrinsics::_equalsC:                  return inline_array_equals(StrIntrinsicNode::UU);
 533   case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
 534   case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
 535   case vmIntrinsics::_clone:                    return inline_native_clone(intrinsic()->is_virtual());
 536 
 537   case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
 538   case vmIntrinsics::_newArray:                   return inline_unsafe_newArray(false);
 539   case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
 540   case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
 541   case vmIntrinsics::_newNullableAtomicArray:     return inline_newArray(/* null_free */ false, /* atomic */ true);
 542   case vmIntrinsics::_isFlatArray:              return inline_getArrayProperties(IsFlat);
 543   case vmIntrinsics::_isNullRestrictedArray:    return inline_getArrayProperties(IsNullRestricted);
 544   case vmIntrinsics::_isAtomicArray:            return inline_getArrayProperties(IsAtomic);
 545 
 546   case vmIntrinsics::_isAssignableFrom:         return inline_native_subtype_check();
 547 
 548   case vmIntrinsics::_isInstance:
 549   case vmIntrinsics::_isHidden:
 550   case vmIntrinsics::_getSuperclass:            return inline_native_Class_query(intrinsic_id());
 551 
 552   case vmIntrinsics::_floatToRawIntBits:
 553   case vmIntrinsics::_floatToIntBits:
 554   case vmIntrinsics::_intBitsToFloat:
 555   case vmIntrinsics::_doubleToRawLongBits:
 556   case vmIntrinsics::_doubleToLongBits:
 557   case vmIntrinsics::_longBitsToDouble:
 558   case vmIntrinsics::_floatToFloat16:
 559   case vmIntrinsics::_float16ToFloat:           return inline_fp_conversions(intrinsic_id());
 560   case vmIntrinsics::_sqrt_float16:             return inline_fp16_operations(intrinsic_id(), 1);
 561   case vmIntrinsics::_fma_float16:              return inline_fp16_operations(intrinsic_id(), 3);
 562   case vmIntrinsics::_floatIsFinite:
 563   case vmIntrinsics::_floatIsInfinite:
 564   case vmIntrinsics::_doubleIsFinite:
 565   case vmIntrinsics::_doubleIsInfinite:         return inline_fp_range_check(intrinsic_id());
 566 
 567   case vmIntrinsics::_numberOfLeadingZeros_i:
 568   case vmIntrinsics::_numberOfLeadingZeros_l:
 569   case vmIntrinsics::_numberOfTrailingZeros_i:
 570   case vmIntrinsics::_numberOfTrailingZeros_l:
 571   case vmIntrinsics::_bitCount_i:
 572   case vmIntrinsics::_bitCount_l:
 573   case vmIntrinsics::_reverse_i:
 574   case vmIntrinsics::_reverse_l:
 575   case vmIntrinsics::_reverseBytes_i:
 576   case vmIntrinsics::_reverseBytes_l:
 577   case vmIntrinsics::_reverseBytes_s:
 578   case vmIntrinsics::_reverseBytes_c:           return inline_number_methods(intrinsic_id());
 579 
 580   case vmIntrinsics::_compress_i:
 581   case vmIntrinsics::_compress_l:
 582   case vmIntrinsics::_expand_i:
 583   case vmIntrinsics::_expand_l:                 return inline_bitshuffle_methods(intrinsic_id());
 584 
 585   case vmIntrinsics::_compareUnsigned_i:
 586   case vmIntrinsics::_compareUnsigned_l:        return inline_compare_unsigned(intrinsic_id());
 587 
 588   case vmIntrinsics::_divideUnsigned_i:
 589   case vmIntrinsics::_divideUnsigned_l:
 590   case vmIntrinsics::_remainderUnsigned_i:
 591   case vmIntrinsics::_remainderUnsigned_l:      return inline_divmod_methods(intrinsic_id());
 592 
 593   case vmIntrinsics::_getCallerClass:           return inline_native_Reflection_getCallerClass();
 594 
 595   case vmIntrinsics::_Reference_get0:           return inline_reference_get0();
 596   case vmIntrinsics::_Reference_refersTo0:      return inline_reference_refersTo0(false);
 597   case vmIntrinsics::_Reference_reachabilityFence: return inline_reference_reachabilityFence();
 598   case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
 599   case vmIntrinsics::_Reference_clear0:         return inline_reference_clear0(false);
 600   case vmIntrinsics::_PhantomReference_clear0:  return inline_reference_clear0(true);
 601 
 602   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 603 
 604   case vmIntrinsics::_aescrypt_encryptBlock:
 605   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 606 
 607   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 608   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 609     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 610 
 611   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 612   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 613     return inline_electronicCodeBook_AESCrypt(intrinsic_id());
 614 
 615   case vmIntrinsics::_counterMode_AESCrypt:
 616     return inline_counterMode_AESCrypt(intrinsic_id());
 617 
 618   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 619     return inline_galoisCounterMode_AESCrypt();
 620 
 621   case vmIntrinsics::_md5_implCompress:
 622   case vmIntrinsics::_sha_implCompress:
 623   case vmIntrinsics::_sha2_implCompress:
 624   case vmIntrinsics::_sha5_implCompress:
 625   case vmIntrinsics::_sha3_implCompress:
 626     return inline_digestBase_implCompress(intrinsic_id());
 627   case vmIntrinsics::_double_keccak:
 628     return inline_double_keccak();
 629 
 630   case vmIntrinsics::_digestBase_implCompressMB:
 631     return inline_digestBase_implCompressMB(predicate);
 632 
 633   case vmIntrinsics::_multiplyToLen:
 634     return inline_multiplyToLen();
 635 
 636   case vmIntrinsics::_squareToLen:
 637     return inline_squareToLen();
 638 
 639   case vmIntrinsics::_mulAdd:
 640     return inline_mulAdd();
 641 
 642   case vmIntrinsics::_montgomeryMultiply:
 643     return inline_montgomeryMultiply();
 644   case vmIntrinsics::_montgomerySquare:
 645     return inline_montgomerySquare();
 646 
 647   case vmIntrinsics::_bigIntegerRightShiftWorker:
 648     return inline_bigIntegerShift(true);
 649   case vmIntrinsics::_bigIntegerLeftShiftWorker:
 650     return inline_bigIntegerShift(false);
 651 
 652   case vmIntrinsics::_vectorizedMismatch:
 653     return inline_vectorizedMismatch();
 654 
 655   case vmIntrinsics::_ghash_processBlocks:
 656     return inline_ghash_processBlocks();
 657   case vmIntrinsics::_chacha20Block:
 658     return inline_chacha20Block();
 659   case vmIntrinsics::_kyberNtt:
 660     return inline_kyberNtt();
 661   case vmIntrinsics::_kyberInverseNtt:
 662     return inline_kyberInverseNtt();
 663   case vmIntrinsics::_kyberNttMult:
 664     return inline_kyberNttMult();
 665   case vmIntrinsics::_kyberAddPoly_2:
 666     return inline_kyberAddPoly_2();
 667   case vmIntrinsics::_kyberAddPoly_3:
 668     return inline_kyberAddPoly_3();
 669   case vmIntrinsics::_kyber12To16:
 670     return inline_kyber12To16();
 671   case vmIntrinsics::_kyberBarrettReduce:
 672     return inline_kyberBarrettReduce();
 673   case vmIntrinsics::_dilithiumAlmostNtt:
 674     return inline_dilithiumAlmostNtt();
 675   case vmIntrinsics::_dilithiumAlmostInverseNtt:
 676     return inline_dilithiumAlmostInverseNtt();
 677   case vmIntrinsics::_dilithiumNttMult:
 678     return inline_dilithiumNttMult();
 679   case vmIntrinsics::_dilithiumMontMulByConstant:
 680     return inline_dilithiumMontMulByConstant();
 681   case vmIntrinsics::_dilithiumDecomposePoly:
 682     return inline_dilithiumDecomposePoly();
 683   case vmIntrinsics::_base64_encodeBlock:
 684     return inline_base64_encodeBlock();
 685   case vmIntrinsics::_base64_decodeBlock:
 686     return inline_base64_decodeBlock();
 687   case vmIntrinsics::_poly1305_processBlocks:
 688     return inline_poly1305_processBlocks();
 689   case vmIntrinsics::_intpoly_montgomeryMult_P256:
 690     return inline_intpoly_montgomeryMult_P256();
 691   case vmIntrinsics::_intpoly_assign:
 692     return inline_intpoly_assign();
 693   case vmIntrinsics::_encodeISOArray:
 694   case vmIntrinsics::_encodeByteISOArray:
 695     return inline_encodeISOArray(false);
 696   case vmIntrinsics::_encodeAsciiArray:
 697     return inline_encodeISOArray(true);
 698 
 699   case vmIntrinsics::_updateCRC32:
 700     return inline_updateCRC32();
 701   case vmIntrinsics::_updateBytesCRC32:
 702     return inline_updateBytesCRC32();
 703   case vmIntrinsics::_updateByteBufferCRC32:
 704     return inline_updateByteBufferCRC32();
 705 
 706   case vmIntrinsics::_updateBytesCRC32C:
 707     return inline_updateBytesCRC32C();
 708   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 709     return inline_updateDirectByteBufferCRC32C();
 710 
 711   case vmIntrinsics::_updateBytesAdler32:
 712     return inline_updateBytesAdler32();
 713   case vmIntrinsics::_updateByteBufferAdler32:
 714     return inline_updateByteBufferAdler32();
 715 
 716   case vmIntrinsics::_profileBoolean:
 717     return inline_profileBoolean();
 718   case vmIntrinsics::_isCompileConstant:
 719     return inline_isCompileConstant();
 720 
 721   case vmIntrinsics::_countPositives:
 722     return inline_countPositives();
 723 
 724   case vmIntrinsics::_fmaD:
 725   case vmIntrinsics::_fmaF:
 726     return inline_fma(intrinsic_id());
 727 
 728   case vmIntrinsics::_isDigit:
 729   case vmIntrinsics::_isLowerCase:
 730   case vmIntrinsics::_isUpperCase:
 731   case vmIntrinsics::_isWhitespace:
 732     return inline_character_compare(intrinsic_id());
 733 
 734   case vmIntrinsics::_min:
 735   case vmIntrinsics::_max:
 736   case vmIntrinsics::_min_strict:
 737   case vmIntrinsics::_max_strict:
 738   case vmIntrinsics::_minL:
 739   case vmIntrinsics::_maxL:
 740   case vmIntrinsics::_minF:
 741   case vmIntrinsics::_maxF:
 742   case vmIntrinsics::_minD:
 743   case vmIntrinsics::_maxD:
 744   case vmIntrinsics::_minF_strict:
 745   case vmIntrinsics::_maxF_strict:
 746   case vmIntrinsics::_minD_strict:
 747   case vmIntrinsics::_maxD_strict:
 748     return inline_min_max(intrinsic_id());
 749 
 750   case vmIntrinsics::_VectorUnaryOp:
 751     return inline_vector_nary_operation(1);
 752   case vmIntrinsics::_VectorBinaryOp:
 753     return inline_vector_nary_operation(2);
 754   case vmIntrinsics::_VectorUnaryLibOp:
 755     return inline_vector_call(1);
 756   case vmIntrinsics::_VectorBinaryLibOp:
 757     return inline_vector_call(2);
 758   case vmIntrinsics::_VectorTernaryOp:
 759     return inline_vector_nary_operation(3);
 760   case vmIntrinsics::_VectorFromBitsCoerced:
 761     return inline_vector_frombits_coerced();
 762   case vmIntrinsics::_VectorMaskOp:
 763     return inline_vector_mask_operation();
 764   case vmIntrinsics::_VectorLoadOp:
 765     return inline_vector_mem_operation(/*is_store=*/false);
 766   case vmIntrinsics::_VectorLoadMaskedOp:
 767     return inline_vector_mem_masked_operation(/*is_store*/false);
 768   case vmIntrinsics::_VectorStoreOp:
 769     return inline_vector_mem_operation(/*is_store=*/true);
 770   case vmIntrinsics::_VectorStoreMaskedOp:
 771     return inline_vector_mem_masked_operation(/*is_store=*/true);
 772   case vmIntrinsics::_VectorGatherOp:
 773     return inline_vector_gather_scatter(/*is_scatter*/ false);
 774   case vmIntrinsics::_VectorScatterOp:
 775     return inline_vector_gather_scatter(/*is_scatter*/ true);
 776   case vmIntrinsics::_VectorReductionCoerced:
 777     return inline_vector_reduction();
 778   case vmIntrinsics::_VectorTest:
 779     return inline_vector_test();
 780   case vmIntrinsics::_VectorBlend:
 781     return inline_vector_blend();
 782   case vmIntrinsics::_VectorRearrange:
 783     return inline_vector_rearrange();
 784   case vmIntrinsics::_VectorSelectFrom:
 785     return inline_vector_select_from();
 786   case vmIntrinsics::_VectorCompare:
 787     return inline_vector_compare();
 788   case vmIntrinsics::_VectorBroadcastInt:
 789     return inline_vector_broadcast_int();
 790   case vmIntrinsics::_VectorConvert:
 791     return inline_vector_convert();
 792   case vmIntrinsics::_VectorInsert:
 793     return inline_vector_insert();
 794   case vmIntrinsics::_VectorExtract:
 795     return inline_vector_extract();
 796   case vmIntrinsics::_VectorCompressExpand:
 797     return inline_vector_compress_expand();
 798   case vmIntrinsics::_VectorSelectFromTwoVectorOp:
 799     return inline_vector_select_from_two_vectors();
 800   case vmIntrinsics::_IndexVector:
 801     return inline_index_vector();
 802   case vmIntrinsics::_IndexPartiallyInUpperRange:
 803     return inline_index_partially_in_upper_range();
 804 
 805   case vmIntrinsics::_getObjectSize:
 806     return inline_getObjectSize();
 807 
 808   case vmIntrinsics::_blackhole:
 809     return inline_blackhole();
 810 
 811   default:
 812     // If you get here, it may be that someone has added a new intrinsic
 813     // to the list in vmIntrinsics.hpp without implementing it here.
 814 #ifndef PRODUCT
 815     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 816       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 817                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 818     }
 819 #endif
 820     return false;
 821   }
 822 }
 823 
 824 Node* LibraryCallKit::try_to_predicate(int predicate) {
 825   if (!jvms()->has_method()) {
 826     // Root JVMState has a null method.
 827     assert(map()->memory()->Opcode() == Op_Parm, "");
 828     // Insert the memory aliasing node
 829     set_all_memory(reset_memory());
 830   }
 831   assert(merged_memory(), "");
 832 
 833   switch (intrinsic_id()) {
 834   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 835     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 836   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 837     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 838   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 839     return inline_electronicCodeBook_AESCrypt_predicate(false);
 840   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 841     return inline_electronicCodeBook_AESCrypt_predicate(true);
 842   case vmIntrinsics::_counterMode_AESCrypt:
 843     return inline_counterMode_AESCrypt_predicate();
 844   case vmIntrinsics::_digestBase_implCompressMB:
 845     return inline_digestBase_implCompressMB_predicate(predicate);
 846   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 847     return inline_galoisCounterMode_AESCrypt_predicate();
 848 
 849   default:
 850     // If you get here, it may be that someone has added a new intrinsic
 851     // to the list in vmIntrinsics.hpp without implementing it here.
 852 #ifndef PRODUCT
 853     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 854       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 855                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 856     }
 857 #endif
 858     Node* slow_ctl = control();
 859     set_control(top()); // No fast path intrinsic
 860     return slow_ctl;
 861   }
 862 }
 863 
 864 //------------------------------set_result-------------------------------
 865 // Helper function for finishing intrinsics.
 866 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 867   record_for_igvn(region);
 868   set_control(_gvn.transform(region));
 869   set_result( _gvn.transform(value));
 870   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 871 }
 872 
 873 RegionNode* LibraryCallKit::create_bailout() {
 874   RegionNode* bailout = new RegionNode(1);
 875   record_for_igvn(bailout);
 876   return bailout;
 877 }
 878 
 879 bool LibraryCallKit::check_bailout(RegionNode* bailout) {
 880   if (bailout->req() > 1) {
 881     bailout = _gvn.transform(bailout)->as_Region();
 882     Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
 883     Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic"));
 884     C->root()->add_req(halt);
 885   }
 886   return stopped();
 887 }
 888 
 889 //------------------------------generate_guard---------------------------
 890 // Helper function for generating guarded fast-slow graph structures.
 891 // The given 'test', if true, guards a slow path.  If the test fails
 892 // then a fast path can be taken.  (We generally hope it fails.)
 893 // In all cases, GraphKit::control() is updated to the fast path.
 894 // The returned value represents the control for the slow path.
 895 // The return value is never 'top'; it is either a valid control
 896 // or null if it is obvious that the slow path can never be taken.
 897 // Also, if region and the slow control are not null, the slow edge
 898 // is appended to the region.
 899 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 900   if (stopped()) {
 901     // Already short circuited.
 902     return nullptr;
 903   }
 904 
 905   // Build an if node and its projections.
 906   // If test is true we take the slow path, which we assume is uncommon.
 907   if (_gvn.type(test) == TypeInt::ZERO) {
 908     // The slow branch is never taken.  No need to build this guard.
 909     return nullptr;
 910   }
 911 
 912   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 913 
 914   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
 915   if (if_slow == top()) {
 916     // The slow branch is never taken.  No need to build this guard.
 917     return nullptr;
 918   }
 919 
 920   if (region != nullptr)
 921     region->add_req(if_slow);
 922 
 923   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
 924   set_control(if_fast);
 925 
 926   return if_slow;
 927 }
 928 
 929 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 930   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 931 }
 932 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 933   return generate_guard(test, region, PROB_FAIR);
 934 }
 935 
 936 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 937                                                      Node** pos_index, bool with_opaque) {
 938   if (stopped())
 939     return nullptr;                // already stopped
 940   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 941     return nullptr;                // index is already adequately typed
 942   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
 943   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 944   if (with_opaque) {
 945     bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
 946   }
 947   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 948   if (is_neg != nullptr && pos_index != nullptr) {
 949     // Emulate effect of Parse::adjust_map_after_if.
 950     Node* ccast = new CastIINode(control(), index, TypeInt::POS);
 951     (*pos_index) = _gvn.transform(ccast);
 952   }
 953   return is_neg;
 954 }
 955 
 956 // Make sure that 'position' is a valid limit index, in [0..length].
 957 // There are two equivalent plans for checking this:
 958 //   A. (offset + copyLength)  unsigned<=  arrayLength
 959 //   B. offset  <=  (arrayLength - copyLength)
 960 // We require that all of the values above, except for the sum and
 961 // difference, are already known to be non-negative.
 962 // Plan A is robust in the face of overflow, if offset and copyLength
 963 // are both hugely positive.
 964 //
 965 // Plan B is less direct and intuitive, but it does not overflow at
 966 // all, since the difference of two non-negatives is always
 967 // representable.  Whenever Java methods must perform the equivalent
 968 // check they generally use Plan B instead of Plan A.
 969 // For the moment we use Plan A.
 970 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 971                                                   Node* subseq_length,
 972                                                   Node* array_length,
 973                                                   RegionNode* region,
 974                                                   bool with_opaque) {
 975   if (stopped())
 976     return nullptr;                // already stopped
 977   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 978   if (zero_offset && subseq_length->eqv_uncast(array_length))
 979     return nullptr;                // common case of whole-array copy
 980   Node* last = subseq_length;
 981   if (!zero_offset)             // last += offset
 982     last = _gvn.transform(new AddINode(last, offset));
 983   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
 984   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 985   if (with_opaque) {
 986     bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
 987   }
 988   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 989   return is_over;
 990 }
 991 
 992 // Emit range checks for the given String.value byte array
 993 void LibraryCallKit::generate_string_range_check(Node* array,
 994                                                  Node* offset,
 995                                                  Node* count,
 996                                                  bool char_count,
 997                                                  RegionNode* region) {
 998   if (stopped()) {
 999     return; // already stopped
1000   }
1001   if (char_count) {
1002     // Convert char count to byte count
1003     count = _gvn.transform(new LShiftINode(count, intcon(1)));
1004   }
1005   // Offset and count must not be negative
1006   generate_negative_guard(offset, region, nullptr, true);
1007   generate_negative_guard(count, region, nullptr, true);
1008   // Offset + count must not exceed length of array
1009   generate_limit_guard(offset, count, load_array_length(array), region, true);
1010 }
1011 
1012 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
1013                                             bool is_immutable) {
1014   ciKlass* thread_klass = env()->Thread_klass();
1015   const Type* thread_type
1016     = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1017 
1018   Node* thread = _gvn.transform(new ThreadLocalNode());
1019   Node* p = off_heap_plus_addr(thread, in_bytes(handle_offset));
1020   tls_output = thread;
1021 
1022   Node* thread_obj_handle
1023     = (is_immutable
1024       ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1025         TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1026       : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1027   thread_obj_handle = _gvn.transform(thread_obj_handle);
1028 
1029   DecoratorSet decorators = IN_NATIVE;
1030   if (is_immutable) {
1031     decorators |= C2_IMMUTABLE_MEMORY;
1032   }
1033   return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1034 }
1035 
1036 //--------------------------generate_current_thread--------------------
1037 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1038   return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1039                                /*is_immutable*/false);
1040 }
1041 
1042 //--------------------------generate_virtual_thread--------------------
1043 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1044   return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1045                                !C->method()->changes_current_thread());
1046 }
1047 
1048 //------------------------------make_string_method_node------------------------
1049 // Helper method for String intrinsic functions. This version is called with
1050 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1051 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1052 // containing the lengths of str1 and str2.
1053 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1054   Node* result = nullptr;
1055   switch (opcode) {
1056   case Op_StrIndexOf:
1057     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1058                                 str1_start, cnt1, str2_start, cnt2, ae);
1059     break;
1060   case Op_StrComp:
1061     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1062                              str1_start, cnt1, str2_start, cnt2, ae);
1063     break;
1064   case Op_StrEquals:
1065     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1066     // Use the constant length if there is one because optimized match rule may exist.
1067     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1068                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1069     break;
1070   default:
1071     ShouldNotReachHere();
1072     return nullptr;
1073   }
1074 
1075   // All these intrinsics have checks.
1076   C->set_has_split_ifs(true); // Has chance for split-if optimization
1077   clear_upper_avx();
1078 
1079   return _gvn.transform(result);
1080 }
1081 
1082 //------------------------------inline_string_compareTo------------------------
1083 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1084   Node* arg1 = argument(0);
1085   Node* arg2 = argument(1);
1086 
1087   arg1 = must_be_not_null(arg1, true);
1088   arg2 = must_be_not_null(arg2, true);
1089 
1090   // Get start addr and length of first argument
1091   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1092   Node* arg1_cnt    = load_array_length(arg1);
1093 
1094   // Get start addr and length of second argument
1095   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1096   Node* arg2_cnt    = load_array_length(arg2);
1097 
1098   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1099   set_result(result);
1100   return true;
1101 }
1102 
1103 //------------------------------inline_string_equals------------------------
1104 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1105   Node* arg1 = argument(0);
1106   Node* arg2 = argument(1);
1107 
1108   // paths (plus control) merge
1109   RegionNode* region = new RegionNode(3);
1110   Node* phi = new PhiNode(region, TypeInt::BOOL);
1111 
1112   if (!stopped()) {
1113 
1114     arg1 = must_be_not_null(arg1, true);
1115     arg2 = must_be_not_null(arg2, true);
1116 
1117     // Get start addr and length of first argument
1118     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1119     Node* arg1_cnt    = load_array_length(arg1);
1120 
1121     // Get start addr and length of second argument
1122     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1123     Node* arg2_cnt    = load_array_length(arg2);
1124 
1125     // Check for arg1_cnt != arg2_cnt
1126     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1127     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1128     Node* if_ne = generate_slow_guard(bol, nullptr);
1129     if (if_ne != nullptr) {
1130       phi->init_req(2, intcon(0));
1131       region->init_req(2, if_ne);
1132     }
1133 
1134     // Check for count == 0 is done by assembler code for StrEquals.
1135 
1136     if (!stopped()) {
1137       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1138       phi->init_req(1, equals);
1139       region->init_req(1, control());
1140     }
1141   }
1142 
1143   // post merge
1144   set_control(_gvn.transform(region));
1145   record_for_igvn(region);
1146 
1147   set_result(_gvn.transform(phi));
1148   return true;
1149 }
1150 
1151 //------------------------------inline_array_equals----------------------------
1152 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1153   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1154   Node* arg1 = argument(0);
1155   Node* arg2 = argument(1);
1156 
1157   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1158   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1159   clear_upper_avx();
1160 
1161   return true;
1162 }
1163 
1164 
1165 //------------------------------inline_countPositives------------------------------
1166 // int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len)
1167 bool LibraryCallKit::inline_countPositives() {
1168   assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1169   // no receiver since it is static method
1170   Node* ba         = argument(0);
1171   Node* offset     = argument(1);
1172   Node* len        = argument(2);
1173 
1174   ba = must_be_not_null(ba, true);
1175   RegionNode* bailout = create_bailout();
1176   generate_string_range_check(ba, offset, len, false, bailout);
1177   if (check_bailout(bailout)) {
1178     return true;
1179   }
1180 
1181   Node* ba_start = array_element_address(ba, offset, T_BYTE);
1182   Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1183   set_result(_gvn.transform(result));
1184   clear_upper_avx();
1185   return true;
1186 }
1187 
1188 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1189   Node* index = argument(0);
1190   Node* length = bt == T_INT ? argument(1) : argument(2);
1191   if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1192     return false;
1193   }
1194 
1195   // check that length is positive
1196   Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1197   Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1198 
1199   {
1200     BuildCutout unless(this, len_pos_bol, PROB_MAX);
1201     uncommon_trap(Deoptimization::Reason_intrinsic,
1202                   Deoptimization::Action_make_not_entrant);
1203   }
1204 
1205   if (stopped()) {
1206     // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1207     return true;
1208   }
1209 
1210   // length is now known positive, add a cast node to make this explicit
1211   jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1212   Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1213       control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1214       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1215   casted_length = _gvn.transform(casted_length);
1216   replace_in_map(length, casted_length);
1217   length = casted_length;
1218 
1219   // Use an unsigned comparison for the range check itself
1220   Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1221   BoolTest::mask btest = BoolTest::lt;
1222   Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1223   RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1224   _gvn.set_type(rc, rc->Value(&_gvn));
1225   if (!rc_bool->is_Con()) {
1226     record_for_igvn(rc);
1227   }
1228   set_control(_gvn.transform(new IfTrueNode(rc)));
1229   {
1230     PreserveJVMState pjvms(this);
1231     set_control(_gvn.transform(new IfFalseNode(rc)));
1232     uncommon_trap(Deoptimization::Reason_range_check,
1233                   Deoptimization::Action_make_not_entrant);
1234   }
1235 
1236   if (stopped()) {
1237     // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1238     return true;
1239   }
1240 
1241   // index is now known to be >= 0 and < length, cast it
1242   Node* result = ConstraintCastNode::make_cast_for_basic_type(
1243       control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1244       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1245   result = _gvn.transform(result);
1246   set_result(result);
1247   replace_in_map(index, result);
1248   return true;
1249 }
1250 
1251 //------------------------------inline_string_indexOf------------------------
1252 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1253   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1254     return false;
1255   }
1256   Node* src = argument(0);
1257   Node* tgt = argument(1);
1258 
1259   // Make the merge point
1260   RegionNode* result_rgn = new RegionNode(4);
1261   Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1262 
1263   src = must_be_not_null(src, true);
1264   tgt = must_be_not_null(tgt, true);
1265 
1266   // Get start addr and length of source string
1267   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1268   Node* src_count = load_array_length(src);
1269 
1270   // Get start addr and length of substring
1271   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1272   Node* tgt_count = load_array_length(tgt);
1273 
1274   Node* result = nullptr;
1275   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1276 
1277   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1278     // Divide src size by 2 if String is UTF16 encoded
1279     src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1280   }
1281   if (ae == StrIntrinsicNode::UU) {
1282     // Divide substring size by 2 if String is UTF16 encoded
1283     tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1284   }
1285 
1286   if (call_opt_stub) {
1287     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1288                                    StubRoutines::_string_indexof_array[ae],
1289                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1290                                    src_count, tgt_start, tgt_count);
1291     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1292   } else {
1293     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1294                                result_rgn, result_phi, ae);
1295   }
1296   if (result != nullptr) {
1297     result_phi->init_req(3, result);
1298     result_rgn->init_req(3, control());
1299   }
1300   set_control(_gvn.transform(result_rgn));
1301   record_for_igvn(result_rgn);
1302   set_result(_gvn.transform(result_phi));
1303 
1304   return true;
1305 }
1306 
1307 //-----------------------------inline_string_indexOfI-----------------------
1308 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1309   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1310     return false;
1311   }
1312 
1313   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1314   Node* src         = argument(0); // byte[]
1315   Node* src_count   = argument(1); // char count
1316   Node* tgt         = argument(2); // byte[]
1317   Node* tgt_count   = argument(3); // char count
1318   Node* from_index  = argument(4); // char index
1319 
1320   src = must_be_not_null(src, true);
1321   tgt = must_be_not_null(tgt, true);
1322 
1323   // Multiply byte array index by 2 if String is UTF16 encoded
1324   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1325   src_count = _gvn.transform(new SubINode(src_count, from_index));
1326   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1327   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1328 
1329   // Range checks
1330   RegionNode* bailout = create_bailout();
1331   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL, bailout);
1332   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU, bailout);
1333   if (check_bailout(bailout)) {
1334     return true;
1335   }
1336 
1337   RegionNode* region = new RegionNode(5);
1338   Node* phi = new PhiNode(region, TypeInt::INT);
1339   Node* result = nullptr;
1340 
1341   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1342 
1343   if (call_opt_stub) {
1344     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1345                                    StubRoutines::_string_indexof_array[ae],
1346                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1347                                    src_count, tgt_start, tgt_count);
1348     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1349   } else {
1350     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1351                                region, phi, ae);
1352   }
1353   if (result != nullptr) {
1354     // The result is index relative to from_index if substring was found, -1 otherwise.
1355     // Generate code which will fold into cmove.
1356     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1357     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1358 
1359     Node* if_lt = generate_slow_guard(bol, nullptr);
1360     if (if_lt != nullptr) {
1361       // result == -1
1362       phi->init_req(3, result);
1363       region->init_req(3, if_lt);
1364     }
1365     if (!stopped()) {
1366       result = _gvn.transform(new AddINode(result, from_index));
1367       phi->init_req(4, result);
1368       region->init_req(4, control());
1369     }
1370   }
1371 
1372   set_control(_gvn.transform(region));
1373   record_for_igvn(region);
1374   set_result(_gvn.transform(phi));
1375   clear_upper_avx();
1376 
1377   return true;
1378 }
1379 
1380 // Create StrIndexOfNode with fast path checks
1381 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1382                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1383   // Check for substr count > string count
1384   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1385   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1386   Node* if_gt = generate_slow_guard(bol, nullptr);
1387   if (if_gt != nullptr) {
1388     phi->init_req(1, intcon(-1));
1389     region->init_req(1, if_gt);
1390   }
1391   if (!stopped()) {
1392     // Check for substr count == 0
1393     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1394     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1395     Node* if_zero = generate_slow_guard(bol, nullptr);
1396     if (if_zero != nullptr) {
1397       phi->init_req(2, intcon(0));
1398       region->init_req(2, if_zero);
1399     }
1400   }
1401   if (!stopped()) {
1402     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1403   }
1404   return nullptr;
1405 }
1406 
1407 //-----------------------------inline_string_indexOfChar-----------------------
1408 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1409   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1410     return false;
1411   }
1412   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1413     return false;
1414   }
1415   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1416   Node* src         = argument(0); // byte[]
1417   Node* int_ch      = argument(1);
1418   Node* from_index  = argument(2);
1419   Node* max         = argument(3);
1420 
1421   src = must_be_not_null(src, true);
1422 
1423   Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1424   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1425   Node* src_count = _gvn.transform(new SubINode(max, from_index));
1426 
1427   // Range checks
1428   RegionNode* bailout = create_bailout();
1429   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U, bailout);
1430   if (check_bailout(bailout)) {
1431     return true;
1432   }
1433 
1434   // Check for int_ch >= 0
1435   Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1436   Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1437   {
1438     BuildCutout unless(this, int_ch_bol, PROB_MAX);
1439     uncommon_trap(Deoptimization::Reason_intrinsic,
1440                   Deoptimization::Action_maybe_recompile);
1441   }
1442   if (stopped()) {
1443     return true;
1444   }
1445 
1446   RegionNode* region = new RegionNode(3);
1447   Node* phi = new PhiNode(region, TypeInt::INT);
1448 
1449   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1450   C->set_has_split_ifs(true); // Has chance for split-if optimization
1451   _gvn.transform(result);
1452 
1453   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1454   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1455 
1456   Node* if_lt = generate_slow_guard(bol, nullptr);
1457   if (if_lt != nullptr) {
1458     // result == -1
1459     phi->init_req(2, result);
1460     region->init_req(2, if_lt);
1461   }
1462   if (!stopped()) {
1463     result = _gvn.transform(new AddINode(result, from_index));
1464     phi->init_req(1, result);
1465     region->init_req(1, control());
1466   }
1467   set_control(_gvn.transform(region));
1468   record_for_igvn(region);
1469   set_result(_gvn.transform(phi));
1470   clear_upper_avx();
1471 
1472   return true;
1473 }
1474 //---------------------------inline_string_copy---------------------
1475 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1476 //   int StringUTF16.compress0(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1477 //   int StringUTF16.compress0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1478 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1479 //   void StringLatin1.inflate0(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1480 //   void StringLatin1.inflate0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1481 bool LibraryCallKit::inline_string_copy(bool compress) {
1482   int nargs = 5;  // 2 oops, 3 ints
1483   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1484 
1485   Node* src         = argument(0);
1486   Node* src_offset  = argument(1);
1487   Node* dst         = argument(2);
1488   Node* dst_offset  = argument(3);
1489   Node* length      = argument(4);
1490 
1491   // Check for allocation before we add nodes that would confuse
1492   // tightly_coupled_allocation()
1493   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1494 
1495   // Figure out the size and type of the elements we will be copying.
1496   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1497   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1498   if (src_type == nullptr || dst_type == nullptr) {
1499     return false;
1500   }
1501   BasicType src_elem = src_type->elem()->array_element_basic_type();
1502   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1503   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1504          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1505          "Unsupported array types for inline_string_copy");
1506 
1507   src = must_be_not_null(src, true);
1508   dst = must_be_not_null(dst, true);
1509 
1510   // Convert char[] offsets to byte[] offsets
1511   bool convert_src = (compress && src_elem == T_BYTE);
1512   bool convert_dst = (!compress && dst_elem == T_BYTE);
1513   if (convert_src) {
1514     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1515   } else if (convert_dst) {
1516     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1517   }
1518 
1519   // Range checks
1520   RegionNode* bailout = create_bailout();
1521   generate_string_range_check(src, src_offset, length, convert_src, bailout);
1522   generate_string_range_check(dst, dst_offset, length, convert_dst, bailout);
1523   if (check_bailout(bailout)) {
1524     return true;
1525   }
1526 
1527   Node* src_start = array_element_address(src, src_offset, src_elem);
1528   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1529   // 'src_start' points to src array + scaled offset
1530   // 'dst_start' points to dst array + scaled offset
1531   Node* count = nullptr;
1532   if (compress) {
1533     count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1534   } else {
1535     inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1536   }
1537 
1538   if (alloc != nullptr) {
1539     if (alloc->maybe_set_complete(&_gvn)) {
1540       // "You break it, you buy it."
1541       InitializeNode* init = alloc->initialization();
1542       assert(init->is_complete(), "we just did this");
1543       init->set_complete_with_arraycopy();
1544       assert(dst->is_CheckCastPP(), "sanity");
1545       assert(dst->in(0)->in(0) == init, "dest pinned");
1546     }
1547     // Do not let stores that initialize this object be reordered with
1548     // a subsequent store that would make this object accessible by
1549     // other threads.
1550     // Record what AllocateNode this StoreStore protects so that
1551     // escape analysis can go from the MemBarStoreStoreNode to the
1552     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1553     // based on the escape status of the AllocateNode.
1554     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1555   }
1556   if (compress) {
1557     set_result(_gvn.transform(count));
1558   }
1559   clear_upper_avx();
1560 
1561   return true;
1562 }
1563 
1564 #ifdef _LP64
1565 #define XTOP ,top() /*additional argument*/
1566 #else  //_LP64
1567 #define XTOP        /*no additional argument*/
1568 #endif //_LP64
1569 
1570 //------------------------inline_string_toBytesU--------------------------
1571 // public static byte[] StringUTF16.toBytes0(char[] value, int off, int len)
1572 bool LibraryCallKit::inline_string_toBytesU() {
1573   // Get the arguments.
1574   assert(callee()->signature()->size() == 3, "character array encoder requires 3 arguments");
1575   Node* value     = argument(0);
1576   Node* offset    = argument(1);
1577   Node* length    = argument(2);
1578 
1579   Node* newcopy = nullptr;
1580 
1581   // Set the original stack and the reexecute bit for the interpreter to reexecute
1582   // the bytecode that invokes StringUTF16.toBytes0() if deoptimization happens.
1583   { PreserveReexecuteState preexecs(this);
1584     jvms()->set_should_reexecute(true);
1585 
1586     value = must_be_not_null(value, true);
1587     RegionNode* bailout = create_bailout();
1588     generate_negative_guard(offset, bailout, nullptr, true);
1589     generate_negative_guard(length, bailout, nullptr, true);
1590     generate_limit_guard(offset, length, load_array_length(value), bailout, true);
1591     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1592     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout, true);
1593     if (check_bailout(bailout)) {
1594       return true;
1595     }
1596 
1597     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1598     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1599     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1600     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1601     guarantee(alloc != nullptr, "created above");
1602 
1603     // Calculate starting addresses.
1604     Node* src_start = array_element_address(value, offset, T_CHAR);
1605     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1606 
1607     // Check if dst array address is aligned to HeapWordSize
1608     bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1609     // If true, then check if src array address is aligned to HeapWordSize
1610     if (aligned) {
1611       const TypeInt* toffset = gvn().type(offset)->is_int();
1612       aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1613                                        toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1614     }
1615 
1616     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1617     const char* copyfunc_name = "arraycopy";
1618     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1619     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1620                       OptoRuntime::fast_arraycopy_Type(),
1621                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1622                       src_start, dst_start, ConvI2X(length) XTOP);
1623     // Do not let reads from the cloned object float above the arraycopy.
1624     if (alloc->maybe_set_complete(&_gvn)) {
1625       // "You break it, you buy it."
1626       InitializeNode* init = alloc->initialization();
1627       assert(init->is_complete(), "we just did this");
1628       init->set_complete_with_arraycopy();
1629       assert(newcopy->is_CheckCastPP(), "sanity");
1630       assert(newcopy->in(0)->in(0) == init, "dest pinned");
1631     }
1632     // Do not let stores that initialize this object be reordered with
1633     // a subsequent store that would make this object accessible by
1634     // other threads.
1635     // Record what AllocateNode this StoreStore protects so that
1636     // escape analysis can go from the MemBarStoreStoreNode to the
1637     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1638     // based on the escape status of the AllocateNode.
1639     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1640   } // original reexecute is set back here
1641 
1642   C->set_has_split_ifs(true); // Has chance for split-if optimization
1643   if (!stopped()) {
1644     set_result(newcopy);
1645   }
1646   clear_upper_avx();
1647 
1648   return true;
1649 }
1650 
1651 //------------------------inline_string_getCharsU--------------------------
1652 // public void StringUTF16.getChars0(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1653 bool LibraryCallKit::inline_string_getCharsU() {
1654   assert(callee()->signature()->size() == 5, "StringUTF16.getChars0() has 5 arguments");
1655   // Get the arguments.
1656   Node* src       = argument(0);
1657   Node* src_begin = argument(1);
1658   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1659   Node* dst       = argument(3);
1660   Node* dst_begin = argument(4);
1661 
1662   // Check for allocation before we add nodes that would confuse
1663   // tightly_coupled_allocation()
1664   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1665 
1666   // Check if a null path was taken unconditionally.
1667   src = must_be_not_null(src, true);
1668   dst = must_be_not_null(dst, true);
1669   if (stopped()) {
1670     return true;
1671   }
1672 
1673   // Get length and convert char[] offset to byte[] offset
1674   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1675   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1676 
1677   // Range checks
1678   RegionNode* bailout = create_bailout();
1679   generate_string_range_check(src, src_begin, length, true, bailout);
1680   generate_string_range_check(dst, dst_begin, length, false, bailout);
1681   if (check_bailout(bailout)) {
1682     return true;
1683   }
1684 
1685   // Calculate starting addresses.
1686   Node* src_start = array_element_address(src, src_begin, T_BYTE);
1687   Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1688 
1689   // Check if array addresses are aligned to HeapWordSize
1690   const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1691   const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1692   bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1693                  tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1694 
1695   // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1696   const char* copyfunc_name = "arraycopy";
1697   address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1698   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1699                     OptoRuntime::fast_arraycopy_Type(),
1700                     copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1701                     src_start, dst_start, ConvI2X(length) XTOP);
1702   // Do not let reads from the cloned object float above the arraycopy.
1703   if (alloc != nullptr) {
1704     if (alloc->maybe_set_complete(&_gvn)) {
1705       // "You break it, you buy it."
1706       InitializeNode* init = alloc->initialization();
1707       assert(init->is_complete(), "we just did this");
1708       init->set_complete_with_arraycopy();
1709       assert(dst->is_CheckCastPP(), "sanity");
1710       assert(dst->in(0)->in(0) == init, "dest pinned");
1711     }
1712     // Do not let stores that initialize this object be reordered with
1713     // a subsequent store that would make this object accessible by
1714     // other threads.
1715     // Record what AllocateNode this StoreStore protects so that
1716     // escape analysis can go from the MemBarStoreStoreNode to the
1717     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1718     // based on the escape status of the AllocateNode.
1719     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1720   } else {
1721     insert_mem_bar(Op_MemBarCPUOrder);
1722   }
1723 
1724   C->set_has_split_ifs(true); // Has chance for split-if optimization
1725   return true;
1726 }
1727 
1728 //----------------------inline_string_char_access----------------------------
1729 // Store/Load char to/from byte[] array.
1730 // static void StringUTF16.putChar(byte[] val, int index, int c)
1731 // static char StringUTF16.getChar(byte[] val, int index)
1732 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1733   Node* ch;
1734   if (is_store) {
1735     assert(callee()->signature()->size() == 3, "StringUTF16.putChar() has 3 arguments");
1736     ch = argument(2);
1737   } else {
1738     assert(callee()->signature()->size() == 2, "StringUTF16.getChar() has 2 arguments");
1739     ch = nullptr;
1740   }
1741   Node* value  = argument(0);
1742   Node* index  = argument(1);
1743 
1744   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1745   // correctly requires matched array shapes.
1746   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1747           "sanity: byte[] and char[] bases agree");
1748   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1749           "sanity: byte[] and char[] scales agree");
1750 
1751   // Bail when getChar over constants is requested: constant folding would
1752   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1753   // Java method would constant fold nicely instead.
1754   if (!is_store && value->is_Con() && index->is_Con()) {
1755     return false;
1756   }
1757 
1758   // Save state and restore on bailout
1759   SavedState old_state(this);
1760 
1761   value = must_be_not_null(value, true);
1762 
1763   Node* adr = array_element_address(value, index, T_CHAR);
1764   if (adr->is_top()) {
1765     return false;
1766   }
1767   old_state.discard();
1768   if (is_store) {
1769     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1770   } else {
1771     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);
1772     set_result(ch);
1773   }
1774   return true;
1775 }
1776 
1777 
1778 //------------------------------inline_math-----------------------------------
1779 // public static double Math.abs(double)
1780 // public static double Math.sqrt(double)
1781 // public static double Math.log(double)
1782 // public static double Math.log10(double)
1783 // public static double Math.round(double)
1784 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1785   Node* arg = argument(0);
1786   Node* n = nullptr;
1787   switch (id) {
1788   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1789   case vmIntrinsics::_dsqrt:
1790   case vmIntrinsics::_dsqrt_strict:
1791                               n = new SqrtDNode(C, control(),  arg);  break;
1792   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1793   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1794   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1795   case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1796   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1797   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1798   default:  fatal_unexpected_iid(id);  break;
1799   }
1800   set_result(_gvn.transform(n));
1801   return true;
1802 }
1803 
1804 //------------------------------inline_math-----------------------------------
1805 // public static float Math.abs(float)
1806 // public static int Math.abs(int)
1807 // public static long Math.abs(long)
1808 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1809   Node* arg = argument(0);
1810   Node* n = nullptr;
1811   switch (id) {
1812   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
1813   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
1814   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
1815   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1816   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1817   case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1818   default:  fatal_unexpected_iid(id);  break;
1819   }
1820   set_result(_gvn.transform(n));
1821   return true;
1822 }
1823 
1824 //------------------------------runtime_math-----------------------------
1825 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1826   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1827          "must be (DD)D or (D)D type");
1828 
1829   // Inputs
1830   Node* a = argument(0);
1831   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1832 
1833   const TypePtr* no_memory_effects = nullptr;
1834   Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1835                                  no_memory_effects,
1836                                  a, top(), b, b ? top() : nullptr);
1837   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1838 #ifdef ASSERT
1839   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1840   assert(value_top == top(), "second value must be top");
1841 #endif
1842 
1843   set_result(value);
1844   return true;
1845 }
1846 
1847 //------------------------------inline_math_pow-----------------------------
1848 bool LibraryCallKit::inline_math_pow() {
1849   Node* base = argument(0);
1850   Node* exp = argument(2);
1851 
1852   CallNode* pow = new PowDNode(C, base, exp);
1853   set_predefined_input_for_runtime_call(pow);
1854   pow = _gvn.transform(pow)->as_CallLeafPure();
1855   set_predefined_output_for_runtime_call(pow);
1856   Node* result = _gvn.transform(new ProjNode(pow, TypeFunc::Parms + 0));
1857   record_for_igvn(pow);
1858   set_result(result);
1859   return true;
1860 }
1861 
1862 //------------------------------inline_math_native-----------------------------
1863 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1864   switch (id) {
1865   case vmIntrinsics::_dsin:
1866     return StubRoutines::dsin() != nullptr ?
1867       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1868       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin),   "SIN");
1869   case vmIntrinsics::_dcos:
1870     return StubRoutines::dcos() != nullptr ?
1871       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1872       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos),   "COS");
1873   case vmIntrinsics::_dtan:
1874     return StubRoutines::dtan() != nullptr ?
1875       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1876       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1877   case vmIntrinsics::_dsinh:
1878     return StubRoutines::dsinh() != nullptr ?
1879       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1880   case vmIntrinsics::_dtanh:
1881     return StubRoutines::dtanh() != nullptr ?
1882       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1883   case vmIntrinsics::_dcbrt:
1884     return StubRoutines::dcbrt() != nullptr ?
1885       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1886   case vmIntrinsics::_dexp:
1887     return StubRoutines::dexp() != nullptr ?
1888       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1889       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp),  "EXP");
1890   case vmIntrinsics::_dlog:
1891     return StubRoutines::dlog() != nullptr ?
1892       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1893       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog),   "LOG");
1894   case vmIntrinsics::_dlog10:
1895     return StubRoutines::dlog10() != nullptr ?
1896       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1897       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1898 
1899   case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1900   case vmIntrinsics::_ceil:
1901   case vmIntrinsics::_floor:
1902   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1903 
1904   case vmIntrinsics::_dsqrt:
1905   case vmIntrinsics::_dsqrt_strict:
1906                               return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1907   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
1908   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
1909   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
1910   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
1911 
1912   case vmIntrinsics::_dpow:      return inline_math_pow();
1913   case vmIntrinsics::_dcopySign: return inline_double_math(id);
1914   case vmIntrinsics::_fcopySign: return inline_math(id);
1915   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1916   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1917   case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1918 
1919    // These intrinsics are not yet correctly implemented
1920   case vmIntrinsics::_datan2:
1921     return false;
1922 
1923   default:
1924     fatal_unexpected_iid(id);
1925     return false;
1926   }
1927 }
1928 
1929 //----------------------------inline_notify-----------------------------------*
1930 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1931   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1932   address func;
1933   if (id == vmIntrinsics::_notify) {
1934     func = OptoRuntime::monitor_notify_Java();
1935   } else {
1936     func = OptoRuntime::monitor_notifyAll_Java();
1937   }
1938   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1939   make_slow_call_ex(call, env()->Throwable_klass(), false);
1940   return true;
1941 }
1942 
1943 
1944 //----------------------------inline_min_max-----------------------------------
1945 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1946   Node* a = nullptr;
1947   Node* b = nullptr;
1948   Node* n = nullptr;
1949   switch (id) {
1950     case vmIntrinsics::_min:
1951     case vmIntrinsics::_max:
1952     case vmIntrinsics::_minF:
1953     case vmIntrinsics::_maxF:
1954     case vmIntrinsics::_minF_strict:
1955     case vmIntrinsics::_maxF_strict:
1956     case vmIntrinsics::_min_strict:
1957     case vmIntrinsics::_max_strict:
1958       assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
1959       a = argument(0);
1960       b = argument(1);
1961       break;
1962     case vmIntrinsics::_minD:
1963     case vmIntrinsics::_maxD:
1964     case vmIntrinsics::_minD_strict:
1965     case vmIntrinsics::_maxD_strict:
1966       assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
1967       a = argument(0);
1968       b = argument(2);
1969       break;
1970     case vmIntrinsics::_minL:
1971     case vmIntrinsics::_maxL:
1972       assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
1973       a = argument(0);
1974       b = argument(2);
1975       break;
1976     default:
1977       fatal_unexpected_iid(id);
1978       break;
1979   }
1980 
1981   switch (id) {
1982     case vmIntrinsics::_min:
1983     case vmIntrinsics::_min_strict:
1984       n = new MinINode(a, b);
1985       break;
1986     case vmIntrinsics::_max:
1987     case vmIntrinsics::_max_strict:
1988       n = new MaxINode(a, b);
1989       break;
1990     case vmIntrinsics::_minF:
1991     case vmIntrinsics::_minF_strict:
1992       n = new MinFNode(a, b);
1993       break;
1994     case vmIntrinsics::_maxF:
1995     case vmIntrinsics::_maxF_strict:
1996       n = new MaxFNode(a, b);
1997       break;
1998     case vmIntrinsics::_minD:
1999     case vmIntrinsics::_minD_strict:
2000       n = new MinDNode(a, b);
2001       break;
2002     case vmIntrinsics::_maxD:
2003     case vmIntrinsics::_maxD_strict:
2004       n = new MaxDNode(a, b);
2005       break;
2006     case vmIntrinsics::_minL:
2007       n = new MinLNode(_gvn.C, a, b);
2008       break;
2009     case vmIntrinsics::_maxL:
2010       n = new MaxLNode(_gvn.C, a, b);
2011       break;
2012     default:
2013       fatal_unexpected_iid(id);
2014       break;
2015   }
2016 
2017   set_result(_gvn.transform(n));
2018   return true;
2019 }
2020 
2021 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2022   if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2023                                    env()->ArithmeticException_instance())) {
2024     // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2025     // so let's bail out intrinsic rather than risking deopting again.
2026     return false;
2027   }
2028 
2029   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2030   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2031   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2032   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2033 
2034   {
2035     PreserveJVMState pjvms(this);
2036     PreserveReexecuteState preexecs(this);
2037     jvms()->set_should_reexecute(true);
2038 
2039     set_control(slow_path);
2040     set_i_o(i_o());
2041 
2042     builtin_throw(Deoptimization::Reason_intrinsic,
2043                   env()->ArithmeticException_instance(),
2044                   /*allow_too_many_traps*/ false);
2045   }
2046 
2047   set_control(fast_path);
2048   set_result(math);
2049   return true;
2050 }
2051 
2052 template <typename OverflowOp>
2053 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2054   typedef typename OverflowOp::MathOp MathOp;
2055 
2056   MathOp* mathOp = new MathOp(arg1, arg2);
2057   Node* operation = _gvn.transform( mathOp );
2058   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2059   return inline_math_mathExact(operation, ofcheck);
2060 }
2061 
2062 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2063   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2064 }
2065 
2066 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2067   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2068 }
2069 
2070 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2071   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2072 }
2073 
2074 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2075   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2076 }
2077 
2078 bool LibraryCallKit::inline_math_negateExactI() {
2079   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2080 }
2081 
2082 bool LibraryCallKit::inline_math_negateExactL() {
2083   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2084 }
2085 
2086 bool LibraryCallKit::inline_math_multiplyExactI() {
2087   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2088 }
2089 
2090 bool LibraryCallKit::inline_math_multiplyExactL() {
2091   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2092 }
2093 
2094 bool LibraryCallKit::inline_math_multiplyHigh() {
2095   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2096   return true;
2097 }
2098 
2099 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2100   set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2101   return true;
2102 }
2103 
2104 inline int
2105 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2106   const TypePtr* base_type = TypePtr::NULL_PTR;
2107   if (base != nullptr)  base_type = _gvn.type(base)->isa_ptr();
2108   if (base_type == nullptr) {
2109     // Unknown type.
2110     return Type::AnyPtr;
2111   } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2112     // Since this is a null+long form, we have to switch to a rawptr.
2113     base   = _gvn.transform(new CastX2PNode(offset));
2114     offset = MakeConX(0);
2115     return Type::RawPtr;
2116   } else if (base_type->base() == Type::RawPtr) {
2117     return Type::RawPtr;
2118   } else if (base_type->isa_oopptr()) {
2119     // Base is never null => always a heap address.
2120     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2121       return Type::OopPtr;
2122     }
2123     // Offset is small => always a heap address.
2124     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2125     if (offset_type != nullptr &&
2126         base_type->offset() == 0 &&     // (should always be?)
2127         offset_type->_lo >= 0 &&
2128         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2129       return Type::OopPtr;
2130     } else if (type == T_OBJECT) {
2131       // off heap access to an oop doesn't make any sense. Has to be on
2132       // heap.
2133       return Type::OopPtr;
2134     }
2135     // Otherwise, it might either be oop+off or null+addr.
2136     return Type::AnyPtr;
2137   } else {
2138     // No information:
2139     return Type::AnyPtr;
2140   }
2141 }
2142 
2143 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2144   Node* uncasted_base = base;
2145   int kind = classify_unsafe_addr(uncasted_base, offset, type);
2146   if (kind == Type::RawPtr) {
2147     return off_heap_plus_addr(uncasted_base, offset);
2148   } else if (kind == Type::AnyPtr) {
2149     assert(base == uncasted_base, "unexpected base change");
2150     if (can_cast) {
2151       if (!_gvn.type(base)->speculative_maybe_null() &&
2152           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2153         // According to profiling, this access is always on
2154         // heap. Casting the base to not null and thus avoiding membars
2155         // around the access should allow better optimizations
2156         Node* null_ctl = top();
2157         base = null_check_oop(base, &null_ctl, true, true, true);
2158         assert(null_ctl->is_top(), "no null control here");
2159         return basic_plus_adr(base, offset);
2160       } else if (_gvn.type(base)->speculative_always_null() &&
2161                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2162         // According to profiling, this access is always off
2163         // heap.
2164         base = null_assert(base);
2165         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2166         offset = MakeConX(0);
2167         return off_heap_plus_addr(raw_base, offset);
2168       }
2169     }
2170     // We don't know if it's an on heap or off heap access. Fall back
2171     // to raw memory access.
2172     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2173     return off_heap_plus_addr(raw, offset);
2174   } else {
2175     assert(base == uncasted_base, "unexpected base change");
2176     // We know it's an on heap access so base can't be null
2177     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2178       base = must_be_not_null(base, true);
2179     }
2180     return basic_plus_adr(base, offset);
2181   }
2182 }
2183 
2184 //--------------------------inline_number_methods-----------------------------
2185 // inline int     Integer.numberOfLeadingZeros(int)
2186 // inline int        Long.numberOfLeadingZeros(long)
2187 //
2188 // inline int     Integer.numberOfTrailingZeros(int)
2189 // inline int        Long.numberOfTrailingZeros(long)
2190 //
2191 // inline int     Integer.bitCount(int)
2192 // inline int        Long.bitCount(long)
2193 //
2194 // inline char  Character.reverseBytes(char)
2195 // inline short     Short.reverseBytes(short)
2196 // inline int     Integer.reverseBytes(int)
2197 // inline long       Long.reverseBytes(long)
2198 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2199   Node* arg = argument(0);
2200   Node* n = nullptr;
2201   switch (id) {
2202   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg); break;
2203   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg); break;
2204   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg); break;
2205   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg); break;
2206   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg); break;
2207   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg); break;
2208   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(     arg); break;
2209   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode(      arg); break;
2210   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode(      arg); break;
2211   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode(      arg); break;
2212   case vmIntrinsics::_reverse_i:                n = new ReverseINode(           arg); break;
2213   case vmIntrinsics::_reverse_l:                n = new ReverseLNode(           arg); break;
2214   default:  fatal_unexpected_iid(id);  break;
2215   }
2216   set_result(_gvn.transform(n));
2217   return true;
2218 }
2219 
2220 //--------------------------inline_bitshuffle_methods-----------------------------
2221 // inline int Integer.compress(int, int)
2222 // inline int Integer.expand(int, int)
2223 // inline long Long.compress(long, long)
2224 // inline long Long.expand(long, long)
2225 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2226   Node* n = nullptr;
2227   switch (id) {
2228     case vmIntrinsics::_compress_i:  n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2229     case vmIntrinsics::_expand_i:    n = new ExpandBitsNode(argument(0),  argument(1), TypeInt::INT); break;
2230     case vmIntrinsics::_compress_l:  n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2231     case vmIntrinsics::_expand_l:    n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2232     default:  fatal_unexpected_iid(id);  break;
2233   }
2234   set_result(_gvn.transform(n));
2235   return true;
2236 }
2237 
2238 //--------------------------inline_number_methods-----------------------------
2239 // inline int Integer.compareUnsigned(int, int)
2240 // inline int    Long.compareUnsigned(long, long)
2241 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2242   Node* arg1 = argument(0);
2243   Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2244   Node* n = nullptr;
2245   switch (id) {
2246     case vmIntrinsics::_compareUnsigned_i:   n = new CmpU3Node(arg1, arg2);  break;
2247     case vmIntrinsics::_compareUnsigned_l:   n = new CmpUL3Node(arg1, arg2); break;
2248     default:  fatal_unexpected_iid(id);  break;
2249   }
2250   set_result(_gvn.transform(n));
2251   return true;
2252 }
2253 
2254 //--------------------------inline_unsigned_divmod_methods-----------------------------
2255 // inline int Integer.divideUnsigned(int, int)
2256 // inline int Integer.remainderUnsigned(int, int)
2257 // inline long Long.divideUnsigned(long, long)
2258 // inline long Long.remainderUnsigned(long, long)
2259 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2260   Node* n = nullptr;
2261   switch (id) {
2262     case vmIntrinsics::_divideUnsigned_i: {
2263       zero_check_int(argument(1));
2264       // Compile-time detect of null-exception
2265       if (stopped()) {
2266         return true; // keep the graph constructed so far
2267       }
2268       n = new UDivINode(control(), argument(0), argument(1));
2269       break;
2270     }
2271     case vmIntrinsics::_divideUnsigned_l: {
2272       zero_check_long(argument(2));
2273       // Compile-time detect of null-exception
2274       if (stopped()) {
2275         return true; // keep the graph constructed so far
2276       }
2277       n = new UDivLNode(control(), argument(0), argument(2));
2278       break;
2279     }
2280     case vmIntrinsics::_remainderUnsigned_i: {
2281       zero_check_int(argument(1));
2282       // Compile-time detect of null-exception
2283       if (stopped()) {
2284         return true; // keep the graph constructed so far
2285       }
2286       n = new UModINode(control(), argument(0), argument(1));
2287       break;
2288     }
2289     case vmIntrinsics::_remainderUnsigned_l: {
2290       zero_check_long(argument(2));
2291       // Compile-time detect of null-exception
2292       if (stopped()) {
2293         return true; // keep the graph constructed so far
2294       }
2295       n = new UModLNode(control(), argument(0), argument(2));
2296       break;
2297     }
2298     default:  fatal_unexpected_iid(id);  break;
2299   }
2300   set_result(_gvn.transform(n));
2301   return true;
2302 }
2303 
2304 //----------------------------inline_unsafe_access----------------------------
2305 
2306 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2307   // Attempt to infer a sharper value type from the offset and base type.
2308   ciKlass* sharpened_klass = nullptr;
2309   bool null_free = false;
2310 
2311   // See if it is an instance field, with an object type.
2312   if (alias_type->field() != nullptr) {
2313     if (alias_type->field()->type()->is_klass()) {
2314       sharpened_klass = alias_type->field()->type()->as_klass();
2315       null_free = alias_type->field()->is_null_free();
2316     }
2317   }
2318 
2319   const TypeOopPtr* result = nullptr;
2320   // See if it is a narrow oop array.
2321   if (adr_type->isa_aryptr()) {
2322     if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2323       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2324       null_free = adr_type->is_aryptr()->is_null_free();
2325       if (elem_type != nullptr && elem_type->is_loaded()) {
2326         // Sharpen the value type.
2327         result = elem_type;
2328       }
2329     }
2330   }
2331 
2332   // The sharpened class might be unloaded if there is no class loader
2333   // contraint in place.
2334   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2335     // Sharpen the value type.
2336     result = TypeOopPtr::make_from_klass(sharpened_klass);
2337     if (null_free) {
2338       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2339     }
2340   }
2341   if (result != nullptr) {
2342 #ifndef PRODUCT
2343     if (C->print_intrinsics() || C->print_inlining()) {
2344       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2345       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2346     }
2347 #endif
2348   }
2349   return result;
2350 }
2351 
2352 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2353   switch (kind) {
2354       case Relaxed:
2355         return MO_UNORDERED;
2356       case Opaque:
2357         return MO_RELAXED;
2358       case Acquire:
2359         return MO_ACQUIRE;
2360       case Release:
2361         return MO_RELEASE;
2362       case Volatile:
2363         return MO_SEQ_CST;
2364       default:
2365         ShouldNotReachHere();
2366         return 0;
2367   }
2368 }
2369 
2370 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2371   if (callee()->is_static())  return false;  // caller must have the capability!
2372   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2373   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2374   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2375   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2376 
2377   if (is_reference_type(type)) {
2378     decorators |= ON_UNKNOWN_OOP_REF;
2379   }
2380 
2381   if (unaligned) {
2382     decorators |= C2_UNALIGNED;
2383   }
2384 
2385 #ifndef PRODUCT
2386   {
2387     ResourceMark rm;
2388     // Check the signatures.
2389     ciSignature* sig = callee()->signature();
2390 #ifdef ASSERT
2391     if (!is_store) {
2392       // Object getReference(Object base, int/long offset), etc.
2393       BasicType rtype = sig->return_type()->basic_type();
2394       assert(rtype == type, "getter must return the expected value");
2395       assert(sig->count() == 2, "oop getter has 2 arguments");
2396       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2397       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2398     } else {
2399       // void putReference(Object base, int/long offset, Object x), etc.
2400       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2401       assert(sig->count() == 3, "oop putter has 3 arguments");
2402       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2403       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2404       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2405       assert(vtype == type, "putter must accept the expected value");
2406     }
2407 #endif // ASSERT
2408  }
2409 #endif //PRODUCT
2410 
2411   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2412 
2413   Node* receiver = argument(0);  // type: oop
2414 
2415   // Build address expression.
2416   Node* heap_base_oop = top();
2417 
2418   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2419   Node* base = argument(1);  // type: oop
2420   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2421   Node* offset = argument(2);  // type: long
2422   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2423   // to be plain byte offsets, which are also the same as those accepted
2424   // by oopDesc::field_addr.
2425   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2426          "fieldOffset must be byte-scaled");
2427 
2428   if (base->is_InlineType()) {
2429     assert(!is_store, "InlineTypeNodes are non-larval value objects");
2430     InlineTypeNode* vt = base->as_InlineType();
2431     if (offset->is_Con()) {
2432       long off = find_long_con(offset, 0);
2433       ciInlineKlass* vk = vt->type()->inline_klass();
2434       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2435         return false;
2436       }
2437 
2438       ciField* field = vk->get_non_flat_field_by_offset(off);
2439       if (field != nullptr) {
2440         BasicType bt = type2field[field->type()->basic_type()];
2441         if (bt == T_ARRAY || bt == T_NARROWOOP) {
2442           bt = T_OBJECT;
2443         }
2444         if (bt == type && !field->is_flat()) {
2445           Node* value = vt->field_value_by_offset(off, false);
2446           const Type* value_type = _gvn.type(value);
2447           if (value->is_InlineType()) {
2448             value = value->as_InlineType()->adjust_scalarization_depth(this);
2449           } else if (value_type->is_inlinetypeptr()) {
2450             value = InlineTypeNode::make_from_oop(this, value, value_type->inline_klass());
2451           }
2452           set_result(value);
2453           return true;
2454         }
2455       }
2456     }
2457     {
2458       // Re-execute the unsafe access if allocation triggers deoptimization.
2459       PreserveReexecuteState preexecs(this);
2460       jvms()->set_should_reexecute(true);
2461       vt = vt->buffer(this);
2462     }
2463     base = vt->get_oop();
2464   }
2465 
2466   // 32-bit machines ignore the high half!
2467   offset = ConvL2X(offset);
2468 
2469   // Save state and restore on bailout
2470   SavedState old_state(this);
2471 
2472   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2473   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2474 
2475   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2476     if (type != T_OBJECT) {
2477       decorators |= IN_NATIVE; // off-heap primitive access
2478     } else {
2479       return false; // off-heap oop accesses are not supported
2480     }
2481   } else {
2482     heap_base_oop = base; // on-heap or mixed access
2483   }
2484 
2485   // Can base be null? Otherwise, always on-heap access.
2486   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2487 
2488   if (!can_access_non_heap) {
2489     decorators |= IN_HEAP;
2490   }
2491 
2492   Node* val = is_store ? argument(4) : nullptr;
2493 
2494   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2495   if (adr_type == TypePtr::NULL_PTR) {
2496     return false; // off-heap access with zero address
2497   }
2498 
2499   // Try to categorize the address.
2500   Compile::AliasType* alias_type = C->alias_type(adr_type);
2501   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2502 
2503   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2504       alias_type->adr_type() == TypeAryPtr::RANGE) {
2505     return false; // not supported
2506   }
2507 
2508   bool mismatched = false;
2509   BasicType bt = T_ILLEGAL;
2510   ciField* field = nullptr;
2511   if (adr_type->isa_instptr()) {
2512     const TypeInstPtr* instptr = adr_type->is_instptr();
2513     ciInstanceKlass* k = instptr->instance_klass();
2514     int off = instptr->offset();
2515     if (instptr->const_oop() != nullptr &&
2516         k == ciEnv::current()->Class_klass() &&
2517         instptr->offset() >= (k->size_helper() * wordSize)) {
2518       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2519       field = k->get_field_by_offset(off, true);
2520     } else {
2521       field = k->get_non_flat_field_by_offset(off);
2522     }
2523     if (field != nullptr) {
2524       bt = type2field[field->type()->basic_type()];
2525     }
2526     if (bt != alias_type->basic_type()) {
2527       // Type mismatch. Is it an access to a nested flat field?
2528       field = k->get_field_by_offset(off, false);
2529       if (field != nullptr) {
2530         bt = type2field[field->type()->basic_type()];
2531       }
2532     }
2533     assert(bt == alias_type->basic_type(), "should match");
2534   } else {
2535     bt = alias_type->basic_type();
2536   }
2537 
2538   if (bt != T_ILLEGAL) {
2539     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2540     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2541       // Alias type doesn't differentiate between byte[] and boolean[]).
2542       // Use address type to get the element type.
2543       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2544     }
2545     if (is_reference_type(bt, true)) {
2546       // accessing an array field with getReference is not a mismatch
2547       bt = T_OBJECT;
2548     }
2549     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2550       // Don't intrinsify mismatched object accesses
2551       return false;
2552     }
2553     mismatched = (bt != type);
2554   } else if (alias_type->adr_type()->isa_oopptr()) {
2555     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2556   }
2557 
2558   old_state.discard();
2559   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2560 
2561   if (mismatched) {
2562     decorators |= C2_MISMATCHED;
2563   }
2564 
2565   // First guess at the value type.
2566   const Type *value_type = Type::get_const_basic_type(type);
2567 
2568   // Figure out the memory ordering.
2569   decorators |= mo_decorator_for_access_kind(kind);
2570 
2571   if (!is_store) {
2572     if (type == T_OBJECT) {
2573       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2574       if (tjp != nullptr) {
2575         value_type = tjp;
2576       }
2577     }
2578   }
2579 
2580   receiver = null_check(receiver);
2581   if (stopped()) {
2582     return true;
2583   }
2584   // Heap pointers get a null-check from the interpreter,
2585   // as a courtesy.  However, this is not guaranteed by Unsafe,
2586   // and it is not possible to fully distinguish unintended nulls
2587   // from intended ones in this API.
2588 
2589   if (!is_store) {
2590     Node* p = nullptr;
2591     // Try to constant fold a load from a constant field
2592 
2593     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2594       // final or stable field
2595       p = make_constant_from_field(field, heap_base_oop);
2596     }
2597 
2598     if (p == nullptr) { // Could not constant fold the load
2599       p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2600       const TypeOopPtr* ptr = value_type->make_oopptr();
2601       if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2602         // Load a non-flattened inline type from memory
2603         p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2604       }
2605       // Normalize the value returned by getBoolean in the following cases
2606       if (type == T_BOOLEAN &&
2607           (mismatched ||
2608            heap_base_oop == top() ||                  // - heap_base_oop is null or
2609            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2610                                                       //   and the unsafe access is made to large offset
2611                                                       //   (i.e., larger than the maximum offset necessary for any
2612                                                       //   field access)
2613             ) {
2614           IdealKit ideal = IdealKit(this);
2615 #define __ ideal.
2616           IdealVariable normalized_result(ideal);
2617           __ declarations_done();
2618           __ set(normalized_result, p);
2619           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2620           __ set(normalized_result, ideal.ConI(1));
2621           ideal.end_if();
2622           final_sync(ideal);
2623           p = __ value(normalized_result);
2624 #undef __
2625       }
2626     }
2627     if (type == T_ADDRESS) {
2628       p = gvn().transform(new CastP2XNode(nullptr, p));
2629       p = ConvX2UL(p);
2630     }
2631     // The load node has the control of the preceding MemBarCPUOrder.  All
2632     // following nodes will have the control of the MemBarCPUOrder inserted at
2633     // the end of this method.  So, pushing the load onto the stack at a later
2634     // point is fine.
2635     set_result(p);
2636   } else {
2637     if (bt == T_ADDRESS) {
2638       // Repackage the long as a pointer.
2639       val = ConvL2X(val);
2640       val = gvn().transform(new CastX2PNode(val));
2641     }
2642     access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2643   }
2644 
2645   return true;
2646 }
2647 
2648 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2649 #ifdef ASSERT
2650   {
2651     ResourceMark rm;
2652     // Check the signatures.
2653     ciSignature* sig = callee()->signature();
2654     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2655     assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2656     assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2657     assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2658     if (is_store) {
2659       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2660       assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2661       assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2662     } else {
2663       assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2664       assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2665     }
2666  }
2667 #endif // ASSERT
2668 
2669   assert(kind == Relaxed, "Only plain accesses for now");
2670   if (callee()->is_static()) {
2671     // caller must have the capability!
2672     return false;
2673   }
2674   C->set_has_unsafe_access(true);
2675 
2676   const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2677   if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2678     // parameter valueType is not a constant
2679     return false;
2680   }
2681   ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2682   if (!mirror_type->is_inlinetype()) {
2683     // Dead code
2684     return false;
2685   }
2686   ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2687 
2688   const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2689   if (layout_type == nullptr || !layout_type->is_con()) {
2690     // parameter layoutKind is not a constant
2691     return false;
2692   }
2693   assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2694          layout_type->get_con() < static_cast<int>(LayoutKind::UNKNOWN),
2695          "invalid layoutKind %d", layout_type->get_con());
2696   LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2697   assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NULL_FREE_NON_ATOMIC_FLAT ||
2698          layout == LayoutKind::NULL_FREE_ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2699          "unexpected layoutKind %d", layout_type->get_con());
2700 
2701   null_check(argument(0));
2702   if (stopped()) {
2703     return true;
2704   }
2705 
2706   Node* base = must_be_not_null(argument(1), true);
2707   Node* offset = argument(2);
2708   const Type* base_type = _gvn.type(base);
2709 
2710   Node* ptr;
2711   bool immutable_memory = false;
2712   DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2713   if (base_type->isa_instptr()) {
2714     const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2715     if (offset_type == nullptr || !offset_type->is_con()) {
2716       // Offset into a non-array should be a constant
2717       decorators |= C2_MISMATCHED;
2718     } else {
2719       int offset_con = checked_cast<int>(offset_type->get_con());
2720       ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2721       ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2722       if (field == nullptr) {
2723         assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2724         decorators |= C2_MISMATCHED;
2725       } else {
2726         assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2727                offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2728         immutable_memory = field->is_strict() && field->is_final();
2729 
2730         if (base->is_InlineType()) {
2731           assert(!is_store, "Cannot store into a non-larval value object");
2732           set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2733           return true;
2734         }
2735       }
2736     }
2737 
2738     if (base->is_InlineType()) {
2739       assert(!is_store, "Cannot store into a non-larval value object");
2740       base = base->as_InlineType()->buffer(this, true);
2741     }
2742     ptr = basic_plus_adr(base, ConvL2X(offset));
2743   } else if (base_type->isa_aryptr()) {
2744     decorators |= IS_ARRAY;
2745     if (layout == LayoutKind::REFERENCE) {
2746       if (!base_type->is_aryptr()->is_not_flat()) {
2747         const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2748         Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2749         replace_in_map(base, new_base);
2750         base = new_base;
2751       }
2752       ptr = basic_plus_adr(base, ConvL2X(offset));
2753     } else {
2754       if (UseArrayFlattening) {
2755         // Flat array must have an exact type
2756         bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2757         bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2758         Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
2759         replace_in_map(base, new_base);
2760         base = new_base;
2761         ptr = basic_plus_adr(base, ConvL2X(offset));
2762         const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2763         if (ptr_type->field_offset().get() != 0) {
2764           ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2765         }
2766       } else {
2767         uncommon_trap(Deoptimization::Reason_intrinsic,
2768                       Deoptimization::Action_none);
2769         return true;
2770       }
2771     }
2772   } else {
2773     decorators |= C2_MISMATCHED;
2774     ptr = basic_plus_adr(base, ConvL2X(offset));
2775   }
2776 
2777   if (is_store) {
2778     Node* value = argument(6);
2779     const Type* value_type = _gvn.type(value);
2780     if (!value_type->is_inlinetypeptr()) {
2781       value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2782       Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2783       new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2784       replace_in_map(value, new_value);
2785       value = new_value;
2786     }
2787 
2788     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());
2789     if (layout == LayoutKind::REFERENCE) {
2790       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2791       access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2792     } else {
2793       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2794       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2795       value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2796     }
2797 
2798     return true;
2799   } else {
2800     decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2801     InlineTypeNode* result;
2802     if (layout == LayoutKind::REFERENCE) {
2803       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2804       Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2805       result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2806     } else {
2807       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2808       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2809       result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2810     }
2811 
2812     set_result(result);
2813     return true;
2814   }
2815 }
2816 
2817 //----------------------------inline_unsafe_load_store----------------------------
2818 // This method serves a couple of different customers (depending on LoadStoreKind):
2819 //
2820 // LS_cmp_swap:
2821 //
2822 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2823 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
2824 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
2825 //
2826 // LS_cmp_swap_weak:
2827 //
2828 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
2829 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
2830 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2831 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2832 //
2833 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
2834 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
2835 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
2836 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
2837 //
2838 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
2839 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
2840 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
2841 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
2842 //
2843 // LS_cmp_exchange:
2844 //
2845 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2846 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2847 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2848 //
2849 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
2850 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
2851 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
2852 //
2853 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
2854 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
2855 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
2856 //
2857 // LS_get_add:
2858 //
2859 //   int  getAndAddInt( Object o, long offset, int  delta)
2860 //   long getAndAddLong(Object o, long offset, long delta)
2861 //
2862 // LS_get_set:
2863 //
2864 //   int    getAndSet(Object o, long offset, int    newValue)
2865 //   long   getAndSet(Object o, long offset, long   newValue)
2866 //   Object getAndSet(Object o, long offset, Object newValue)
2867 //
2868 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2869   // This basic scheme here is the same as inline_unsafe_access, but
2870   // differs in enough details that combining them would make the code
2871   // overly confusing.  (This is a true fact! I originally combined
2872   // them, but even I was confused by it!) As much code/comments as
2873   // possible are retained from inline_unsafe_access though to make
2874   // the correspondences clearer. - dl
2875 
2876   if (callee()->is_static())  return false;  // caller must have the capability!
2877 
2878   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2879   decorators |= mo_decorator_for_access_kind(access_kind);
2880 
2881 #ifndef PRODUCT
2882   BasicType rtype;
2883   {
2884     ResourceMark rm;
2885     // Check the signatures.
2886     ciSignature* sig = callee()->signature();
2887     rtype = sig->return_type()->basic_type();
2888     switch(kind) {
2889       case LS_get_add:
2890       case LS_get_set: {
2891       // Check the signatures.
2892 #ifdef ASSERT
2893       assert(rtype == type, "get and set must return the expected type");
2894       assert(sig->count() == 3, "get and set has 3 arguments");
2895       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2896       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2897       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2898       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
2899 #endif // ASSERT
2900         break;
2901       }
2902       case LS_cmp_swap:
2903       case LS_cmp_swap_weak: {
2904       // Check the signatures.
2905 #ifdef ASSERT
2906       assert(rtype == T_BOOLEAN, "CAS must return boolean");
2907       assert(sig->count() == 4, "CAS has 4 arguments");
2908       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2909       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2910 #endif // ASSERT
2911         break;
2912       }
2913       case LS_cmp_exchange: {
2914       // Check the signatures.
2915 #ifdef ASSERT
2916       assert(rtype == type, "CAS must return the expected type");
2917       assert(sig->count() == 4, "CAS has 4 arguments");
2918       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2919       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2920 #endif // ASSERT
2921         break;
2922       }
2923       default:
2924         ShouldNotReachHere();
2925     }
2926   }
2927 #endif //PRODUCT
2928 
2929   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2930 
2931   // Get arguments:
2932   Node* receiver = nullptr;
2933   Node* base     = nullptr;
2934   Node* offset   = nullptr;
2935   Node* oldval   = nullptr;
2936   Node* newval   = nullptr;
2937   switch(kind) {
2938     case LS_cmp_swap:
2939     case LS_cmp_swap_weak:
2940     case LS_cmp_exchange: {
2941       const bool two_slot_type = type2size[type] == 2;
2942       receiver = argument(0);  // type: oop
2943       base     = argument(1);  // type: oop
2944       offset   = argument(2);  // type: long
2945       oldval   = argument(4);  // type: oop, int, or long
2946       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
2947       break;
2948     }
2949     case LS_get_add:
2950     case LS_get_set: {
2951       receiver = argument(0);  // type: oop
2952       base     = argument(1);  // type: oop
2953       offset   = argument(2);  // type: long
2954       oldval   = nullptr;
2955       newval   = argument(4);  // type: oop, int, or long
2956       break;
2957     }
2958     default:
2959       ShouldNotReachHere();
2960   }
2961 
2962   // Build field offset expression.
2963   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2964   // to be plain byte offsets, which are also the same as those accepted
2965   // by oopDesc::field_addr.
2966   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2967   // 32-bit machines ignore the high half of long offsets
2968   offset = ConvL2X(offset);
2969   // Save state and restore on bailout
2970   SavedState old_state(this);
2971   Node* adr = make_unsafe_address(base, offset,type, false);
2972   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2973 
2974   Compile::AliasType* alias_type = C->alias_type(adr_type);
2975   BasicType bt = alias_type->basic_type();
2976   if (bt != T_ILLEGAL &&
2977       (is_reference_type(bt) != (type == T_OBJECT))) {
2978     // Don't intrinsify mismatched object accesses.
2979     return false;
2980   }
2981 
2982   old_state.discard();
2983 
2984   // For CAS, unlike inline_unsafe_access, there seems no point in
2985   // trying to refine types. Just use the coarse types here.
2986   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2987   const Type *value_type = Type::get_const_basic_type(type);
2988 
2989   switch (kind) {
2990     case LS_get_set:
2991     case LS_cmp_exchange: {
2992       if (type == T_OBJECT) {
2993         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2994         if (tjp != nullptr) {
2995           value_type = tjp;
2996         }
2997       }
2998       break;
2999     }
3000     case LS_cmp_swap:
3001     case LS_cmp_swap_weak:
3002     case LS_get_add:
3003       break;
3004     default:
3005       ShouldNotReachHere();
3006   }
3007 
3008   // Null check receiver.
3009   receiver = null_check(receiver);
3010   if (stopped()) {
3011     return true;
3012   }
3013 
3014   int alias_idx = C->get_alias_index(adr_type);
3015 
3016   if (is_reference_type(type)) {
3017     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3018 
3019     if (oldval != nullptr && oldval->is_InlineType()) {
3020       // Re-execute the unsafe access if allocation triggers deoptimization.
3021       PreserveReexecuteState preexecs(this);
3022       jvms()->set_should_reexecute(true);
3023       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3024     }
3025     if (newval != nullptr && newval->is_InlineType()) {
3026       // Re-execute the unsafe access if allocation triggers deoptimization.
3027       PreserveReexecuteState preexecs(this);
3028       jvms()->set_should_reexecute(true);
3029       newval = newval->as_InlineType()->buffer(this)->get_oop();
3030     }
3031 
3032     // Transformation of a value which could be null pointer (CastPP #null)
3033     // could be delayed during Parse (for example, in adjust_map_after_if()).
3034     // Execute transformation here to avoid barrier generation in such case.
3035     if (_gvn.type(newval) == TypePtr::NULL_PTR)
3036       newval = _gvn.makecon(TypePtr::NULL_PTR);
3037 
3038     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3039       // Refine the value to a null constant, when it is known to be null
3040       oldval = _gvn.makecon(TypePtr::NULL_PTR);
3041     }
3042   }
3043 
3044   Node* result = nullptr;
3045   switch (kind) {
3046     case LS_cmp_exchange: {
3047       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3048                                             oldval, newval, value_type, type, decorators);
3049       break;
3050     }
3051     case LS_cmp_swap_weak:
3052       decorators |= C2_WEAK_CMPXCHG;
3053     case LS_cmp_swap: {
3054       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3055                                              oldval, newval, value_type, type, decorators);
3056       break;
3057     }
3058     case LS_get_set: {
3059       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3060                                      newval, value_type, type, decorators);
3061       break;
3062     }
3063     case LS_get_add: {
3064       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3065                                     newval, value_type, type, decorators);
3066       break;
3067     }
3068     default:
3069       ShouldNotReachHere();
3070   }
3071 
3072   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3073   set_result(result);
3074   return true;
3075 }
3076 
3077 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3078   // Regardless of form, don't allow previous ld/st to move down,
3079   // then issue acquire, release, or volatile mem_bar.
3080   insert_mem_bar(Op_MemBarCPUOrder);
3081   switch(id) {
3082     case vmIntrinsics::_loadFence:
3083       insert_mem_bar(Op_LoadFence);
3084       return true;
3085     case vmIntrinsics::_storeFence:
3086       insert_mem_bar(Op_StoreFence);
3087       return true;
3088     case vmIntrinsics::_storeStoreFence:
3089       insert_mem_bar(Op_StoreStoreFence);
3090       return true;
3091     case vmIntrinsics::_fullFence:
3092       insert_mem_bar(Op_MemBarFull);
3093       return true;
3094     default:
3095       fatal_unexpected_iid(id);
3096       return false;
3097   }
3098 }
3099 
3100 // private native int arrayInstanceBaseOffset0(Object[] array);
3101 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3102   Node* array = argument(1);
3103   Node* klass_node = load_object_klass(array);
3104 
3105   jint  layout_con = Klass::_lh_neutral_value;
3106   Node* layout_val = get_layout_helper(klass_node, layout_con);
3107   int   layout_is_con = (layout_val == nullptr);
3108 
3109   Node* header_size = nullptr;
3110   if (layout_is_con) {
3111     int hsize = Klass::layout_helper_header_size(layout_con);
3112     header_size = intcon(hsize);
3113   } else {
3114     Node* hss = intcon(Klass::_lh_header_size_shift);
3115     Node* hsm = intcon(Klass::_lh_header_size_mask);
3116     header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3117     header_size = _gvn.transform(new AndINode(header_size, hsm));
3118   }
3119   set_result(header_size);
3120   return true;
3121 }
3122 
3123 // private native int arrayInstanceIndexScale0(Object[] array);
3124 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3125   Node* array = argument(1);
3126   Node* klass_node = load_object_klass(array);
3127 
3128   jint  layout_con = Klass::_lh_neutral_value;
3129   Node* layout_val = get_layout_helper(klass_node, layout_con);
3130   int   layout_is_con = (layout_val == nullptr);
3131 
3132   Node* element_size = nullptr;
3133   if (layout_is_con) {
3134     int log_element_size  = Klass::layout_helper_log2_element_size(layout_con);
3135     int elem_size = 1 << log_element_size;
3136     element_size = intcon(elem_size);
3137   } else {
3138     Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3139     Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3140     Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3141     log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3142     element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3143   }
3144   set_result(element_size);
3145   return true;
3146 }
3147 
3148 // private native int arrayLayout0(Object[] array);
3149 bool LibraryCallKit::inline_arrayLayout() {
3150   RegionNode* region = new RegionNode(2);
3151   Node* phi = new PhiNode(region, TypeInt::POS);
3152 
3153   Node* array = argument(1);
3154   Node* klass_node = load_object_klass(array);
3155   generate_refArray_guard(klass_node, region);
3156   if (region->req() == 3) {
3157     phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3158   }
3159 
3160   int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3161   Node* layout_kind_addr = basic_plus_adr(top(), klass_node, layout_kind_offset);
3162   Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3163 
3164   region->init_req(1, control());
3165   phi->init_req(1, layout_kind);
3166 
3167   set_control(_gvn.transform(region));
3168   set_result(_gvn.transform(phi));
3169   return true;
3170 }
3171 
3172 // private native int[] getFieldMap0(Class <?> c);
3173 //   int offset = c._klass._acmp_maps_offset;
3174 //   return (int[])c.obj_field(offset);
3175 bool LibraryCallKit::inline_getFieldMap() {
3176   Node* mirror = argument(1);
3177   Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
3178 
3179   int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
3180   Node* field_map_offset_addr = basic_plus_adr(top(), klass, field_map_offset_offset);
3181   Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
3182   field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
3183 
3184   Node* map_addr = basic_plus_adr(mirror, field_map_offset);
3185   const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
3186   // TODO 8350865 Remove this
3187   val_type = val_type->cast_to_not_flat(true)->cast_to_not_null_free(true);
3188   Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
3189 
3190   set_result(map);
3191   return true;
3192 }
3193 
3194 bool LibraryCallKit::inline_onspinwait() {
3195   insert_mem_bar(Op_OnSpinWait);
3196   return true;
3197 }
3198 
3199 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3200   if (!kls->is_Con()) {
3201     return true;
3202   }
3203   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3204   if (klsptr == nullptr) {
3205     return true;
3206   }
3207   ciInstanceKlass* ik = klsptr->instance_klass();
3208   // don't need a guard for a klass that is already initialized
3209   return !ik->is_initialized();
3210 }
3211 
3212 //----------------------------inline_unsafe_writeback0-------------------------
3213 // public native void Unsafe.writeback0(long address)
3214 bool LibraryCallKit::inline_unsafe_writeback0() {
3215   if (!Matcher::has_match_rule(Op_CacheWB)) {
3216     return false;
3217   }
3218 #ifndef PRODUCT
3219   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3220   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3221   ciSignature* sig = callee()->signature();
3222   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3223 #endif
3224   null_check_receiver();  // null-check, then ignore
3225   Node *addr = argument(1);
3226   addr = new CastX2PNode(addr);
3227   addr = _gvn.transform(addr);
3228   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3229   flush = _gvn.transform(flush);
3230   set_memory(flush, TypeRawPtr::BOTTOM);
3231   return true;
3232 }
3233 
3234 //----------------------------inline_unsafe_writeback0-------------------------
3235 // public native void Unsafe.writeback0(long address)
3236 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3237   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3238     return false;
3239   }
3240   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3241     return false;
3242   }
3243 #ifndef PRODUCT
3244   assert(Matcher::has_match_rule(Op_CacheWB),
3245          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3246                 : "found match rule for CacheWBPostSync but not CacheWB"));
3247 
3248 #endif
3249   null_check_receiver();  // null-check, then ignore
3250   Node *sync;
3251   if (is_pre) {
3252     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3253   } else {
3254     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3255   }
3256   sync = _gvn.transform(sync);
3257   set_memory(sync, TypeRawPtr::BOTTOM);
3258   return true;
3259 }
3260 
3261 //----------------------------inline_unsafe_allocate---------------------------
3262 // public native Object Unsafe.allocateInstance(Class<?> cls);
3263 bool LibraryCallKit::inline_unsafe_allocate() {
3264 
3265 #if INCLUDE_JVMTI
3266   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3267     return false;
3268   }
3269 #endif //INCLUDE_JVMTI
3270 
3271   if (callee()->is_static())  return false;  // caller must have the capability!
3272 
3273   null_check_receiver();  // null-check, then ignore
3274   Node* cls = null_check(argument(1));
3275   if (stopped())  return true;
3276 
3277   Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3278   kls = null_check(kls);
3279   if (stopped())  return true;  // argument was like int.class
3280 
3281 #if INCLUDE_JVMTI
3282     // Don't try to access new allocated obj in the intrinsic.
3283     // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3284     // Deoptimize and allocate in interpreter instead.
3285     Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3286     Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3287     Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3288     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3289     {
3290       BuildCutout unless(this, tst, PROB_MAX);
3291       uncommon_trap(Deoptimization::Reason_intrinsic,
3292                     Deoptimization::Action_make_not_entrant);
3293     }
3294     if (stopped()) {
3295       return true;
3296     }
3297 #endif //INCLUDE_JVMTI
3298 
3299   Node* test = nullptr;
3300   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3301     // Note:  The argument might still be an illegal value like
3302     // Serializable.class or Object[].class.   The runtime will handle it.
3303     // But we must make an explicit check for initialization.
3304     Node* insp = off_heap_plus_addr(kls, in_bytes(InstanceKlass::init_state_offset()));
3305     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3306     // can generate code to load it as unsigned byte.
3307     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3308     Node* bits = intcon(InstanceKlass::fully_initialized);
3309     test = _gvn.transform(new SubINode(inst, bits));
3310     // The 'test' is non-zero if we need to take a slow path.
3311   }
3312   Node* obj = new_instance(kls, test);
3313   set_result(obj);
3314   return true;
3315 }
3316 
3317 //------------------------inline_native_time_funcs--------------
3318 // inline code for System.currentTimeMillis() and System.nanoTime()
3319 // these have the same type and signature
3320 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3321   const TypeFunc* tf = OptoRuntime::void_long_Type();
3322   const TypePtr* no_memory_effects = nullptr;
3323   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3324   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3325 #ifdef ASSERT
3326   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3327   assert(value_top == top(), "second value must be top");
3328 #endif
3329   set_result(value);
3330   return true;
3331 }
3332 
3333 //--------------------inline_native_vthread_start_transition--------------------
3334 // inline void startTransition(boolean is_mount);
3335 // inline void startFinalTransition();
3336 // Pseudocode of implementation:
3337 //
3338 // java_lang_Thread::set_is_in_vthread_transition(vthread, true);
3339 // carrier->set_is_in_vthread_transition(true);
3340 // OrderAccess::storeload();
3341 // int disable_requests = java_lang_Thread::vthread_transition_disable_count(vthread)
3342 //                        + global_vthread_transition_disable_count();
3343 // if (disable_requests > 0) {
3344 //   slow path: runtime call
3345 // }
3346 bool LibraryCallKit::inline_native_vthread_start_transition(address funcAddr, const char* funcName, bool is_final_transition) {
3347   Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
3348   IdealKit ideal(this);
3349 
3350   Node* thread = ideal.thread();
3351   Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3352   Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3353   access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3354   access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3355   insert_mem_bar(Op_MemBarStoreLoad);
3356   ideal.sync_kit(this);
3357 
3358   Node* global_disable_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::global_vthread_transition_disable_count_address()));
3359   Node* global_disable = ideal.load(ideal.ctrl(), global_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3360   Node* vt_disable_addr = basic_plus_adr(vt_oop, java_lang_Thread::vthread_transition_disable_count_offset());
3361   const TypePtr* vt_disable_addr_t = _gvn.type(vt_disable_addr)->is_ptr();
3362   Node* vt_disable = ideal.load(ideal.ctrl(), vt_disable_addr, TypeInt::INT, T_INT, C->get_alias_index(vt_disable_addr_t), true /*require_atomic_access*/);
3363   Node* disabled = _gvn.transform(new AddINode(global_disable, vt_disable));
3364 
3365   ideal.if_then(disabled, BoolTest::ne, ideal.ConI(0)); {
3366     sync_kit(ideal);
3367     Node* is_mount = is_final_transition ? ideal.ConI(0) : argument(1);
3368     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3369     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3370     ideal.sync_kit(this);
3371   }
3372   ideal.end_if();
3373 
3374   final_sync(ideal);
3375   return true;
3376 }
3377 
3378 bool LibraryCallKit::inline_native_vthread_end_transition(address funcAddr, const char* funcName, bool is_first_transition) {
3379   Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
3380   IdealKit ideal(this);
3381 
3382   Node* _notify_jvmti_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::notify_jvmti_events_address()));
3383   Node* _notify_jvmti = ideal.load(ideal.ctrl(), _notify_jvmti_addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3384 
3385   ideal.if_then(_notify_jvmti, BoolTest::eq, ideal.ConI(1)); {
3386     sync_kit(ideal);
3387     Node* is_mount = is_first_transition ? ideal.ConI(1) : argument(1);
3388     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3389     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3390     ideal.sync_kit(this);
3391   } ideal.else_(); {
3392     Node* thread = ideal.thread();
3393     Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3394     Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3395 
3396     sync_kit(ideal);
3397     access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3398     access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3399     ideal.sync_kit(this);
3400   } ideal.end_if();
3401 
3402   final_sync(ideal);
3403   return true;
3404 }
3405 
3406 #if INCLUDE_JVMTI
3407 
3408 // Always update the is_disable_suspend bit.
3409 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3410   if (!DoJVMTIVirtualThreadTransitions) {
3411     return true;
3412   }
3413   IdealKit ideal(this);
3414 
3415   {
3416     // unconditionally update the is_disable_suspend bit in current JavaThread
3417     Node* thread = ideal.thread();
3418     Node* arg = argument(0); // argument for notification
3419     Node* addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3420     const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3421 
3422     sync_kit(ideal);
3423     access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3424     ideal.sync_kit(this);
3425   }
3426   final_sync(ideal);
3427 
3428   return true;
3429 }
3430 
3431 #endif // INCLUDE_JVMTI
3432 
3433 #ifdef JFR_HAVE_INTRINSICS
3434 
3435 /**
3436  * if oop->klass != null
3437  *   // normal class
3438  *   epoch = _epoch_state ? 2 : 1
3439  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3440  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3441  *   }
3442  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3443  * else
3444  *   // primitive class
3445  *   if oop->array_klass != null
3446  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3447  *   else
3448  *     id = LAST_TYPE_ID + 1 // void class path
3449  *   if (!signaled)
3450  *     signaled = true
3451  */
3452 bool LibraryCallKit::inline_native_classID() {
3453   Node* cls = argument(0);
3454 
3455   IdealKit ideal(this);
3456 #define __ ideal.
3457   IdealVariable result(ideal); __ declarations_done();
3458   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3459                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
3460                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3461 
3462 
3463   __ if_then(kls, BoolTest::ne, null()); {
3464     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3465     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3466 
3467     Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3468     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3469     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3470     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3471     mask = _gvn.transform(new OrLNode(mask, epoch));
3472     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3473 
3474     float unlikely  = PROB_UNLIKELY(0.999);
3475     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3476       sync_kit(ideal);
3477       make_runtime_call(RC_LEAF,
3478                         OptoRuntime::class_id_load_barrier_Type(),
3479                         CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3480                         "class id load barrier",
3481                         TypePtr::BOTTOM,
3482                         kls);
3483       ideal.sync_kit(this);
3484     } __ end_if();
3485 
3486     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3487   } __ else_(); {
3488     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3489                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3490                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3491     __ if_then(array_kls, BoolTest::ne, null()); {
3492       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3493       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3494       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3495       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3496     } __ else_(); {
3497       // void class case
3498       ideal.set(result, longcon(LAST_TYPE_ID + 1));
3499     } __ end_if();
3500 
3501     Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3502     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3503     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3504       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3505     } __ end_if();
3506   } __ end_if();
3507 
3508   final_sync(ideal);
3509   set_result(ideal.value(result));
3510 #undef __
3511   return true;
3512 }
3513 
3514 //------------------------inline_native_jvm_commit------------------
3515 bool LibraryCallKit::inline_native_jvm_commit() {
3516   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3517 
3518   // Save input memory and i_o state.
3519   Node* input_memory_state = reset_memory();
3520   set_all_memory(input_memory_state);
3521   Node* input_io_state = i_o();
3522 
3523   // TLS.
3524   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3525   // Jfr java buffer.
3526   Node* java_buffer_offset = _gvn.transform(AddPNode::make_off_heap(tls_ptr, MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR))));
3527   Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3528   Node* java_buffer_pos_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET))));
3529 
3530   // Load the current value of the notified field in the JfrThreadLocal.
3531   Node* notified_offset = off_heap_plus_addr(tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3532   Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3533 
3534   // Test for notification.
3535   Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3536   Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3537   IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3538 
3539   // True branch, is notified.
3540   Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3541   set_control(is_notified);
3542 
3543   // Reset notified state.
3544   store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3545   Node* notified_reset_memory = reset_memory();
3546 
3547   // 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.
3548   Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3549   // Convert the machine-word to a long.
3550   Node* current_pos = ConvX2L(current_pos_X);
3551 
3552   // False branch, not notified.
3553   Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3554   set_control(not_notified);
3555   set_all_memory(input_memory_state);
3556 
3557   // Arg is the next position as a long.
3558   Node* arg = argument(0);
3559   // Convert long to machine-word.
3560   Node* next_pos_X = ConvL2X(arg);
3561 
3562   // Store the next_position to the underlying jfr java buffer.
3563   store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3564 
3565   Node* commit_memory = reset_memory();
3566   set_all_memory(commit_memory);
3567 
3568   // 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.
3569   Node* java_buffer_flags_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET))));
3570   Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3571   Node* lease_constant = _gvn.intcon(4);
3572 
3573   // And flags with lease constant.
3574   Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3575 
3576   // Branch on lease to conditionalize returning the leased java buffer.
3577   Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3578   Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3579   IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3580 
3581   // False branch, not a lease.
3582   Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3583 
3584   // True branch, is lease.
3585   Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3586   set_control(is_lease);
3587 
3588   // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3589   Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3590                                               OptoRuntime::void_void_Type(),
3591                                               SharedRuntime::jfr_return_lease(),
3592                                               "return_lease", TypePtr::BOTTOM);
3593   Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3594 
3595   RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3596   record_for_igvn(lease_compare_rgn);
3597   PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3598   record_for_igvn(lease_compare_mem);
3599   PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3600   record_for_igvn(lease_compare_io);
3601   PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3602   record_for_igvn(lease_result_value);
3603 
3604   // Update control and phi nodes.
3605   lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3606   lease_compare_rgn->init_req(_false_path, not_lease);
3607 
3608   lease_compare_mem->init_req(_true_path, reset_memory());
3609   lease_compare_mem->init_req(_false_path, commit_memory);
3610 
3611   lease_compare_io->init_req(_true_path, i_o());
3612   lease_compare_io->init_req(_false_path, input_io_state);
3613 
3614   lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3615   lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3616 
3617   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3618   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3619   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3620   PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3621 
3622   // Update control and phi nodes.
3623   result_rgn->init_req(_true_path, is_notified);
3624   result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3625 
3626   result_mem->init_req(_true_path, notified_reset_memory);
3627   result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3628 
3629   result_io->init_req(_true_path, input_io_state);
3630   result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3631 
3632   result_value->init_req(_true_path, current_pos);
3633   result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3634 
3635   // Set output state.
3636   set_control(_gvn.transform(result_rgn));
3637   set_all_memory(_gvn.transform(result_mem));
3638   set_i_o(_gvn.transform(result_io));
3639   set_result(result_rgn, result_value);
3640   return true;
3641 }
3642 
3643 /*
3644  * The intrinsic is a model of this pseudo-code:
3645  *
3646  * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3647  * jobject h_event_writer = tl->java_event_writer();
3648  * if (h_event_writer == nullptr) {
3649  *   return nullptr;
3650  * }
3651  * oop threadObj = Thread::threadObj();
3652  * oop vthread = java_lang_Thread::vthread(threadObj);
3653  * traceid tid;
3654  * bool pinVirtualThread;
3655  * bool excluded;
3656  * if (vthread != threadObj) {  // i.e. current thread is virtual
3657  *   tid = java_lang_Thread::tid(vthread);
3658  *   u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3659  *   pinVirtualThread = VMContinuations;
3660  *   excluded = vthread_epoch_raw & excluded_mask;
3661  *   if (!excluded) {
3662  *     traceid current_epoch = JfrTraceIdEpoch::current_generation();
3663  *     u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3664  *     if (vthread_epoch != current_epoch) {
3665  *       write_checkpoint();
3666  *     }
3667  *   }
3668  * } else {
3669  *   tid = java_lang_Thread::tid(threadObj);
3670  *   u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3671  *   pinVirtualThread = false;
3672  *   excluded = thread_epoch_raw & excluded_mask;
3673  * }
3674  * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3675  * traceid tid_in_event_writer = getField(event_writer, "threadID");
3676  * if (tid_in_event_writer != tid) {
3677  *   setField(event_writer, "pinVirtualThread", pinVirtualThread);
3678  *   setField(event_writer, "excluded", excluded);
3679  *   setField(event_writer, "threadID", tid);
3680  * }
3681  * return event_writer
3682  */
3683 bool LibraryCallKit::inline_native_getEventWriter() {
3684   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3685 
3686   // Save input memory and i_o state.
3687   Node* input_memory_state = reset_memory();
3688   set_all_memory(input_memory_state);
3689   Node* input_io_state = i_o();
3690 
3691   // The most significant bit of the u2 is used to denote thread exclusion
3692   Node* excluded_shift = _gvn.intcon(15);
3693   Node* excluded_mask = _gvn.intcon(1 << 15);
3694   // The epoch generation is the range [1-32767]
3695   Node* epoch_mask = _gvn.intcon(32767);
3696 
3697   // TLS
3698   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3699 
3700   // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3701   Node* jobj_ptr = off_heap_plus_addr(tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3702 
3703   // Load the eventwriter jobject handle.
3704   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3705 
3706   // Null check the jobject handle.
3707   Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3708   Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3709   IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3710 
3711   // False path, jobj is null.
3712   Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3713 
3714   // True path, jobj is not null.
3715   Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3716 
3717   set_control(jobj_is_not_null);
3718 
3719   // Load the threadObj for the CarrierThread.
3720   Node* threadObj = generate_current_thread(tls_ptr);
3721 
3722   // Load the vthread.
3723   Node* vthread = generate_virtual_thread(tls_ptr);
3724 
3725   // If vthread != threadObj, this is a virtual thread.
3726   Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3727   Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3728   IfNode* iff_vthread_not_equal_threadObj =
3729     create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3730 
3731   // False branch, fallback to threadObj.
3732   Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3733   set_control(vthread_equal_threadObj);
3734 
3735   // Load the tid field from the vthread object.
3736   Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3737 
3738   // Load the raw epoch value from the threadObj.
3739   Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3740   Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3741                                              _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3742                                              TypeInt::CHAR, T_CHAR,
3743                                              IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3744 
3745   // Mask off the excluded information from the epoch.
3746   Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3747 
3748   // True branch, this is a virtual thread.
3749   Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3750   set_control(vthread_not_equal_threadObj);
3751 
3752   // Load the tid field from the vthread object.
3753   Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3754 
3755   // Continuation support determines if a virtual thread should be pinned.
3756   Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3757   Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3758 
3759   // Load the raw epoch value from the vthread.
3760   Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3761   Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3762                                            TypeInt::CHAR, T_CHAR,
3763                                            IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3764 
3765   // Mask off the excluded information from the epoch.
3766   Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, excluded_mask));
3767 
3768   // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3769   Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, excluded_mask));
3770   Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3771   IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3772 
3773   // False branch, vthread is excluded, no need to write epoch info.
3774   Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3775 
3776   // True branch, vthread is included, update epoch info.
3777   Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3778   set_control(included);
3779 
3780   // Get epoch value.
3781   Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, epoch_mask));
3782 
3783   // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3784   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3785   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3786 
3787   // Compare the epoch in the vthread to the current epoch generation.
3788   Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3789   Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3790   IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3791 
3792   // False path, epoch is equal, checkpoint information is valid.
3793   Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3794 
3795   // True path, epoch is not equal, write a checkpoint for the vthread.
3796   Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3797 
3798   set_control(epoch_is_not_equal);
3799 
3800   // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3801   // The call also updates the native thread local thread id and the vthread with the current epoch.
3802   Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3803                                                   OptoRuntime::jfr_write_checkpoint_Type(),
3804                                                   SharedRuntime::jfr_write_checkpoint(),
3805                                                   "write_checkpoint", TypePtr::BOTTOM);
3806   Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3807 
3808   // vthread epoch != current epoch
3809   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3810   record_for_igvn(epoch_compare_rgn);
3811   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3812   record_for_igvn(epoch_compare_mem);
3813   PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3814   record_for_igvn(epoch_compare_io);
3815 
3816   // Update control and phi nodes.
3817   epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3818   epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3819   epoch_compare_mem->init_req(_true_path, reset_memory());
3820   epoch_compare_mem->init_req(_false_path, input_memory_state);
3821   epoch_compare_io->init_req(_true_path, i_o());
3822   epoch_compare_io->init_req(_false_path, input_io_state);
3823 
3824   // excluded != true
3825   RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3826   record_for_igvn(exclude_compare_rgn);
3827   PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3828   record_for_igvn(exclude_compare_mem);
3829   PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3830   record_for_igvn(exclude_compare_io);
3831 
3832   // Update control and phi nodes.
3833   exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3834   exclude_compare_rgn->init_req(_false_path, excluded);
3835   exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3836   exclude_compare_mem->init_req(_false_path, input_memory_state);
3837   exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3838   exclude_compare_io->init_req(_false_path, input_io_state);
3839 
3840   // vthread != threadObj
3841   RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3842   record_for_igvn(vthread_compare_rgn);
3843   PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3844   PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3845   record_for_igvn(vthread_compare_io);
3846   PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3847   record_for_igvn(tid);
3848   PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3849   record_for_igvn(exclusion);
3850   PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
3851   record_for_igvn(pinVirtualThread);
3852 
3853   // Update control and phi nodes.
3854   vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
3855   vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
3856   vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
3857   vthread_compare_mem->init_req(_false_path, input_memory_state);
3858   vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
3859   vthread_compare_io->init_req(_false_path, input_io_state);
3860   tid->init_req(_true_path, vthread_tid);
3861   tid->init_req(_false_path, thread_obj_tid);
3862   exclusion->init_req(_true_path, vthread_is_excluded);
3863   exclusion->init_req(_false_path, threadObj_is_excluded);
3864   pinVirtualThread->init_req(_true_path, continuation_support);
3865   pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
3866 
3867   // Update branch state.
3868   set_control(_gvn.transform(vthread_compare_rgn));
3869   set_all_memory(_gvn.transform(vthread_compare_mem));
3870   set_i_o(_gvn.transform(vthread_compare_io));
3871 
3872   // Load the event writer oop by dereferencing the jobject handle.
3873   ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
3874   assert(klass_EventWriter->is_loaded(), "invariant");
3875   ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
3876   const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
3877   const TypeOopPtr* const xtype = aklass->as_instance_type();
3878   Node* jobj_untagged = _gvn.transform(AddPNode::make_off_heap(jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
3879   Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3880 
3881   // Load the current thread id from the event writer object.
3882   Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
3883   // Get the field offset to, conditionally, store an updated tid value later.
3884   Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
3885   // Get the field offset to, conditionally, store an updated exclusion value later.
3886   Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
3887   // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
3888   Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
3889 
3890   RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
3891   record_for_igvn(event_writer_tid_compare_rgn);
3892   PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3893   record_for_igvn(event_writer_tid_compare_mem);
3894   PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
3895   record_for_igvn(event_writer_tid_compare_io);
3896 
3897   // Compare the current tid from the thread object to what is currently stored in the event writer object.
3898   Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
3899   Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
3900   IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3901 
3902   // False path, tids are the same.
3903   Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
3904 
3905   // True path, tid is not equal, need to update the tid in the event writer.
3906   Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
3907   record_for_igvn(tid_is_not_equal);
3908 
3909   // Store the pin state to the event writer.
3910   store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
3911 
3912   // Store the exclusion state to the event writer.
3913   Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
3914   store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
3915 
3916   // Store the tid to the event writer.
3917   store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
3918 
3919   // Update control and phi nodes.
3920   event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
3921   event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
3922   event_writer_tid_compare_mem->init_req(_true_path, reset_memory());
3923   event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
3924   event_writer_tid_compare_io->init_req(_true_path, i_o());
3925   event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
3926 
3927   // Result of top level CFG, Memory, IO and Value.
3928   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3929   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3930   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3931   PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
3932 
3933   // Result control.
3934   result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
3935   result_rgn->init_req(_false_path, jobj_is_null);
3936 
3937   // Result memory.
3938   result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
3939   result_mem->init_req(_false_path, input_memory_state);
3940 
3941   // Result IO.
3942   result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
3943   result_io->init_req(_false_path, input_io_state);
3944 
3945   // Result value.
3946   result_value->init_req(_true_path, event_writer); // return event writer oop
3947   result_value->init_req(_false_path, null()); // return null
3948 
3949   // Set output state.
3950   set_control(_gvn.transform(result_rgn));
3951   set_all_memory(_gvn.transform(result_mem));
3952   set_i_o(_gvn.transform(result_io));
3953   set_result(result_rgn, result_value);
3954   return true;
3955 }
3956 
3957 /*
3958  * The intrinsic is a model of this pseudo-code:
3959  *
3960  * JfrThreadLocal* const tl = thread->jfr_thread_local();
3961  * if (carrierThread != thread) { // is virtual thread
3962  *   const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
3963  *   bool excluded = vthread_epoch_raw & excluded_mask;
3964  *   AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
3965  *   AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
3966  *   if (!excluded) {
3967  *     const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3968  *     AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
3969  *   }
3970  *   AtomicAccess::release_store(&tl->_vthread, true);
3971  *   return;
3972  * }
3973  * AtomicAccess::release_store(&tl->_vthread, false);
3974  */
3975 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
3976   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3977 
3978   Node* input_memory_state = reset_memory();
3979   set_all_memory(input_memory_state);
3980 
3981   // The most significant bit of the u2 is used to denote thread exclusion
3982   Node* excluded_mask = _gvn.intcon(1 << 15);
3983   // The epoch generation is the range [1-32767]
3984   Node* epoch_mask = _gvn.intcon(32767);
3985 
3986   Node* const carrierThread = generate_current_thread(jt);
3987   // If thread != carrierThread, this is a virtual thread.
3988   Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
3989   Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
3990   IfNode* iff_thread_not_equal_carrierThread =
3991     create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
3992 
3993   Node* vthread_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
3994 
3995   // False branch, is carrierThread.
3996   Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
3997   // Store release
3998   Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
3999 
4000   set_all_memory(input_memory_state);
4001 
4002   // True branch, is virtual thread.
4003   Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
4004   set_control(thread_not_equal_carrierThread);
4005 
4006   // Load the raw epoch value from the vthread.
4007   Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
4008   Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
4009                                    IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
4010 
4011   // Mask off the excluded information from the epoch.
4012   Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, excluded_mask));
4013 
4014   // Load the tid field from the thread.
4015   Node* tid = load_field_from_object(thread, "tid", "J");
4016 
4017   // Store the vthread tid to the jfr thread local.
4018   Node* thread_id_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
4019   Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
4020 
4021   // Branch is_excluded to conditionalize updating the epoch .
4022   Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, excluded_mask));
4023   Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
4024   IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
4025 
4026   // True branch, vthread is excluded, no need to write epoch info.
4027   Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
4028   set_control(excluded);
4029   Node* vthread_is_excluded = _gvn.intcon(1);
4030 
4031   // False branch, vthread is included, update epoch info.
4032   Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
4033   set_control(included);
4034   Node* vthread_is_included = _gvn.intcon(0);
4035 
4036   // Get epoch value.
4037   Node* epoch = _gvn.transform(new AndINode(epoch_raw, epoch_mask));
4038 
4039   // Store the vthread epoch to the jfr thread local.
4040   Node* vthread_epoch_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
4041   Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
4042 
4043   RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
4044   record_for_igvn(excluded_rgn);
4045   PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
4046   record_for_igvn(excluded_mem);
4047   PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
4048   record_for_igvn(exclusion);
4049 
4050   // Merge the excluded control and memory.
4051   excluded_rgn->init_req(_true_path, excluded);
4052   excluded_rgn->init_req(_false_path, included);
4053   excluded_mem->init_req(_true_path, tid_memory);
4054   excluded_mem->init_req(_false_path, included_memory);
4055   exclusion->init_req(_true_path, vthread_is_excluded);
4056   exclusion->init_req(_false_path, vthread_is_included);
4057 
4058   // Set intermediate state.
4059   set_control(_gvn.transform(excluded_rgn));
4060   set_all_memory(excluded_mem);
4061 
4062   // Store the vthread exclusion state to the jfr thread local.
4063   Node* thread_local_excluded_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
4064   store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
4065 
4066   // Store release
4067   Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
4068 
4069   RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
4070   record_for_igvn(thread_compare_rgn);
4071   PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4072   record_for_igvn(thread_compare_mem);
4073   PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
4074   record_for_igvn(vthread);
4075 
4076   // Merge the thread_compare control and memory.
4077   thread_compare_rgn->init_req(_true_path, control());
4078   thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
4079   thread_compare_mem->init_req(_true_path, vthread_true_memory);
4080   thread_compare_mem->init_req(_false_path, vthread_false_memory);
4081 
4082   // Set output state.
4083   set_control(_gvn.transform(thread_compare_rgn));
4084   set_all_memory(_gvn.transform(thread_compare_mem));
4085 }
4086 
4087 #endif // JFR_HAVE_INTRINSICS
4088 
4089 //------------------------inline_native_currentCarrierThread------------------
4090 bool LibraryCallKit::inline_native_currentCarrierThread() {
4091   Node* junk = nullptr;
4092   set_result(generate_current_thread(junk));
4093   return true;
4094 }
4095 
4096 //------------------------inline_native_currentThread------------------
4097 bool LibraryCallKit::inline_native_currentThread() {
4098   Node* junk = nullptr;
4099   set_result(generate_virtual_thread(junk));
4100   return true;
4101 }
4102 
4103 //------------------------inline_native_setVthread------------------
4104 bool LibraryCallKit::inline_native_setCurrentThread() {
4105   assert(C->method()->changes_current_thread(),
4106          "method changes current Thread but is not annotated ChangesCurrentThread");
4107   Node* arr = argument(1);
4108   Node* thread = _gvn.transform(new ThreadLocalNode());
4109   Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::vthread_offset()));
4110   Node* thread_obj_handle
4111     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4112   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4113   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4114 
4115   // Change the _monitor_owner_id of the JavaThread
4116   Node* tid = load_field_from_object(arr, "tid", "J");
4117   Node* monitor_owner_id_offset = off_heap_plus_addr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4118   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4119 
4120   JFR_ONLY(extend_setCurrentThread(thread, arr);)
4121   return true;
4122 }
4123 
4124 const Type* LibraryCallKit::scopedValueCache_type() {
4125   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4126   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4127   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
4128 
4129   // Because we create the scopedValue cache lazily we have to make the
4130   // type of the result BotPTR.
4131   bool xk = etype->klass_is_exact();
4132   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4133   return objects_type;
4134 }
4135 
4136 Node* LibraryCallKit::scopedValueCache_helper() {
4137   Node* thread = _gvn.transform(new ThreadLocalNode());
4138   Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::scopedValueCache_offset()));
4139   // We cannot use immutable_memory() because we might flip onto a
4140   // different carrier thread, at which point we'll need to use that
4141   // carrier thread's cache.
4142   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4143   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4144   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4145 }
4146 
4147 //------------------------inline_native_scopedValueCache------------------
4148 bool LibraryCallKit::inline_native_scopedValueCache() {
4149   Node* cache_obj_handle = scopedValueCache_helper();
4150   const Type* objects_type = scopedValueCache_type();
4151   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4152 
4153   return true;
4154 }
4155 
4156 //------------------------inline_native_setScopedValueCache------------------
4157 bool LibraryCallKit::inline_native_setScopedValueCache() {
4158   Node* arr = argument(0);
4159   Node* cache_obj_handle = scopedValueCache_helper();
4160   const Type* objects_type = scopedValueCache_type();
4161 
4162   const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4163   access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4164 
4165   return true;
4166 }
4167 
4168 //------------------------inline_native_Continuation_pin and unpin-----------
4169 
4170 // Shared implementation routine for both pin and unpin.
4171 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4172   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4173 
4174   // Save input memory.
4175   Node* input_memory_state = reset_memory();
4176   set_all_memory(input_memory_state);
4177 
4178   // TLS
4179   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4180   Node* last_continuation_offset = off_heap_plus_addr(tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4181   Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4182 
4183   // Null check the last continuation object.
4184   Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4185   Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4186   IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4187 
4188   // False path, last continuation is null.
4189   Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4190 
4191   // True path, last continuation is not null.
4192   Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4193 
4194   set_control(continuation_is_not_null);
4195 
4196   // Load the pin count from the last continuation.
4197   Node* pin_count_offset = off_heap_plus_addr(last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4198   Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4199 
4200   // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4201   Node* pin_count_rhs;
4202   if (unpin) {
4203     pin_count_rhs = _gvn.intcon(0);
4204   } else {
4205     pin_count_rhs = _gvn.intcon(UINT32_MAX);
4206   }
4207   Node* pin_count_cmp = _gvn.transform(new CmpUNode(pin_count, pin_count_rhs));
4208   Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4209   IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4210 
4211   // True branch, pin count over/underflow.
4212   Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4213   {
4214     // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4215     // which will throw IllegalStateException for pin count over/underflow.
4216     // No memory changed so far - we can use memory create by reset_memory()
4217     // at the beginning of this intrinsic. No need to call reset_memory() again.
4218     PreserveJVMState pjvms(this);
4219     set_control(pin_count_over_underflow);
4220     uncommon_trap(Deoptimization::Reason_intrinsic,
4221                   Deoptimization::Action_none);
4222     assert(stopped(), "invariant");
4223   }
4224 
4225   // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4226   Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4227   set_control(valid_pin_count);
4228 
4229   Node* next_pin_count;
4230   if (unpin) {
4231     next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4232   } else {
4233     next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4234   }
4235 
4236   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4237 
4238   // Result of top level CFG and Memory.
4239   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4240   record_for_igvn(result_rgn);
4241   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4242   record_for_igvn(result_mem);
4243 
4244   result_rgn->init_req(_true_path, valid_pin_count);
4245   result_rgn->init_req(_false_path, continuation_is_null);
4246   result_mem->init_req(_true_path, reset_memory());
4247   result_mem->init_req(_false_path, input_memory_state);
4248 
4249   // Set output state.
4250   set_control(_gvn.transform(result_rgn));
4251   set_all_memory(_gvn.transform(result_mem));
4252 
4253   return true;
4254 }
4255 
4256 //---------------------------load_mirror_from_klass----------------------------
4257 // Given a klass oop, load its java mirror (a java.lang.Class oop).
4258 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
4259   Node* p = off_heap_plus_addr(klass, in_bytes(Klass::java_mirror_offset()));
4260   Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4261   // mirror = ((OopHandle)mirror)->resolve();
4262   return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4263 }
4264 
4265 //-----------------------load_klass_from_mirror_common-------------------------
4266 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4267 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4268 // and branch to the given path on the region.
4269 // If never_see_null, take an uncommon trap on null, so we can optimistically
4270 // compile for the non-null case.
4271 // If the region is null, force never_see_null = true.
4272 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4273                                                     bool never_see_null,
4274                                                     RegionNode* region,
4275                                                     int null_path,
4276                                                     int offset) {
4277   if (region == nullptr)  never_see_null = true;
4278   Node* p = basic_plus_adr(mirror, offset);
4279   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4280   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4281   Node* null_ctl = top();
4282   kls = null_check_oop(kls, &null_ctl, never_see_null);
4283   if (region != nullptr) {
4284     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4285     region->init_req(null_path, null_ctl);
4286   } else {
4287     assert(null_ctl == top(), "no loose ends");
4288   }
4289   return kls;
4290 }
4291 
4292 //--------------------(inline_native_Class_query helpers)---------------------
4293 // Use this for JVM_ACC_INTERFACE.
4294 // Fall through if (mods & mask) == bits, take the guard otherwise.
4295 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4296                                                  ByteSize offset, const Type* type, BasicType bt) {
4297   // Branch around if the given klass has the given modifier bit set.
4298   // Like generate_guard, adds a new path onto the region.
4299   Node* modp = off_heap_plus_addr(kls, in_bytes(offset));
4300   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4301   Node* mask = intcon(modifier_mask);
4302   Node* bits = intcon(modifier_bits);
4303   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4304   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4305   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4306   return generate_fair_guard(bol, region);
4307 }
4308 
4309 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4310   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4311                                     InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4312 }
4313 
4314 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4315 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4316   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4317                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4318 }
4319 
4320 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4321   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4322 }
4323 
4324 //-------------------------inline_native_Class_query-------------------
4325 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4326   const Type* return_type = TypeInt::BOOL;
4327   Node* prim_return_value = top();  // what happens if it's a primitive class?
4328   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4329   bool expect_prim = false;     // most of these guys expect to work on refs
4330 
4331   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4332 
4333   Node* mirror = argument(0);
4334   Node* obj    = top();
4335 
4336   switch (id) {
4337   case vmIntrinsics::_isInstance:
4338     // nothing is an instance of a primitive type
4339     prim_return_value = intcon(0);
4340     obj = argument(1);
4341     break;
4342   case vmIntrinsics::_isHidden:
4343     prim_return_value = intcon(0);
4344     break;
4345   case vmIntrinsics::_getSuperclass:
4346     prim_return_value = null();
4347     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4348     break;
4349   default:
4350     fatal_unexpected_iid(id);
4351     break;
4352   }
4353 
4354   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4355   if (mirror_con == nullptr)  return false;  // cannot happen?
4356 
4357 #ifndef PRODUCT
4358   if (C->print_intrinsics() || C->print_inlining()) {
4359     ciType* k = mirror_con->java_mirror_type();
4360     if (k) {
4361       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4362       k->print_name();
4363       tty->cr();
4364     }
4365   }
4366 #endif
4367 
4368   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4369   RegionNode* region = new RegionNode(PATH_LIMIT);
4370   record_for_igvn(region);
4371   PhiNode* phi = new PhiNode(region, return_type);
4372 
4373   // The mirror will never be null of Reflection.getClassAccessFlags, however
4374   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4375   // if it is. See bug 4774291.
4376 
4377   // For Reflection.getClassAccessFlags(), the null check occurs in
4378   // the wrong place; see inline_unsafe_access(), above, for a similar
4379   // situation.
4380   mirror = null_check(mirror);
4381   // If mirror or obj is dead, only null-path is taken.
4382   if (stopped())  return true;
4383 
4384   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
4385 
4386   // Now load the mirror's klass metaobject, and null-check it.
4387   // Side-effects region with the control path if the klass is null.
4388   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4389   // If kls is null, we have a primitive mirror.
4390   phi->init_req(_prim_path, prim_return_value);
4391   if (stopped()) { set_result(region, phi); return true; }
4392   bool safe_for_replace = (region->in(_prim_path) == top());
4393 
4394   Node* p;  // handy temp
4395   Node* null_ctl;
4396 
4397   // Now that we have the non-null klass, we can perform the real query.
4398   // For constant classes, the query will constant-fold in LoadNode::Value.
4399   Node* query_value = top();
4400   switch (id) {
4401   case vmIntrinsics::_isInstance:
4402     // nothing is an instance of a primitive type
4403     query_value = gen_instanceof(obj, kls, safe_for_replace);
4404     break;
4405 
4406   case vmIntrinsics::_isHidden:
4407     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4408     if (generate_hidden_class_guard(kls, region) != nullptr)
4409       // A guard was added.  If the guard is taken, it was an hidden class.
4410       phi->add_req(intcon(1));
4411     // If we fall through, it's a plain class.
4412     query_value = intcon(0);
4413     break;
4414 
4415 
4416   case vmIntrinsics::_getSuperclass:
4417     // The rules here are somewhat unfortunate, but we can still do better
4418     // with random logic than with a JNI call.
4419     // Interfaces store null or Object as _super, but must report null.
4420     // Arrays store an intermediate super as _super, but must report Object.
4421     // Other types can report the actual _super.
4422     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4423     if (generate_array_guard(kls, region) != nullptr) {
4424       // A guard was added.  If the guard is taken, it was an array.
4425       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4426     }
4427     // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4428     // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4429     if (generate_interface_guard(kls, region) != nullptr) {
4430       // A guard was added.  If the guard is taken, it was an interface.
4431       phi->add_req(null());
4432     }
4433     // If we fall through, it's a plain class.  Get its _super.
4434     if (!stopped()) {
4435       p = basic_plus_adr(top(), kls, in_bytes(Klass::super_offset()));
4436       kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4437       null_ctl = top();
4438       kls = null_check_oop(kls, &null_ctl);
4439       if (null_ctl != top()) {
4440         // If the guard is taken, Object.superClass is null (both klass and mirror).
4441         region->add_req(null_ctl);
4442         phi   ->add_req(null());
4443       }
4444       if (!stopped()) {
4445         query_value = load_mirror_from_klass(kls);
4446       }
4447     }
4448     break;
4449 
4450   default:
4451     fatal_unexpected_iid(id);
4452     break;
4453   }
4454 
4455   // Fall-through is the normal case of a query to a real class.
4456   phi->init_req(1, query_value);
4457   region->init_req(1, control());
4458 
4459   C->set_has_split_ifs(true); // Has chance for split-if optimization
4460   set_result(region, phi);
4461   return true;
4462 }
4463 
4464 
4465 //-------------------------inline_Class_cast-------------------
4466 bool LibraryCallKit::inline_Class_cast() {
4467   Node* mirror = argument(0); // Class
4468   Node* obj    = argument(1);
4469   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4470   if (mirror_con == nullptr) {
4471     return false;  // dead path (mirror->is_top()).
4472   }
4473   if (obj == nullptr || obj->is_top()) {
4474     return false;  // dead path
4475   }
4476   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4477 
4478   // First, see if Class.cast() can be folded statically.
4479   // java_mirror_type() returns non-null for compile-time Class constants.
4480   ciType* tm = mirror_con->java_mirror_type();
4481   if (tm != nullptr && tm->is_klass() &&
4482       tp != nullptr) {
4483     if (!tp->is_loaded()) {
4484       // Don't use intrinsic when class is not loaded.
4485       return false;
4486     } else {
4487       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4488       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4489       if (static_res == Compile::SSC_always_true) {
4490         // isInstance() is true - fold the code.
4491         set_result(obj);
4492         return true;
4493       } else if (static_res == Compile::SSC_always_false) {
4494         // Don't use intrinsic, have to throw ClassCastException.
4495         // If the reference is null, the non-intrinsic bytecode will
4496         // be optimized appropriately.
4497         return false;
4498       }
4499     }
4500   }
4501 
4502   // Bailout intrinsic and do normal inlining if exception path is frequent.
4503   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4504     return false;
4505   }
4506 
4507   // Generate dynamic checks.
4508   // Class.cast() is java implementation of _checkcast bytecode.
4509   // Do checkcast (Parse::do_checkcast()) optimizations here.
4510 
4511   mirror = null_check(mirror);
4512   // If mirror is dead, only null-path is taken.
4513   if (stopped()) {
4514     return true;
4515   }
4516 
4517   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4518   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4519   RegionNode* region = new RegionNode(PATH_LIMIT);
4520   record_for_igvn(region);
4521 
4522   // Now load the mirror's klass metaobject, and null-check it.
4523   // If kls is null, we have a primitive mirror and
4524   // nothing is an instance of a primitive type.
4525   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4526 
4527   Node* res = top();
4528   Node* io = i_o();
4529   Node* mem = merged_memory();
4530   SafePointNode* new_cast_failure_map = nullptr;
4531 
4532   if (!stopped()) {
4533 
4534     Node* bad_type_ctrl = top();
4535     // Do checkcast optimizations.
4536     res = gen_checkcast(obj, kls, &bad_type_ctrl, &new_cast_failure_map);
4537     region->init_req(_bad_type_path, bad_type_ctrl);
4538   }
4539   if (region->in(_prim_path) != top() ||
4540       region->in(_bad_type_path) != top() ||
4541       region->in(_npe_path) != top()) {
4542     // Let Interpreter throw ClassCastException.
4543     PreserveJVMState pjvms(this);
4544     if (new_cast_failure_map != nullptr) {
4545       // The current map on the success path could have been modified. Use the dedicated failure path map.
4546       set_map(new_cast_failure_map);
4547     }
4548     set_control(_gvn.transform(region));
4549     // Set IO and memory because gen_checkcast may override them when buffering inline types
4550     set_i_o(io);
4551     set_all_memory(mem);
4552     uncommon_trap(Deoptimization::Reason_intrinsic,
4553                   Deoptimization::Action_maybe_recompile);
4554   }
4555   if (!stopped()) {
4556     set_result(res);
4557   }
4558   return true;
4559 }
4560 
4561 
4562 //--------------------------inline_native_subtype_check------------------------
4563 // This intrinsic takes the JNI calls out of the heart of
4564 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4565 bool LibraryCallKit::inline_native_subtype_check() {
4566   // Pull both arguments off the stack.
4567   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4568   args[0] = argument(0);
4569   args[1] = argument(1);
4570   Node* klasses[2];             // corresponding Klasses: superk, subk
4571   klasses[0] = klasses[1] = top();
4572 
4573   enum {
4574     // A full decision tree on {superc is prim, subc is prim}:
4575     _prim_0_path = 1,           // {P,N} => false
4576                                 // {P,P} & superc!=subc => false
4577     _prim_same_path,            // {P,P} & superc==subc => true
4578     _prim_1_path,               // {N,P} => false
4579     _ref_subtype_path,          // {N,N} & subtype check wins => true
4580     _both_ref_path,             // {N,N} & subtype check loses => false
4581     PATH_LIMIT
4582   };
4583 
4584   RegionNode* region = new RegionNode(PATH_LIMIT);
4585   RegionNode* prim_region = new RegionNode(2);
4586   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4587   record_for_igvn(region);
4588   record_for_igvn(prim_region);
4589 
4590   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4591   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4592   int class_klass_offset = java_lang_Class::klass_offset();
4593 
4594   // First null-check both mirrors and load each mirror's klass metaobject.
4595   int which_arg;
4596   for (which_arg = 0; which_arg <= 1; which_arg++) {
4597     Node* arg = args[which_arg];
4598     arg = null_check(arg);
4599     if (stopped())  break;
4600     args[which_arg] = arg;
4601 
4602     Node* p = basic_plus_adr(arg, class_klass_offset);
4603     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4604     klasses[which_arg] = _gvn.transform(kls);
4605   }
4606 
4607   // Having loaded both klasses, test each for null.
4608   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4609   for (which_arg = 0; which_arg <= 1; which_arg++) {
4610     Node* kls = klasses[which_arg];
4611     Node* null_ctl = top();
4612     kls = null_check_oop(kls, &null_ctl, never_see_null);
4613     if (which_arg == 0) {
4614       prim_region->init_req(1, null_ctl);
4615     } else {
4616       region->init_req(_prim_1_path, null_ctl);
4617     }
4618     if (stopped())  break;
4619     klasses[which_arg] = kls;
4620   }
4621 
4622   if (!stopped()) {
4623     // now we have two reference types, in klasses[0..1]
4624     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4625     Node* superk = klasses[0];  // the receiver
4626     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4627     region->set_req(_ref_subtype_path, control());
4628   }
4629 
4630   // If both operands are primitive (both klasses null), then
4631   // we must return true when they are identical primitives.
4632   // It is convenient to test this after the first null klass check.
4633   // This path is also used if superc is a value mirror.
4634   set_control(_gvn.transform(prim_region));
4635   if (!stopped()) {
4636     // Since superc is primitive, make a guard for the superc==subc case.
4637     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4638     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4639     generate_fair_guard(bol_eq, region);
4640     if (region->req() == PATH_LIMIT+1) {
4641       // A guard was added.  If the added guard is taken, superc==subc.
4642       region->swap_edges(PATH_LIMIT, _prim_same_path);
4643       region->del_req(PATH_LIMIT);
4644     }
4645     region->set_req(_prim_0_path, control()); // Not equal after all.
4646   }
4647 
4648   // these are the only paths that produce 'true':
4649   phi->set_req(_prim_same_path,   intcon(1));
4650   phi->set_req(_ref_subtype_path, intcon(1));
4651 
4652   // pull together the cases:
4653   assert(region->req() == PATH_LIMIT, "sane region");
4654   for (uint i = 1; i < region->req(); i++) {
4655     Node* ctl = region->in(i);
4656     if (ctl == nullptr || ctl == top()) {
4657       region->set_req(i, top());
4658       phi   ->set_req(i, top());
4659     } else if (phi->in(i) == nullptr) {
4660       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4661     }
4662   }
4663 
4664   set_control(_gvn.transform(region));
4665   set_result(_gvn.transform(phi));
4666   return true;
4667 }
4668 
4669 //---------------------generate_array_guard_common------------------------
4670 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4671 
4672   if (stopped()) {
4673     return nullptr;
4674   }
4675 
4676   // Like generate_guard, adds a new path onto the region.
4677   jint  layout_con = 0;
4678   Node* layout_val = get_layout_helper(kls, layout_con);
4679   if (layout_val == nullptr) {
4680     bool query = 0;
4681     switch(kind) {
4682       case RefArray:       query = Klass::layout_helper_is_refArray(layout_con); break;
4683       case NonRefArray:    query = !Klass::layout_helper_is_refArray(layout_con); break;
4684       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
4685       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
4686       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
4687       default:
4688         ShouldNotReachHere();
4689     }
4690     if (!query) {
4691       return nullptr;                       // never a branch
4692     } else {                             // always a branch
4693       Node* always_branch = control();
4694       if (region != nullptr)
4695         region->add_req(always_branch);
4696       set_control(top());
4697       return always_branch;
4698     }
4699   }
4700   unsigned int value = 0;
4701   BoolTest::mask btest = BoolTest::illegal;
4702   switch(kind) {
4703     case RefArray:
4704     case NonRefArray: {
4705       value = Klass::_lh_array_tag_ref_value;
4706       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4707       btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4708       break;
4709     }
4710     case TypeArray: {
4711       value = Klass::_lh_array_tag_type_value;
4712       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4713       btest = BoolTest::eq;
4714       break;
4715     }
4716     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4717     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4718     default:
4719       ShouldNotReachHere();
4720   }
4721   // Now test the correct condition.
4722   jint nval = (jint)value;
4723   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4724   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4725   Node* ctrl = generate_fair_guard(bol, region);
4726   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4727   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4728     // Keep track of the fact that 'obj' is an array to prevent
4729     // array specific accesses from floating above the guard.
4730     *obj = _gvn.transform(new CheckCastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4731   }
4732   return ctrl;
4733 }
4734 
4735 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4736 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4737 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4738 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4739   assert(null_free || atomic, "nullable implies atomic");
4740   Node* componentType = argument(0);
4741   Node* length = argument(1);
4742   Node* init_val = null_free ? argument(2) : nullptr;
4743 
4744   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4745   if (tp != nullptr) {
4746     ciInstanceKlass* ik = tp->instance_klass();
4747     if (ik == C->env()->Class_klass()) {
4748       ciType* t = tp->java_mirror_type();
4749       if (t != nullptr && t->is_inlinetype()) {
4750 
4751         ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4752         assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4753 
4754         // TOOD 8350865 ZGC needs card marks on initializing oop stores
4755         if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4756           return false;
4757         }
4758 
4759         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4760           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4761           if (null_free) {
4762             if (init_val->is_InlineType()) {
4763               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4764                 // Zeroing is enough because the init value is the all-zero value
4765                 init_val = nullptr;
4766               } else {
4767                 init_val = init_val->as_InlineType()->buffer(this);
4768               }
4769             }
4770             // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4771             // If we insert a checkcast here, we can be sure that init_val is an InlineTypeNode, so
4772             // when we folded a field load from an allocation (e.g. during escape analysis), we can
4773             // remove the check init_val->is_InlineType().
4774           }
4775           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4776           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4777           assert(arytype->is_null_free() == null_free, "inconsistency");
4778           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4779           set_result(obj);
4780           return true;
4781         }
4782       }
4783     }
4784   }
4785   return false;
4786 }
4787 
4788 // public static native boolean ValueClass::isFlatArray(Object array);
4789 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4790 // public static native boolean ValueClass::isAtomicArray(Object array);
4791 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4792   Node* array = argument(0);
4793 
4794   Node* bol;
4795   switch(check) {
4796     case IsFlat:
4797       // TODO 8350865 Use the object version here instead of loading the klass
4798       // The problem is that PhaseMacroExpand::expand_flatarraycheck_node can only handle some IR shapes and will fail, for example, if the bol is directly wired to a ReturnNode
4799       bol = flat_array_test(load_object_klass(array));
4800       break;
4801     case IsNullRestricted:
4802       bol = null_free_array_test(array);
4803       break;
4804     case IsAtomic:
4805       // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4806       // Enable TestIntrinsics::test87/88 once this is implemented
4807       // bol = null_free_atomic_array_test
4808       return false;
4809     default:
4810       ShouldNotReachHere();
4811   }
4812 
4813   Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4814   set_result(res);
4815   return true;
4816 }
4817 
4818 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4819 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4820 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4821   RegionNode* region = new RegionNode(2);
4822   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4823 
4824   if (type_array_guard) {
4825     generate_typeArray_guard(klass_node, region);
4826     if (region->req() == 3) {
4827       phi->add_req(klass_node);
4828     }
4829   }
4830   Node* adr_refined_klass = basic_plus_adr(top(), klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4831   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4832 
4833   // Can be null if not initialized yet, just deopt
4834   Node* null_ctl = top();
4835   refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4836 
4837   region->init_req(1, control());
4838   phi->init_req(1, refined_klass);
4839 
4840   set_control(_gvn.transform(region));
4841   return _gvn.transform(phi);
4842 }
4843 
4844 // Load the non-refined array klass from an ObjArrayKlass.
4845 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
4846   const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
4847   if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
4848     return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
4849   }
4850 
4851   RegionNode* region = new RegionNode(2);
4852   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
4853 
4854   generate_typeArray_guard(klass_node, region);
4855   if (region->req() == 3) {
4856     phi->add_req(klass_node);
4857   }
4858   Node* super_adr = basic_plus_adr(top(), klass_node, in_bytes(Klass::super_offset()));
4859   Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
4860 
4861   region->init_req(1, control());
4862   phi->init_req(1, super_klass);
4863 
4864   set_control(_gvn.transform(region));
4865   return _gvn.transform(phi);
4866 }
4867 
4868 //-----------------------inline_native_newArray--------------------------
4869 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
4870 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4871 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4872   Node* mirror;
4873   Node* count_val;
4874   if (uninitialized) {
4875     null_check_receiver();
4876     mirror    = argument(1);
4877     count_val = argument(2);
4878   } else {
4879     mirror    = argument(0);
4880     count_val = argument(1);
4881   }
4882 
4883   mirror = null_check(mirror);
4884   // If mirror or obj is dead, only null-path is taken.
4885   if (stopped())  return true;
4886 
4887   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4888   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4889   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4890   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4891   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4892 
4893   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4894   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
4895                                                   result_reg, _slow_path);
4896   Node* normal_ctl   = control();
4897   Node* no_array_ctl = result_reg->in(_slow_path);
4898 
4899   // Generate code for the slow case.  We make a call to newArray().
4900   set_control(no_array_ctl);
4901   if (!stopped()) {
4902     // Either the input type is void.class, or else the
4903     // array klass has not yet been cached.  Either the
4904     // ensuing call will throw an exception, or else it
4905     // will cache the array klass for next time.
4906     PreserveJVMState pjvms(this);
4907     CallJavaNode* slow_call = nullptr;
4908     if (uninitialized) {
4909       // Generate optimized virtual call (holder class 'Unsafe' is final)
4910       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4911     } else {
4912       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4913     }
4914     Node* slow_result = set_results_for_java_call(slow_call);
4915     // this->control() comes from set_results_for_java_call
4916     result_reg->set_req(_slow_path, control());
4917     result_val->set_req(_slow_path, slow_result);
4918     result_io ->set_req(_slow_path, i_o());
4919     result_mem->set_req(_slow_path, reset_memory());
4920   }
4921 
4922   set_control(normal_ctl);
4923   if (!stopped()) {
4924     // Normal case:  The array type has been cached in the java.lang.Class.
4925     // The following call works fine even if the array type is polymorphic.
4926     // It could be a dynamic mix of int[], boolean[], Object[], etc.
4927 
4928     klass_node = load_default_refined_array_klass(klass_node);
4929 
4930     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
4931     result_reg->init_req(_normal_path, control());
4932     result_val->init_req(_normal_path, obj);
4933     result_io ->init_req(_normal_path, i_o());
4934     result_mem->init_req(_normal_path, reset_memory());
4935 
4936     if (uninitialized) {
4937       // Mark the allocation so that zeroing is skipped
4938       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4939       alloc->maybe_set_complete(&_gvn);
4940     }
4941   }
4942 
4943   // Return the combined state.
4944   set_i_o(        _gvn.transform(result_io)  );
4945   set_all_memory( _gvn.transform(result_mem));
4946 
4947   C->set_has_split_ifs(true); // Has chance for split-if optimization
4948   set_result(result_reg, result_val);
4949   return true;
4950 }
4951 
4952 //----------------------inline_native_getLength--------------------------
4953 // public static native int java.lang.reflect.Array.getLength(Object array);
4954 bool LibraryCallKit::inline_native_getLength() {
4955   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
4956 
4957   Node* array = null_check(argument(0));
4958   // If array is dead, only null-path is taken.
4959   if (stopped())  return true;
4960 
4961   // Deoptimize if it is a non-array.
4962   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
4963 
4964   if (non_array != nullptr) {
4965     PreserveJVMState pjvms(this);
4966     set_control(non_array);
4967     uncommon_trap(Deoptimization::Reason_intrinsic,
4968                   Deoptimization::Action_maybe_recompile);
4969   }
4970 
4971   // If control is dead, only non-array-path is taken.
4972   if (stopped())  return true;
4973 
4974   // The works fine even if the array type is polymorphic.
4975   // It could be a dynamic mix of int[], boolean[], Object[], etc.
4976   Node* result = load_array_length(array);
4977 
4978   C->set_has_split_ifs(true);  // Has chance for split-if optimization
4979   set_result(result);
4980   return true;
4981 }
4982 
4983 //------------------------inline_array_copyOf----------------------------
4984 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
4985 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
4986 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
4987   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
4988 
4989   // Get the arguments.
4990   Node* original          = argument(0);
4991   Node* start             = is_copyOfRange? argument(1): intcon(0);
4992   Node* end               = is_copyOfRange? argument(2): argument(1);
4993   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
4994 
4995   Node* newcopy = nullptr;
4996 
4997   // Set the original stack and the reexecute bit for the interpreter to reexecute
4998   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4999   { PreserveReexecuteState preexecs(this);
5000     jvms()->set_should_reexecute(true);
5001 
5002     array_type_mirror = null_check(array_type_mirror);
5003     original          = null_check(original);
5004 
5005     // Check if a null path was taken unconditionally.
5006     if (stopped())  return true;
5007 
5008     Node* orig_length = load_array_length(original);
5009 
5010     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5011     klass_node = null_check(klass_node);
5012 
5013     RegionNode* bailout = new RegionNode(1);
5014     record_for_igvn(bailout);
5015 
5016     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5017     // Bail out if that is so.
5018     // Inline type array may have object field that would require a
5019     // write barrier. Conservatively, go to slow path.
5020     // TODO 8251971: Optimize for the case when flat src/dst are later found
5021     // to not contain oops (i.e., move this check to the macro expansion phase).
5022     // TODO 8382226: Revisit for flat abstract value class arrays
5023     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5024     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5025     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5026     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5027                         // Can src array be flat and contain oops?
5028                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5029                         // Can dest array be flat and contain oops?
5030                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5031     Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5032 
5033     Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5034 
5035     if (not_objArray != nullptr) {
5036       // Improve the klass node's type from the new optimistic assumption:
5037       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5038       bool not_flat = !UseArrayFlattening;
5039       bool not_null_free = !Arguments::is_valhalla_enabled();
5040       const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5041       Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5042       refined_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     // TODO 8251971 This is too strong
5062     generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5063     generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5064     generate_fair_guard(null_free_array_test(original), bailout);
5065 
5066     // Bail out if start is larger than the original length
5067     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5068     generate_negative_guard(orig_tail, bailout, &orig_tail);
5069 
5070     if (bailout->req() > 1) {
5071       PreserveJVMState pjvms(this);
5072       set_control(_gvn.transform(bailout));
5073       uncommon_trap(Deoptimization::Reason_intrinsic,
5074                     Deoptimization::Action_maybe_recompile);
5075     }
5076 
5077     if (!stopped()) {
5078       // How many elements will we copy from the original?
5079       // The answer is MinI(orig_tail, length).
5080       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5081 
5082       // Generate a direct call to the right arraycopy function(s).
5083       // We know the copy is disjoint but we might not know if the
5084       // oop stores need checking.
5085       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
5086       // This will fail a store-check if x contains any non-nulls.
5087 
5088       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5089       // loads/stores but it is legal only if we're sure the
5090       // Arrays.copyOf would succeed. So we need all input arguments
5091       // to the copyOf to be validated, including that the copy to the
5092       // new array won't trigger an ArrayStoreException. That subtype
5093       // check can be optimized if we know something on the type of
5094       // the input array from type speculation.
5095       if (_gvn.type(klass_node)->singleton()) {
5096         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5097         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5098 
5099         int test = C->static_subtype_check(superk, subk);
5100         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5101           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5102           if (t_original->speculative_type() != nullptr) {
5103             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5104           }
5105         }
5106       }
5107 
5108       bool validated = false;
5109       // Reason_class_check rather than Reason_intrinsic because we
5110       // want to intrinsify even if this traps.
5111       if (!too_many_traps(Deoptimization::Reason_class_check)) {
5112         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5113 
5114         if (not_subtype_ctrl != top()) {
5115           PreserveJVMState pjvms(this);
5116           set_control(not_subtype_ctrl);
5117           uncommon_trap(Deoptimization::Reason_class_check,
5118                         Deoptimization::Action_make_not_entrant);
5119           assert(stopped(), "Should be stopped");
5120         }
5121         validated = true;
5122       }
5123 
5124       if (!stopped()) {
5125         newcopy = new_array(refined_klass_node, length, 0);  // no arguments to push
5126 
5127         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5128                                                 load_object_klass(original), klass_node);
5129         if (!is_copyOfRange) {
5130           ac->set_copyof(validated);
5131         } else {
5132           ac->set_copyofrange(validated);
5133         }
5134         Node* n = _gvn.transform(ac);
5135         if (n == ac) {
5136           ac->connect_outputs(this);
5137         } else {
5138           assert(validated, "shouldn't transform if all arguments not validated");
5139           set_all_memory(n);
5140         }
5141       }
5142     }
5143   } // original reexecute is set back here
5144 
5145   C->set_has_split_ifs(true); // Has chance for split-if optimization
5146   if (!stopped()) {
5147     set_result(newcopy);
5148   }
5149   return true;
5150 }
5151 
5152 
5153 //----------------------generate_virtual_guard---------------------------
5154 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
5155 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5156                                              RegionNode* slow_region) {
5157   ciMethod* method = callee();
5158   int vtable_index = method->vtable_index();
5159   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5160          "bad index %d", vtable_index);
5161   // Get the Method* out of the appropriate vtable entry.
5162   int entry_offset = in_bytes(Klass::vtable_start_offset()) +
5163                      vtable_index*vtableEntry::size_in_bytes() +
5164                      in_bytes(vtableEntry::method_offset());
5165   Node* entry_addr = off_heap_plus_addr(obj_klass, entry_offset);
5166   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5167 
5168   // Compare the target method with the expected method (e.g., Object.hashCode).
5169   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5170 
5171   Node* native_call = makecon(native_call_addr);
5172   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
5173   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5174 
5175   return generate_slow_guard(test_native, slow_region);
5176 }
5177 
5178 //-----------------------generate_method_call----------------------------
5179 // Use generate_method_call to make a slow-call to the real
5180 // method if the fast path fails.  An alternative would be to
5181 // use a stub like OptoRuntime::slow_arraycopy_Java.
5182 // This only works for expanding the current library call,
5183 // not another intrinsic.  (E.g., don't use this for making an
5184 // arraycopy call inside of the copyOf intrinsic.)
5185 CallJavaNode*
5186 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5187   // When compiling the intrinsic method itself, do not use this technique.
5188   guarantee(callee() != C->method(), "cannot make slow-call to self");
5189 
5190   ciMethod* method = callee();
5191   // ensure the JVMS we have will be correct for this call
5192   guarantee(method_id == method->intrinsic_id(), "must match");
5193 
5194   const TypeFunc* tf = TypeFunc::make(method);
5195   if (res_not_null) {
5196     assert(tf->return_type() == T_OBJECT, "");
5197     const TypeTuple* range = tf->range_cc();
5198     const Type** fields = TypeTuple::fields(range->cnt());
5199     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5200     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5201     tf = TypeFunc::make(tf->domain_cc(), new_range);
5202   }
5203   CallJavaNode* slow_call;
5204   if (is_static) {
5205     assert(!is_virtual, "");
5206     slow_call = new CallStaticJavaNode(C, tf,
5207                            SharedRuntime::get_resolve_static_call_stub(), method);
5208   } else if (is_virtual) {
5209     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5210     int vtable_index = Method::invalid_vtable_index;
5211     if (UseInlineCaches) {
5212       // Suppress the vtable call
5213     } else {
5214       // hashCode and clone are not a miranda methods,
5215       // so the vtable index is fixed.
5216       // No need to use the linkResolver to get it.
5217        vtable_index = method->vtable_index();
5218        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5219               "bad index %d", vtable_index);
5220     }
5221     slow_call = new CallDynamicJavaNode(tf,
5222                           SharedRuntime::get_resolve_virtual_call_stub(),
5223                           method, vtable_index);
5224   } else {  // neither virtual nor static:  opt_virtual
5225     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5226     slow_call = new CallStaticJavaNode(C, tf,
5227                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5228     slow_call->set_optimized_virtual(true);
5229   }
5230   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5231     // To be able to issue a direct call (optimized virtual or virtual)
5232     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5233     // about the method being invoked should be attached to the call site to
5234     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5235     slow_call->set_override_symbolic_info(true);
5236   }
5237   set_arguments_for_java_call(slow_call);
5238   set_edges_for_java_call(slow_call);
5239   return slow_call;
5240 }
5241 
5242 
5243 /**
5244  * Build special case code for calls to hashCode on an object. This call may
5245  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5246  * slightly different code.
5247  */
5248 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5249   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5250   assert(!(is_virtual && is_static), "either virtual, special, or static");
5251 
5252   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5253 
5254   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5255   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5256   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5257   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5258   Node* obj = argument(0);
5259 
5260   // Don't intrinsify hashcode on inline types for now.
5261   // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5262   if (gvn().type(obj)->is_inlinetypeptr()) {
5263     return false;
5264   }
5265 
5266   if (!is_static) {
5267     // Check for hashing null object
5268     obj = null_check_receiver();
5269     if (stopped())  return true;        // unconditionally null
5270     result_reg->init_req(_null_path, top());
5271     result_val->init_req(_null_path, top());
5272   } else {
5273     // Do a null check, and return zero if null.
5274     // System.identityHashCode(null) == 0
5275     Node* null_ctl = top();
5276     obj = null_check_oop(obj, &null_ctl);
5277     result_reg->init_req(_null_path, null_ctl);
5278     result_val->init_req(_null_path, _gvn.intcon(0));
5279   }
5280 
5281   // Unconditionally null?  Then return right away.
5282   if (stopped()) {
5283     set_control( result_reg->in(_null_path));
5284     if (!stopped())
5285       set_result(result_val->in(_null_path));
5286     return true;
5287   }
5288 
5289   // We only go to the fast case code if we pass a number of guards.  The
5290   // paths which do not pass are accumulated in the slow_region.
5291   RegionNode* slow_region = new RegionNode(1);
5292   record_for_igvn(slow_region);
5293 
5294   // If this is a virtual call, we generate a funny guard.  We pull out
5295   // the vtable entry corresponding to hashCode() from the target object.
5296   // If the target method which we are calling happens to be the native
5297   // Object hashCode() method, we pass the guard.  We do not need this
5298   // guard for non-virtual calls -- the caller is known to be the native
5299   // Object hashCode().
5300   if (is_virtual) {
5301     // After null check, get the object's klass.
5302     Node* obj_klass = load_object_klass(obj);
5303     generate_virtual_guard(obj_klass, slow_region);
5304   }
5305 
5306   // Get the header out of the object, use LoadMarkNode when available
5307   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5308   // The control of the load must be null. Otherwise, the load can move before
5309   // the null check after castPP removal.
5310   Node* no_ctrl = nullptr;
5311   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5312 
5313   if (!UseObjectMonitorTable) {
5314     // Test the header to see if it is safe to read w.r.t. locking.
5315     // We cannot use the inline type mask as this may check bits that are overriden
5316     // by an object monitor's pointer when inflating locking.
5317     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
5318     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5319     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5320     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5321     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5322 
5323     generate_slow_guard(test_monitor, slow_region);
5324   }
5325 
5326   // Get the hash value and check to see that it has been properly assigned.
5327   // We depend on hash_mask being at most 32 bits and avoid the use of
5328   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5329   // vm: see markWord.hpp.
5330   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5331   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5332   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5333   // This hack lets the hash bits live anywhere in the mark object now, as long
5334   // as the shift drops the relevant bits into the low 32 bits.  Note that
5335   // Java spec says that HashCode is an int so there's no point in capturing
5336   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5337   hshifted_header      = ConvX2I(hshifted_header);
5338   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5339 
5340   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
5341   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5342   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5343 
5344   generate_slow_guard(test_assigned, slow_region);
5345 
5346   Node* init_mem = reset_memory();
5347   // fill in the rest of the null path:
5348   result_io ->init_req(_null_path, i_o());
5349   result_mem->init_req(_null_path, init_mem);
5350 
5351   result_val->init_req(_fast_path, hash_val);
5352   result_reg->init_req(_fast_path, control());
5353   result_io ->init_req(_fast_path, i_o());
5354   result_mem->init_req(_fast_path, init_mem);
5355 
5356   // Generate code for the slow case.  We make a call to hashCode().
5357   set_control(_gvn.transform(slow_region));
5358   if (!stopped()) {
5359     // No need for PreserveJVMState, because we're using up the present state.
5360     set_all_memory(init_mem);
5361     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5362     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5363     Node* slow_result = set_results_for_java_call(slow_call);
5364     // this->control() comes from set_results_for_java_call
5365     result_reg->init_req(_slow_path, control());
5366     result_val->init_req(_slow_path, slow_result);
5367     result_io  ->set_req(_slow_path, i_o());
5368     result_mem ->set_req(_slow_path, reset_memory());
5369   }
5370 
5371   // Return the combined state.
5372   set_i_o(        _gvn.transform(result_io)  );
5373   set_all_memory( _gvn.transform(result_mem));
5374 
5375   set_result(result_reg, result_val);
5376   return true;
5377 }
5378 
5379 //---------------------------inline_native_getClass----------------------------
5380 // public final native Class<?> java.lang.Object.getClass();
5381 //
5382 // Build special case code for calls to getClass on an object.
5383 bool LibraryCallKit::inline_native_getClass() {
5384   Node* obj = argument(0);
5385   if (obj->is_InlineType()) {
5386     const Type* t = _gvn.type(obj);
5387     if (t->maybe_null()) {
5388       null_check(obj);
5389     }
5390     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5391     return true;
5392   }
5393   obj = null_check_receiver();
5394   if (stopped())  return true;
5395   set_result(load_mirror_from_klass(load_object_klass(obj)));
5396   return true;
5397 }
5398 
5399 //-----------------inline_native_Reflection_getCallerClass---------------------
5400 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5401 //
5402 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5403 //
5404 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5405 // in that it must skip particular security frames and checks for
5406 // caller sensitive methods.
5407 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5408 #ifndef PRODUCT
5409   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5410     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5411   }
5412 #endif
5413 
5414   if (!jvms()->has_method()) {
5415 #ifndef PRODUCT
5416     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5417       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
5418     }
5419 #endif
5420     return false;
5421   }
5422 
5423   // Walk back up the JVM state to find the caller at the required
5424   // depth.
5425   JVMState* caller_jvms = jvms();
5426 
5427   // Cf. JVM_GetCallerClass
5428   // NOTE: Start the loop at depth 1 because the current JVM state does
5429   // not include the Reflection.getCallerClass() frame.
5430   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5431     ciMethod* m = caller_jvms->method();
5432     switch (n) {
5433     case 0:
5434       fatal("current JVM state does not include the Reflection.getCallerClass frame");
5435       break;
5436     case 1:
5437       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5438       if (!m->caller_sensitive()) {
5439 #ifndef PRODUCT
5440         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5441           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
5442         }
5443 #endif
5444         return false;  // bail-out; let JVM_GetCallerClass do the work
5445       }
5446       break;
5447     default:
5448       if (!m->is_ignored_by_security_stack_walk()) {
5449         // We have reached the desired frame; return the holder class.
5450         // Acquire method holder as java.lang.Class and push as constant.
5451         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5452         ciInstance* caller_mirror = caller_klass->java_mirror();
5453         set_result(makecon(TypeInstPtr::make(caller_mirror)));
5454 
5455 #ifndef PRODUCT
5456         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5457           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());
5458           tty->print_cr("  JVM state at this point:");
5459           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5460             ciMethod* m = jvms()->of_depth(i)->method();
5461             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5462           }
5463         }
5464 #endif
5465         return true;
5466       }
5467       break;
5468     }
5469   }
5470 
5471 #ifndef PRODUCT
5472   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5473     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5474     tty->print_cr("  JVM state at this point:");
5475     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5476       ciMethod* m = jvms()->of_depth(i)->method();
5477       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5478     }
5479   }
5480 #endif
5481 
5482   return false;  // bail-out; let JVM_GetCallerClass do the work
5483 }
5484 
5485 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5486   Node* arg = argument(0);
5487   Node* result = nullptr;
5488 
5489   switch (id) {
5490   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
5491   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
5492   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
5493   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
5494   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
5495   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
5496 
5497   case vmIntrinsics::_doubleToLongBits: {
5498     // two paths (plus control) merge in a wood
5499     RegionNode *r = new RegionNode(3);
5500     Node *phi = new PhiNode(r, TypeLong::LONG);
5501 
5502     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5503     // Build the boolean node
5504     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5505 
5506     // Branch either way.
5507     // NaN case is less traveled, which makes all the difference.
5508     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5509     Node *opt_isnan = _gvn.transform(ifisnan);
5510     assert( opt_isnan->is_If(), "Expect an IfNode");
5511     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5512     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5513 
5514     set_control(iftrue);
5515 
5516     static const jlong nan_bits = CONST64(0x7ff8000000000000);
5517     Node *slow_result = longcon(nan_bits); // return NaN
5518     phi->init_req(1, _gvn.transform( slow_result ));
5519     r->init_req(1, iftrue);
5520 
5521     // Else fall through
5522     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5523     set_control(iffalse);
5524 
5525     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5526     r->init_req(2, iffalse);
5527 
5528     // Post merge
5529     set_control(_gvn.transform(r));
5530     record_for_igvn(r);
5531 
5532     C->set_has_split_ifs(true); // Has chance for split-if optimization
5533     result = phi;
5534     assert(result->bottom_type()->isa_long(), "must be");
5535     break;
5536   }
5537 
5538   case vmIntrinsics::_floatToIntBits: {
5539     // two paths (plus control) merge in a wood
5540     RegionNode *r = new RegionNode(3);
5541     Node *phi = new PhiNode(r, TypeInt::INT);
5542 
5543     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5544     // Build the boolean node
5545     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5546 
5547     // Branch either way.
5548     // NaN case is less traveled, which makes all the difference.
5549     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5550     Node *opt_isnan = _gvn.transform(ifisnan);
5551     assert( opt_isnan->is_If(), "Expect an IfNode");
5552     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5553     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5554 
5555     set_control(iftrue);
5556 
5557     static const jint nan_bits = 0x7fc00000;
5558     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5559     phi->init_req(1, _gvn.transform( slow_result ));
5560     r->init_req(1, iftrue);
5561 
5562     // Else fall through
5563     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5564     set_control(iffalse);
5565 
5566     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5567     r->init_req(2, iffalse);
5568 
5569     // Post merge
5570     set_control(_gvn.transform(r));
5571     record_for_igvn(r);
5572 
5573     C->set_has_split_ifs(true); // Has chance for split-if optimization
5574     result = phi;
5575     assert(result->bottom_type()->isa_int(), "must be");
5576     break;
5577   }
5578 
5579   default:
5580     fatal_unexpected_iid(id);
5581     break;
5582   }
5583   set_result(_gvn.transform(result));
5584   return true;
5585 }
5586 
5587 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5588   Node* arg = argument(0);
5589   Node* result = nullptr;
5590 
5591   switch (id) {
5592   case vmIntrinsics::_floatIsInfinite:
5593     result = new IsInfiniteFNode(arg);
5594     break;
5595   case vmIntrinsics::_floatIsFinite:
5596     result = new IsFiniteFNode(arg);
5597     break;
5598   case vmIntrinsics::_doubleIsInfinite:
5599     result = new IsInfiniteDNode(arg);
5600     break;
5601   case vmIntrinsics::_doubleIsFinite:
5602     result = new IsFiniteDNode(arg);
5603     break;
5604   default:
5605     fatal_unexpected_iid(id);
5606     break;
5607   }
5608   set_result(_gvn.transform(result));
5609   return true;
5610 }
5611 
5612 //----------------------inline_unsafe_copyMemory-------------------------
5613 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5614 
5615 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5616   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5617   const Type*       base_t = gvn.type(base);
5618 
5619   bool in_native = (base_t == TypePtr::NULL_PTR);
5620   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
5621   bool is_mixed  = !in_heap && !in_native;
5622 
5623   if (is_mixed) {
5624     return true; // mixed accesses can touch both on-heap and off-heap memory
5625   }
5626   if (in_heap) {
5627     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5628     if (!is_prim_array) {
5629       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5630       // there's not enough type information available to determine proper memory slice for it.
5631       return true;
5632     }
5633   }
5634   return false;
5635 }
5636 
5637 bool LibraryCallKit::inline_unsafe_copyMemory() {
5638   if (callee()->is_static())  return false;  // caller must have the capability!
5639   null_check_receiver();  // null-check receiver
5640   if (stopped())  return true;
5641 
5642   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5643 
5644   Node* src_base =         argument(1);  // type: oop
5645   Node* src_off  = ConvL2X(argument(2)); // type: long
5646   Node* dst_base =         argument(4);  // type: oop
5647   Node* dst_off  = ConvL2X(argument(5)); // type: long
5648   Node* size     = ConvL2X(argument(7)); // type: long
5649 
5650   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5651          "fieldOffset must be byte-scaled");
5652 
5653   Node* src_addr = make_unsafe_address(src_base, src_off);
5654   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5655 
5656   Node* thread = _gvn.transform(new ThreadLocalNode());
5657   Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5658   BasicType doing_unsafe_access_bt = T_BYTE;
5659   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5660 
5661   // update volatile field
5662   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5663 
5664   int flags = RC_LEAF | RC_NO_FP;
5665 
5666   const TypePtr* dst_type = TypePtr::BOTTOM;
5667 
5668   // Adjust memory effects of the runtime call based on input values.
5669   if (!has_wide_mem(_gvn, src_addr, src_base) &&
5670       !has_wide_mem(_gvn, dst_addr, dst_base)) {
5671     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5672 
5673     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5674     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5675       flags |= RC_NARROW_MEM; // narrow in memory
5676     }
5677   }
5678 
5679   // Call it.  Note that the length argument is not scaled.
5680   make_runtime_call(flags,
5681                     OptoRuntime::fast_arraycopy_Type(),
5682                     StubRoutines::unsafe_arraycopy(),
5683                     "unsafe_arraycopy",
5684                     dst_type,
5685                     src_addr, dst_addr, size XTOP);
5686 
5687   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5688 
5689   return true;
5690 }
5691 
5692 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5693 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5694 bool LibraryCallKit::inline_unsafe_setMemory() {
5695   if (callee()->is_static())  return false;  // caller must have the capability!
5696   null_check_receiver();  // null-check receiver
5697   if (stopped())  return true;
5698 
5699   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5700 
5701   Node* dst_base =         argument(1);  // type: oop
5702   Node* dst_off  = ConvL2X(argument(2)); // type: long
5703   Node* size     = ConvL2X(argument(4)); // type: long
5704   Node* byte     =         argument(6);  // type: byte
5705 
5706   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5707          "fieldOffset must be byte-scaled");
5708 
5709   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5710 
5711   Node* thread = _gvn.transform(new ThreadLocalNode());
5712   Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5713   BasicType doing_unsafe_access_bt = T_BYTE;
5714   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5715 
5716   // update volatile field
5717   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5718 
5719   int flags = RC_LEAF | RC_NO_FP;
5720 
5721   const TypePtr* dst_type = TypePtr::BOTTOM;
5722 
5723   // Adjust memory effects of the runtime call based on input values.
5724   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5725     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5726 
5727     flags |= RC_NARROW_MEM; // narrow in memory
5728   }
5729 
5730   // Call it.  Note that the length argument is not scaled.
5731   make_runtime_call(flags,
5732                     OptoRuntime::unsafe_setmemory_Type(),
5733                     StubRoutines::unsafe_setmemory(),
5734                     "unsafe_setmemory",
5735                     dst_type,
5736                     dst_addr, size XTOP, byte);
5737 
5738   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5739 
5740   return true;
5741 }
5742 
5743 #undef XTOP
5744 
5745 //------------------------clone_coping-----------------------------------
5746 // Helper function for inline_native_clone.
5747 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5748   assert(obj_size != nullptr, "");
5749   Node* raw_obj = alloc_obj->in(1);
5750   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5751 
5752   AllocateNode* alloc = nullptr;
5753   if (ReduceBulkZeroing &&
5754       // If we are implementing an array clone without knowing its source type
5755       // (can happen when compiling the array-guarded branch of a reflective
5756       // Object.clone() invocation), initialize the array within the allocation.
5757       // This is needed because some GCs (e.g. ZGC) might fall back in this case
5758       // to a runtime clone call that assumes fully initialized source arrays.
5759       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5760     // We will be completely responsible for initializing this object -
5761     // mark Initialize node as complete.
5762     alloc = AllocateNode::Ideal_allocation(alloc_obj);
5763     // The object was just allocated - there should be no any stores!
5764     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5765     // Mark as complete_with_arraycopy so that on AllocateNode
5766     // expansion, we know this AllocateNode is initialized by an array
5767     // copy and a StoreStore barrier exists after the array copy.
5768     alloc->initialization()->set_complete_with_arraycopy();
5769   }
5770 
5771   Node* size = _gvn.transform(obj_size);
5772   access_clone(obj, alloc_obj, size, is_array);
5773 
5774   // Do not let reads from the cloned object float above the arraycopy.
5775   if (alloc != nullptr) {
5776     // Do not let stores that initialize this object be reordered with
5777     // a subsequent store that would make this object accessible by
5778     // other threads.
5779     // Record what AllocateNode this StoreStore protects so that
5780     // escape analysis can go from the MemBarStoreStoreNode to the
5781     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5782     // based on the escape status of the AllocateNode.
5783     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5784   } else {
5785     insert_mem_bar(Op_MemBarCPUOrder);
5786   }
5787 }
5788 
5789 //------------------------inline_native_clone----------------------------
5790 // protected native Object java.lang.Object.clone();
5791 //
5792 // Here are the simple edge cases:
5793 //  null receiver => normal trap
5794 //  virtual and clone was overridden => slow path to out-of-line clone
5795 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5796 //
5797 // The general case has two steps, allocation and copying.
5798 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5799 //
5800 // Copying also has two cases, oop arrays and everything else.
5801 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5802 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5803 //
5804 // These steps fold up nicely if and when the cloned object's klass
5805 // can be sharply typed as an object array, a type array, or an instance.
5806 //
5807 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5808   PhiNode* result_val;
5809 
5810   // Set the reexecute bit for the interpreter to reexecute
5811   // the bytecode that invokes Object.clone if deoptimization happens.
5812   { PreserveReexecuteState preexecs(this);
5813     jvms()->set_should_reexecute(true);
5814 
5815     Node* obj = argument(0);
5816     obj = null_check_receiver();
5817     if (stopped())  return true;
5818 
5819     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5820     if (obj_type->is_inlinetypeptr()) {
5821       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5822       // no identity.
5823       set_result(obj);
5824       return true;
5825     }
5826 
5827     // If we are going to clone an instance, we need its exact type to
5828     // know the number and types of fields to convert the clone to
5829     // loads/stores. Maybe a speculative type can help us.
5830     if (!obj_type->klass_is_exact() &&
5831         obj_type->speculative_type() != nullptr &&
5832         obj_type->speculative_type()->is_instance_klass() &&
5833         !obj_type->speculative_type()->is_inlinetype()) {
5834       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5835       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5836           !spec_ik->has_injected_fields()) {
5837         if (!obj_type->isa_instptr() ||
5838             obj_type->is_instptr()->instance_klass()->has_subklass()) {
5839           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5840         }
5841       }
5842     }
5843 
5844     // Conservatively insert a memory barrier on all memory slices.
5845     // Do not let writes into the original float below the clone.
5846     insert_mem_bar(Op_MemBarCPUOrder);
5847 
5848     // paths into result_reg:
5849     enum {
5850       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
5851       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
5852       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
5853       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
5854       PATH_LIMIT
5855     };
5856     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5857     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5858     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
5859     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5860     record_for_igvn(result_reg);
5861 
5862     Node* obj_klass = load_object_klass(obj);
5863     // We only go to the fast case code if we pass a number of guards.
5864     // The paths which do not pass are accumulated in the slow_region.
5865     RegionNode* slow_region = new RegionNode(1);
5866     record_for_igvn(slow_region);
5867 
5868     Node* array_obj = obj;
5869     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5870     if (array_ctl != nullptr) {
5871       // It's an array.
5872       PreserveJVMState pjvms(this);
5873       set_control(array_ctl);
5874 
5875       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5876       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
5877       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
5878           obj_type->can_be_inline_array() &&
5879           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
5880         // Flat inline type array may have object field that would require a
5881         // write barrier. Conservatively, go to slow path.
5882         generate_fair_guard(flat_array_test(obj_klass), slow_region);
5883       }
5884 
5885       if (!stopped()) {
5886         Node* obj_length = load_array_length(array_obj);
5887         Node* array_size = nullptr; // Size of the array without object alignment padding.
5888         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5889 
5890         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5891         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5892           // If it is an oop array, it requires very special treatment,
5893           // because gc barriers are required when accessing the array.
5894           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
5895           if (is_obja != nullptr) {
5896             PreserveJVMState pjvms2(this);
5897             set_control(is_obja);
5898             // Generate a direct call to the right arraycopy function(s).
5899             // Clones are always tightly coupled.
5900             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5901             ac->set_clone_oop_array();
5902             Node* n = _gvn.transform(ac);
5903             assert(n == ac, "cannot disappear");
5904             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5905 
5906             result_reg->init_req(_objArray_path, control());
5907             result_val->init_req(_objArray_path, alloc_obj);
5908             result_i_o ->set_req(_objArray_path, i_o());
5909             result_mem ->set_req(_objArray_path, reset_memory());
5910           }
5911         }
5912         // Otherwise, there are no barriers to worry about.
5913         // (We can dispense with card marks if we know the allocation
5914         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
5915         //  causes the non-eden paths to take compensating steps to
5916         //  simulate a fresh allocation, so that no further
5917         //  card marks are required in compiled code to initialize
5918         //  the object.)
5919 
5920         if (!stopped()) {
5921           copy_to_clone(obj, alloc_obj, array_size, true);
5922 
5923           // Present the results of the copy.
5924           result_reg->init_req(_array_path, control());
5925           result_val->init_req(_array_path, alloc_obj);
5926           result_i_o ->set_req(_array_path, i_o());
5927           result_mem ->set_req(_array_path, reset_memory());
5928         }
5929       }
5930     }
5931 
5932     if (!stopped()) {
5933       // It's an instance (we did array above).  Make the slow-path tests.
5934       // If this is a virtual call, we generate a funny guard.  We grab
5935       // the vtable entry corresponding to clone() from the target object.
5936       // If the target method which we are calling happens to be the
5937       // Object clone() method, we pass the guard.  We do not need this
5938       // guard for non-virtual calls; the caller is known to be the native
5939       // Object clone().
5940       if (is_virtual) {
5941         generate_virtual_guard(obj_klass, slow_region);
5942       }
5943 
5944       // The object must be easily cloneable and must not have a finalizer.
5945       // Both of these conditions may be checked in a single test.
5946       // We could optimize the test further, but we don't care.
5947       generate_misc_flags_guard(obj_klass,
5948                                 // Test both conditions:
5949                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5950                                 // Must be cloneable but not finalizer:
5951                                 KlassFlags::_misc_is_cloneable_fast,
5952                                 slow_region);
5953     }
5954 
5955     if (!stopped()) {
5956       // It's an instance, and it passed the slow-path tests.
5957       PreserveJVMState pjvms(this);
5958       Node* obj_size = nullptr; // Total object size, including object alignment padding.
5959       // Need to deoptimize on exception from allocation since Object.clone intrinsic
5960       // is reexecuted if deoptimization occurs and there could be problems when merging
5961       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
5962       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
5963 
5964       copy_to_clone(obj, alloc_obj, obj_size, false);
5965 
5966       // Present the results of the slow call.
5967       result_reg->init_req(_instance_path, control());
5968       result_val->init_req(_instance_path, alloc_obj);
5969       result_i_o ->set_req(_instance_path, i_o());
5970       result_mem ->set_req(_instance_path, reset_memory());
5971     }
5972 
5973     // Generate code for the slow case.  We make a call to clone().
5974     set_control(_gvn.transform(slow_region));
5975     if (!stopped()) {
5976       PreserveJVMState pjvms(this);
5977       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
5978       // We need to deoptimize on exception (see comment above)
5979       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
5980       // this->control() comes from set_results_for_java_call
5981       result_reg->init_req(_slow_path, control());
5982       result_val->init_req(_slow_path, slow_result);
5983       result_i_o ->set_req(_slow_path, i_o());
5984       result_mem ->set_req(_slow_path, reset_memory());
5985     }
5986 
5987     // Return the combined state.
5988     set_control(    _gvn.transform(result_reg));
5989     set_i_o(        _gvn.transform(result_i_o));
5990     set_all_memory( _gvn.transform(result_mem));
5991   } // original reexecute is set back here
5992 
5993   set_result(_gvn.transform(result_val));
5994   return true;
5995 }
5996 
5997 // If we have a tightly coupled allocation, the arraycopy may take care
5998 // of the array initialization. If one of the guards we insert between
5999 // the allocation and the arraycopy causes a deoptimization, an
6000 // uninitialized array will escape the compiled method. To prevent that
6001 // we set the JVM state for uncommon traps between the allocation and
6002 // the arraycopy to the state before the allocation so, in case of
6003 // deoptimization, we'll reexecute the allocation and the
6004 // initialization.
6005 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6006   if (alloc != nullptr) {
6007     ciMethod* trap_method = alloc->jvms()->method();
6008     int trap_bci = alloc->jvms()->bci();
6009 
6010     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6011         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6012       // Make sure there's no store between the allocation and the
6013       // arraycopy otherwise visible side effects could be rexecuted
6014       // in case of deoptimization and cause incorrect execution.
6015       bool no_interfering_store = true;
6016       Node* mem = alloc->in(TypeFunc::Memory);
6017       if (mem->is_MergeMem()) {
6018         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6019           Node* n = mms.memory();
6020           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6021             assert(n->is_Store(), "what else?");
6022             no_interfering_store = false;
6023             break;
6024           }
6025         }
6026       } else {
6027         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6028           Node* n = mms.memory();
6029           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6030             assert(n->is_Store(), "what else?");
6031             no_interfering_store = false;
6032             break;
6033           }
6034         }
6035       }
6036 
6037       if (no_interfering_store) {
6038         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6039 
6040         JVMState* saved_jvms = jvms();
6041         saved_reexecute_sp = _reexecute_sp;
6042 
6043         set_jvms(sfpt->jvms());
6044         _reexecute_sp = jvms()->sp();
6045 
6046         return saved_jvms;
6047       }
6048     }
6049   }
6050   return nullptr;
6051 }
6052 
6053 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6054 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6055 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6056   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6057   uint size = alloc->req();
6058   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6059   old_jvms->set_map(sfpt);
6060   for (uint i = 0; i < size; i++) {
6061     sfpt->init_req(i, alloc->in(i));
6062   }
6063   int adjustment = 1;
6064   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6065   if (ary_klass_ptr->is_null_free()) {
6066     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6067     // also requires the componentType and initVal on stack for re-execution.
6068     // Re-create and push the componentType.
6069     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6070     ciInstance* instance = klass->component_mirror_instance();
6071     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6072     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6073     adjustment++;
6074   }
6075   // re-push array length for deoptimization
6076   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6077   if (ary_klass_ptr->is_null_free()) {
6078     // Re-create and push the initVal.
6079     Node* init_val = alloc->in(AllocateNode::InitValue);
6080     if (init_val == nullptr) {
6081       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6082     } else if (UseCompressedOops) {
6083       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6084     }
6085     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6086     adjustment++;
6087   }
6088   old_jvms->set_sp(old_jvms->sp() + adjustment);
6089   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6090   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6091   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6092   old_jvms->set_should_reexecute(true);
6093 
6094   sfpt->set_i_o(map()->i_o());
6095   sfpt->set_memory(map()->memory());
6096   sfpt->set_control(map()->control());
6097   return sfpt;
6098 }
6099 
6100 // In case of a deoptimization, we restart execution at the
6101 // allocation, allocating a new array. We would leave an uninitialized
6102 // array in the heap that GCs wouldn't expect. Move the allocation
6103 // after the traps so we don't allocate the array if we
6104 // deoptimize. This is possible because tightly_coupled_allocation()
6105 // guarantees there's no observer of the allocated array at this point
6106 // and the control flow is simple enough.
6107 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6108                                                     int saved_reexecute_sp, uint new_idx) {
6109   if (saved_jvms_before_guards != nullptr && !stopped()) {
6110     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6111 
6112     assert(alloc != nullptr, "only with a tightly coupled allocation");
6113     // restore JVM state to the state at the arraycopy
6114     saved_jvms_before_guards->map()->set_control(map()->control());
6115     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6116     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6117     // If we've improved the types of some nodes (null check) while
6118     // emitting the guards, propagate them to the current state
6119     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6120     set_jvms(saved_jvms_before_guards);
6121     _reexecute_sp = saved_reexecute_sp;
6122 
6123     // Remove the allocation from above the guards
6124     CallProjections* callprojs = alloc->extract_projections(true);
6125     InitializeNode* init = alloc->initialization();
6126     Node* alloc_mem = alloc->in(TypeFunc::Memory);
6127     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6128     init->replace_mem_projs_by(alloc_mem, C);
6129 
6130     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6131     // the allocation (i.e. is only valid if the allocation succeeds):
6132     // 1) replace CastIINode with AllocateArrayNode's length here
6133     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6134     //
6135     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6136     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6137     Node* init_control = init->proj_out(TypeFunc::Control);
6138     Node* alloc_length = alloc->Ideal_length();
6139 #ifdef ASSERT
6140     Node* prev_cast = nullptr;
6141 #endif
6142     for (uint i = 0; i < init_control->outcnt(); i++) {
6143       Node* init_out = init_control->raw_out(i);
6144       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6145 #ifdef ASSERT
6146         if (prev_cast == nullptr) {
6147           prev_cast = init_out;
6148         } else {
6149           if (prev_cast->cmp(*init_out) == false) {
6150             prev_cast->dump();
6151             init_out->dump();
6152             assert(false, "not equal CastIINode");
6153           }
6154         }
6155 #endif
6156         C->gvn_replace_by(init_out, alloc_length);
6157       }
6158     }
6159     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6160 
6161     // move the allocation here (after the guards)
6162     _gvn.hash_delete(alloc);
6163     alloc->set_req(TypeFunc::Control, control());
6164     alloc->set_req(TypeFunc::I_O, i_o());
6165     Node *mem = reset_memory();
6166     set_all_memory(mem);
6167     alloc->set_req(TypeFunc::Memory, mem);
6168     set_control(init->proj_out_or_null(TypeFunc::Control));
6169     set_i_o(callprojs->fallthrough_ioproj);
6170 
6171     // Update memory as done in GraphKit::set_output_for_allocation()
6172     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6173     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6174     if (ary_type->isa_aryptr() && length_type != nullptr) {
6175       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6176     }
6177     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6178     int            elemidx  = C->get_alias_index(telemref);
6179     // Need to properly move every memory projection for the Initialize
6180 #ifdef ASSERT
6181     int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6182     int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6183 #endif
6184     auto move_proj = [&](ProjNode* proj) {
6185       int alias_idx = C->get_alias_index(proj->adr_type());
6186       assert(alias_idx == Compile::AliasIdxRaw ||
6187              alias_idx == elemidx ||
6188              alias_idx == mark_idx ||
6189              alias_idx == klass_idx, "should be raw memory or array element type");
6190       set_memory(proj, alias_idx);
6191     };
6192     init->for_each_proj(move_proj, TypeFunc::Memory);
6193 
6194     Node* allocx = _gvn.transform(alloc);
6195     assert(allocx == alloc, "where has the allocation gone?");
6196     assert(dest->is_CheckCastPP(), "not an allocation result?");
6197 
6198     _gvn.hash_delete(dest);
6199     dest->set_req(0, control());
6200     Node* destx = _gvn.transform(dest);
6201     assert(destx == dest, "where has the allocation result gone?");
6202 
6203     array_ideal_length(alloc, ary_type, true);
6204   }
6205 }
6206 
6207 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6208 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6209 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6210 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6211 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6212 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6213 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6214                                                                        JVMState* saved_jvms_before_guards) {
6215   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6216     // There is at least one unrelated uncommon trap which needs to be replaced.
6217     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6218 
6219     JVMState* saved_jvms = jvms();
6220     const int saved_reexecute_sp = _reexecute_sp;
6221     set_jvms(sfpt->jvms());
6222     _reexecute_sp = jvms()->sp();
6223 
6224     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6225 
6226     // Restore state
6227     set_jvms(saved_jvms);
6228     _reexecute_sp = saved_reexecute_sp;
6229   }
6230 }
6231 
6232 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6233 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6234 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6235   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6236   while (if_proj->is_IfProj()) {
6237     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6238     if (uncommon_trap != nullptr) {
6239       create_new_uncommon_trap(uncommon_trap);
6240     }
6241     assert(if_proj->in(0)->is_If(), "must be If");
6242     if_proj = if_proj->in(0)->in(0);
6243   }
6244   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6245          "must have reached control projection of init node");
6246 }
6247 
6248 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6249   const int trap_request = uncommon_trap_call->uncommon_trap_request();
6250   assert(trap_request != 0, "no valid UCT trap request");
6251   PreserveJVMState pjvms(this);
6252   set_control(uncommon_trap_call->in(0));
6253   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6254                 Deoptimization::trap_request_action(trap_request));
6255   assert(stopped(), "Should be stopped");
6256   _gvn.hash_delete(uncommon_trap_call);
6257   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6258 }
6259 
6260 // Common checks for array sorting intrinsics arguments.
6261 // Returns `true` if checks passed.
6262 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6263   // check address of the class
6264   if (elementType == nullptr || elementType->is_top()) {
6265     return false;  // dead path
6266   }
6267   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6268   if (elem_klass == nullptr) {
6269     return false;  // dead path
6270   }
6271   // java_mirror_type() returns non-null for compile-time Class constants only
6272   ciType* elem_type = elem_klass->java_mirror_type();
6273   if (elem_type == nullptr) {
6274     return false;
6275   }
6276   bt = elem_type->basic_type();
6277   // Disable the intrinsic if the CPU does not support SIMD sort
6278   if (!Matcher::supports_simd_sort(bt)) {
6279     return false;
6280   }
6281   // check address of the array
6282   if (obj == nullptr || obj->is_top()) {
6283     return false;  // dead path
6284   }
6285   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6286   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6287     return false; // failed input validation
6288   }
6289   return true;
6290 }
6291 
6292 //------------------------------inline_array_partition-----------------------
6293 bool LibraryCallKit::inline_array_partition() {
6294   address stubAddr = StubRoutines::select_array_partition_function();
6295   if (stubAddr == nullptr) {
6296     return false; // Intrinsic's stub is not implemented on this platform
6297   }
6298   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6299 
6300   // no receiver because it is a static method
6301   Node* elementType     = argument(0);
6302   Node* obj             = argument(1);
6303   Node* offset          = argument(2); // long
6304   Node* fromIndex       = argument(4);
6305   Node* toIndex         = argument(5);
6306   Node* indexPivot1     = argument(6);
6307   Node* indexPivot2     = argument(7);
6308   // PartitionOperation:  argument(8) is ignored
6309 
6310   Node* pivotIndices = nullptr;
6311   BasicType bt = T_ILLEGAL;
6312 
6313   if (!check_array_sort_arguments(elementType, obj, bt)) {
6314     return false;
6315   }
6316   null_check(obj);
6317   // If obj is dead, only null-path is taken.
6318   if (stopped()) {
6319     return true;
6320   }
6321   // Set the original stack and the reexecute bit for the interpreter to reexecute
6322   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6323   { PreserveReexecuteState preexecs(this);
6324     jvms()->set_should_reexecute(true);
6325 
6326     Node* obj_adr = make_unsafe_address(obj, offset);
6327 
6328     // create the pivotIndices array of type int and size = 2
6329     Node* size = intcon(2);
6330     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6331     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
6332     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6333     guarantee(alloc != nullptr, "created above");
6334     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6335 
6336     // pass the basic type enum to the stub
6337     Node* elemType = intcon(bt);
6338 
6339     // Call the stub
6340     const char *stubName = "array_partition_stub";
6341     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6342                       stubAddr, stubName, TypePtr::BOTTOM,
6343                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6344                       indexPivot1, indexPivot2);
6345 
6346   } // original reexecute is set back here
6347 
6348   if (!stopped()) {
6349     set_result(pivotIndices);
6350   }
6351 
6352   return true;
6353 }
6354 
6355 
6356 //------------------------------inline_array_sort-----------------------
6357 bool LibraryCallKit::inline_array_sort() {
6358   address stubAddr = StubRoutines::select_arraysort_function();
6359   if (stubAddr == nullptr) {
6360     return false; // Intrinsic's stub is not implemented on this platform
6361   }
6362   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6363 
6364   // no receiver because it is a static method
6365   Node* elementType     = argument(0);
6366   Node* obj             = argument(1);
6367   Node* offset          = argument(2); // long
6368   Node* fromIndex       = argument(4);
6369   Node* toIndex         = argument(5);
6370   // SortOperation:       argument(6) is ignored
6371 
6372   BasicType bt = T_ILLEGAL;
6373 
6374   if (!check_array_sort_arguments(elementType, obj, bt)) {
6375     return false;
6376   }
6377   null_check(obj);
6378   // If obj is dead, only null-path is taken.
6379   if (stopped()) {
6380     return true;
6381   }
6382   Node* obj_adr = make_unsafe_address(obj, offset);
6383 
6384   // pass the basic type enum to the stub
6385   Node* elemType = intcon(bt);
6386 
6387   // Call the stub.
6388   const char *stubName = "arraysort_stub";
6389   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6390                     stubAddr, stubName, TypePtr::BOTTOM,
6391                     obj_adr, elemType, fromIndex, toIndex);
6392 
6393   return true;
6394 }
6395 
6396 
6397 //------------------------------inline_arraycopy-----------------------
6398 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
6399 //                                                      Object dest, int destPos,
6400 //                                                      int length);
6401 bool LibraryCallKit::inline_arraycopy() {
6402   // Get the arguments.
6403   Node* src         = argument(0);  // type: oop
6404   Node* src_offset  = argument(1);  // type: int
6405   Node* dest        = argument(2);  // type: oop
6406   Node* dest_offset = argument(3);  // type: int
6407   Node* length      = argument(4);  // type: int
6408 
6409   uint new_idx = C->unique();
6410 
6411   // Check for allocation before we add nodes that would confuse
6412   // tightly_coupled_allocation()
6413   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6414 
6415   int saved_reexecute_sp = -1;
6416   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6417   // See arraycopy_restore_alloc_state() comment
6418   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6419   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6420   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6421   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6422 
6423   // The following tests must be performed
6424   // (1) src and dest are arrays.
6425   // (2) src and dest arrays must have elements of the same BasicType
6426   // (3) src and dest must not be null.
6427   // (4) src_offset must not be negative.
6428   // (5) dest_offset must not be negative.
6429   // (6) length must not be negative.
6430   // (7) src_offset + length must not exceed length of src.
6431   // (8) dest_offset + length must not exceed length of dest.
6432   // (9) each element of an oop array must be assignable
6433 
6434   // (3) src and dest must not be null.
6435   // always do this here because we need the JVM state for uncommon traps
6436   Node* null_ctl = top();
6437   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6438   assert(null_ctl->is_top(), "no null control here");
6439   dest = null_check(dest, T_ARRAY);
6440 
6441   if (!can_emit_guards) {
6442     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6443     // guards but the arraycopy node could still take advantage of a
6444     // tightly allocated allocation. tightly_coupled_allocation() is
6445     // called again to make sure it takes the null check above into
6446     // account: the null check is mandatory and if it caused an
6447     // uncommon trap to be emitted then the allocation can't be
6448     // considered tightly coupled in this context.
6449     alloc = tightly_coupled_allocation(dest);
6450   }
6451 
6452   bool validated = false;
6453 
6454   const Type* src_type  = _gvn.type(src);
6455   const Type* dest_type = _gvn.type(dest);
6456   const TypeAryPtr* top_src  = src_type->isa_aryptr();
6457   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6458 
6459   // Do we have the type of src?
6460   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6461   // Do we have the type of dest?
6462   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6463   // Is the type for src from speculation?
6464   bool src_spec = false;
6465   // Is the type for dest from speculation?
6466   bool dest_spec = false;
6467 
6468   if ((!has_src || !has_dest) && can_emit_guards) {
6469     // We don't have sufficient type information, let's see if
6470     // speculative types can help. We need to have types for both src
6471     // and dest so that it pays off.
6472 
6473     // Do we already have or could we have type information for src
6474     bool could_have_src = has_src;
6475     // Do we already have or could we have type information for dest
6476     bool could_have_dest = has_dest;
6477 
6478     ciKlass* src_k = nullptr;
6479     if (!has_src) {
6480       src_k = src_type->speculative_type_not_null();
6481       if (src_k != nullptr && src_k->is_array_klass()) {
6482         could_have_src = true;
6483       }
6484     }
6485 
6486     ciKlass* dest_k = nullptr;
6487     if (!has_dest) {
6488       dest_k = dest_type->speculative_type_not_null();
6489       if (dest_k != nullptr && dest_k->is_array_klass()) {
6490         could_have_dest = true;
6491       }
6492     }
6493 
6494     if (could_have_src && could_have_dest) {
6495       // This is going to pay off so emit the required guards
6496       if (!has_src) {
6497         src = maybe_cast_profiled_obj(src, src_k, true);
6498         src_type  = _gvn.type(src);
6499         top_src  = src_type->isa_aryptr();
6500         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6501         src_spec = true;
6502       }
6503       if (!has_dest) {
6504         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6505         dest_type  = _gvn.type(dest);
6506         top_dest  = dest_type->isa_aryptr();
6507         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6508         dest_spec = true;
6509       }
6510     }
6511   }
6512 
6513   if (has_src && has_dest && can_emit_guards) {
6514     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6515     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6516     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6517     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6518 
6519     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6520       // If both arrays are object arrays then having the exact types
6521       // for both will remove the need for a subtype check at runtime
6522       // before the call and may make it possible to pick a faster copy
6523       // routine (without a subtype check on every element)
6524       // Do we have the exact type of src?
6525       bool could_have_src = src_spec;
6526       // Do we have the exact type of dest?
6527       bool could_have_dest = dest_spec;
6528       ciKlass* src_k = nullptr;
6529       ciKlass* dest_k = nullptr;
6530       if (!src_spec) {
6531         src_k = src_type->speculative_type_not_null();
6532         if (src_k != nullptr && src_k->is_array_klass()) {
6533           could_have_src = true;
6534         }
6535       }
6536       if (!dest_spec) {
6537         dest_k = dest_type->speculative_type_not_null();
6538         if (dest_k != nullptr && dest_k->is_array_klass()) {
6539           could_have_dest = true;
6540         }
6541       }
6542       if (could_have_src && could_have_dest) {
6543         // If we can have both exact types, emit the missing guards
6544         if (could_have_src && !src_spec) {
6545           src = maybe_cast_profiled_obj(src, src_k, true);
6546           src_type = _gvn.type(src);
6547           top_src = src_type->isa_aryptr();
6548         }
6549         if (could_have_dest && !dest_spec) {
6550           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6551           dest_type = _gvn.type(dest);
6552           top_dest = dest_type->isa_aryptr();
6553         }
6554       }
6555     }
6556   }
6557 
6558   ciMethod* trap_method = method();
6559   int trap_bci = bci();
6560   if (saved_jvms_before_guards != nullptr) {
6561     trap_method = alloc->jvms()->method();
6562     trap_bci = alloc->jvms()->bci();
6563   }
6564 
6565   bool negative_length_guard_generated = false;
6566 
6567   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6568       can_emit_guards && !src->is_top() && !dest->is_top()) {
6569     // validate arguments: enables transformation the ArrayCopyNode
6570     validated = true;
6571 
6572     RegionNode* slow_region = new RegionNode(1);
6573     record_for_igvn(slow_region);
6574 
6575     // (1) src and dest are arrays.
6576     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6577     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6578 
6579     // (2) src and dest arrays must have elements of the same BasicType
6580     // done at macro expansion or at Ideal transformation time
6581 
6582     // (4) src_offset must not be negative.
6583     generate_negative_guard(src_offset, slow_region);
6584 
6585     // (5) dest_offset must not be negative.
6586     generate_negative_guard(dest_offset, slow_region);
6587 
6588     // (7) src_offset + length must not exceed length of src.
6589     generate_limit_guard(src_offset, length,
6590                          load_array_length(src),
6591                          slow_region);
6592 
6593     // (8) dest_offset + length must not exceed length of dest.
6594     generate_limit_guard(dest_offset, length,
6595                          load_array_length(dest),
6596                          slow_region);
6597 
6598     // (6) length must not be negative.
6599     // This is also checked in generate_arraycopy() during macro expansion, but
6600     // we also have to check it here for the case where the ArrayCopyNode will
6601     // be eliminated by Escape Analysis.
6602     if (EliminateAllocations) {
6603       generate_negative_guard(length, slow_region);
6604       negative_length_guard_generated = true;
6605     }
6606 
6607     // (9) each element of an oop array must be assignable
6608     Node* dest_klass = load_object_klass(dest);
6609     Node* refined_dest_klass = dest_klass;
6610     if (src != dest) {
6611       dest_klass = load_non_refined_array_klass(refined_dest_klass);
6612       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6613       slow_region->add_req(not_subtype_ctrl);
6614     }
6615 
6616     // TODO 8251971 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6617     // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6618     Node* src_klass = load_object_klass(src);
6619     Node* adr_prop_src = basic_plus_adr(top(), src_klass, in_bytes(ArrayKlass::properties_offset()));
6620     Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src,
6621                                                    _gvn.type(adr_prop_src)->is_ptr(), TypeInt::INT, T_INT,
6622                                                    MemNode::unordered));
6623     Node* adr_prop_dest = basic_plus_adr(top(), refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6624     Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest,
6625                                                     _gvn.type(adr_prop_dest)->is_ptr(), TypeInt::INT, T_INT,
6626                                                     MemNode::unordered));
6627 
6628     const ArrayProperties props_null_restricted = ArrayProperties::Default().with_null_restricted();
6629     jint props_value = (jint)props_null_restricted.value();
6630 
6631     prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(props_value)));
6632     prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6633     prop_src = _gvn.transform(new AndINode(prop_src, intcon(props_value)));
6634 
6635     Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(props_value)));
6636     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6637     generate_fair_guard(tst, slow_region);
6638 
6639     // TODO 8251971 This is too strong
6640     generate_fair_guard(flat_array_test(src), slow_region);
6641     generate_fair_guard(flat_array_test(dest), slow_region);
6642 
6643     {
6644       PreserveJVMState pjvms(this);
6645       set_control(_gvn.transform(slow_region));
6646       uncommon_trap(Deoptimization::Reason_intrinsic,
6647                     Deoptimization::Action_make_not_entrant);
6648       assert(stopped(), "Should be stopped");
6649     }
6650 
6651     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6652     if (dest_klass_t == nullptr) {
6653       // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6654       // are in a dead path.
6655       uncommon_trap(Deoptimization::Reason_intrinsic,
6656                     Deoptimization::Action_make_not_entrant);
6657       return true;
6658     }
6659 
6660     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6661     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6662     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6663   }
6664 
6665   if (stopped()) {
6666     return true;
6667   }
6668 
6669   Node* dest_klass = load_object_klass(dest);
6670   dest_klass = load_non_refined_array_klass(dest_klass);
6671 
6672   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6673                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6674                                           // so the compiler has a chance to eliminate them: during macro expansion,
6675                                           // we have to set their control (CastPP nodes are eliminated).
6676                                           load_object_klass(src), dest_klass,
6677                                           load_array_length(src), load_array_length(dest));
6678 
6679   ac->set_arraycopy(validated);
6680 
6681   Node* n = _gvn.transform(ac);
6682   if (n == ac) {
6683     ac->connect_outputs(this);
6684   } else {
6685     assert(validated, "shouldn't transform if all arguments not validated");
6686     set_all_memory(n);
6687   }
6688   clear_upper_avx();
6689 
6690 
6691   return true;
6692 }
6693 
6694 
6695 // Helper function which determines if an arraycopy immediately follows
6696 // an allocation, with no intervening tests or other escapes for the object.
6697 AllocateArrayNode*
6698 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6699   if (stopped())             return nullptr;  // no fast path
6700   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
6701 
6702   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6703   if (alloc == nullptr)  return nullptr;
6704 
6705   Node* rawmem = memory(Compile::AliasIdxRaw);
6706   // Is the allocation's memory state untouched?
6707   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6708     // Bail out if there have been raw-memory effects since the allocation.
6709     // (Example:  There might have been a call or safepoint.)
6710     return nullptr;
6711   }
6712   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6713   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6714     return nullptr;
6715   }
6716 
6717   // There must be no unexpected observers of this allocation.
6718   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6719     Node* obs = ptr->fast_out(i);
6720     if (obs != this->map()) {
6721       return nullptr;
6722     }
6723   }
6724 
6725   // This arraycopy must unconditionally follow the allocation of the ptr.
6726   Node* alloc_ctl = ptr->in(0);
6727   Node* ctl = control();
6728   while (ctl != alloc_ctl) {
6729     // There may be guards which feed into the slow_region.
6730     // Any other control flow means that we might not get a chance
6731     // to finish initializing the allocated object.
6732     // Various low-level checks bottom out in uncommon traps. These
6733     // are considered safe since we've already checked above that
6734     // there is no unexpected observer of this allocation.
6735     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6736       assert(ctl->in(0)->is_If(), "must be If");
6737       ctl = ctl->in(0)->in(0);
6738     } else {
6739       return nullptr;
6740     }
6741   }
6742 
6743   // If we get this far, we have an allocation which immediately
6744   // precedes the arraycopy, and we can take over zeroing the new object.
6745   // The arraycopy will finish the initialization, and provide
6746   // a new control state to which we will anchor the destination pointer.
6747 
6748   return alloc;
6749 }
6750 
6751 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6752   if (node->is_IfProj()) {
6753     IfProjNode* other_proj = node->as_IfProj()->other_if_proj();
6754     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6755       Node* obs = other_proj->fast_out(j);
6756       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6757           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6758         return obs->as_CallStaticJava();
6759       }
6760     }
6761   }
6762   return nullptr;
6763 }
6764 
6765 //-------------inline_encodeISOArray-----------------------------------
6766 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6767 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6768 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6769 // encode char[] to byte[] in ISO_8859_1 or ASCII
6770 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6771   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6772   // no receiver since it is static method
6773   Node *src         = argument(0);
6774   Node *src_offset  = argument(1);
6775   Node *dst         = argument(2);
6776   Node *dst_offset  = argument(3);
6777   Node *length      = argument(4);
6778 
6779   // Cast source & target arrays to not-null
6780   src = must_be_not_null(src, true);
6781   dst = must_be_not_null(dst, true);
6782   if (stopped()) {
6783     return true;
6784   }
6785 
6786   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6787   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6788   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6789       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6790     // failed array check
6791     return false;
6792   }
6793 
6794   // Figure out the size and type of the elements we will be copying.
6795   BasicType src_elem = src_type->elem()->array_element_basic_type();
6796   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6797   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6798     return false;
6799   }
6800 
6801   // Check source & target bounds
6802   RegionNode* bailout = create_bailout();
6803   generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, bailout);
6804   generate_string_range_check(dst, dst_offset, length, false, bailout);
6805   if (check_bailout(bailout)) {
6806     return true;
6807   }
6808 
6809   Node* src_start = array_element_address(src, src_offset, T_CHAR);
6810   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6811   // 'src_start' points to src array + scaled offset
6812   // 'dst_start' points to dst array + scaled offset
6813 
6814   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
6815   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
6816   enc = _gvn.transform(enc);
6817   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6818   set_memory(res_mem, mtype);
6819   set_result(enc);
6820   clear_upper_avx();
6821 
6822   return true;
6823 }
6824 
6825 //-------------inline_multiplyToLen-----------------------------------
6826 bool LibraryCallKit::inline_multiplyToLen() {
6827   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
6828 
6829   address stubAddr = StubRoutines::multiplyToLen();
6830   if (stubAddr == nullptr) {
6831     return false; // Intrinsic's stub is not implemented on this platform
6832   }
6833   const char* stubName = "multiplyToLen";
6834 
6835   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
6836 
6837   // no receiver because it is a static method
6838   Node* x    = argument(0);
6839   Node* xlen = argument(1);
6840   Node* y    = argument(2);
6841   Node* ylen = argument(3);
6842   Node* z    = argument(4);
6843 
6844   x = must_be_not_null(x, true);
6845   y = must_be_not_null(y, true);
6846 
6847   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6848   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
6849   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6850       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
6851     // failed array check
6852     return false;
6853   }
6854 
6855   BasicType x_elem = x_type->elem()->array_element_basic_type();
6856   BasicType y_elem = y_type->elem()->array_element_basic_type();
6857   if (x_elem != T_INT || y_elem != T_INT) {
6858     return false;
6859   }
6860 
6861   Node* x_start = array_element_address(x, intcon(0), x_elem);
6862   Node* y_start = array_element_address(y, intcon(0), y_elem);
6863   // 'x_start' points to x array + scaled xlen
6864   // 'y_start' points to y array + scaled ylen
6865 
6866   Node* z_start = array_element_address(z, intcon(0), T_INT);
6867 
6868   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6869                                  OptoRuntime::multiplyToLen_Type(),
6870                                  stubAddr, stubName, TypePtr::BOTTOM,
6871                                  x_start, xlen, y_start, ylen, z_start);
6872 
6873   C->set_has_split_ifs(true); // Has chance for split-if optimization
6874   set_result(z);
6875   return true;
6876 }
6877 
6878 //-------------inline_squareToLen------------------------------------
6879 bool LibraryCallKit::inline_squareToLen() {
6880   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
6881 
6882   address stubAddr = StubRoutines::squareToLen();
6883   if (stubAddr == nullptr) {
6884     return false; // Intrinsic's stub is not implemented on this platform
6885   }
6886   const char* stubName = "squareToLen";
6887 
6888   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
6889 
6890   Node* x    = argument(0);
6891   Node* len  = argument(1);
6892   Node* z    = argument(2);
6893   Node* zlen = argument(3);
6894 
6895   x = must_be_not_null(x, true);
6896   z = must_be_not_null(z, true);
6897 
6898   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6899   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
6900   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6901       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
6902     // failed array check
6903     return false;
6904   }
6905 
6906   BasicType x_elem = x_type->elem()->array_element_basic_type();
6907   BasicType z_elem = z_type->elem()->array_element_basic_type();
6908   if (x_elem != T_INT || z_elem != T_INT) {
6909     return false;
6910   }
6911 
6912 
6913   Node* x_start = array_element_address(x, intcon(0), x_elem);
6914   Node* z_start = array_element_address(z, intcon(0), z_elem);
6915 
6916   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
6917                                   OptoRuntime::squareToLen_Type(),
6918                                   stubAddr, stubName, TypePtr::BOTTOM,
6919                                   x_start, len, z_start, zlen);
6920 
6921   set_result(z);
6922   return true;
6923 }
6924 
6925 //-------------inline_mulAdd------------------------------------------
6926 bool LibraryCallKit::inline_mulAdd() {
6927   assert(UseMulAddIntrinsic, "not implemented on this platform");
6928 
6929   address stubAddr = StubRoutines::mulAdd();
6930   if (stubAddr == nullptr) {
6931     return false; // Intrinsic's stub is not implemented on this platform
6932   }
6933   const char* stubName = "mulAdd";
6934 
6935   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
6936 
6937   Node* out      = argument(0);
6938   Node* in       = argument(1);
6939   Node* offset   = argument(2);
6940   Node* len      = argument(3);
6941   Node* k        = argument(4);
6942 
6943   in = must_be_not_null(in, true);
6944   out = must_be_not_null(out, true);
6945 
6946   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
6947   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
6948   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
6949        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
6950     // failed array check
6951     return false;
6952   }
6953 
6954   BasicType out_elem = out_type->elem()->array_element_basic_type();
6955   BasicType in_elem = in_type->elem()->array_element_basic_type();
6956   if (out_elem != T_INT || in_elem != T_INT) {
6957     return false;
6958   }
6959 
6960   Node* outlen = load_array_length(out);
6961   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
6962   Node* out_start = array_element_address(out, intcon(0), out_elem);
6963   Node* in_start = array_element_address(in, intcon(0), in_elem);
6964 
6965   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
6966                                   OptoRuntime::mulAdd_Type(),
6967                                   stubAddr, stubName, TypePtr::BOTTOM,
6968                                   out_start,in_start, new_offset, len, k);
6969   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6970   set_result(result);
6971   return true;
6972 }
6973 
6974 //-------------inline_montgomeryMultiply-----------------------------------
6975 bool LibraryCallKit::inline_montgomeryMultiply() {
6976   address stubAddr = StubRoutines::montgomeryMultiply();
6977   if (stubAddr == nullptr) {
6978     return false; // Intrinsic's stub is not implemented on this platform
6979   }
6980 
6981   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
6982   const char* stubName = "montgomery_multiply";
6983 
6984   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
6985 
6986   Node* a    = argument(0);
6987   Node* b    = argument(1);
6988   Node* n    = argument(2);
6989   Node* len  = argument(3);
6990   Node* inv  = argument(4);
6991   Node* m    = argument(6);
6992 
6993   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
6994   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
6995   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
6996   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
6997   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
6998       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
6999       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7000       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7001     // failed array check
7002     return false;
7003   }
7004 
7005   BasicType a_elem = a_type->elem()->array_element_basic_type();
7006   BasicType b_elem = b_type->elem()->array_element_basic_type();
7007   BasicType n_elem = n_type->elem()->array_element_basic_type();
7008   BasicType m_elem = m_type->elem()->array_element_basic_type();
7009   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7010     return false;
7011   }
7012 
7013   // Make the call
7014   {
7015     Node* a_start = array_element_address(a, intcon(0), a_elem);
7016     Node* b_start = array_element_address(b, intcon(0), b_elem);
7017     Node* n_start = array_element_address(n, intcon(0), n_elem);
7018     Node* m_start = array_element_address(m, intcon(0), m_elem);
7019 
7020     Node* call = make_runtime_call(RC_LEAF,
7021                                    OptoRuntime::montgomeryMultiply_Type(),
7022                                    stubAddr, stubName, TypePtr::BOTTOM,
7023                                    a_start, b_start, n_start, len, inv, top(),
7024                                    m_start);
7025     set_result(m);
7026   }
7027 
7028   return true;
7029 }
7030 
7031 bool LibraryCallKit::inline_montgomerySquare() {
7032   address stubAddr = StubRoutines::montgomerySquare();
7033   if (stubAddr == nullptr) {
7034     return false; // Intrinsic's stub is not implemented on this platform
7035   }
7036 
7037   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7038   const char* stubName = "montgomery_square";
7039 
7040   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7041 
7042   Node* a    = argument(0);
7043   Node* n    = argument(1);
7044   Node* len  = argument(2);
7045   Node* inv  = argument(3);
7046   Node* m    = argument(5);
7047 
7048   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7049   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7050   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7051   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7052       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7053       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7054     // failed array check
7055     return false;
7056   }
7057 
7058   BasicType a_elem = a_type->elem()->array_element_basic_type();
7059   BasicType n_elem = n_type->elem()->array_element_basic_type();
7060   BasicType m_elem = m_type->elem()->array_element_basic_type();
7061   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7062     return false;
7063   }
7064 
7065   // Make the call
7066   {
7067     Node* a_start = array_element_address(a, intcon(0), a_elem);
7068     Node* n_start = array_element_address(n, intcon(0), n_elem);
7069     Node* m_start = array_element_address(m, intcon(0), m_elem);
7070 
7071     Node* call = make_runtime_call(RC_LEAF,
7072                                    OptoRuntime::montgomerySquare_Type(),
7073                                    stubAddr, stubName, TypePtr::BOTTOM,
7074                                    a_start, n_start, len, inv, top(),
7075                                    m_start);
7076     set_result(m);
7077   }
7078 
7079   return true;
7080 }
7081 
7082 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7083   address stubAddr = nullptr;
7084   const char* stubName = nullptr;
7085 
7086   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7087   if (stubAddr == nullptr) {
7088     return false; // Intrinsic's stub is not implemented on this platform
7089   }
7090 
7091   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7092 
7093   assert(callee()->signature()->size() == 5, "expected 5 arguments");
7094 
7095   Node* newArr = argument(0);
7096   Node* oldArr = argument(1);
7097   Node* newIdx = argument(2);
7098   Node* shiftCount = argument(3);
7099   Node* numIter = argument(4);
7100 
7101   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7102   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7103   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7104       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7105     return false;
7106   }
7107 
7108   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7109   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7110   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7111     return false;
7112   }
7113 
7114   // Make the call
7115   {
7116     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7117     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7118 
7119     Node* call = make_runtime_call(RC_LEAF,
7120                                    OptoRuntime::bigIntegerShift_Type(),
7121                                    stubAddr,
7122                                    stubName,
7123                                    TypePtr::BOTTOM,
7124                                    newArr_start,
7125                                    oldArr_start,
7126                                    newIdx,
7127                                    shiftCount,
7128                                    numIter);
7129   }
7130 
7131   return true;
7132 }
7133 
7134 //-------------inline_vectorizedMismatch------------------------------
7135 bool LibraryCallKit::inline_vectorizedMismatch() {
7136   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7137 
7138   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7139   Node* obja    = argument(0); // Object
7140   Node* aoffset = argument(1); // long
7141   Node* objb    = argument(3); // Object
7142   Node* boffset = argument(4); // long
7143   Node* length  = argument(6); // int
7144   Node* scale   = argument(7); // int
7145 
7146   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7147   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7148   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7149       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7150       scale == top()) {
7151     return false; // failed input validation
7152   }
7153 
7154   Node* obja_adr = make_unsafe_address(obja, aoffset);
7155   Node* objb_adr = make_unsafe_address(objb, boffset);
7156 
7157   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7158   //
7159   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
7160   //    if (length <= inline_limit) {
7161   //      inline_path:
7162   //        vmask   = VectorMaskGen length
7163   //        vload1  = LoadVectorMasked obja, vmask
7164   //        vload2  = LoadVectorMasked objb, vmask
7165   //        result1 = VectorCmpMasked vload1, vload2, vmask
7166   //    } else {
7167   //      call_stub_path:
7168   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7169   //    }
7170   //    exit_block:
7171   //      return Phi(result1, result2);
7172   //
7173   enum { inline_path = 1,  // input is small enough to process it all at once
7174          stub_path   = 2,  // input is too large; call into the VM
7175          PATH_LIMIT  = 3
7176   };
7177 
7178   Node* exit_block = new RegionNode(PATH_LIMIT);
7179   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7180   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7181 
7182   Node* call_stub_path = control();
7183 
7184   BasicType elem_bt = T_ILLEGAL;
7185 
7186   const TypeInt* scale_t = _gvn.type(scale)->is_int();
7187   if (scale_t->is_con()) {
7188     switch (scale_t->get_con()) {
7189       case 0: elem_bt = T_BYTE;  break;
7190       case 1: elem_bt = T_SHORT; break;
7191       case 2: elem_bt = T_INT;   break;
7192       case 3: elem_bt = T_LONG;  break;
7193 
7194       default: elem_bt = T_ILLEGAL; break; // not supported
7195     }
7196   }
7197 
7198   int inline_limit = 0;
7199   bool do_partial_inline = false;
7200 
7201   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7202     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7203     do_partial_inline = inline_limit >= 16;
7204   }
7205 
7206   if (do_partial_inline) {
7207     assert(elem_bt != T_ILLEGAL, "sanity");
7208 
7209     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
7210         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7211         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
7212 
7213       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7214       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7215       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7216 
7217       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7218 
7219       if (!stopped()) {
7220         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7221 
7222         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7223         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7224         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7225         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7226 
7227         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7228         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7229         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7230         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7231 
7232         exit_block->init_req(inline_path, control());
7233         memory_phi->init_req(inline_path, map()->memory());
7234         result_phi->init_req(inline_path, result);
7235 
7236         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7237         clear_upper_avx();
7238       }
7239     }
7240   }
7241 
7242   if (call_stub_path != nullptr) {
7243     set_control(call_stub_path);
7244 
7245     Node* call = make_runtime_call(RC_LEAF,
7246                                    OptoRuntime::vectorizedMismatch_Type(),
7247                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7248                                    obja_adr, objb_adr, length, scale);
7249 
7250     exit_block->init_req(stub_path, control());
7251     memory_phi->init_req(stub_path, map()->memory());
7252     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7253   }
7254 
7255   exit_block = _gvn.transform(exit_block);
7256   memory_phi = _gvn.transform(memory_phi);
7257   result_phi = _gvn.transform(result_phi);
7258 
7259   record_for_igvn(exit_block);
7260   record_for_igvn(memory_phi);
7261   record_for_igvn(result_phi);
7262 
7263   set_control(exit_block);
7264   set_all_memory(memory_phi);
7265   set_result(result_phi);
7266 
7267   return true;
7268 }
7269 
7270 //------------------------------inline_vectorizedHashcode----------------------------
7271 bool LibraryCallKit::inline_vectorizedHashCode() {
7272   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7273 
7274   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7275   Node* array          = argument(0);
7276   Node* offset         = argument(1);
7277   Node* length         = argument(2);
7278   Node* initialValue   = argument(3);
7279   Node* basic_type     = argument(4);
7280 
7281   if (basic_type == top()) {
7282     return false; // failed input validation
7283   }
7284 
7285   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7286   if (!basic_type_t->is_con()) {
7287     return false; // Only intrinsify if mode argument is constant
7288   }
7289 
7290   array = must_be_not_null(array, true);
7291 
7292   BasicType bt = (BasicType)basic_type_t->get_con();
7293 
7294   // Resolve address of first element
7295   Node* array_start = array_element_address(array, offset, bt);
7296 
7297   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
7298     array_start, length, initialValue, basic_type)));
7299   clear_upper_avx();
7300 
7301   return true;
7302 }
7303 
7304 /**
7305  * Calculate CRC32 for byte.
7306  * int java.util.zip.CRC32.update(int crc, int b)
7307  */
7308 bool LibraryCallKit::inline_updateCRC32() {
7309   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7310   assert(callee()->signature()->size() == 2, "update has 2 parameters");
7311   // no receiver since it is static method
7312   Node* crc  = argument(0); // type: int
7313   Node* b    = argument(1); // type: int
7314 
7315   /*
7316    *    int c = ~ crc;
7317    *    b = timesXtoThe32[(b ^ c) & 0xFF];
7318    *    b = b ^ (c >>> 8);
7319    *    crc = ~b;
7320    */
7321 
7322   Node* M1 = intcon(-1);
7323   crc = _gvn.transform(new XorINode(crc, M1));
7324   Node* result = _gvn.transform(new XorINode(crc, b));
7325   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7326 
7327   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7328   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7329   Node* adr = off_heap_plus_addr(base, ConvI2X(offset));
7330   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7331 
7332   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7333   result = _gvn.transform(new XorINode(crc, result));
7334   result = _gvn.transform(new XorINode(result, M1));
7335   set_result(result);
7336   return true;
7337 }
7338 
7339 /**
7340  * Calculate CRC32 for byte[] array.
7341  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7342  */
7343 bool LibraryCallKit::inline_updateBytesCRC32() {
7344   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7345   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7346   // no receiver since it is static method
7347   Node* crc     = argument(0); // type: int
7348   Node* src     = argument(1); // type: oop
7349   Node* offset  = argument(2); // type: int
7350   Node* length  = argument(3); // type: int
7351 
7352   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7353   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7354     // failed array check
7355     return false;
7356   }
7357 
7358   // Figure out the size and type of the elements we will be copying.
7359   BasicType src_elem = src_type->elem()->array_element_basic_type();
7360   if (src_elem != T_BYTE) {
7361     return false;
7362   }
7363 
7364   // 'src_start' points to src array + scaled offset
7365   src = must_be_not_null(src, true);
7366   Node* src_start = array_element_address(src, offset, src_elem);
7367 
7368   // We assume that range check is done by caller.
7369   // TODO: generate range check (offset+length < src.length) in debug VM.
7370 
7371   // Call the stub.
7372   address stubAddr = StubRoutines::updateBytesCRC32();
7373   const char *stubName = "updateBytesCRC32";
7374 
7375   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7376                                  stubAddr, stubName, TypePtr::BOTTOM,
7377                                  crc, src_start, length);
7378   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7379   set_result(result);
7380   return true;
7381 }
7382 
7383 /**
7384  * Calculate CRC32 for ByteBuffer.
7385  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7386  */
7387 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7388   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7389   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7390   // no receiver since it is static method
7391   Node* crc     = argument(0); // type: int
7392   Node* src     = argument(1); // type: long
7393   Node* offset  = argument(3); // type: int
7394   Node* length  = argument(4); // type: int
7395 
7396   src = ConvL2X(src);  // adjust Java long to machine word
7397   Node* base = _gvn.transform(new CastX2PNode(src));
7398   offset = ConvI2X(offset);
7399 
7400   // 'src_start' points to src array + scaled offset
7401   Node* src_start = off_heap_plus_addr(base, offset);
7402 
7403   // Call the stub.
7404   address stubAddr = StubRoutines::updateBytesCRC32();
7405   const char *stubName = "updateBytesCRC32";
7406 
7407   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7408                                  stubAddr, stubName, TypePtr::BOTTOM,
7409                                  crc, src_start, length);
7410   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7411   set_result(result);
7412   return true;
7413 }
7414 
7415 //------------------------------get_table_from_crc32c_class-----------------------
7416 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7417   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7418   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7419 
7420   return table;
7421 }
7422 
7423 //------------------------------inline_updateBytesCRC32C-----------------------
7424 //
7425 // Calculate CRC32C for byte[] array.
7426 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7427 //
7428 bool LibraryCallKit::inline_updateBytesCRC32C() {
7429   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7430   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7431   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7432   // no receiver since it is a static method
7433   Node* crc     = argument(0); // type: int
7434   Node* src     = argument(1); // type: oop
7435   Node* offset  = argument(2); // type: int
7436   Node* end     = argument(3); // type: int
7437 
7438   Node* length = _gvn.transform(new SubINode(end, offset));
7439 
7440   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7441   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7442     // failed array check
7443     return false;
7444   }
7445 
7446   // Figure out the size and type of the elements we will be copying.
7447   BasicType src_elem = src_type->elem()->array_element_basic_type();
7448   if (src_elem != T_BYTE) {
7449     return false;
7450   }
7451 
7452   // 'src_start' points to src array + scaled offset
7453   src = must_be_not_null(src, true);
7454   Node* src_start = array_element_address(src, offset, src_elem);
7455 
7456   // static final int[] byteTable in class CRC32C
7457   Node* table = get_table_from_crc32c_class(callee()->holder());
7458   table = must_be_not_null(table, true);
7459   Node* table_start = array_element_address(table, intcon(0), T_INT);
7460 
7461   // We assume that range check is done by caller.
7462   // TODO: generate range check (offset+length < src.length) in debug VM.
7463 
7464   // Call the stub.
7465   address stubAddr = StubRoutines::updateBytesCRC32C();
7466   const char *stubName = "updateBytesCRC32C";
7467 
7468   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7469                                  stubAddr, stubName, TypePtr::BOTTOM,
7470                                  crc, src_start, length, table_start);
7471   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7472   set_result(result);
7473   return true;
7474 }
7475 
7476 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7477 //
7478 // Calculate CRC32C for DirectByteBuffer.
7479 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7480 //
7481 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7482   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7483   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7484   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7485   // no receiver since it is a static method
7486   Node* crc     = argument(0); // type: int
7487   Node* src     = argument(1); // type: long
7488   Node* offset  = argument(3); // type: int
7489   Node* end     = argument(4); // type: int
7490 
7491   Node* length = _gvn.transform(new SubINode(end, offset));
7492 
7493   src = ConvL2X(src);  // adjust Java long to machine word
7494   Node* base = _gvn.transform(new CastX2PNode(src));
7495   offset = ConvI2X(offset);
7496 
7497   // 'src_start' points to src array + scaled offset
7498   Node* src_start = off_heap_plus_addr(base, offset);
7499 
7500   // static final int[] byteTable in class CRC32C
7501   Node* table = get_table_from_crc32c_class(callee()->holder());
7502   table = must_be_not_null(table, true);
7503   Node* table_start = array_element_address(table, intcon(0), T_INT);
7504 
7505   // Call the stub.
7506   address stubAddr = StubRoutines::updateBytesCRC32C();
7507   const char *stubName = "updateBytesCRC32C";
7508 
7509   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7510                                  stubAddr, stubName, TypePtr::BOTTOM,
7511                                  crc, src_start, length, table_start);
7512   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7513   set_result(result);
7514   return true;
7515 }
7516 
7517 //------------------------------inline_updateBytesAdler32----------------------
7518 //
7519 // Calculate Adler32 checksum for byte[] array.
7520 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7521 //
7522 bool LibraryCallKit::inline_updateBytesAdler32() {
7523   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7524   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7525   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7526   // no receiver since it is static method
7527   Node* crc     = argument(0); // type: int
7528   Node* src     = argument(1); // type: oop
7529   Node* offset  = argument(2); // type: int
7530   Node* length  = argument(3); // type: int
7531 
7532   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7533   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7534     // failed array check
7535     return false;
7536   }
7537 
7538   // Figure out the size and type of the elements we will be copying.
7539   BasicType src_elem = src_type->elem()->array_element_basic_type();
7540   if (src_elem != T_BYTE) {
7541     return false;
7542   }
7543 
7544   // 'src_start' points to src array + scaled offset
7545   Node* src_start = array_element_address(src, offset, src_elem);
7546 
7547   // We assume that range check is done by caller.
7548   // TODO: generate range check (offset+length < src.length) in debug VM.
7549 
7550   // Call the stub.
7551   address stubAddr = StubRoutines::updateBytesAdler32();
7552   const char *stubName = "updateBytesAdler32";
7553 
7554   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7555                                  stubAddr, stubName, TypePtr::BOTTOM,
7556                                  crc, src_start, length);
7557   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7558   set_result(result);
7559   return true;
7560 }
7561 
7562 //------------------------------inline_updateByteBufferAdler32---------------
7563 //
7564 // Calculate Adler32 checksum for DirectByteBuffer.
7565 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7566 //
7567 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7568   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7569   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7570   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7571   // no receiver since it is static method
7572   Node* crc     = argument(0); // type: int
7573   Node* src     = argument(1); // type: long
7574   Node* offset  = argument(3); // type: int
7575   Node* length  = argument(4); // type: int
7576 
7577   src = ConvL2X(src);  // adjust Java long to machine word
7578   Node* base = _gvn.transform(new CastX2PNode(src));
7579   offset = ConvI2X(offset);
7580 
7581   // 'src_start' points to src array + scaled offset
7582   Node* src_start = off_heap_plus_addr(base, offset);
7583 
7584   // Call the stub.
7585   address stubAddr = StubRoutines::updateBytesAdler32();
7586   const char *stubName = "updateBytesAdler32";
7587 
7588   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7589                                  stubAddr, stubName, TypePtr::BOTTOM,
7590                                  crc, src_start, length);
7591 
7592   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7593   set_result(result);
7594   return true;
7595 }
7596 
7597 //----------------------------inline_reference_get0----------------------------
7598 // public T java.lang.ref.Reference.get();
7599 bool LibraryCallKit::inline_reference_get0() {
7600   const int referent_offset = java_lang_ref_Reference::referent_offset();
7601 
7602   // Get the argument:
7603   Node* reference_obj = null_check_receiver();
7604   if (stopped()) return true;
7605 
7606   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7607   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7608                                         decorators, /*is_static*/ false,
7609                                         env()->Reference_klass());
7610   if (result == nullptr) return false;
7611 
7612   // Add memory barrier to prevent commoning reads from this field
7613   // across safepoint since GC can change its value.
7614   insert_mem_bar(Op_MemBarCPUOrder);
7615 
7616   set_result(result);
7617   return true;
7618 }
7619 
7620 //----------------------------inline_reference_refersTo0----------------------------
7621 // bool java.lang.ref.Reference.refersTo0();
7622 // bool java.lang.ref.PhantomReference.refersTo0();
7623 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7624   // Get arguments:
7625   Node* reference_obj = null_check_receiver();
7626   Node* other_obj = argument(1);
7627   if (stopped()) return true;
7628 
7629   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7630   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7631   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7632                                           decorators, /*is_static*/ false,
7633                                           env()->Reference_klass());
7634   if (referent == nullptr) return false;
7635 
7636   // Add memory barrier to prevent commoning reads from this field
7637   // across safepoint since GC can change its value.
7638   insert_mem_bar(Op_MemBarCPUOrder);
7639 
7640   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7641   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7642   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7643 
7644   RegionNode* region = new RegionNode(3);
7645   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7646 
7647   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7648   region->init_req(1, if_true);
7649   phi->init_req(1, intcon(1));
7650 
7651   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7652   region->init_req(2, if_false);
7653   phi->init_req(2, intcon(0));
7654 
7655   set_control(_gvn.transform(region));
7656   record_for_igvn(region);
7657   set_result(_gvn.transform(phi));
7658   return true;
7659 }
7660 
7661 //----------------------------inline_reference_clear0----------------------------
7662 // void java.lang.ref.Reference.clear0();
7663 // void java.lang.ref.PhantomReference.clear0();
7664 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7665   // This matches the implementation in JVM_ReferenceClear, see the comments there.
7666 
7667   // Get arguments
7668   Node* reference_obj = null_check_receiver();
7669   if (stopped()) return true;
7670 
7671   // Common access parameters
7672   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7673   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7674   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7675   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7676   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7677 
7678   Node* referent = access_load_at(reference_obj,
7679                                   referent_field_addr,
7680                                   referent_field_addr_type,
7681                                   val_type,
7682                                   T_OBJECT,
7683                                   decorators);
7684 
7685   IdealKit ideal(this);
7686 #define __ ideal.
7687   __ if_then(referent, BoolTest::ne, null());
7688     sync_kit(ideal);
7689     access_store_at(reference_obj,
7690                     referent_field_addr,
7691                     referent_field_addr_type,
7692                     null(),
7693                     val_type,
7694                     T_OBJECT,
7695                     decorators);
7696     __ sync_kit(this);
7697   __ end_if();
7698   final_sync(ideal);
7699 #undef __
7700 
7701   return true;
7702 }
7703 
7704 //-----------------------inline_reference_reachabilityFence-----------------
7705 // bool java.lang.ref.Reference.reachabilityFence();
7706 bool LibraryCallKit::inline_reference_reachabilityFence() {
7707   Node* referent = argument(0);
7708   insert_reachability_fence(referent);
7709   return true;
7710 }
7711 
7712 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7713                                              DecoratorSet decorators, bool is_static,
7714                                              ciInstanceKlass* fromKls) {
7715   if (fromKls == nullptr) {
7716     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7717     assert(tinst != nullptr, "obj is null");
7718     assert(tinst->is_loaded(), "obj is not loaded");
7719     fromKls = tinst->instance_klass();
7720   }
7721   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7722                                               ciSymbol::make(fieldTypeString),
7723                                               is_static);
7724 
7725   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7726   if (field == nullptr) return (Node *) nullptr;
7727 
7728   if (is_static) {
7729     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7730     fromObj = makecon(tip);
7731   }
7732 
7733   // Next code  copied from Parse::do_get_xxx():
7734 
7735   // Compute address and memory type.
7736   int offset  = field->offset_in_bytes();
7737   bool is_vol = field->is_volatile();
7738   ciType* field_klass = field->type();
7739   assert(field_klass->is_loaded(), "should be loaded");
7740   const TypePtr* adr_type = C->alias_type(field)->adr_type();
7741   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7742   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7743     "slice of address and input slice don't match");
7744   BasicType bt = field->layout_type();
7745 
7746   // Build the resultant type of the load
7747   const Type *type;
7748   if (bt == T_OBJECT) {
7749     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7750   } else {
7751     type = Type::get_const_basic_type(bt);
7752   }
7753 
7754   if (is_vol) {
7755     decorators |= MO_SEQ_CST;
7756   }
7757 
7758   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7759 }
7760 
7761 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7762                                                  bool is_exact /* true */, bool is_static /* false */,
7763                                                  ciInstanceKlass * fromKls /* nullptr */) {
7764   if (fromKls == nullptr) {
7765     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7766     assert(tinst != nullptr, "obj is null");
7767     assert(tinst->is_loaded(), "obj is not loaded");
7768     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7769     fromKls = tinst->instance_klass();
7770   }
7771   else {
7772     assert(is_static, "only for static field access");
7773   }
7774   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7775     ciSymbol::make(fieldTypeString),
7776     is_static);
7777 
7778   assert(field != nullptr, "undefined field");
7779   assert(!field->is_volatile(), "not defined for volatile fields");
7780 
7781   if (is_static) {
7782     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7783     fromObj = makecon(tip);
7784   }
7785 
7786   // Next code  copied from Parse::do_get_xxx():
7787 
7788   // Compute address and memory type.
7789   int offset = field->offset_in_bytes();
7790   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7791 
7792   return adr;
7793 }
7794 
7795 //------------------------------inline_aescrypt_Block-----------------------
7796 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7797   address stubAddr = nullptr;
7798   const char *stubName;
7799   bool is_decrypt = false;
7800   assert(UseAES, "need AES instruction support");
7801 
7802   switch(id) {
7803   case vmIntrinsics::_aescrypt_encryptBlock:
7804     stubAddr = StubRoutines::aescrypt_encryptBlock();
7805     stubName = "aescrypt_encryptBlock";
7806     break;
7807   case vmIntrinsics::_aescrypt_decryptBlock:
7808     stubAddr = StubRoutines::aescrypt_decryptBlock();
7809     stubName = "aescrypt_decryptBlock";
7810     is_decrypt = true;
7811     break;
7812   default:
7813     break;
7814   }
7815   if (stubAddr == nullptr) return false;
7816 
7817   Node* aescrypt_object = argument(0);
7818   Node* src             = argument(1);
7819   Node* src_offset      = argument(2);
7820   Node* dest            = argument(3);
7821   Node* dest_offset     = argument(4);
7822 
7823   src = must_be_not_null(src, true);
7824   dest = must_be_not_null(dest, true);
7825 
7826   // (1) src and dest are arrays.
7827   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7828   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7829   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7830          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7831 
7832   // for the quick and dirty code we will skip all the checks.
7833   // we are just trying to get the call to be generated.
7834   Node* src_start  = src;
7835   Node* dest_start = dest;
7836   if (src_offset != nullptr || dest_offset != nullptr) {
7837     assert(src_offset != nullptr && dest_offset != nullptr, "");
7838     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7839     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7840   }
7841 
7842   // now need to get the start of its expanded key array
7843   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7844   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7845   if (k_start == nullptr) return false;
7846 
7847   // Call the stub.
7848   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
7849                     stubAddr, stubName, TypePtr::BOTTOM,
7850                     src_start, dest_start, k_start);
7851 
7852   return true;
7853 }
7854 
7855 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
7856 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
7857   address stubAddr = nullptr;
7858   const char *stubName = nullptr;
7859   bool is_decrypt = false;
7860   assert(UseAES, "need AES instruction support");
7861 
7862   switch(id) {
7863   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
7864     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
7865     stubName = "cipherBlockChaining_encryptAESCrypt";
7866     break;
7867   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
7868     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
7869     stubName = "cipherBlockChaining_decryptAESCrypt";
7870     is_decrypt = true;
7871     break;
7872   default:
7873     break;
7874   }
7875   if (stubAddr == nullptr) return false;
7876 
7877   Node* cipherBlockChaining_object = argument(0);
7878   Node* src                        = argument(1);
7879   Node* src_offset                 = argument(2);
7880   Node* len                        = argument(3);
7881   Node* dest                       = argument(4);
7882   Node* dest_offset                = argument(5);
7883 
7884   src = must_be_not_null(src, false);
7885   dest = must_be_not_null(dest, false);
7886 
7887   // (1) src and dest are arrays.
7888   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7889   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7890   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7891          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7892 
7893   // checks are the responsibility of the caller
7894   Node* src_start  = src;
7895   Node* dest_start = dest;
7896   if (src_offset != nullptr || dest_offset != nullptr) {
7897     assert(src_offset != nullptr && dest_offset != nullptr, "");
7898     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7899     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7900   }
7901 
7902   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7903   // (because of the predicated logic executed earlier).
7904   // so we cast it here safely.
7905   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7906 
7907   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7908   if (embeddedCipherObj == nullptr) return false;
7909 
7910   // cast it to what we know it will be at runtime
7911   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
7912   assert(tinst != nullptr, "CBC obj is null");
7913   assert(tinst->is_loaded(), "CBC obj is not loaded");
7914   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7915   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7916 
7917   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7918   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7919   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7920   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7921   aescrypt_object = _gvn.transform(aescrypt_object);
7922 
7923   // we need to get the start of the aescrypt_object's expanded key array
7924   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7925   if (k_start == nullptr) return false;
7926 
7927   // similarly, get the start address of the r vector
7928   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
7929   if (objRvec == nullptr) return false;
7930   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
7931 
7932   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7933   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
7934                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
7935                                      stubAddr, stubName, TypePtr::BOTTOM,
7936                                      src_start, dest_start, k_start, r_start, len);
7937 
7938   // return cipher length (int)
7939   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
7940   set_result(retvalue);
7941   return true;
7942 }
7943 
7944 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
7945 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
7946   address stubAddr = nullptr;
7947   const char *stubName = nullptr;
7948   bool is_decrypt = false;
7949   assert(UseAES, "need AES instruction support");
7950 
7951   switch (id) {
7952   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
7953     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
7954     stubName = "electronicCodeBook_encryptAESCrypt";
7955     break;
7956   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
7957     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
7958     stubName = "electronicCodeBook_decryptAESCrypt";
7959     is_decrypt = true;
7960     break;
7961   default:
7962     break;
7963   }
7964 
7965   if (stubAddr == nullptr) return false;
7966 
7967   Node* electronicCodeBook_object = argument(0);
7968   Node* src                       = argument(1);
7969   Node* src_offset                = argument(2);
7970   Node* len                       = argument(3);
7971   Node* dest                      = argument(4);
7972   Node* dest_offset               = argument(5);
7973 
7974   // (1) src and dest are arrays.
7975   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7976   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7977   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7978          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7979 
7980   // checks are the responsibility of the caller
7981   Node* src_start = src;
7982   Node* dest_start = dest;
7983   if (src_offset != nullptr || dest_offset != nullptr) {
7984     assert(src_offset != nullptr && dest_offset != nullptr, "");
7985     src_start = array_element_address(src, src_offset, T_BYTE);
7986     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7987   }
7988 
7989   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7990   // (because of the predicated logic executed earlier).
7991   // so we cast it here safely.
7992   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7993 
7994   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7995   if (embeddedCipherObj == nullptr) return false;
7996 
7997   // cast it to what we know it will be at runtime
7998   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
7999   assert(tinst != nullptr, "ECB obj is null");
8000   assert(tinst->is_loaded(), "ECB obj is not loaded");
8001   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8002   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8003 
8004   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8005   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8006   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8007   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8008   aescrypt_object = _gvn.transform(aescrypt_object);
8009 
8010   // we need to get the start of the aescrypt_object's expanded key array
8011   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8012   if (k_start == nullptr) return false;
8013 
8014   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8015   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8016                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
8017                                      stubAddr, stubName, TypePtr::BOTTOM,
8018                                      src_start, dest_start, k_start, len);
8019 
8020   // return cipher length (int)
8021   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8022   set_result(retvalue);
8023   return true;
8024 }
8025 
8026 //------------------------------inline_counterMode_AESCrypt-----------------------
8027 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8028   assert(UseAES, "need AES instruction support");
8029   if (!UseAESCTRIntrinsics) return false;
8030 
8031   address stubAddr = nullptr;
8032   const char *stubName = nullptr;
8033   if (id == vmIntrinsics::_counterMode_AESCrypt) {
8034     stubAddr = StubRoutines::counterMode_AESCrypt();
8035     stubName = "counterMode_AESCrypt";
8036   }
8037   if (stubAddr == nullptr) return false;
8038 
8039   Node* counterMode_object = argument(0);
8040   Node* src = argument(1);
8041   Node* src_offset = argument(2);
8042   Node* len = argument(3);
8043   Node* dest = argument(4);
8044   Node* dest_offset = argument(5);
8045 
8046   // (1) src and dest are arrays.
8047   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8048   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8049   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8050          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8051 
8052   // checks are the responsibility of the caller
8053   Node* src_start = src;
8054   Node* dest_start = dest;
8055   if (src_offset != nullptr || dest_offset != nullptr) {
8056     assert(src_offset != nullptr && dest_offset != nullptr, "");
8057     src_start = array_element_address(src, src_offset, T_BYTE);
8058     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8059   }
8060 
8061   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8062   // (because of the predicated logic executed earlier).
8063   // so we cast it here safely.
8064   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8065   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8066   if (embeddedCipherObj == nullptr) return false;
8067   // cast it to what we know it will be at runtime
8068   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8069   assert(tinst != nullptr, "CTR obj is null");
8070   assert(tinst->is_loaded(), "CTR obj is not loaded");
8071   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8072   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8073   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8074   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8075   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8076   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8077   aescrypt_object = _gvn.transform(aescrypt_object);
8078   // we need to get the start of the aescrypt_object's expanded key array
8079   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
8080   if (k_start == nullptr) return false;
8081   // similarly, get the start address of the r vector
8082   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8083   if (obj_counter == nullptr) return false;
8084   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8085 
8086   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8087   if (saved_encCounter == nullptr) return false;
8088   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8089   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8090 
8091   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8092   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8093                                      OptoRuntime::counterMode_aescrypt_Type(),
8094                                      stubAddr, stubName, TypePtr::BOTTOM,
8095                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8096 
8097   // return cipher length (int)
8098   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8099   set_result(retvalue);
8100   return true;
8101 }
8102 
8103 //------------------------------get_key_start_from_aescrypt_object-----------------------
8104 Node* LibraryCallKit::get_key_start_from_aescrypt_object(Node* aescrypt_object, bool is_decrypt) {
8105   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8106   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8107   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8108   // The following platform specific stubs of encryption and decryption use the same round keys.
8109 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8110   bool use_decryption_key = false;
8111 #else
8112   bool use_decryption_key = is_decrypt;
8113 #endif
8114   Node* objAESCryptKey = load_field_from_object(aescrypt_object, use_decryption_key ? "sessionKd" : "sessionKe", "[I");
8115   assert(objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8116   if (objAESCryptKey == nullptr) return (Node *) nullptr;
8117 
8118   // now have the array, need to get the start address of the selected key array
8119   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8120   return k_start;
8121 }
8122 
8123 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8124 // Return node representing slow path of predicate check.
8125 // the pseudo code we want to emulate with this predicate is:
8126 // for encryption:
8127 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8128 // for decryption:
8129 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8130 //    note cipher==plain is more conservative than the original java code but that's OK
8131 //
8132 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8133   // The receiver was checked for null already.
8134   Node* objCBC = argument(0);
8135 
8136   Node* src = argument(1);
8137   Node* dest = argument(4);
8138 
8139   // Load embeddedCipher field of CipherBlockChaining object.
8140   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8141 
8142   // get AESCrypt klass for instanceOf check
8143   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8144   // will have same classloader as CipherBlockChaining object
8145   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8146   assert(tinst != nullptr, "CBCobj is null");
8147   assert(tinst->is_loaded(), "CBCobj is not loaded");
8148 
8149   // we want to do an instanceof comparison against the AESCrypt class
8150   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8151   if (!klass_AESCrypt->is_loaded()) {
8152     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8153     Node* ctrl = control();
8154     set_control(top()); // no regular fast path
8155     return ctrl;
8156   }
8157 
8158   src = must_be_not_null(src, true);
8159   dest = must_be_not_null(dest, true);
8160 
8161   // Resolve oops to stable for CmpP below.
8162   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8163 
8164   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8165   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
8166   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8167 
8168   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8169 
8170   // for encryption, we are done
8171   if (!decrypting)
8172     return instof_false;  // even if it is null
8173 
8174   // for decryption, we need to add a further check to avoid
8175   // taking the intrinsic path when cipher and plain are the same
8176   // see the original java code for why.
8177   RegionNode* region = new RegionNode(3);
8178   region->init_req(1, instof_false);
8179 
8180   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8181   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8182   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8183   region->init_req(2, src_dest_conjoint);
8184 
8185   record_for_igvn(region);
8186   return _gvn.transform(region);
8187 }
8188 
8189 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8190 // Return node representing slow path of predicate check.
8191 // the pseudo code we want to emulate with this predicate is:
8192 // for encryption:
8193 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8194 // for decryption:
8195 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8196 //    note cipher==plain is more conservative than the original java code but that's OK
8197 //
8198 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8199   // The receiver was checked for null already.
8200   Node* objECB = argument(0);
8201 
8202   // Load embeddedCipher field of ElectronicCodeBook object.
8203   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8204 
8205   // get AESCrypt klass for instanceOf check
8206   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8207   // will have same classloader as ElectronicCodeBook object
8208   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8209   assert(tinst != nullptr, "ECBobj is null");
8210   assert(tinst->is_loaded(), "ECBobj is not loaded");
8211 
8212   // we want to do an instanceof comparison against the AESCrypt class
8213   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8214   if (!klass_AESCrypt->is_loaded()) {
8215     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8216     Node* ctrl = control();
8217     set_control(top()); // no regular fast path
8218     return ctrl;
8219   }
8220   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8221 
8222   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8223   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8224   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8225 
8226   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8227 
8228   // for encryption, we are done
8229   if (!decrypting)
8230     return instof_false;  // even if it is null
8231 
8232   // for decryption, we need to add a further check to avoid
8233   // taking the intrinsic path when cipher and plain are the same
8234   // see the original java code for why.
8235   RegionNode* region = new RegionNode(3);
8236   region->init_req(1, instof_false);
8237   Node* src = argument(1);
8238   Node* dest = argument(4);
8239   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8240   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8241   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8242   region->init_req(2, src_dest_conjoint);
8243 
8244   record_for_igvn(region);
8245   return _gvn.transform(region);
8246 }
8247 
8248 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8249 // Return node representing slow path of predicate check.
8250 // the pseudo code we want to emulate with this predicate is:
8251 // for encryption:
8252 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8253 // for decryption:
8254 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8255 //    note cipher==plain is more conservative than the original java code but that's OK
8256 //
8257 
8258 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8259   // The receiver was checked for null already.
8260   Node* objCTR = argument(0);
8261 
8262   // Load embeddedCipher field of CipherBlockChaining object.
8263   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8264 
8265   // get AESCrypt klass for instanceOf check
8266   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8267   // will have same classloader as CipherBlockChaining object
8268   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8269   assert(tinst != nullptr, "CTRobj is null");
8270   assert(tinst->is_loaded(), "CTRobj is not loaded");
8271 
8272   // we want to do an instanceof comparison against the AESCrypt class
8273   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8274   if (!klass_AESCrypt->is_loaded()) {
8275     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8276     Node* ctrl = control();
8277     set_control(top()); // no regular fast path
8278     return ctrl;
8279   }
8280 
8281   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8282   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8283   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8284   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8285   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8286 
8287   return instof_false; // even if it is null
8288 }
8289 
8290 //------------------------------inline_ghash_processBlocks
8291 bool LibraryCallKit::inline_ghash_processBlocks() {
8292   address stubAddr;
8293   const char *stubName;
8294   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8295 
8296   stubAddr = StubRoutines::ghash_processBlocks();
8297   stubName = "ghash_processBlocks";
8298 
8299   Node* data           = argument(0);
8300   Node* offset         = argument(1);
8301   Node* len            = argument(2);
8302   Node* state          = argument(3);
8303   Node* subkeyH        = argument(4);
8304 
8305   state = must_be_not_null(state, true);
8306   subkeyH = must_be_not_null(subkeyH, true);
8307   data = must_be_not_null(data, true);
8308 
8309   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
8310   assert(state_start, "state is null");
8311   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
8312   assert(subkeyH_start, "subkeyH is null");
8313   Node* data_start  = array_element_address(data, offset, T_BYTE);
8314   assert(data_start, "data is null");
8315 
8316   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8317                                   OptoRuntime::ghash_processBlocks_Type(),
8318                                   stubAddr, stubName, TypePtr::BOTTOM,
8319                                   state_start, subkeyH_start, data_start, len);
8320   return true;
8321 }
8322 
8323 //------------------------------inline_chacha20Block
8324 bool LibraryCallKit::inline_chacha20Block() {
8325   address stubAddr;
8326   const char *stubName;
8327   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8328 
8329   stubAddr = StubRoutines::chacha20Block();
8330   stubName = "chacha20Block";
8331 
8332   Node* state          = argument(0);
8333   Node* result         = argument(1);
8334 
8335   state = must_be_not_null(state, true);
8336   result = must_be_not_null(result, true);
8337 
8338   Node* state_start  = array_element_address(state, intcon(0), T_INT);
8339   assert(state_start, "state is null");
8340   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
8341   assert(result_start, "result is null");
8342 
8343   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8344                                   OptoRuntime::chacha20Block_Type(),
8345                                   stubAddr, stubName, TypePtr::BOTTOM,
8346                                   state_start, result_start);
8347   // return key stream length (int)
8348   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8349   set_result(retvalue);
8350   return true;
8351 }
8352 
8353 //------------------------------inline_kyberNtt
8354 bool LibraryCallKit::inline_kyberNtt() {
8355   address stubAddr;
8356   const char *stubName;
8357   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8358   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8359 
8360   stubAddr = StubRoutines::kyberNtt();
8361   stubName = "kyberNtt";
8362   if (!stubAddr) return false;
8363 
8364   Node* coeffs          = argument(0);
8365   Node* ntt_zetas        = argument(1);
8366 
8367   coeffs = must_be_not_null(coeffs, true);
8368   ntt_zetas = must_be_not_null(ntt_zetas, true);
8369 
8370   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8371   assert(coeffs_start, "coeffs is null");
8372   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8373   assert(ntt_zetas_start, "ntt_zetas is null");
8374   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8375                                   OptoRuntime::kyberNtt_Type(),
8376                                   stubAddr, stubName, TypePtr::BOTTOM,
8377                                   coeffs_start, ntt_zetas_start);
8378   // return an int
8379   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8380   set_result(retvalue);
8381   return true;
8382 }
8383 
8384 //------------------------------inline_kyberInverseNtt
8385 bool LibraryCallKit::inline_kyberInverseNtt() {
8386   address stubAddr;
8387   const char *stubName;
8388   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8389   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8390 
8391   stubAddr = StubRoutines::kyberInverseNtt();
8392   stubName = "kyberInverseNtt";
8393   if (!stubAddr) return false;
8394 
8395   Node* coeffs          = argument(0);
8396   Node* zetas           = argument(1);
8397 
8398   coeffs = must_be_not_null(coeffs, true);
8399   zetas = must_be_not_null(zetas, true);
8400 
8401   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8402   assert(coeffs_start, "coeffs is null");
8403   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8404   assert(zetas_start, "inverseNtt_zetas is null");
8405   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8406                                   OptoRuntime::kyberInverseNtt_Type(),
8407                                   stubAddr, stubName, TypePtr::BOTTOM,
8408                                   coeffs_start, zetas_start);
8409 
8410   // return an int
8411   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8412   set_result(retvalue);
8413   return true;
8414 }
8415 
8416 //------------------------------inline_kyberNttMult
8417 bool LibraryCallKit::inline_kyberNttMult() {
8418   address stubAddr;
8419   const char *stubName;
8420   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8421   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8422 
8423   stubAddr = StubRoutines::kyberNttMult();
8424   stubName = "kyberNttMult";
8425   if (!stubAddr) return false;
8426 
8427   Node* result          = argument(0);
8428   Node* ntta            = argument(1);
8429   Node* nttb            = argument(2);
8430   Node* zetas           = argument(3);
8431 
8432   result = must_be_not_null(result, true);
8433   ntta = must_be_not_null(ntta, true);
8434   nttb = must_be_not_null(nttb, true);
8435   zetas = must_be_not_null(zetas, true);
8436 
8437   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8438   assert(result_start, "result is null");
8439   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
8440   assert(ntta_start, "ntta is null");
8441   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
8442   assert(nttb_start, "nttb is null");
8443   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8444   assert(zetas_start, "nttMult_zetas is null");
8445   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8446                                   OptoRuntime::kyberNttMult_Type(),
8447                                   stubAddr, stubName, TypePtr::BOTTOM,
8448                                   result_start, ntta_start, nttb_start,
8449                                   zetas_start);
8450 
8451   // return an int
8452   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8453   set_result(retvalue);
8454 
8455   return true;
8456 }
8457 
8458 //------------------------------inline_kyberAddPoly_2
8459 bool LibraryCallKit::inline_kyberAddPoly_2() {
8460   address stubAddr;
8461   const char *stubName;
8462   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8463   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8464 
8465   stubAddr = StubRoutines::kyberAddPoly_2();
8466   stubName = "kyberAddPoly_2";
8467   if (!stubAddr) return false;
8468 
8469   Node* result          = argument(0);
8470   Node* a               = argument(1);
8471   Node* b               = argument(2);
8472 
8473   result = must_be_not_null(result, true);
8474   a = must_be_not_null(a, true);
8475   b = must_be_not_null(b, true);
8476 
8477   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8478   assert(result_start, "result is null");
8479   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8480   assert(a_start, "a is null");
8481   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8482   assert(b_start, "b is null");
8483   Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8484                                   OptoRuntime::kyberAddPoly_2_Type(),
8485                                   stubAddr, stubName, TypePtr::BOTTOM,
8486                                   result_start, a_start, b_start);
8487   // return an int
8488   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8489   set_result(retvalue);
8490   return true;
8491 }
8492 
8493 //------------------------------inline_kyberAddPoly_3
8494 bool LibraryCallKit::inline_kyberAddPoly_3() {
8495   address stubAddr;
8496   const char *stubName;
8497   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8498   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8499 
8500   stubAddr = StubRoutines::kyberAddPoly_3();
8501   stubName = "kyberAddPoly_3";
8502   if (!stubAddr) return false;
8503 
8504   Node* result          = argument(0);
8505   Node* a               = argument(1);
8506   Node* b               = argument(2);
8507   Node* c               = argument(3);
8508 
8509   result = must_be_not_null(result, true);
8510   a = must_be_not_null(a, true);
8511   b = must_be_not_null(b, true);
8512   c = must_be_not_null(c, true);
8513 
8514   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8515   assert(result_start, "result is null");
8516   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8517   assert(a_start, "a is null");
8518   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8519   assert(b_start, "b is null");
8520   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
8521   assert(c_start, "c is null");
8522   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8523                                   OptoRuntime::kyberAddPoly_3_Type(),
8524                                   stubAddr, stubName, TypePtr::BOTTOM,
8525                                   result_start, a_start, b_start, c_start);
8526   // return an int
8527   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8528   set_result(retvalue);
8529   return true;
8530 }
8531 
8532 //------------------------------inline_kyber12To16
8533 bool LibraryCallKit::inline_kyber12To16() {
8534   address stubAddr;
8535   const char *stubName;
8536   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8537   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8538 
8539   stubAddr = StubRoutines::kyber12To16();
8540   stubName = "kyber12To16";
8541   if (!stubAddr) return false;
8542 
8543   Node* condensed       = argument(0);
8544   Node* condensedOffs   = argument(1);
8545   Node* parsed          = argument(2);
8546   Node* parsedLength    = argument(3);
8547 
8548   condensed = must_be_not_null(condensed, true);
8549   parsed = must_be_not_null(parsed, true);
8550 
8551   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
8552   assert(condensed_start, "condensed is null");
8553   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
8554   assert(parsed_start, "parsed is null");
8555   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8556                                   OptoRuntime::kyber12To16_Type(),
8557                                   stubAddr, stubName, TypePtr::BOTTOM,
8558                                   condensed_start, condensedOffs, parsed_start, parsedLength);
8559   // return an int
8560   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8561   set_result(retvalue);
8562   return true;
8563 
8564 }
8565 
8566 //------------------------------inline_kyberBarrettReduce
8567 bool LibraryCallKit::inline_kyberBarrettReduce() {
8568   address stubAddr;
8569   const char *stubName;
8570   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8571   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8572 
8573   stubAddr = StubRoutines::kyberBarrettReduce();
8574   stubName = "kyberBarrettReduce";
8575   if (!stubAddr) return false;
8576 
8577   Node* coeffs          = argument(0);
8578 
8579   coeffs = must_be_not_null(coeffs, true);
8580 
8581   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8582   assert(coeffs_start, "coeffs is null");
8583   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8584                                   OptoRuntime::kyberBarrettReduce_Type(),
8585                                   stubAddr, stubName, TypePtr::BOTTOM,
8586                                   coeffs_start);
8587   // return an int
8588   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8589   set_result(retvalue);
8590   return true;
8591 }
8592 
8593 //------------------------------inline_dilithiumAlmostNtt
8594 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8595   address stubAddr;
8596   const char *stubName;
8597   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8598   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8599 
8600   stubAddr = StubRoutines::dilithiumAlmostNtt();
8601   stubName = "dilithiumAlmostNtt";
8602   if (!stubAddr) return false;
8603 
8604   Node* coeffs          = argument(0);
8605   Node* ntt_zetas        = argument(1);
8606 
8607   coeffs = must_be_not_null(coeffs, true);
8608   ntt_zetas = must_be_not_null(ntt_zetas, true);
8609 
8610   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8611   assert(coeffs_start, "coeffs is null");
8612   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
8613   assert(ntt_zetas_start, "ntt_zetas is null");
8614   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8615                                   OptoRuntime::dilithiumAlmostNtt_Type(),
8616                                   stubAddr, stubName, TypePtr::BOTTOM,
8617                                   coeffs_start, ntt_zetas_start);
8618   // return an int
8619   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8620   set_result(retvalue);
8621   return true;
8622 }
8623 
8624 //------------------------------inline_dilithiumAlmostInverseNtt
8625 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8626   address stubAddr;
8627   const char *stubName;
8628   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8629   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8630 
8631   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8632   stubName = "dilithiumAlmostInverseNtt";
8633   if (!stubAddr) return false;
8634 
8635   Node* coeffs          = argument(0);
8636   Node* zetas           = argument(1);
8637 
8638   coeffs = must_be_not_null(coeffs, true);
8639   zetas = must_be_not_null(zetas, true);
8640 
8641   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8642   assert(coeffs_start, "coeffs is null");
8643   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
8644   assert(zetas_start, "inverseNtt_zetas is null");
8645   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8646                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8647                                   stubAddr, stubName, TypePtr::BOTTOM,
8648                                   coeffs_start, zetas_start);
8649   // return an int
8650   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8651   set_result(retvalue);
8652   return true;
8653 }
8654 
8655 //------------------------------inline_dilithiumNttMult
8656 bool LibraryCallKit::inline_dilithiumNttMult() {
8657   address stubAddr;
8658   const char *stubName;
8659   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8660   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8661 
8662   stubAddr = StubRoutines::dilithiumNttMult();
8663   stubName = "dilithiumNttMult";
8664   if (!stubAddr) return false;
8665 
8666   Node* result          = argument(0);
8667   Node* ntta            = argument(1);
8668   Node* nttb            = argument(2);
8669   Node* zetas           = argument(3);
8670 
8671   result = must_be_not_null(result, true);
8672   ntta = must_be_not_null(ntta, true);
8673   nttb = must_be_not_null(nttb, true);
8674   zetas = must_be_not_null(zetas, true);
8675 
8676   Node* result_start  = array_element_address(result, intcon(0), T_INT);
8677   assert(result_start, "result is null");
8678   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
8679   assert(ntta_start, "ntta is null");
8680   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
8681   assert(nttb_start, "nttb is null");
8682   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8683                                   OptoRuntime::dilithiumNttMult_Type(),
8684                                   stubAddr, stubName, TypePtr::BOTTOM,
8685                                   result_start, ntta_start, nttb_start);
8686 
8687   // return an int
8688   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8689   set_result(retvalue);
8690 
8691   return true;
8692 }
8693 
8694 //------------------------------inline_dilithiumMontMulByConstant
8695 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8696   address stubAddr;
8697   const char *stubName;
8698   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8699   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8700 
8701   stubAddr = StubRoutines::dilithiumMontMulByConstant();
8702   stubName = "dilithiumMontMulByConstant";
8703   if (!stubAddr) return false;
8704 
8705   Node* coeffs          = argument(0);
8706   Node* constant        = argument(1);
8707 
8708   coeffs = must_be_not_null(coeffs, true);
8709 
8710   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8711   assert(coeffs_start, "coeffs is null");
8712   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8713                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
8714                                   stubAddr, stubName, TypePtr::BOTTOM,
8715                                   coeffs_start, constant);
8716 
8717   // return an int
8718   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8719   set_result(retvalue);
8720   return true;
8721 }
8722 
8723 
8724 //------------------------------inline_dilithiumDecomposePoly
8725 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8726   address stubAddr;
8727   const char *stubName;
8728   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8729   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8730 
8731   stubAddr = StubRoutines::dilithiumDecomposePoly();
8732   stubName = "dilithiumDecomposePoly";
8733   if (!stubAddr) return false;
8734 
8735   Node* input          = argument(0);
8736   Node* lowPart        = argument(1);
8737   Node* highPart       = argument(2);
8738   Node* twoGamma2      = argument(3);
8739   Node* multiplier     = argument(4);
8740 
8741   input = must_be_not_null(input, true);
8742   lowPart = must_be_not_null(lowPart, true);
8743   highPart = must_be_not_null(highPart, true);
8744 
8745   Node* input_start  = array_element_address(input, intcon(0), T_INT);
8746   assert(input_start, "input is null");
8747   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
8748   assert(lowPart_start, "lowPart is null");
8749   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
8750   assert(highPart_start, "highPart is null");
8751 
8752   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8753                                   OptoRuntime::dilithiumDecomposePoly_Type(),
8754                                   stubAddr, stubName, TypePtr::BOTTOM,
8755                                   input_start, lowPart_start, highPart_start,
8756                                   twoGamma2, multiplier);
8757 
8758   // return an int
8759   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8760   set_result(retvalue);
8761   return true;
8762 }
8763 
8764 bool LibraryCallKit::inline_base64_encodeBlock() {
8765   address stubAddr;
8766   const char *stubName;
8767   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8768   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8769   stubAddr = StubRoutines::base64_encodeBlock();
8770   stubName = "encodeBlock";
8771 
8772   if (!stubAddr) return false;
8773   Node* base64obj = argument(0);
8774   Node* src = argument(1);
8775   Node* offset = argument(2);
8776   Node* len = argument(3);
8777   Node* dest = argument(4);
8778   Node* dp = argument(5);
8779   Node* isURL = argument(6);
8780 
8781   src = must_be_not_null(src, true);
8782   dest = must_be_not_null(dest, true);
8783 
8784   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8785   assert(src_start, "source array is null");
8786   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8787   assert(dest_start, "destination array is null");
8788 
8789   Node* base64 = make_runtime_call(RC_LEAF,
8790                                    OptoRuntime::base64_encodeBlock_Type(),
8791                                    stubAddr, stubName, TypePtr::BOTTOM,
8792                                    src_start, offset, len, dest_start, dp, isURL);
8793   return true;
8794 }
8795 
8796 bool LibraryCallKit::inline_base64_decodeBlock() {
8797   address stubAddr;
8798   const char *stubName;
8799   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8800   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8801   stubAddr = StubRoutines::base64_decodeBlock();
8802   stubName = "decodeBlock";
8803 
8804   if (!stubAddr) return false;
8805   Node* base64obj = argument(0);
8806   Node* src = argument(1);
8807   Node* src_offset = argument(2);
8808   Node* len = argument(3);
8809   Node* dest = argument(4);
8810   Node* dest_offset = argument(5);
8811   Node* isURL = argument(6);
8812   Node* isMIME = argument(7);
8813 
8814   src = must_be_not_null(src, true);
8815   dest = must_be_not_null(dest, true);
8816 
8817   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8818   assert(src_start, "source array is null");
8819   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8820   assert(dest_start, "destination array is null");
8821 
8822   Node* call = make_runtime_call(RC_LEAF,
8823                                  OptoRuntime::base64_decodeBlock_Type(),
8824                                  stubAddr, stubName, TypePtr::BOTTOM,
8825                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
8826   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8827   set_result(result);
8828   return true;
8829 }
8830 
8831 bool LibraryCallKit::inline_poly1305_processBlocks() {
8832   address stubAddr;
8833   const char *stubName;
8834   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
8835   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
8836   stubAddr = StubRoutines::poly1305_processBlocks();
8837   stubName = "poly1305_processBlocks";
8838 
8839   if (!stubAddr) return false;
8840   null_check_receiver();  // null-check receiver
8841   if (stopped())  return true;
8842 
8843   Node* input = argument(1);
8844   Node* input_offset = argument(2);
8845   Node* len = argument(3);
8846   Node* alimbs = argument(4);
8847   Node* rlimbs = argument(5);
8848 
8849   input = must_be_not_null(input, true);
8850   alimbs = must_be_not_null(alimbs, true);
8851   rlimbs = must_be_not_null(rlimbs, true);
8852 
8853   Node* input_start = array_element_address(input, input_offset, T_BYTE);
8854   assert(input_start, "input array is null");
8855   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
8856   assert(acc_start, "acc array is null");
8857   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
8858   assert(r_start, "r array is null");
8859 
8860   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8861                                  OptoRuntime::poly1305_processBlocks_Type(),
8862                                  stubAddr, stubName, TypePtr::BOTTOM,
8863                                  input_start, len, acc_start, r_start);
8864   return true;
8865 }
8866 
8867 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
8868   address stubAddr;
8869   const char *stubName;
8870   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8871   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
8872   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
8873   stubName = "intpoly_montgomeryMult_P256";
8874 
8875   if (!stubAddr) return false;
8876   null_check_receiver();  // null-check receiver
8877   if (stopped())  return true;
8878 
8879   Node* a = argument(1);
8880   Node* b = argument(2);
8881   Node* r = argument(3);
8882 
8883   a = must_be_not_null(a, true);
8884   b = must_be_not_null(b, true);
8885   r = must_be_not_null(r, true);
8886 
8887   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8888   assert(a_start, "a array is null");
8889   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8890   assert(b_start, "b array is null");
8891   Node* r_start = array_element_address(r, intcon(0), T_LONG);
8892   assert(r_start, "r array is null");
8893 
8894   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8895                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
8896                                  stubAddr, stubName, TypePtr::BOTTOM,
8897                                  a_start, b_start, r_start);
8898   return true;
8899 }
8900 
8901 bool LibraryCallKit::inline_intpoly_assign() {
8902   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8903   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
8904   const char *stubName = "intpoly_assign";
8905   address stubAddr = StubRoutines::intpoly_assign();
8906   if (!stubAddr) return false;
8907 
8908   Node* set = argument(0);
8909   Node* a = argument(1);
8910   Node* b = argument(2);
8911   Node* arr_length = load_array_length(a);
8912 
8913   a = must_be_not_null(a, true);
8914   b = must_be_not_null(b, true);
8915 
8916   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8917   assert(a_start, "a array is null");
8918   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8919   assert(b_start, "b array is null");
8920 
8921   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8922                                  OptoRuntime::intpoly_assign_Type(),
8923                                  stubAddr, stubName, TypePtr::BOTTOM,
8924                                  set, a_start, b_start, arr_length);
8925   return true;
8926 }
8927 
8928 //------------------------------inline_digestBase_implCompress-----------------------
8929 //
8930 // Calculate MD5 for single-block byte[] array.
8931 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
8932 //
8933 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
8934 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
8935 //
8936 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
8937 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
8938 //
8939 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
8940 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
8941 //
8942 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
8943 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
8944 //
8945 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
8946   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
8947 
8948   Node* digestBase_obj = argument(0);
8949   Node* src            = argument(1); // type oop
8950   Node* ofs            = argument(2); // type int
8951 
8952   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8953   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
8954     // failed array check
8955     return false;
8956   }
8957   // Figure out the size and type of the elements we will be copying.
8958   BasicType src_elem = src_type->elem()->array_element_basic_type();
8959   if (src_elem != T_BYTE) {
8960     return false;
8961   }
8962   // 'src_start' points to src array + offset
8963   src = must_be_not_null(src, true);
8964   Node* src_start = array_element_address(src, ofs, src_elem);
8965   Node* state = nullptr;
8966   Node* block_size = nullptr;
8967   address stubAddr;
8968   const char *stubName;
8969 
8970   switch(id) {
8971   case vmIntrinsics::_md5_implCompress:
8972     assert(UseMD5Intrinsics, "need MD5 instruction support");
8973     state = get_state_from_digest_object(digestBase_obj, T_INT);
8974     stubAddr = StubRoutines::md5_implCompress();
8975     stubName = "md5_implCompress";
8976     break;
8977   case vmIntrinsics::_sha_implCompress:
8978     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
8979     state = get_state_from_digest_object(digestBase_obj, T_INT);
8980     stubAddr = StubRoutines::sha1_implCompress();
8981     stubName = "sha1_implCompress";
8982     break;
8983   case vmIntrinsics::_sha2_implCompress:
8984     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
8985     state = get_state_from_digest_object(digestBase_obj, T_INT);
8986     stubAddr = StubRoutines::sha256_implCompress();
8987     stubName = "sha256_implCompress";
8988     break;
8989   case vmIntrinsics::_sha5_implCompress:
8990     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
8991     state = get_state_from_digest_object(digestBase_obj, T_LONG);
8992     stubAddr = StubRoutines::sha512_implCompress();
8993     stubName = "sha512_implCompress";
8994     break;
8995   case vmIntrinsics::_sha3_implCompress:
8996     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
8997     state = get_state_from_digest_object(digestBase_obj, T_LONG);
8998     stubAddr = StubRoutines::sha3_implCompress();
8999     stubName = "sha3_implCompress";
9000     block_size = get_block_size_from_digest_object(digestBase_obj);
9001     if (block_size == nullptr) return false;
9002     break;
9003   default:
9004     fatal_unexpected_iid(id);
9005     return false;
9006   }
9007   if (state == nullptr) return false;
9008 
9009   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9010   if (stubAddr == nullptr) return false;
9011 
9012   // Call the stub.
9013   Node* call;
9014   if (block_size == nullptr) {
9015     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9016                              stubAddr, stubName, TypePtr::BOTTOM,
9017                              src_start, state);
9018   } else {
9019     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9020                              stubAddr, stubName, TypePtr::BOTTOM,
9021                              src_start, state, block_size);
9022   }
9023 
9024   return true;
9025 }
9026 
9027 //------------------------------inline_double_keccak
9028 bool LibraryCallKit::inline_double_keccak() {
9029   address stubAddr;
9030   const char *stubName;
9031   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9032   assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
9033 
9034   stubAddr = StubRoutines::double_keccak();
9035   stubName = "double_keccak";
9036   if (!stubAddr) return false;
9037 
9038   Node* status0        = argument(0);
9039   Node* status1        = argument(1);
9040 
9041   status0 = must_be_not_null(status0, true);
9042   status1 = must_be_not_null(status1, true);
9043 
9044   Node* status0_start  = array_element_address(status0, intcon(0), T_LONG);
9045   assert(status0_start, "status0 is null");
9046   Node* status1_start  = array_element_address(status1, intcon(0), T_LONG);
9047   assert(status1_start, "status1 is null");
9048   Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9049                                   OptoRuntime::double_keccak_Type(),
9050                                   stubAddr, stubName, TypePtr::BOTTOM,
9051                                   status0_start, status1_start);
9052   // return an int
9053   Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
9054   set_result(retvalue);
9055   return true;
9056 }
9057 
9058 
9059 //------------------------------inline_digestBase_implCompressMB-----------------------
9060 //
9061 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9062 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9063 //
9064 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9065   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9066          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9067   assert((uint)predicate < 5, "sanity");
9068   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9069 
9070   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9071   Node* src            = argument(1); // byte[] array
9072   Node* ofs            = argument(2); // type int
9073   Node* limit          = argument(3); // type int
9074 
9075   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9076   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9077     // failed array check
9078     return false;
9079   }
9080   // Figure out the size and type of the elements we will be copying.
9081   BasicType src_elem = src_type->elem()->array_element_basic_type();
9082   if (src_elem != T_BYTE) {
9083     return false;
9084   }
9085   // 'src_start' points to src array + offset
9086   src = must_be_not_null(src, false);
9087   Node* src_start = array_element_address(src, ofs, src_elem);
9088 
9089   const char* klass_digestBase_name = nullptr;
9090   const char* stub_name = nullptr;
9091   address     stub_addr = nullptr;
9092   BasicType elem_type = T_INT;
9093 
9094   switch (predicate) {
9095   case 0:
9096     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9097       klass_digestBase_name = "sun/security/provider/MD5";
9098       stub_name = "md5_implCompressMB";
9099       stub_addr = StubRoutines::md5_implCompressMB();
9100     }
9101     break;
9102   case 1:
9103     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9104       klass_digestBase_name = "sun/security/provider/SHA";
9105       stub_name = "sha1_implCompressMB";
9106       stub_addr = StubRoutines::sha1_implCompressMB();
9107     }
9108     break;
9109   case 2:
9110     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9111       klass_digestBase_name = "sun/security/provider/SHA2";
9112       stub_name = "sha256_implCompressMB";
9113       stub_addr = StubRoutines::sha256_implCompressMB();
9114     }
9115     break;
9116   case 3:
9117     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9118       klass_digestBase_name = "sun/security/provider/SHA5";
9119       stub_name = "sha512_implCompressMB";
9120       stub_addr = StubRoutines::sha512_implCompressMB();
9121       elem_type = T_LONG;
9122     }
9123     break;
9124   case 4:
9125     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9126       klass_digestBase_name = "sun/security/provider/SHA3";
9127       stub_name = "sha3_implCompressMB";
9128       stub_addr = StubRoutines::sha3_implCompressMB();
9129       elem_type = T_LONG;
9130     }
9131     break;
9132   default:
9133     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9134   }
9135   if (klass_digestBase_name != nullptr) {
9136     assert(stub_addr != nullptr, "Stub is generated");
9137     if (stub_addr == nullptr) return false;
9138 
9139     // get DigestBase klass to lookup for SHA klass
9140     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9141     assert(tinst != nullptr, "digestBase_obj is not instance???");
9142     assert(tinst->is_loaded(), "DigestBase is not loaded");
9143 
9144     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9145     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9146     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9147     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9148   }
9149   return false;
9150 }
9151 
9152 //------------------------------inline_digestBase_implCompressMB-----------------------
9153 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9154                                                       BasicType elem_type, address stubAddr, const char *stubName,
9155                                                       Node* src_start, Node* ofs, Node* limit) {
9156   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9157   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9158   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9159   digest_obj = _gvn.transform(digest_obj);
9160 
9161   Node* state = get_state_from_digest_object(digest_obj, elem_type);
9162   if (state == nullptr) return false;
9163 
9164   Node* block_size = nullptr;
9165   if (strcmp("sha3_implCompressMB", stubName) == 0) {
9166     block_size = get_block_size_from_digest_object(digest_obj);
9167     if (block_size == nullptr) return false;
9168   }
9169 
9170   // Call the stub.
9171   Node* call;
9172   if (block_size == nullptr) {
9173     call = make_runtime_call(RC_LEAF|RC_NO_FP,
9174                              OptoRuntime::digestBase_implCompressMB_Type(false),
9175                              stubAddr, stubName, TypePtr::BOTTOM,
9176                              src_start, state, ofs, limit);
9177   } else {
9178      call = make_runtime_call(RC_LEAF|RC_NO_FP,
9179                              OptoRuntime::digestBase_implCompressMB_Type(true),
9180                              stubAddr, stubName, TypePtr::BOTTOM,
9181                              src_start, state, block_size, ofs, limit);
9182   }
9183 
9184   // return ofs (int)
9185   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9186   set_result(result);
9187 
9188   return true;
9189 }
9190 
9191 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9192 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9193   assert(UseAES, "need AES instruction support");
9194   address stubAddr = nullptr;
9195   const char *stubName = nullptr;
9196   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9197   stubName = "galoisCounterMode_AESCrypt";
9198 
9199   if (stubAddr == nullptr) return false;
9200 
9201   Node* in      = argument(0);
9202   Node* inOfs   = argument(1);
9203   Node* len     = argument(2);
9204   Node* ct      = argument(3);
9205   Node* ctOfs   = argument(4);
9206   Node* out     = argument(5);
9207   Node* outOfs  = argument(6);
9208   Node* gctr_object = argument(7);
9209   Node* ghash_object = argument(8);
9210 
9211   // (1) in, ct and out are arrays.
9212   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9213   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9214   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9215   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
9216           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
9217          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9218 
9219   // checks are the responsibility of the caller
9220   Node* in_start = in;
9221   Node* ct_start = ct;
9222   Node* out_start = out;
9223   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9224     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9225     in_start = array_element_address(in, inOfs, T_BYTE);
9226     ct_start = array_element_address(ct, ctOfs, T_BYTE);
9227     out_start = array_element_address(out, outOfs, T_BYTE);
9228   }
9229 
9230   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9231   // (because of the predicated logic executed earlier).
9232   // so we cast it here safely.
9233   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9234   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9235   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9236   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9237   Node* state = load_field_from_object(ghash_object, "state", "[J");
9238 
9239   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9240     return false;
9241   }
9242   // cast it to what we know it will be at runtime
9243   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9244   assert(tinst != nullptr, "GCTR obj is null");
9245   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9246   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9247   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9248   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9249   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9250   const TypeOopPtr* xtype = aklass->as_instance_type();
9251   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9252   aescrypt_object = _gvn.transform(aescrypt_object);
9253   // we need to get the start of the aescrypt_object's expanded key array
9254   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
9255   if (k_start == nullptr) return false;
9256   // similarly, get the start address of the r vector
9257   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9258   Node* state_start = array_element_address(state, intcon(0), T_LONG);
9259   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9260 
9261 
9262   // Call the stub, passing params
9263   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9264                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
9265                                stubAddr, stubName, TypePtr::BOTTOM,
9266                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9267 
9268   // return cipher length (int)
9269   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9270   set_result(retvalue);
9271 
9272   return true;
9273 }
9274 
9275 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9276 // Return node representing slow path of predicate check.
9277 // the pseudo code we want to emulate with this predicate is:
9278 // for encryption:
9279 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9280 // for decryption:
9281 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9282 //    note cipher==plain is more conservative than the original java code but that's OK
9283 //
9284 
9285 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9286   // The receiver was checked for null already.
9287   Node* objGCTR = argument(7);
9288   // Load embeddedCipher field of GCTR object.
9289   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9290   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9291 
9292   // get AESCrypt klass for instanceOf check
9293   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9294   // will have same classloader as CipherBlockChaining object
9295   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9296   assert(tinst != nullptr, "GCTR obj is null");
9297   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9298 
9299   // we want to do an instanceof comparison against the AESCrypt class
9300   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9301   if (!klass_AESCrypt->is_loaded()) {
9302     // if AESCrypt is not even loaded, we never take the intrinsic fast path
9303     Node* ctrl = control();
9304     set_control(top()); // no regular fast path
9305     return ctrl;
9306   }
9307 
9308   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9309   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9310   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9311   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9312   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9313 
9314   return instof_false; // even if it is null
9315 }
9316 
9317 //------------------------------get_state_from_digest_object-----------------------
9318 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9319   const char* state_type;
9320   switch (elem_type) {
9321     case T_BYTE: state_type = "[B"; break;
9322     case T_INT:  state_type = "[I"; break;
9323     case T_LONG: state_type = "[J"; break;
9324     default: ShouldNotReachHere();
9325   }
9326   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9327   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9328   if (digest_state == nullptr) return (Node *) nullptr;
9329 
9330   // now have the array, need to get the start address of the state array
9331   Node* state = array_element_address(digest_state, intcon(0), elem_type);
9332   return state;
9333 }
9334 
9335 //------------------------------get_block_size_from_sha3_object----------------------------------
9336 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9337   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9338   assert (block_size != nullptr, "sanity");
9339   return block_size;
9340 }
9341 
9342 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9343 // Return node representing slow path of predicate check.
9344 // the pseudo code we want to emulate with this predicate is:
9345 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9346 //
9347 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9348   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9349          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9350   assert((uint)predicate < 5, "sanity");
9351 
9352   // The receiver was checked for null already.
9353   Node* digestBaseObj = argument(0);
9354 
9355   // get DigestBase klass for instanceOf check
9356   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9357   assert(tinst != nullptr, "digestBaseObj is null");
9358   assert(tinst->is_loaded(), "DigestBase is not loaded");
9359 
9360   const char* klass_name = nullptr;
9361   switch (predicate) {
9362   case 0:
9363     if (UseMD5Intrinsics) {
9364       // we want to do an instanceof comparison against the MD5 class
9365       klass_name = "sun/security/provider/MD5";
9366     }
9367     break;
9368   case 1:
9369     if (UseSHA1Intrinsics) {
9370       // we want to do an instanceof comparison against the SHA class
9371       klass_name = "sun/security/provider/SHA";
9372     }
9373     break;
9374   case 2:
9375     if (UseSHA256Intrinsics) {
9376       // we want to do an instanceof comparison against the SHA2 class
9377       klass_name = "sun/security/provider/SHA2";
9378     }
9379     break;
9380   case 3:
9381     if (UseSHA512Intrinsics) {
9382       // we want to do an instanceof comparison against the SHA5 class
9383       klass_name = "sun/security/provider/SHA5";
9384     }
9385     break;
9386   case 4:
9387     if (UseSHA3Intrinsics) {
9388       // we want to do an instanceof comparison against the SHA3 class
9389       klass_name = "sun/security/provider/SHA3";
9390     }
9391     break;
9392   default:
9393     fatal("unknown SHA intrinsic predicate: %d", predicate);
9394   }
9395 
9396   ciKlass* klass = nullptr;
9397   if (klass_name != nullptr) {
9398     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9399   }
9400   if ((klass == nullptr) || !klass->is_loaded()) {
9401     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9402     Node* ctrl = control();
9403     set_control(top()); // no intrinsic path
9404     return ctrl;
9405   }
9406   ciInstanceKlass* instklass = klass->as_instance_klass();
9407 
9408   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9409   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9410   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9411   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9412 
9413   return instof_false;  // even if it is null
9414 }
9415 
9416 //-------------inline_fma-----------------------------------
9417 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9418   Node *a = nullptr;
9419   Node *b = nullptr;
9420   Node *c = nullptr;
9421   Node* result = nullptr;
9422   switch (id) {
9423   case vmIntrinsics::_fmaD:
9424     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9425     // no receiver since it is static method
9426     a = argument(0);
9427     b = argument(2);
9428     c = argument(4);
9429     result = _gvn.transform(new FmaDNode(a, b, c));
9430     break;
9431   case vmIntrinsics::_fmaF:
9432     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9433     a = argument(0);
9434     b = argument(1);
9435     c = argument(2);
9436     result = _gvn.transform(new FmaFNode(a, b, c));
9437     break;
9438   default:
9439     fatal_unexpected_iid(id);  break;
9440   }
9441   set_result(result);
9442   return true;
9443 }
9444 
9445 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9446   // argument(0) is receiver
9447   Node* codePoint = argument(1);
9448   Node* n = nullptr;
9449 
9450   switch (id) {
9451     case vmIntrinsics::_isDigit :
9452       n = new DigitNode(control(), codePoint);
9453       break;
9454     case vmIntrinsics::_isLowerCase :
9455       n = new LowerCaseNode(control(), codePoint);
9456       break;
9457     case vmIntrinsics::_isUpperCase :
9458       n = new UpperCaseNode(control(), codePoint);
9459       break;
9460     case vmIntrinsics::_isWhitespace :
9461       n = new WhitespaceNode(control(), codePoint);
9462       break;
9463     default:
9464       fatal_unexpected_iid(id);
9465   }
9466 
9467   set_result(_gvn.transform(n));
9468   return true;
9469 }
9470 
9471 bool LibraryCallKit::inline_profileBoolean() {
9472   Node* counts = argument(1);
9473   const TypeAryPtr* ary = nullptr;
9474   ciArray* aobj = nullptr;
9475   if (counts->is_Con()
9476       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9477       && (aobj = ary->const_oop()->as_array()) != nullptr
9478       && (aobj->length() == 2)) {
9479     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9480     jint false_cnt = aobj->element_value(0).as_int();
9481     jint  true_cnt = aobj->element_value(1).as_int();
9482 
9483     if (C->log() != nullptr) {
9484       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9485                      false_cnt, true_cnt);
9486     }
9487 
9488     if (false_cnt + true_cnt == 0) {
9489       // According to profile, never executed.
9490       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9491                           Deoptimization::Action_reinterpret);
9492       return true;
9493     }
9494 
9495     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9496     // is a number of each value occurrences.
9497     Node* result = argument(0);
9498     if (false_cnt == 0 || true_cnt == 0) {
9499       // According to profile, one value has been never seen.
9500       int expected_val = (false_cnt == 0) ? 1 : 0;
9501 
9502       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9503       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9504 
9505       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9506       Node* fast_path = _gvn.transform(new IfTrueNode(check));
9507       Node* slow_path = _gvn.transform(new IfFalseNode(check));
9508 
9509       { // Slow path: uncommon trap for never seen value and then reexecute
9510         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9511         // the value has been seen at least once.
9512         PreserveJVMState pjvms(this);
9513         PreserveReexecuteState preexecs(this);
9514         jvms()->set_should_reexecute(true);
9515 
9516         set_control(slow_path);
9517         set_i_o(i_o());
9518 
9519         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9520                             Deoptimization::Action_reinterpret);
9521       }
9522       // The guard for never seen value enables sharpening of the result and
9523       // returning a constant. It allows to eliminate branches on the same value
9524       // later on.
9525       set_control(fast_path);
9526       result = intcon(expected_val);
9527     }
9528     // Stop profiling.
9529     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9530     // By replacing method body with profile data (represented as ProfileBooleanNode
9531     // on IR level) we effectively disable profiling.
9532     // It enables full speed execution once optimized code is generated.
9533     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9534     C->record_for_igvn(profile);
9535     set_result(profile);
9536     return true;
9537   } else {
9538     // Continue profiling.
9539     // Profile data isn't available at the moment. So, execute method's bytecode version.
9540     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9541     // is compiled and counters aren't available since corresponding MethodHandle
9542     // isn't a compile-time constant.
9543     return false;
9544   }
9545 }
9546 
9547 bool LibraryCallKit::inline_isCompileConstant() {
9548   Node* n = argument(0);
9549   set_result(n->is_Con() ? intcon(1) : intcon(0));
9550   return true;
9551 }
9552 
9553 //------------------------------- inline_getObjectSize --------------------------------------
9554 //
9555 // Calculate the runtime size of the object/array.
9556 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9557 //
9558 bool LibraryCallKit::inline_getObjectSize() {
9559   Node* obj = argument(3);
9560   Node* klass_node = load_object_klass(obj);
9561 
9562   jint  layout_con = Klass::_lh_neutral_value;
9563   Node* layout_val = get_layout_helper(klass_node, layout_con);
9564   int   layout_is_con = (layout_val == nullptr);
9565 
9566   if (layout_is_con) {
9567     // Layout helper is constant, can figure out things at compile time.
9568 
9569     if (Klass::layout_helper_is_instance(layout_con)) {
9570       // Instance case:  layout_con contains the size itself.
9571       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9572       set_result(size);
9573     } else {
9574       // Array case: size is round(header + element_size*arraylength).
9575       // Since arraylength is different for every array instance, we have to
9576       // compute the whole thing at runtime.
9577 
9578       Node* arr_length = load_array_length(obj);
9579 
9580       int round_mask = MinObjAlignmentInBytes - 1;
9581       int hsize  = Klass::layout_helper_header_size(layout_con);
9582       int eshift = Klass::layout_helper_log2_element_size(layout_con);
9583 
9584       if ((round_mask & ~right_n_bits(eshift)) == 0) {
9585         round_mask = 0;  // strength-reduce it if it goes away completely
9586       }
9587       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9588       Node* header_size = intcon(hsize + round_mask);
9589 
9590       Node* lengthx = ConvI2X(arr_length);
9591       Node* headerx = ConvI2X(header_size);
9592 
9593       Node* abody = lengthx;
9594       if (eshift != 0) {
9595         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9596       }
9597       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9598       if (round_mask != 0) {
9599         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9600       }
9601       size = ConvX2L(size);
9602       set_result(size);
9603     }
9604   } else {
9605     // Layout helper is not constant, need to test for array-ness at runtime.
9606 
9607     enum { _instance_path = 1, _array_path, PATH_LIMIT };
9608     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9609     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9610     record_for_igvn(result_reg);
9611 
9612     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9613     if (array_ctl != nullptr) {
9614       // Array case: size is round(header + element_size*arraylength).
9615       // Since arraylength is different for every array instance, we have to
9616       // compute the whole thing at runtime.
9617 
9618       PreserveJVMState pjvms(this);
9619       set_control(array_ctl);
9620       Node* arr_length = load_array_length(obj);
9621 
9622       int round_mask = MinObjAlignmentInBytes - 1;
9623       Node* mask = intcon(round_mask);
9624 
9625       Node* hss = intcon(Klass::_lh_header_size_shift);
9626       Node* hsm = intcon(Klass::_lh_header_size_mask);
9627       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9628       header_size = _gvn.transform(new AndINode(header_size, hsm));
9629       header_size = _gvn.transform(new AddINode(header_size, mask));
9630 
9631       // There is no need to mask or shift this value.
9632       // The semantics of LShiftINode include an implicit mask to 0x1F.
9633       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9634       Node* elem_shift = layout_val;
9635 
9636       Node* lengthx = ConvI2X(arr_length);
9637       Node* headerx = ConvI2X(header_size);
9638 
9639       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9640       Node* size = _gvn.transform(new AddXNode(headerx, abody));
9641       if (round_mask != 0) {
9642         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9643       }
9644       size = ConvX2L(size);
9645 
9646       result_reg->init_req(_array_path, control());
9647       result_val->init_req(_array_path, size);
9648     }
9649 
9650     if (!stopped()) {
9651       // Instance case: the layout helper gives us instance size almost directly,
9652       // but we need to mask out the _lh_instance_slow_path_bit.
9653       Node* size = ConvI2X(layout_val);
9654       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9655       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9656       size = _gvn.transform(new AndXNode(size, mask));
9657       size = ConvX2L(size);
9658 
9659       result_reg->init_req(_instance_path, control());
9660       result_val->init_req(_instance_path, size);
9661     }
9662 
9663     set_result(result_reg, result_val);
9664   }
9665 
9666   return true;
9667 }
9668 
9669 //------------------------------- inline_blackhole --------------------------------------
9670 //
9671 // Make sure all arguments to this node are alive.
9672 // This matches methods that were requested to be blackholed through compile commands.
9673 //
9674 bool LibraryCallKit::inline_blackhole() {
9675   assert(callee()->is_static(), "Should have been checked before: only static methods here");
9676   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9677   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9678 
9679   // Blackhole node pinches only the control, not memory. This allows
9680   // the blackhole to be pinned in the loop that computes blackholed
9681   // values, but have no other side effects, like breaking the optimizations
9682   // across the blackhole.
9683 
9684   Node* bh = _gvn.transform(new BlackholeNode(control()));
9685   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9686 
9687   // Bind call arguments as blackhole arguments to keep them alive
9688   uint nargs = callee()->arg_size();
9689   for (uint i = 0; i < nargs; i++) {
9690     bh->add_req(argument(i));
9691   }
9692 
9693   return true;
9694 }
9695 
9696 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9697   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9698   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9699     return nullptr; // box klass is not Float16
9700   }
9701 
9702   // Null check; get notnull casted pointer
9703   Node* null_ctl = top();
9704   Node* not_null_box = null_check_oop(box, &null_ctl, true);
9705   // If not_null_box is dead, only null-path is taken
9706   if (stopped()) {
9707     set_control(null_ctl);
9708     return nullptr;
9709   }
9710   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9711   const TypePtr* adr_type = C->alias_type(field)->adr_type();
9712   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9713   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9714 }
9715 
9716 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9717   PreserveReexecuteState preexecs(this);
9718   jvms()->set_should_reexecute(true);
9719 
9720   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9721   Node* klass_node = makecon(klass_type);
9722   Node* box = new_instance(klass_node);
9723 
9724   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9725   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9726 
9727   Node* field_store = _gvn.transform(access_store_at(box,
9728                                                      value_field,
9729                                                      value_adr_type,
9730                                                      value,
9731                                                      TypeInt::SHORT,
9732                                                      T_SHORT,
9733                                                      IN_HEAP));
9734   set_memory(field_store, value_adr_type);
9735   return box;
9736 }
9737 
9738 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9739   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9740       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9741     return false;
9742   }
9743 
9744   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9745   if (box_type == nullptr || box_type->const_oop() == nullptr) {
9746     return false;
9747   }
9748 
9749   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9750   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9751   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9752                                                     ciSymbols::short_signature(),
9753                                                     false);
9754   assert(field != nullptr, "");
9755 
9756   // Transformed nodes
9757   Node* fld1 = nullptr;
9758   Node* fld2 = nullptr;
9759   Node* fld3 = nullptr;
9760   switch(num_args) {
9761     case 3:
9762       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9763       if (fld3 == nullptr) {
9764         return false;
9765       }
9766       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9767     // fall-through
9768     case 2:
9769       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9770       if (fld2 == nullptr) {
9771         return false;
9772       }
9773       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9774     // fall-through
9775     case 1:
9776       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9777       if (fld1 == nullptr) {
9778         return false;
9779       }
9780       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9781       break;
9782     default: fatal("Unsupported number of arguments %d", num_args);
9783   }
9784 
9785   Node* result = nullptr;
9786   switch (id) {
9787     // Unary operations
9788     case vmIntrinsics::_sqrt_float16:
9789       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9790       break;
9791     // Ternary operations
9792     case vmIntrinsics::_fma_float16:
9793       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9794       break;
9795     default:
9796       fatal_unexpected_iid(id);
9797       break;
9798   }
9799   result = _gvn.transform(new ReinterpretHF2SNode(result));
9800   set_result(box_fp16_value(float16_box_type, field, result));
9801   return true;
9802 }
9803