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::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
 598   case vmIntrinsics::_Reference_clear0:         return inline_reference_clear0(false);
 599   case vmIntrinsics::_PhantomReference_clear0:  return inline_reference_clear0(true);
 600 
 601   case vmIntrinsics::_Class_cast:               return inline_Class_cast();
 602 
 603   case vmIntrinsics::_aescrypt_encryptBlock:
 604   case vmIntrinsics::_aescrypt_decryptBlock:    return inline_aescrypt_Block(intrinsic_id());
 605 
 606   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 607   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 608     return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
 609 
 610   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 611   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 612     return inline_electronicCodeBook_AESCrypt(intrinsic_id());
 613 
 614   case vmIntrinsics::_counterMode_AESCrypt:
 615     return inline_counterMode_AESCrypt(intrinsic_id());
 616 
 617   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 618     return inline_galoisCounterMode_AESCrypt();
 619 
 620   case vmIntrinsics::_md5_implCompress:
 621   case vmIntrinsics::_sha_implCompress:
 622   case vmIntrinsics::_sha2_implCompress:
 623   case vmIntrinsics::_sha5_implCompress:
 624   case vmIntrinsics::_sha3_implCompress:
 625     return inline_digestBase_implCompress(intrinsic_id());
 626   case vmIntrinsics::_double_keccak:
 627     return inline_double_keccak();
 628 
 629   case vmIntrinsics::_digestBase_implCompressMB:
 630     return inline_digestBase_implCompressMB(predicate);
 631 
 632   case vmIntrinsics::_multiplyToLen:
 633     return inline_multiplyToLen();
 634 
 635   case vmIntrinsics::_squareToLen:
 636     return inline_squareToLen();
 637 
 638   case vmIntrinsics::_mulAdd:
 639     return inline_mulAdd();
 640 
 641   case vmIntrinsics::_montgomeryMultiply:
 642     return inline_montgomeryMultiply();
 643   case vmIntrinsics::_montgomerySquare:
 644     return inline_montgomerySquare();
 645 
 646   case vmIntrinsics::_bigIntegerRightShiftWorker:
 647     return inline_bigIntegerShift(true);
 648   case vmIntrinsics::_bigIntegerLeftShiftWorker:
 649     return inline_bigIntegerShift(false);
 650 
 651   case vmIntrinsics::_vectorizedMismatch:
 652     return inline_vectorizedMismatch();
 653 
 654   case vmIntrinsics::_ghash_processBlocks:
 655     return inline_ghash_processBlocks();
 656   case vmIntrinsics::_chacha20Block:
 657     return inline_chacha20Block();
 658   case vmIntrinsics::_kyberNtt:
 659     return inline_kyberNtt();
 660   case vmIntrinsics::_kyberInverseNtt:
 661     return inline_kyberInverseNtt();
 662   case vmIntrinsics::_kyberNttMult:
 663     return inline_kyberNttMult();
 664   case vmIntrinsics::_kyberAddPoly_2:
 665     return inline_kyberAddPoly_2();
 666   case vmIntrinsics::_kyberAddPoly_3:
 667     return inline_kyberAddPoly_3();
 668   case vmIntrinsics::_kyber12To16:
 669     return inline_kyber12To16();
 670   case vmIntrinsics::_kyberBarrettReduce:
 671     return inline_kyberBarrettReduce();
 672   case vmIntrinsics::_dilithiumAlmostNtt:
 673     return inline_dilithiumAlmostNtt();
 674   case vmIntrinsics::_dilithiumAlmostInverseNtt:
 675     return inline_dilithiumAlmostInverseNtt();
 676   case vmIntrinsics::_dilithiumNttMult:
 677     return inline_dilithiumNttMult();
 678   case vmIntrinsics::_dilithiumMontMulByConstant:
 679     return inline_dilithiumMontMulByConstant();
 680   case vmIntrinsics::_dilithiumDecomposePoly:
 681     return inline_dilithiumDecomposePoly();
 682   case vmIntrinsics::_base64_encodeBlock:
 683     return inline_base64_encodeBlock();
 684   case vmIntrinsics::_base64_decodeBlock:
 685     return inline_base64_decodeBlock();
 686   case vmIntrinsics::_poly1305_processBlocks:
 687     return inline_poly1305_processBlocks();
 688   case vmIntrinsics::_intpoly_montgomeryMult_P256:
 689     return inline_intpoly_montgomeryMult_P256();
 690   case vmIntrinsics::_intpoly_assign:
 691     return inline_intpoly_assign();
 692   case vmIntrinsics::_encodeISOArray:
 693   case vmIntrinsics::_encodeByteISOArray:
 694     return inline_encodeISOArray(false);
 695   case vmIntrinsics::_encodeAsciiArray:
 696     return inline_encodeISOArray(true);
 697 
 698   case vmIntrinsics::_updateCRC32:
 699     return inline_updateCRC32();
 700   case vmIntrinsics::_updateBytesCRC32:
 701     return inline_updateBytesCRC32();
 702   case vmIntrinsics::_updateByteBufferCRC32:
 703     return inline_updateByteBufferCRC32();
 704 
 705   case vmIntrinsics::_updateBytesCRC32C:
 706     return inline_updateBytesCRC32C();
 707   case vmIntrinsics::_updateDirectByteBufferCRC32C:
 708     return inline_updateDirectByteBufferCRC32C();
 709 
 710   case vmIntrinsics::_updateBytesAdler32:
 711     return inline_updateBytesAdler32();
 712   case vmIntrinsics::_updateByteBufferAdler32:
 713     return inline_updateByteBufferAdler32();
 714 
 715   case vmIntrinsics::_profileBoolean:
 716     return inline_profileBoolean();
 717   case vmIntrinsics::_isCompileConstant:
 718     return inline_isCompileConstant();
 719 
 720   case vmIntrinsics::_countPositives:
 721     return inline_countPositives();
 722 
 723   case vmIntrinsics::_fmaD:
 724   case vmIntrinsics::_fmaF:
 725     return inline_fma(intrinsic_id());
 726 
 727   case vmIntrinsics::_isDigit:
 728   case vmIntrinsics::_isLowerCase:
 729   case vmIntrinsics::_isUpperCase:
 730   case vmIntrinsics::_isWhitespace:
 731     return inline_character_compare(intrinsic_id());
 732 
 733   case vmIntrinsics::_min:
 734   case vmIntrinsics::_max:
 735   case vmIntrinsics::_min_strict:
 736   case vmIntrinsics::_max_strict:
 737   case vmIntrinsics::_minL:
 738   case vmIntrinsics::_maxL:
 739   case vmIntrinsics::_minF:
 740   case vmIntrinsics::_maxF:
 741   case vmIntrinsics::_minD:
 742   case vmIntrinsics::_maxD:
 743   case vmIntrinsics::_minF_strict:
 744   case vmIntrinsics::_maxF_strict:
 745   case vmIntrinsics::_minD_strict:
 746   case vmIntrinsics::_maxD_strict:
 747     return inline_min_max(intrinsic_id());
 748 
 749   case vmIntrinsics::_VectorUnaryOp:
 750     return inline_vector_nary_operation(1);
 751   case vmIntrinsics::_VectorBinaryOp:
 752     return inline_vector_nary_operation(2);
 753   case vmIntrinsics::_VectorUnaryLibOp:
 754     return inline_vector_call(1);
 755   case vmIntrinsics::_VectorBinaryLibOp:
 756     return inline_vector_call(2);
 757   case vmIntrinsics::_VectorTernaryOp:
 758     return inline_vector_nary_operation(3);
 759   case vmIntrinsics::_VectorFromBitsCoerced:
 760     return inline_vector_frombits_coerced();
 761   case vmIntrinsics::_VectorMaskOp:
 762     return inline_vector_mask_operation();
 763   case vmIntrinsics::_VectorLoadOp:
 764     return inline_vector_mem_operation(/*is_store=*/false);
 765   case vmIntrinsics::_VectorLoadMaskedOp:
 766     return inline_vector_mem_masked_operation(/*is_store*/false);
 767   case vmIntrinsics::_VectorStoreOp:
 768     return inline_vector_mem_operation(/*is_store=*/true);
 769   case vmIntrinsics::_VectorStoreMaskedOp:
 770     return inline_vector_mem_masked_operation(/*is_store=*/true);
 771   case vmIntrinsics::_VectorGatherOp:
 772     return inline_vector_gather_scatter(/*is_scatter*/ false);
 773   case vmIntrinsics::_VectorScatterOp:
 774     return inline_vector_gather_scatter(/*is_scatter*/ true);
 775   case vmIntrinsics::_VectorReductionCoerced:
 776     return inline_vector_reduction();
 777   case vmIntrinsics::_VectorTest:
 778     return inline_vector_test();
 779   case vmIntrinsics::_VectorBlend:
 780     return inline_vector_blend();
 781   case vmIntrinsics::_VectorRearrange:
 782     return inline_vector_rearrange();
 783   case vmIntrinsics::_VectorSelectFrom:
 784     return inline_vector_select_from();
 785   case vmIntrinsics::_VectorCompare:
 786     return inline_vector_compare();
 787   case vmIntrinsics::_VectorBroadcastInt:
 788     return inline_vector_broadcast_int();
 789   case vmIntrinsics::_VectorConvert:
 790     return inline_vector_convert();
 791   case vmIntrinsics::_VectorInsert:
 792     return inline_vector_insert();
 793   case vmIntrinsics::_VectorExtract:
 794     return inline_vector_extract();
 795   case vmIntrinsics::_VectorCompressExpand:
 796     return inline_vector_compress_expand();
 797   case vmIntrinsics::_VectorSelectFromTwoVectorOp:
 798     return inline_vector_select_from_two_vectors();
 799   case vmIntrinsics::_IndexVector:
 800     return inline_index_vector();
 801   case vmIntrinsics::_IndexPartiallyInUpperRange:
 802     return inline_index_partially_in_upper_range();
 803 
 804   case vmIntrinsics::_getObjectSize:
 805     return inline_getObjectSize();
 806 
 807   case vmIntrinsics::_blackhole:
 808     return inline_blackhole();
 809 
 810   default:
 811     // If you get here, it may be that someone has added a new intrinsic
 812     // to the list in vmIntrinsics.hpp without implementing it here.
 813 #ifndef PRODUCT
 814     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 815       tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
 816                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 817     }
 818 #endif
 819     return false;
 820   }
 821 }
 822 
 823 Node* LibraryCallKit::try_to_predicate(int predicate) {
 824   if (!jvms()->has_method()) {
 825     // Root JVMState has a null method.
 826     assert(map()->memory()->Opcode() == Op_Parm, "");
 827     // Insert the memory aliasing node
 828     set_all_memory(reset_memory());
 829   }
 830   assert(merged_memory(), "");
 831 
 832   switch (intrinsic_id()) {
 833   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
 834     return inline_cipherBlockChaining_AESCrypt_predicate(false);
 835   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
 836     return inline_cipherBlockChaining_AESCrypt_predicate(true);
 837   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
 838     return inline_electronicCodeBook_AESCrypt_predicate(false);
 839   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
 840     return inline_electronicCodeBook_AESCrypt_predicate(true);
 841   case vmIntrinsics::_counterMode_AESCrypt:
 842     return inline_counterMode_AESCrypt_predicate();
 843   case vmIntrinsics::_digestBase_implCompressMB:
 844     return inline_digestBase_implCompressMB_predicate(predicate);
 845   case vmIntrinsics::_galoisCounterMode_AESCrypt:
 846     return inline_galoisCounterMode_AESCrypt_predicate();
 847 
 848   default:
 849     // If you get here, it may be that someone has added a new intrinsic
 850     // to the list in vmIntrinsics.hpp without implementing it here.
 851 #ifndef PRODUCT
 852     if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
 853       tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
 854                     vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
 855     }
 856 #endif
 857     Node* slow_ctl = control();
 858     set_control(top()); // No fast path intrinsic
 859     return slow_ctl;
 860   }
 861 }
 862 
 863 //------------------------------set_result-------------------------------
 864 // Helper function for finishing intrinsics.
 865 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
 866   record_for_igvn(region);
 867   set_control(_gvn.transform(region));
 868   set_result( _gvn.transform(value));
 869   assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
 870 }
 871 
 872 //------------------------------generate_guard---------------------------
 873 // Helper function for generating guarded fast-slow graph structures.
 874 // The given 'test', if true, guards a slow path.  If the test fails
 875 // then a fast path can be taken.  (We generally hope it fails.)
 876 // In all cases, GraphKit::control() is updated to the fast path.
 877 // The returned value represents the control for the slow path.
 878 // The return value is never 'top'; it is either a valid control
 879 // or null if it is obvious that the slow path can never be taken.
 880 // Also, if region and the slow control are not null, the slow edge
 881 // is appended to the region.
 882 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
 883   if (stopped()) {
 884     // Already short circuited.
 885     return nullptr;
 886   }
 887 
 888   // Build an if node and its projections.
 889   // If test is true we take the slow path, which we assume is uncommon.
 890   if (_gvn.type(test) == TypeInt::ZERO) {
 891     // The slow branch is never taken.  No need to build this guard.
 892     return nullptr;
 893   }
 894 
 895   IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
 896 
 897   Node* if_slow = _gvn.transform(new IfTrueNode(iff));
 898   if (if_slow == top()) {
 899     // The slow branch is never taken.  No need to build this guard.
 900     return nullptr;
 901   }
 902 
 903   if (region != nullptr)
 904     region->add_req(if_slow);
 905 
 906   Node* if_fast = _gvn.transform(new IfFalseNode(iff));
 907   set_control(if_fast);
 908 
 909   return if_slow;
 910 }
 911 
 912 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
 913   return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
 914 }
 915 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
 916   return generate_guard(test, region, PROB_FAIR);
 917 }
 918 
 919 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
 920                                                      Node* *pos_index) {
 921   if (stopped())
 922     return nullptr;                // already stopped
 923   if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
 924     return nullptr;                // index is already adequately typed
 925   Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
 926   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 927   Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
 928   if (is_neg != nullptr && pos_index != nullptr) {
 929     // Emulate effect of Parse::adjust_map_after_if.
 930     Node* ccast = new CastIINode(control(), index, TypeInt::POS);
 931     (*pos_index) = _gvn.transform(ccast);
 932   }
 933   return is_neg;
 934 }
 935 
 936 // Make sure that 'position' is a valid limit index, in [0..length].
 937 // There are two equivalent plans for checking this:
 938 //   A. (offset + copyLength)  unsigned<=  arrayLength
 939 //   B. offset  <=  (arrayLength - copyLength)
 940 // We require that all of the values above, except for the sum and
 941 // difference, are already known to be non-negative.
 942 // Plan A is robust in the face of overflow, if offset and copyLength
 943 // are both hugely positive.
 944 //
 945 // Plan B is less direct and intuitive, but it does not overflow at
 946 // all, since the difference of two non-negatives is always
 947 // representable.  Whenever Java methods must perform the equivalent
 948 // check they generally use Plan B instead of Plan A.
 949 // For the moment we use Plan A.
 950 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
 951                                                   Node* subseq_length,
 952                                                   Node* array_length,
 953                                                   RegionNode* region) {
 954   if (stopped())
 955     return nullptr;                // already stopped
 956   bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
 957   if (zero_offset && subseq_length->eqv_uncast(array_length))
 958     return nullptr;                // common case of whole-array copy
 959   Node* last = subseq_length;
 960   if (!zero_offset)             // last += offset
 961     last = _gvn.transform(new AddINode(last, offset));
 962   Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
 963   Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
 964   Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
 965   return is_over;
 966 }
 967 
 968 // Emit range checks for the given String.value byte array
 969 void LibraryCallKit::generate_string_range_check(Node* array, Node* offset, Node* count, bool char_count) {
 970   if (stopped()) {
 971     return; // already stopped
 972   }
 973   RegionNode* bailout = new RegionNode(1);
 974   record_for_igvn(bailout);
 975   if (char_count) {
 976     // Convert char count to byte count
 977     count = _gvn.transform(new LShiftINode(count, intcon(1)));
 978   }
 979 
 980   // Offset and count must not be negative
 981   generate_negative_guard(offset, bailout);
 982   generate_negative_guard(count, bailout);
 983   // Offset + count must not exceed length of array
 984   generate_limit_guard(offset, count, load_array_length(array), bailout);
 985 
 986   if (bailout->req() > 1) {
 987     PreserveJVMState pjvms(this);
 988     set_control(_gvn.transform(bailout));
 989     uncommon_trap(Deoptimization::Reason_intrinsic,
 990                   Deoptimization::Action_maybe_recompile);
 991   }
 992 }
 993 
 994 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
 995                                             bool is_immutable) {
 996   ciKlass* thread_klass = env()->Thread_klass();
 997   const Type* thread_type
 998     = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
 999 
1000   Node* thread = _gvn.transform(new ThreadLocalNode());
1001   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(handle_offset));
1002   tls_output = thread;
1003 
1004   Node* thread_obj_handle
1005     = (is_immutable
1006       ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1007         TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1008       : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1009   thread_obj_handle = _gvn.transform(thread_obj_handle);
1010 
1011   DecoratorSet decorators = IN_NATIVE;
1012   if (is_immutable) {
1013     decorators |= C2_IMMUTABLE_MEMORY;
1014   }
1015   return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1016 }
1017 
1018 //--------------------------generate_current_thread--------------------
1019 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1020   return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1021                                /*is_immutable*/false);
1022 }
1023 
1024 //--------------------------generate_virtual_thread--------------------
1025 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1026   return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1027                                !C->method()->changes_current_thread());
1028 }
1029 
1030 //------------------------------make_string_method_node------------------------
1031 // Helper method for String intrinsic functions. This version is called with
1032 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1033 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1034 // containing the lengths of str1 and str2.
1035 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1036   Node* result = nullptr;
1037   switch (opcode) {
1038   case Op_StrIndexOf:
1039     result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1040                                 str1_start, cnt1, str2_start, cnt2, ae);
1041     break;
1042   case Op_StrComp:
1043     result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1044                              str1_start, cnt1, str2_start, cnt2, ae);
1045     break;
1046   case Op_StrEquals:
1047     // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1048     // Use the constant length if there is one because optimized match rule may exist.
1049     result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1050                                str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1051     break;
1052   default:
1053     ShouldNotReachHere();
1054     return nullptr;
1055   }
1056 
1057   // All these intrinsics have checks.
1058   C->set_has_split_ifs(true); // Has chance for split-if optimization
1059   clear_upper_avx();
1060 
1061   return _gvn.transform(result);
1062 }
1063 
1064 //------------------------------inline_string_compareTo------------------------
1065 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1066   Node* arg1 = argument(0);
1067   Node* arg2 = argument(1);
1068 
1069   arg1 = must_be_not_null(arg1, true);
1070   arg2 = must_be_not_null(arg2, true);
1071 
1072   // Get start addr and length of first argument
1073   Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1074   Node* arg1_cnt    = load_array_length(arg1);
1075 
1076   // Get start addr and length of second argument
1077   Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1078   Node* arg2_cnt    = load_array_length(arg2);
1079 
1080   Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1081   set_result(result);
1082   return true;
1083 }
1084 
1085 //------------------------------inline_string_equals------------------------
1086 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1087   Node* arg1 = argument(0);
1088   Node* arg2 = argument(1);
1089 
1090   // paths (plus control) merge
1091   RegionNode* region = new RegionNode(3);
1092   Node* phi = new PhiNode(region, TypeInt::BOOL);
1093 
1094   if (!stopped()) {
1095 
1096     arg1 = must_be_not_null(arg1, true);
1097     arg2 = must_be_not_null(arg2, true);
1098 
1099     // Get start addr and length of first argument
1100     Node* arg1_start  = array_element_address(arg1, intcon(0), T_BYTE);
1101     Node* arg1_cnt    = load_array_length(arg1);
1102 
1103     // Get start addr and length of second argument
1104     Node* arg2_start  = array_element_address(arg2, intcon(0), T_BYTE);
1105     Node* arg2_cnt    = load_array_length(arg2);
1106 
1107     // Check for arg1_cnt != arg2_cnt
1108     Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1109     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1110     Node* if_ne = generate_slow_guard(bol, nullptr);
1111     if (if_ne != nullptr) {
1112       phi->init_req(2, intcon(0));
1113       region->init_req(2, if_ne);
1114     }
1115 
1116     // Check for count == 0 is done by assembler code for StrEquals.
1117 
1118     if (!stopped()) {
1119       Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1120       phi->init_req(1, equals);
1121       region->init_req(1, control());
1122     }
1123   }
1124 
1125   // post merge
1126   set_control(_gvn.transform(region));
1127   record_for_igvn(region);
1128 
1129   set_result(_gvn.transform(phi));
1130   return true;
1131 }
1132 
1133 //------------------------------inline_array_equals----------------------------
1134 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1135   assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1136   Node* arg1 = argument(0);
1137   Node* arg2 = argument(1);
1138 
1139   const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1140   set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
1141   clear_upper_avx();
1142 
1143   return true;
1144 }
1145 
1146 
1147 //------------------------------inline_countPositives------------------------------
1148 bool LibraryCallKit::inline_countPositives() {
1149   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1150     return false;
1151   }
1152 
1153   assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1154   // no receiver since it is static method
1155   Node* ba         = argument(0);
1156   Node* offset     = argument(1);
1157   Node* len        = argument(2);
1158 
1159   ba = must_be_not_null(ba, true);
1160 
1161   // Range checks
1162   generate_string_range_check(ba, offset, len, false);
1163   if (stopped()) {
1164     return true;
1165   }
1166   Node* ba_start = array_element_address(ba, offset, T_BYTE);
1167   Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1168   set_result(_gvn.transform(result));
1169   clear_upper_avx();
1170   return true;
1171 }
1172 
1173 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1174   Node* index = argument(0);
1175   Node* length = bt == T_INT ? argument(1) : argument(2);
1176   if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1177     return false;
1178   }
1179 
1180   // check that length is positive
1181   Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1182   Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1183 
1184   {
1185     BuildCutout unless(this, len_pos_bol, PROB_MAX);
1186     uncommon_trap(Deoptimization::Reason_intrinsic,
1187                   Deoptimization::Action_make_not_entrant);
1188   }
1189 
1190   if (stopped()) {
1191     // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1192     return true;
1193   }
1194 
1195   // length is now known positive, add a cast node to make this explicit
1196   jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1197   Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1198       control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1199       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1200   casted_length = _gvn.transform(casted_length);
1201   replace_in_map(length, casted_length);
1202   length = casted_length;
1203 
1204   // Use an unsigned comparison for the range check itself
1205   Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1206   BoolTest::mask btest = BoolTest::lt;
1207   Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1208   RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1209   _gvn.set_type(rc, rc->Value(&_gvn));
1210   if (!rc_bool->is_Con()) {
1211     record_for_igvn(rc);
1212   }
1213   set_control(_gvn.transform(new IfTrueNode(rc)));
1214   {
1215     PreserveJVMState pjvms(this);
1216     set_control(_gvn.transform(new IfFalseNode(rc)));
1217     uncommon_trap(Deoptimization::Reason_range_check,
1218                   Deoptimization::Action_make_not_entrant);
1219   }
1220 
1221   if (stopped()) {
1222     // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1223     return true;
1224   }
1225 
1226   // index is now known to be >= 0 and < length, cast it
1227   Node* result = ConstraintCastNode::make_cast_for_basic_type(
1228       control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1229       ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1230   result = _gvn.transform(result);
1231   set_result(result);
1232   replace_in_map(index, result);
1233   return true;
1234 }
1235 
1236 //------------------------------inline_string_indexOf------------------------
1237 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1238   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1239     return false;
1240   }
1241   Node* src = argument(0);
1242   Node* tgt = argument(1);
1243 
1244   // Make the merge point
1245   RegionNode* result_rgn = new RegionNode(4);
1246   Node*       result_phi = new PhiNode(result_rgn, TypeInt::INT);
1247 
1248   src = must_be_not_null(src, true);
1249   tgt = must_be_not_null(tgt, true);
1250 
1251   // Get start addr and length of source string
1252   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1253   Node* src_count = load_array_length(src);
1254 
1255   // Get start addr and length of substring
1256   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1257   Node* tgt_count = load_array_length(tgt);
1258 
1259   Node* result = nullptr;
1260   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1261 
1262   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1263     // Divide src size by 2 if String is UTF16 encoded
1264     src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1265   }
1266   if (ae == StrIntrinsicNode::UU) {
1267     // Divide substring size by 2 if String is UTF16 encoded
1268     tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1269   }
1270 
1271   if (call_opt_stub) {
1272     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1273                                    StubRoutines::_string_indexof_array[ae],
1274                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1275                                    src_count, tgt_start, tgt_count);
1276     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1277   } else {
1278     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1279                                result_rgn, result_phi, ae);
1280   }
1281   if (result != nullptr) {
1282     result_phi->init_req(3, result);
1283     result_rgn->init_req(3, control());
1284   }
1285   set_control(_gvn.transform(result_rgn));
1286   record_for_igvn(result_rgn);
1287   set_result(_gvn.transform(result_phi));
1288 
1289   return true;
1290 }
1291 
1292 //-----------------------------inline_string_indexOfI-----------------------
1293 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1294   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1295     return false;
1296   }
1297   if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1298     return false;
1299   }
1300 
1301   assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1302   Node* src         = argument(0); // byte[]
1303   Node* src_count   = argument(1); // char count
1304   Node* tgt         = argument(2); // byte[]
1305   Node* tgt_count   = argument(3); // char count
1306   Node* from_index  = argument(4); // char index
1307 
1308   src = must_be_not_null(src, true);
1309   tgt = must_be_not_null(tgt, true);
1310 
1311   // Multiply byte array index by 2 if String is UTF16 encoded
1312   Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1313   src_count = _gvn.transform(new SubINode(src_count, from_index));
1314   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1315   Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1316 
1317   // Range checks
1318   generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL);
1319   generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU);
1320   if (stopped()) {
1321     return true;
1322   }
1323 
1324   RegionNode* region = new RegionNode(5);
1325   Node* phi = new PhiNode(region, TypeInt::INT);
1326   Node* result = nullptr;
1327 
1328   bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1329 
1330   if (call_opt_stub) {
1331     Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1332                                    StubRoutines::_string_indexof_array[ae],
1333                                    "stringIndexOf", TypePtr::BOTTOM, src_start,
1334                                    src_count, tgt_start, tgt_count);
1335     result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1336   } else {
1337     result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1338                                region, phi, ae);
1339   }
1340   if (result != nullptr) {
1341     // The result is index relative to from_index if substring was found, -1 otherwise.
1342     // Generate code which will fold into cmove.
1343     Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1344     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1345 
1346     Node* if_lt = generate_slow_guard(bol, nullptr);
1347     if (if_lt != nullptr) {
1348       // result == -1
1349       phi->init_req(3, result);
1350       region->init_req(3, if_lt);
1351     }
1352     if (!stopped()) {
1353       result = _gvn.transform(new AddINode(result, from_index));
1354       phi->init_req(4, result);
1355       region->init_req(4, control());
1356     }
1357   }
1358 
1359   set_control(_gvn.transform(region));
1360   record_for_igvn(region);
1361   set_result(_gvn.transform(phi));
1362   clear_upper_avx();
1363 
1364   return true;
1365 }
1366 
1367 // Create StrIndexOfNode with fast path checks
1368 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1369                                         RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1370   // Check for substr count > string count
1371   Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1372   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1373   Node* if_gt = generate_slow_guard(bol, nullptr);
1374   if (if_gt != nullptr) {
1375     phi->init_req(1, intcon(-1));
1376     region->init_req(1, if_gt);
1377   }
1378   if (!stopped()) {
1379     // Check for substr count == 0
1380     cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1381     bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1382     Node* if_zero = generate_slow_guard(bol, nullptr);
1383     if (if_zero != nullptr) {
1384       phi->init_req(2, intcon(0));
1385       region->init_req(2, if_zero);
1386     }
1387   }
1388   if (!stopped()) {
1389     return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1390   }
1391   return nullptr;
1392 }
1393 
1394 //-----------------------------inline_string_indexOfChar-----------------------
1395 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1396   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1397     return false;
1398   }
1399   if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1400     return false;
1401   }
1402   assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1403   Node* src         = argument(0); // byte[]
1404   Node* int_ch      = argument(1);
1405   Node* from_index  = argument(2);
1406   Node* max         = argument(3);
1407 
1408   src = must_be_not_null(src, true);
1409 
1410   Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1411   Node* src_start = array_element_address(src, src_offset, T_BYTE);
1412   Node* src_count = _gvn.transform(new SubINode(max, from_index));
1413 
1414   // Range checks
1415   generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U);
1416 
1417   // Check for int_ch >= 0
1418   Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1419   Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1420   {
1421     BuildCutout unless(this, int_ch_bol, PROB_MAX);
1422     uncommon_trap(Deoptimization::Reason_intrinsic,
1423                   Deoptimization::Action_maybe_recompile);
1424   }
1425   if (stopped()) {
1426     return true;
1427   }
1428 
1429   RegionNode* region = new RegionNode(3);
1430   Node* phi = new PhiNode(region, TypeInt::INT);
1431 
1432   Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1433   C->set_has_split_ifs(true); // Has chance for split-if optimization
1434   _gvn.transform(result);
1435 
1436   Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1437   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1438 
1439   Node* if_lt = generate_slow_guard(bol, nullptr);
1440   if (if_lt != nullptr) {
1441     // result == -1
1442     phi->init_req(2, result);
1443     region->init_req(2, if_lt);
1444   }
1445   if (!stopped()) {
1446     result = _gvn.transform(new AddINode(result, from_index));
1447     phi->init_req(1, result);
1448     region->init_req(1, control());
1449   }
1450   set_control(_gvn.transform(region));
1451   record_for_igvn(region);
1452   set_result(_gvn.transform(phi));
1453   clear_upper_avx();
1454 
1455   return true;
1456 }
1457 //---------------------------inline_string_copy---------------------
1458 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1459 //   int StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1460 //   int StringUTF16.compress(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1461 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1462 //   void StringLatin1.inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1463 //   void StringLatin1.inflate(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1464 bool LibraryCallKit::inline_string_copy(bool compress) {
1465   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1466     return false;
1467   }
1468   int nargs = 5;  // 2 oops, 3 ints
1469   assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1470 
1471   Node* src         = argument(0);
1472   Node* src_offset  = argument(1);
1473   Node* dst         = argument(2);
1474   Node* dst_offset  = argument(3);
1475   Node* length      = argument(4);
1476 
1477   // Check for allocation before we add nodes that would confuse
1478   // tightly_coupled_allocation()
1479   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1480 
1481   // Figure out the size and type of the elements we will be copying.
1482   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1483   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1484   if (src_type == nullptr || dst_type == nullptr) {
1485     return false;
1486   }
1487   BasicType src_elem = src_type->elem()->array_element_basic_type();
1488   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1489   assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1490          (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1491          "Unsupported array types for inline_string_copy");
1492 
1493   src = must_be_not_null(src, true);
1494   dst = must_be_not_null(dst, true);
1495 
1496   // Convert char[] offsets to byte[] offsets
1497   bool convert_src = (compress && src_elem == T_BYTE);
1498   bool convert_dst = (!compress && dst_elem == T_BYTE);
1499   if (convert_src) {
1500     src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1501   } else if (convert_dst) {
1502     dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1503   }
1504 
1505   // Range checks
1506   generate_string_range_check(src, src_offset, length, convert_src);
1507   generate_string_range_check(dst, dst_offset, length, convert_dst);
1508   if (stopped()) {
1509     return true;
1510   }
1511 
1512   Node* src_start = array_element_address(src, src_offset, src_elem);
1513   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1514   // 'src_start' points to src array + scaled offset
1515   // 'dst_start' points to dst array + scaled offset
1516   Node* count = nullptr;
1517   if (compress) {
1518     count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1519   } else {
1520     inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1521   }
1522 
1523   if (alloc != nullptr) {
1524     if (alloc->maybe_set_complete(&_gvn)) {
1525       // "You break it, you buy it."
1526       InitializeNode* init = alloc->initialization();
1527       assert(init->is_complete(), "we just did this");
1528       init->set_complete_with_arraycopy();
1529       assert(dst->is_CheckCastPP(), "sanity");
1530       assert(dst->in(0)->in(0) == init, "dest pinned");
1531     }
1532     // Do not let stores that initialize this object be reordered with
1533     // a subsequent store that would make this object accessible by
1534     // other threads.
1535     // Record what AllocateNode this StoreStore protects so that
1536     // escape analysis can go from the MemBarStoreStoreNode to the
1537     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1538     // based on the escape status of the AllocateNode.
1539     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1540   }
1541   if (compress) {
1542     set_result(_gvn.transform(count));
1543   }
1544   clear_upper_avx();
1545 
1546   return true;
1547 }
1548 
1549 #ifdef _LP64
1550 #define XTOP ,top() /*additional argument*/
1551 #else  //_LP64
1552 #define XTOP        /*no additional argument*/
1553 #endif //_LP64
1554 
1555 //------------------------inline_string_toBytesU--------------------------
1556 // public static byte[] StringUTF16.toBytes(char[] value, int off, int len)
1557 bool LibraryCallKit::inline_string_toBytesU() {
1558   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1559     return false;
1560   }
1561   // Get the arguments.
1562   Node* value     = argument(0);
1563   Node* offset    = argument(1);
1564   Node* length    = argument(2);
1565 
1566   Node* newcopy = nullptr;
1567 
1568   // Set the original stack and the reexecute bit for the interpreter to reexecute
1569   // the bytecode that invokes StringUTF16.toBytes() if deoptimization happens.
1570   { PreserveReexecuteState preexecs(this);
1571     jvms()->set_should_reexecute(true);
1572 
1573     // Check if a null path was taken unconditionally.
1574     value = null_check(value);
1575 
1576     RegionNode* bailout = new RegionNode(1);
1577     record_for_igvn(bailout);
1578 
1579     // Range checks
1580     generate_negative_guard(offset, bailout);
1581     generate_negative_guard(length, bailout);
1582     generate_limit_guard(offset, length, load_array_length(value), bailout);
1583     // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1584     generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout);
1585 
1586     if (bailout->req() > 1) {
1587       PreserveJVMState pjvms(this);
1588       set_control(_gvn.transform(bailout));
1589       uncommon_trap(Deoptimization::Reason_intrinsic,
1590                     Deoptimization::Action_maybe_recompile);
1591     }
1592     if (stopped()) {
1593       return true;
1594     }
1595 
1596     Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1597     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1598     newcopy = new_array(klass_node, size, 0);  // no arguments to push
1599     AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1600     guarantee(alloc != nullptr, "created above");
1601 
1602     // Calculate starting addresses.
1603     Node* src_start = array_element_address(value, offset, T_CHAR);
1604     Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1605 
1606     // Check if dst array address is aligned to HeapWordSize
1607     bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1608     // If true, then check if src array address is aligned to HeapWordSize
1609     if (aligned) {
1610       const TypeInt* toffset = gvn().type(offset)->is_int();
1611       aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1612                                        toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1613     }
1614 
1615     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1616     const char* copyfunc_name = "arraycopy";
1617     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1618     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1619                       OptoRuntime::fast_arraycopy_Type(),
1620                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1621                       src_start, dst_start, ConvI2X(length) XTOP);
1622     // Do not let reads from the cloned object float above the arraycopy.
1623     if (alloc->maybe_set_complete(&_gvn)) {
1624       // "You break it, you buy it."
1625       InitializeNode* init = alloc->initialization();
1626       assert(init->is_complete(), "we just did this");
1627       init->set_complete_with_arraycopy();
1628       assert(newcopy->is_CheckCastPP(), "sanity");
1629       assert(newcopy->in(0)->in(0) == init, "dest pinned");
1630     }
1631     // Do not let stores that initialize this object be reordered with
1632     // a subsequent store that would make this object accessible by
1633     // other threads.
1634     // Record what AllocateNode this StoreStore protects so that
1635     // escape analysis can go from the MemBarStoreStoreNode to the
1636     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1637     // based on the escape status of the AllocateNode.
1638     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1639   } // original reexecute is set back here
1640 
1641   C->set_has_split_ifs(true); // Has chance for split-if optimization
1642   if (!stopped()) {
1643     set_result(newcopy);
1644   }
1645   clear_upper_avx();
1646 
1647   return true;
1648 }
1649 
1650 //------------------------inline_string_getCharsU--------------------------
1651 // public void StringUTF16.getChars(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1652 bool LibraryCallKit::inline_string_getCharsU() {
1653   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1654     return false;
1655   }
1656 
1657   // Get the arguments.
1658   Node* src       = argument(0);
1659   Node* src_begin = argument(1);
1660   Node* src_end   = argument(2); // exclusive offset (i < src_end)
1661   Node* dst       = argument(3);
1662   Node* dst_begin = argument(4);
1663 
1664   // Check for allocation before we add nodes that would confuse
1665   // tightly_coupled_allocation()
1666   AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1667 
1668   // Check if a null path was taken unconditionally.
1669   src = null_check(src);
1670   dst = null_check(dst);
1671   if (stopped()) {
1672     return true;
1673   }
1674 
1675   // Get length and convert char[] offset to byte[] offset
1676   Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1677   src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1678 
1679   // Range checks
1680   generate_string_range_check(src, src_begin, length, true);
1681   generate_string_range_check(dst, dst_begin, length, false);
1682   if (stopped()) {
1683     return true;
1684   }
1685 
1686   if (!stopped()) {
1687     // Calculate starting addresses.
1688     Node* src_start = array_element_address(src, src_begin, T_BYTE);
1689     Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1690 
1691     // Check if array addresses are aligned to HeapWordSize
1692     const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1693     const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1694     bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1695                    tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1696 
1697     // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1698     const char* copyfunc_name = "arraycopy";
1699     address     copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1700     Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1701                       OptoRuntime::fast_arraycopy_Type(),
1702                       copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1703                       src_start, dst_start, ConvI2X(length) XTOP);
1704     // Do not let reads from the cloned object float above the arraycopy.
1705     if (alloc != nullptr) {
1706       if (alloc->maybe_set_complete(&_gvn)) {
1707         // "You break it, you buy it."
1708         InitializeNode* init = alloc->initialization();
1709         assert(init->is_complete(), "we just did this");
1710         init->set_complete_with_arraycopy();
1711         assert(dst->is_CheckCastPP(), "sanity");
1712         assert(dst->in(0)->in(0) == init, "dest pinned");
1713       }
1714       // Do not let stores that initialize this object be reordered with
1715       // a subsequent store that would make this object accessible by
1716       // other threads.
1717       // Record what AllocateNode this StoreStore protects so that
1718       // escape analysis can go from the MemBarStoreStoreNode to the
1719       // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1720       // based on the escape status of the AllocateNode.
1721       insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1722     } else {
1723       insert_mem_bar(Op_MemBarCPUOrder);
1724     }
1725   }
1726 
1727   C->set_has_split_ifs(true); // Has chance for split-if optimization
1728   return true;
1729 }
1730 
1731 //----------------------inline_string_char_access----------------------------
1732 // Store/Load char to/from byte[] array.
1733 // static void StringUTF16.putChar(byte[] val, int index, int c)
1734 // static char StringUTF16.getChar(byte[] val, int index)
1735 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1736   Node* value  = argument(0);
1737   Node* index  = argument(1);
1738   Node* ch = is_store ? argument(2) : nullptr;
1739 
1740   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1741   // correctly requires matched array shapes.
1742   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1743           "sanity: byte[] and char[] bases agree");
1744   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1745           "sanity: byte[] and char[] scales agree");
1746 
1747   // Bail when getChar over constants is requested: constant folding would
1748   // reject folding mismatched char access over byte[]. A normal inlining for getChar
1749   // Java method would constant fold nicely instead.
1750   if (!is_store && value->is_Con() && index->is_Con()) {
1751     return false;
1752   }
1753 
1754   // Save state and restore on bailout
1755   SavedState old_state(this);
1756 
1757   value = must_be_not_null(value, true);
1758 
1759   Node* adr = array_element_address(value, index, T_CHAR);
1760   if (adr->is_top()) {
1761     return false;
1762   }
1763   old_state.discard();
1764   if (is_store) {
1765     access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1766   } else {
1767     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);
1768     set_result(ch);
1769   }
1770   return true;
1771 }
1772 
1773 
1774 //------------------------------inline_math-----------------------------------
1775 // public static double Math.abs(double)
1776 // public static double Math.sqrt(double)
1777 // public static double Math.log(double)
1778 // public static double Math.log10(double)
1779 // public static double Math.round(double)
1780 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1781   Node* arg = argument(0);
1782   Node* n = nullptr;
1783   switch (id) {
1784   case vmIntrinsics::_dabs:   n = new AbsDNode(                arg);  break;
1785   case vmIntrinsics::_dsqrt:
1786   case vmIntrinsics::_dsqrt_strict:
1787                               n = new SqrtDNode(C, control(),  arg);  break;
1788   case vmIntrinsics::_ceil:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1789   case vmIntrinsics::_floor:  n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1790   case vmIntrinsics::_rint:   n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1791   case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1792   case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1793   case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1794   default:  fatal_unexpected_iid(id);  break;
1795   }
1796   set_result(_gvn.transform(n));
1797   return true;
1798 }
1799 
1800 //------------------------------inline_math-----------------------------------
1801 // public static float Math.abs(float)
1802 // public static int Math.abs(int)
1803 // public static long Math.abs(long)
1804 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1805   Node* arg = argument(0);
1806   Node* n = nullptr;
1807   switch (id) {
1808   case vmIntrinsics::_fabs:   n = new AbsFNode(                arg);  break;
1809   case vmIntrinsics::_iabs:   n = new AbsINode(                arg);  break;
1810   case vmIntrinsics::_labs:   n = new AbsLNode(                arg);  break;
1811   case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1812   case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1813   case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1814   default:  fatal_unexpected_iid(id);  break;
1815   }
1816   set_result(_gvn.transform(n));
1817   return true;
1818 }
1819 
1820 //------------------------------runtime_math-----------------------------
1821 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1822   assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1823          "must be (DD)D or (D)D type");
1824 
1825   // Inputs
1826   Node* a = argument(0);
1827   Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1828 
1829   const TypePtr* no_memory_effects = nullptr;
1830   Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1831                                  no_memory_effects,
1832                                  a, top(), b, b ? top() : nullptr);
1833   Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1834 #ifdef ASSERT
1835   Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1836   assert(value_top == top(), "second value must be top");
1837 #endif
1838 
1839   set_result(value);
1840   return true;
1841 }
1842 
1843 //------------------------------inline_math_pow-----------------------------
1844 bool LibraryCallKit::inline_math_pow() {
1845   Node* exp = argument(2);
1846   const TypeD* d = _gvn.type(exp)->isa_double_constant();
1847   if (d != nullptr) {
1848     if (d->getd() == 2.0) {
1849       // Special case: pow(x, 2.0) => x * x
1850       Node* base = argument(0);
1851       set_result(_gvn.transform(new MulDNode(base, base)));
1852       return true;
1853     } else if (d->getd() == 0.5 && Matcher::match_rule_supported(Op_SqrtD)) {
1854       // Special case: pow(x, 0.5) => sqrt(x)
1855       Node* base = argument(0);
1856       Node* zero = _gvn.zerocon(T_DOUBLE);
1857 
1858       RegionNode* region = new RegionNode(3);
1859       Node* phi = new PhiNode(region, Type::DOUBLE);
1860 
1861       Node* cmp  = _gvn.transform(new CmpDNode(base, zero));
1862       // According to the API specs, pow(-0.0, 0.5) = 0.0 and sqrt(-0.0) = -0.0.
1863       // So pow(-0.0, 0.5) shouldn't be replaced with sqrt(-0.0).
1864       // -0.0/+0.0 are both excluded since floating-point comparison doesn't distinguish -0.0 from +0.0.
1865       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::le));
1866 
1867       Node* if_pow = generate_slow_guard(test, nullptr);
1868       Node* value_sqrt = _gvn.transform(new SqrtDNode(C, control(), base));
1869       phi->init_req(1, value_sqrt);
1870       region->init_req(1, control());
1871 
1872       if (if_pow != nullptr) {
1873         set_control(if_pow);
1874         address target = StubRoutines::dpow() != nullptr ? StubRoutines::dpow() :
1875                                                         CAST_FROM_FN_PTR(address, SharedRuntime::dpow);
1876         const TypePtr* no_memory_effects = nullptr;
1877         Node* trig = make_runtime_call(RC_LEAF, OptoRuntime::Math_DD_D_Type(), target, "POW",
1878                                        no_memory_effects, base, top(), exp, top());
1879         Node* value_pow = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1880 #ifdef ASSERT
1881         Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1882         assert(value_top == top(), "second value must be top");
1883 #endif
1884         phi->init_req(2, value_pow);
1885         region->init_req(2, _gvn.transform(new ProjNode(trig, TypeFunc::Control)));
1886       }
1887 
1888       C->set_has_split_ifs(true); // Has chance for split-if optimization
1889       set_control(_gvn.transform(region));
1890       record_for_igvn(region);
1891       set_result(_gvn.transform(phi));
1892 
1893       return true;
1894     }
1895   }
1896 
1897   return StubRoutines::dpow() != nullptr ?
1898     runtime_math(OptoRuntime::Math_DD_D_Type(), StubRoutines::dpow(),  "dpow") :
1899     runtime_math(OptoRuntime::Math_DD_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dpow),  "POW");
1900 }
1901 
1902 //------------------------------inline_math_native-----------------------------
1903 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1904   switch (id) {
1905   case vmIntrinsics::_dsin:
1906     return StubRoutines::dsin() != nullptr ?
1907       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1908       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin),   "SIN");
1909   case vmIntrinsics::_dcos:
1910     return StubRoutines::dcos() != nullptr ?
1911       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1912       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos),   "COS");
1913   case vmIntrinsics::_dtan:
1914     return StubRoutines::dtan() != nullptr ?
1915       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1916       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1917   case vmIntrinsics::_dsinh:
1918     return StubRoutines::dsinh() != nullptr ?
1919       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1920   case vmIntrinsics::_dtanh:
1921     return StubRoutines::dtanh() != nullptr ?
1922       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1923   case vmIntrinsics::_dcbrt:
1924     return StubRoutines::dcbrt() != nullptr ?
1925       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1926   case vmIntrinsics::_dexp:
1927     return StubRoutines::dexp() != nullptr ?
1928       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(),  "dexp") :
1929       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp),  "EXP");
1930   case vmIntrinsics::_dlog:
1931     return StubRoutines::dlog() != nullptr ?
1932       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1933       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog),   "LOG");
1934   case vmIntrinsics::_dlog10:
1935     return StubRoutines::dlog10() != nullptr ?
1936       runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1937       runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1938 
1939   case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1940   case vmIntrinsics::_ceil:
1941   case vmIntrinsics::_floor:
1942   case vmIntrinsics::_rint:   return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1943 
1944   case vmIntrinsics::_dsqrt:
1945   case vmIntrinsics::_dsqrt_strict:
1946                               return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1947   case vmIntrinsics::_dabs:   return Matcher::has_match_rule(Op_AbsD)   ? inline_double_math(id) : false;
1948   case vmIntrinsics::_fabs:   return Matcher::match_rule_supported(Op_AbsF)   ? inline_math(id) : false;
1949   case vmIntrinsics::_iabs:   return Matcher::match_rule_supported(Op_AbsI)   ? inline_math(id) : false;
1950   case vmIntrinsics::_labs:   return Matcher::match_rule_supported(Op_AbsL)   ? inline_math(id) : false;
1951 
1952   case vmIntrinsics::_dpow:      return inline_math_pow();
1953   case vmIntrinsics::_dcopySign: return inline_double_math(id);
1954   case vmIntrinsics::_fcopySign: return inline_math(id);
1955   case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1956   case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1957   case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1958 
1959    // These intrinsics are not yet correctly implemented
1960   case vmIntrinsics::_datan2:
1961     return false;
1962 
1963   default:
1964     fatal_unexpected_iid(id);
1965     return false;
1966   }
1967 }
1968 
1969 //----------------------------inline_notify-----------------------------------*
1970 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1971   const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1972   address func;
1973   if (id == vmIntrinsics::_notify) {
1974     func = OptoRuntime::monitor_notify_Java();
1975   } else {
1976     func = OptoRuntime::monitor_notifyAll_Java();
1977   }
1978   Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1979   make_slow_call_ex(call, env()->Throwable_klass(), false);
1980   return true;
1981 }
1982 
1983 
1984 //----------------------------inline_min_max-----------------------------------
1985 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1986   Node* a = nullptr;
1987   Node* b = nullptr;
1988   Node* n = nullptr;
1989   switch (id) {
1990     case vmIntrinsics::_min:
1991     case vmIntrinsics::_max:
1992     case vmIntrinsics::_minF:
1993     case vmIntrinsics::_maxF:
1994     case vmIntrinsics::_minF_strict:
1995     case vmIntrinsics::_maxF_strict:
1996     case vmIntrinsics::_min_strict:
1997     case vmIntrinsics::_max_strict:
1998       assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
1999       a = argument(0);
2000       b = argument(1);
2001       break;
2002     case vmIntrinsics::_minD:
2003     case vmIntrinsics::_maxD:
2004     case vmIntrinsics::_minD_strict:
2005     case vmIntrinsics::_maxD_strict:
2006       assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
2007       a = argument(0);
2008       b = argument(2);
2009       break;
2010     case vmIntrinsics::_minL:
2011     case vmIntrinsics::_maxL:
2012       assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
2013       a = argument(0);
2014       b = argument(2);
2015       break;
2016     default:
2017       fatal_unexpected_iid(id);
2018       break;
2019   }
2020 
2021   switch (id) {
2022     case vmIntrinsics::_min:
2023     case vmIntrinsics::_min_strict:
2024       n = new MinINode(a, b);
2025       break;
2026     case vmIntrinsics::_max:
2027     case vmIntrinsics::_max_strict:
2028       n = new MaxINode(a, b);
2029       break;
2030     case vmIntrinsics::_minF:
2031     case vmIntrinsics::_minF_strict:
2032       n = new MinFNode(a, b);
2033       break;
2034     case vmIntrinsics::_maxF:
2035     case vmIntrinsics::_maxF_strict:
2036       n = new MaxFNode(a, b);
2037       break;
2038     case vmIntrinsics::_minD:
2039     case vmIntrinsics::_minD_strict:
2040       n = new MinDNode(a, b);
2041       break;
2042     case vmIntrinsics::_maxD:
2043     case vmIntrinsics::_maxD_strict:
2044       n = new MaxDNode(a, b);
2045       break;
2046     case vmIntrinsics::_minL:
2047       n = new MinLNode(_gvn.C, a, b);
2048       break;
2049     case vmIntrinsics::_maxL:
2050       n = new MaxLNode(_gvn.C, a, b);
2051       break;
2052     default:
2053       fatal_unexpected_iid(id);
2054       break;
2055   }
2056 
2057   set_result(_gvn.transform(n));
2058   return true;
2059 }
2060 
2061 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2062   if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2063                                    env()->ArithmeticException_instance())) {
2064     // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2065     // so let's bail out intrinsic rather than risking deopting again.
2066     return false;
2067   }
2068 
2069   Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2070   IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2071   Node* fast_path = _gvn.transform( new IfFalseNode(check));
2072   Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2073 
2074   {
2075     PreserveJVMState pjvms(this);
2076     PreserveReexecuteState preexecs(this);
2077     jvms()->set_should_reexecute(true);
2078 
2079     set_control(slow_path);
2080     set_i_o(i_o());
2081 
2082     builtin_throw(Deoptimization::Reason_intrinsic,
2083                   env()->ArithmeticException_instance(),
2084                   /*allow_too_many_traps*/ false);
2085   }
2086 
2087   set_control(fast_path);
2088   set_result(math);
2089   return true;
2090 }
2091 
2092 template <typename OverflowOp>
2093 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2094   typedef typename OverflowOp::MathOp MathOp;
2095 
2096   MathOp* mathOp = new MathOp(arg1, arg2);
2097   Node* operation = _gvn.transform( mathOp );
2098   Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2099   return inline_math_mathExact(operation, ofcheck);
2100 }
2101 
2102 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2103   return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2104 }
2105 
2106 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2107   return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2108 }
2109 
2110 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2111   return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2112 }
2113 
2114 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2115   return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2116 }
2117 
2118 bool LibraryCallKit::inline_math_negateExactI() {
2119   return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2120 }
2121 
2122 bool LibraryCallKit::inline_math_negateExactL() {
2123   return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2124 }
2125 
2126 bool LibraryCallKit::inline_math_multiplyExactI() {
2127   return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2128 }
2129 
2130 bool LibraryCallKit::inline_math_multiplyExactL() {
2131   return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2132 }
2133 
2134 bool LibraryCallKit::inline_math_multiplyHigh() {
2135   set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2136   return true;
2137 }
2138 
2139 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2140   set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2141   return true;
2142 }
2143 
2144 inline int
2145 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2146   const TypePtr* base_type = TypePtr::NULL_PTR;
2147   if (base != nullptr)  base_type = _gvn.type(base)->isa_ptr();
2148   if (base_type == nullptr) {
2149     // Unknown type.
2150     return Type::AnyPtr;
2151   } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2152     // Since this is a null+long form, we have to switch to a rawptr.
2153     base   = _gvn.transform(new CastX2PNode(offset));
2154     offset = MakeConX(0);
2155     return Type::RawPtr;
2156   } else if (base_type->base() == Type::RawPtr) {
2157     return Type::RawPtr;
2158   } else if (base_type->isa_oopptr()) {
2159     // Base is never null => always a heap address.
2160     if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2161       return Type::OopPtr;
2162     }
2163     // Offset is small => always a heap address.
2164     const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2165     if (offset_type != nullptr &&
2166         base_type->offset() == 0 &&     // (should always be?)
2167         offset_type->_lo >= 0 &&
2168         !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2169       return Type::OopPtr;
2170     } else if (type == T_OBJECT) {
2171       // off heap access to an oop doesn't make any sense. Has to be on
2172       // heap.
2173       return Type::OopPtr;
2174     }
2175     // Otherwise, it might either be oop+off or null+addr.
2176     return Type::AnyPtr;
2177   } else {
2178     // No information:
2179     return Type::AnyPtr;
2180   }
2181 }
2182 
2183 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2184   Node* uncasted_base = base;
2185   int kind = classify_unsafe_addr(uncasted_base, offset, type);
2186   if (kind == Type::RawPtr) {
2187     return basic_plus_adr(top(), uncasted_base, offset);
2188   } else if (kind == Type::AnyPtr) {
2189     assert(base == uncasted_base, "unexpected base change");
2190     if (can_cast) {
2191       if (!_gvn.type(base)->speculative_maybe_null() &&
2192           !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2193         // According to profiling, this access is always on
2194         // heap. Casting the base to not null and thus avoiding membars
2195         // around the access should allow better optimizations
2196         Node* null_ctl = top();
2197         base = null_check_oop(base, &null_ctl, true, true, true);
2198         assert(null_ctl->is_top(), "no null control here");
2199         return basic_plus_adr(base, offset);
2200       } else if (_gvn.type(base)->speculative_always_null() &&
2201                  !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2202         // According to profiling, this access is always off
2203         // heap.
2204         base = null_assert(base);
2205         Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2206         offset = MakeConX(0);
2207         return basic_plus_adr(top(), raw_base, offset);
2208       }
2209     }
2210     // We don't know if it's an on heap or off heap access. Fall back
2211     // to raw memory access.
2212     Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2213     return basic_plus_adr(top(), raw, offset);
2214   } else {
2215     assert(base == uncasted_base, "unexpected base change");
2216     // We know it's an on heap access so base can't be null
2217     if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2218       base = must_be_not_null(base, true);
2219     }
2220     return basic_plus_adr(base, offset);
2221   }
2222 }
2223 
2224 //--------------------------inline_number_methods-----------------------------
2225 // inline int     Integer.numberOfLeadingZeros(int)
2226 // inline int        Long.numberOfLeadingZeros(long)
2227 //
2228 // inline int     Integer.numberOfTrailingZeros(int)
2229 // inline int        Long.numberOfTrailingZeros(long)
2230 //
2231 // inline int     Integer.bitCount(int)
2232 // inline int        Long.bitCount(long)
2233 //
2234 // inline char  Character.reverseBytes(char)
2235 // inline short     Short.reverseBytes(short)
2236 // inline int     Integer.reverseBytes(int)
2237 // inline long       Long.reverseBytes(long)
2238 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2239   Node* arg = argument(0);
2240   Node* n = nullptr;
2241   switch (id) {
2242   case vmIntrinsics::_numberOfLeadingZeros_i:   n = new CountLeadingZerosINode( arg); break;
2243   case vmIntrinsics::_numberOfLeadingZeros_l:   n = new CountLeadingZerosLNode( arg); break;
2244   case vmIntrinsics::_numberOfTrailingZeros_i:  n = new CountTrailingZerosINode(arg); break;
2245   case vmIntrinsics::_numberOfTrailingZeros_l:  n = new CountTrailingZerosLNode(arg); break;
2246   case vmIntrinsics::_bitCount_i:               n = new PopCountINode(          arg); break;
2247   case vmIntrinsics::_bitCount_l:               n = new PopCountLNode(          arg); break;
2248   case vmIntrinsics::_reverseBytes_c:           n = new ReverseBytesUSNode(     arg); break;
2249   case vmIntrinsics::_reverseBytes_s:           n = new ReverseBytesSNode(      arg); break;
2250   case vmIntrinsics::_reverseBytes_i:           n = new ReverseBytesINode(      arg); break;
2251   case vmIntrinsics::_reverseBytes_l:           n = new ReverseBytesLNode(      arg); break;
2252   case vmIntrinsics::_reverse_i:                n = new ReverseINode(           arg); break;
2253   case vmIntrinsics::_reverse_l:                n = new ReverseLNode(           arg); break;
2254   default:  fatal_unexpected_iid(id);  break;
2255   }
2256   set_result(_gvn.transform(n));
2257   return true;
2258 }
2259 
2260 //--------------------------inline_bitshuffle_methods-----------------------------
2261 // inline int Integer.compress(int, int)
2262 // inline int Integer.expand(int, int)
2263 // inline long Long.compress(long, long)
2264 // inline long Long.expand(long, long)
2265 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2266   Node* n = nullptr;
2267   switch (id) {
2268     case vmIntrinsics::_compress_i:  n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2269     case vmIntrinsics::_expand_i:    n = new ExpandBitsNode(argument(0),  argument(1), TypeInt::INT); break;
2270     case vmIntrinsics::_compress_l:  n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2271     case vmIntrinsics::_expand_l:    n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2272     default:  fatal_unexpected_iid(id);  break;
2273   }
2274   set_result(_gvn.transform(n));
2275   return true;
2276 }
2277 
2278 //--------------------------inline_number_methods-----------------------------
2279 // inline int Integer.compareUnsigned(int, int)
2280 // inline int    Long.compareUnsigned(long, long)
2281 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2282   Node* arg1 = argument(0);
2283   Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2284   Node* n = nullptr;
2285   switch (id) {
2286     case vmIntrinsics::_compareUnsigned_i:   n = new CmpU3Node(arg1, arg2);  break;
2287     case vmIntrinsics::_compareUnsigned_l:   n = new CmpUL3Node(arg1, arg2); break;
2288     default:  fatal_unexpected_iid(id);  break;
2289   }
2290   set_result(_gvn.transform(n));
2291   return true;
2292 }
2293 
2294 //--------------------------inline_unsigned_divmod_methods-----------------------------
2295 // inline int Integer.divideUnsigned(int, int)
2296 // inline int Integer.remainderUnsigned(int, int)
2297 // inline long Long.divideUnsigned(long, long)
2298 // inline long Long.remainderUnsigned(long, long)
2299 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2300   Node* n = nullptr;
2301   switch (id) {
2302     case vmIntrinsics::_divideUnsigned_i: {
2303       zero_check_int(argument(1));
2304       // Compile-time detect of null-exception
2305       if (stopped()) {
2306         return true; // keep the graph constructed so far
2307       }
2308       n = new UDivINode(control(), argument(0), argument(1));
2309       break;
2310     }
2311     case vmIntrinsics::_divideUnsigned_l: {
2312       zero_check_long(argument(2));
2313       // Compile-time detect of null-exception
2314       if (stopped()) {
2315         return true; // keep the graph constructed so far
2316       }
2317       n = new UDivLNode(control(), argument(0), argument(2));
2318       break;
2319     }
2320     case vmIntrinsics::_remainderUnsigned_i: {
2321       zero_check_int(argument(1));
2322       // Compile-time detect of null-exception
2323       if (stopped()) {
2324         return true; // keep the graph constructed so far
2325       }
2326       n = new UModINode(control(), argument(0), argument(1));
2327       break;
2328     }
2329     case vmIntrinsics::_remainderUnsigned_l: {
2330       zero_check_long(argument(2));
2331       // Compile-time detect of null-exception
2332       if (stopped()) {
2333         return true; // keep the graph constructed so far
2334       }
2335       n = new UModLNode(control(), argument(0), argument(2));
2336       break;
2337     }
2338     default:  fatal_unexpected_iid(id);  break;
2339   }
2340   set_result(_gvn.transform(n));
2341   return true;
2342 }
2343 
2344 //----------------------------inline_unsafe_access----------------------------
2345 
2346 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2347   // Attempt to infer a sharper value type from the offset and base type.
2348   ciKlass* sharpened_klass = nullptr;
2349   bool null_free = false;
2350 
2351   // See if it is an instance field, with an object type.
2352   if (alias_type->field() != nullptr) {
2353     if (alias_type->field()->type()->is_klass()) {
2354       sharpened_klass = alias_type->field()->type()->as_klass();
2355       null_free = alias_type->field()->is_null_free();
2356     }
2357   }
2358 
2359   const TypeOopPtr* result = nullptr;
2360   // See if it is a narrow oop array.
2361   if (adr_type->isa_aryptr()) {
2362     if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2363       const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2364       null_free = adr_type->is_aryptr()->is_null_free();
2365       if (elem_type != nullptr && elem_type->is_loaded()) {
2366         // Sharpen the value type.
2367         result = elem_type;
2368       }
2369     }
2370   }
2371 
2372   // The sharpened class might be unloaded if there is no class loader
2373   // contraint in place.
2374   if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2375     // Sharpen the value type.
2376     result = TypeOopPtr::make_from_klass(sharpened_klass);
2377     if (null_free) {
2378       result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2379     }
2380   }
2381   if (result != nullptr) {
2382 #ifndef PRODUCT
2383     if (C->print_intrinsics() || C->print_inlining()) {
2384       tty->print("  from base type:  ");  adr_type->dump(); tty->cr();
2385       tty->print("  sharpened value: ");  result->dump();    tty->cr();
2386     }
2387 #endif
2388   }
2389   return result;
2390 }
2391 
2392 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2393   switch (kind) {
2394       case Relaxed:
2395         return MO_UNORDERED;
2396       case Opaque:
2397         return MO_RELAXED;
2398       case Acquire:
2399         return MO_ACQUIRE;
2400       case Release:
2401         return MO_RELEASE;
2402       case Volatile:
2403         return MO_SEQ_CST;
2404       default:
2405         ShouldNotReachHere();
2406         return 0;
2407   }
2408 }
2409 
2410 LibraryCallKit::SavedState::SavedState(LibraryCallKit* kit) :
2411   _kit(kit),
2412   _sp(kit->sp()),
2413   _jvms(kit->jvms()),
2414   _map(kit->clone_map()),
2415   _discarded(false)
2416 {
2417   for (DUIterator_Fast imax, i = kit->control()->fast_outs(imax); i < imax; i++) {
2418     Node* out = kit->control()->fast_out(i);
2419     if (out->is_CFG()) {
2420       _ctrl_succ.push(out);
2421     }
2422   }
2423 }
2424 
2425 LibraryCallKit::SavedState::~SavedState() {
2426   if (_discarded) {
2427     _kit->destruct_map_clone(_map);
2428     return;
2429   }
2430   _kit->jvms()->set_map(_map);
2431   _kit->jvms()->set_sp(_sp);
2432   _map->set_jvms(_kit->jvms());
2433   _kit->set_map(_map);
2434   _kit->set_sp(_sp);
2435   for (DUIterator_Fast imax, i = _kit->control()->fast_outs(imax); i < imax; i++) {
2436     Node* out = _kit->control()->fast_out(i);
2437     if (out->is_CFG() && out->in(0) == _kit->control() && out != _kit->map() && !_ctrl_succ.member(out)) {
2438       _kit->_gvn.hash_delete(out);
2439       out->set_req(0, _kit->C->top());
2440       _kit->C->record_for_igvn(out);
2441       --i; --imax;
2442       _kit->_gvn.hash_find_insert(out);
2443     }
2444   }
2445 }
2446 
2447 void LibraryCallKit::SavedState::discard() {
2448   _discarded = true;
2449 }
2450 
2451 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2452   if (callee()->is_static())  return false;  // caller must have the capability!
2453   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2454   guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2455   guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2456   assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2457 
2458   if (is_reference_type(type)) {
2459     decorators |= ON_UNKNOWN_OOP_REF;
2460   }
2461 
2462   if (unaligned) {
2463     decorators |= C2_UNALIGNED;
2464   }
2465 
2466 #ifndef PRODUCT
2467   {
2468     ResourceMark rm;
2469     // Check the signatures.
2470     ciSignature* sig = callee()->signature();
2471 #ifdef ASSERT
2472     if (!is_store) {
2473       // Object getReference(Object base, int/long offset), etc.
2474       BasicType rtype = sig->return_type()->basic_type();
2475       assert(rtype == type, "getter must return the expected value");
2476       assert(sig->count() == 2, "oop getter has 2 arguments");
2477       assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2478       assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2479     } else {
2480       // void putReference(Object base, int/long offset, Object x), etc.
2481       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2482       assert(sig->count() == 3, "oop putter has 3 arguments");
2483       assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2484       assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2485       BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2486       assert(vtype == type, "putter must accept the expected value");
2487     }
2488 #endif // ASSERT
2489  }
2490 #endif //PRODUCT
2491 
2492   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
2493 
2494   Node* receiver = argument(0);  // type: oop
2495 
2496   // Build address expression.
2497   Node* heap_base_oop = top();
2498 
2499   // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2500   Node* base = argument(1);  // type: oop
2501   // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2502   Node* offset = argument(2);  // type: long
2503   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2504   // to be plain byte offsets, which are also the same as those accepted
2505   // by oopDesc::field_addr.
2506   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2507          "fieldOffset must be byte-scaled");
2508 
2509   if (base->is_InlineType()) {
2510     assert(!is_store, "InlineTypeNodes are non-larval value objects");
2511     InlineTypeNode* vt = base->as_InlineType();
2512     if (offset->is_Con()) {
2513       long off = find_long_con(offset, 0);
2514       ciInlineKlass* vk = vt->type()->inline_klass();
2515       if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2516         return false;
2517       }
2518 
2519       ciField* field = vk->get_non_flat_field_by_offset(off);
2520       if (field != nullptr) {
2521         BasicType bt = type2field[field->type()->basic_type()];
2522         if (bt == T_ARRAY || bt == T_NARROWOOP) {
2523           bt = T_OBJECT;
2524         }
2525         if (bt == type && !field->is_flat()) {
2526           Node* value = vt->field_value_by_offset(off, false);
2527           if (value->is_InlineType()) {
2528             value = value->as_InlineType()->adjust_scalarization_depth(this);
2529           }
2530           set_result(value);
2531           return true;
2532         }
2533       }
2534     }
2535     {
2536       // Re-execute the unsafe access if allocation triggers deoptimization.
2537       PreserveReexecuteState preexecs(this);
2538       jvms()->set_should_reexecute(true);
2539       vt = vt->buffer(this);
2540     }
2541     base = vt->get_oop();
2542   }
2543 
2544   // 32-bit machines ignore the high half!
2545   offset = ConvL2X(offset);
2546 
2547   // Save state and restore on bailout
2548   SavedState old_state(this);
2549 
2550   Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2551   assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2552 
2553   if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2554     if (type != T_OBJECT) {
2555       decorators |= IN_NATIVE; // off-heap primitive access
2556     } else {
2557       return false; // off-heap oop accesses are not supported
2558     }
2559   } else {
2560     heap_base_oop = base; // on-heap or mixed access
2561   }
2562 
2563   // Can base be null? Otherwise, always on-heap access.
2564   bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2565 
2566   if (!can_access_non_heap) {
2567     decorators |= IN_HEAP;
2568   }
2569 
2570   Node* val = is_store ? argument(4) : nullptr;
2571 
2572   const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2573   if (adr_type == TypePtr::NULL_PTR) {
2574     return false; // off-heap access with zero address
2575   }
2576 
2577   // Try to categorize the address.
2578   Compile::AliasType* alias_type = C->alias_type(adr_type);
2579   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2580 
2581   if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2582       alias_type->adr_type() == TypeAryPtr::RANGE) {
2583     return false; // not supported
2584   }
2585 
2586   bool mismatched = false;
2587   BasicType bt = T_ILLEGAL;
2588   ciField* field = nullptr;
2589   if (adr_type->isa_instptr()) {
2590     const TypeInstPtr* instptr = adr_type->is_instptr();
2591     ciInstanceKlass* k = instptr->instance_klass();
2592     int off = instptr->offset();
2593     if (instptr->const_oop() != nullptr &&
2594         k == ciEnv::current()->Class_klass() &&
2595         instptr->offset() >= (k->size_helper() * wordSize)) {
2596       k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2597       field = k->get_field_by_offset(off, true);
2598     } else {
2599       field = k->get_non_flat_field_by_offset(off);
2600     }
2601     if (field != nullptr) {
2602       bt = type2field[field->type()->basic_type()];
2603     }
2604     if (bt != alias_type->basic_type()) {
2605       // Type mismatch. Is it an access to a nested flat field?
2606       field = k->get_field_by_offset(off, false);
2607       if (field != nullptr) {
2608         bt = type2field[field->type()->basic_type()];
2609       }
2610     }
2611     assert(bt == alias_type->basic_type(), "should match");
2612   } else {
2613     bt = alias_type->basic_type();
2614   }
2615 
2616   if (bt != T_ILLEGAL) {
2617     assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2618     if (bt == T_BYTE && adr_type->isa_aryptr()) {
2619       // Alias type doesn't differentiate between byte[] and boolean[]).
2620       // Use address type to get the element type.
2621       bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2622     }
2623     if (is_reference_type(bt, true)) {
2624       // accessing an array field with getReference is not a mismatch
2625       bt = T_OBJECT;
2626     }
2627     if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2628       // Don't intrinsify mismatched object accesses
2629       return false;
2630     }
2631     mismatched = (bt != type);
2632   } else if (alias_type->adr_type()->isa_oopptr()) {
2633     mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2634   }
2635 
2636   old_state.discard();
2637   assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2638 
2639   if (mismatched) {
2640     decorators |= C2_MISMATCHED;
2641   }
2642 
2643   // First guess at the value type.
2644   const Type *value_type = Type::get_const_basic_type(type);
2645 
2646   // Figure out the memory ordering.
2647   decorators |= mo_decorator_for_access_kind(kind);
2648 
2649   if (!is_store) {
2650     if (type == T_OBJECT) {
2651       const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2652       if (tjp != nullptr) {
2653         value_type = tjp;
2654       }
2655     }
2656   }
2657 
2658   receiver = null_check(receiver);
2659   if (stopped()) {
2660     return true;
2661   }
2662   // Heap pointers get a null-check from the interpreter,
2663   // as a courtesy.  However, this is not guaranteed by Unsafe,
2664   // and it is not possible to fully distinguish unintended nulls
2665   // from intended ones in this API.
2666 
2667   if (!is_store) {
2668     Node* p = nullptr;
2669     // Try to constant fold a load from a constant field
2670 
2671     if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2672       // final or stable field
2673       p = make_constant_from_field(field, heap_base_oop);
2674     }
2675 
2676     if (p == nullptr) { // Could not constant fold the load
2677       p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2678       const TypeOopPtr* ptr = value_type->make_oopptr();
2679       if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2680         // Load a non-flattened inline type from memory
2681         p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2682       }
2683       // Normalize the value returned by getBoolean in the following cases
2684       if (type == T_BOOLEAN &&
2685           (mismatched ||
2686            heap_base_oop == top() ||                  // - heap_base_oop is null or
2687            (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2688                                                       //   and the unsafe access is made to large offset
2689                                                       //   (i.e., larger than the maximum offset necessary for any
2690                                                       //   field access)
2691             ) {
2692           IdealKit ideal = IdealKit(this);
2693 #define __ ideal.
2694           IdealVariable normalized_result(ideal);
2695           __ declarations_done();
2696           __ set(normalized_result, p);
2697           __ if_then(p, BoolTest::ne, ideal.ConI(0));
2698           __ set(normalized_result, ideal.ConI(1));
2699           ideal.end_if();
2700           final_sync(ideal);
2701           p = __ value(normalized_result);
2702 #undef __
2703       }
2704     }
2705     if (type == T_ADDRESS) {
2706       p = gvn().transform(new CastP2XNode(nullptr, p));
2707       p = ConvX2UL(p);
2708     }
2709     // The load node has the control of the preceding MemBarCPUOrder.  All
2710     // following nodes will have the control of the MemBarCPUOrder inserted at
2711     // the end of this method.  So, pushing the load onto the stack at a later
2712     // point is fine.
2713     set_result(p);
2714   } else {
2715     if (bt == T_ADDRESS) {
2716       // Repackage the long as a pointer.
2717       val = ConvL2X(val);
2718       val = gvn().transform(new CastX2PNode(val));
2719     }
2720     access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2721   }
2722 
2723   return true;
2724 }
2725 
2726 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2727 #ifdef ASSERT
2728   {
2729     ResourceMark rm;
2730     // Check the signatures.
2731     ciSignature* sig = callee()->signature();
2732     assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2733     assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2734     assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2735     assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2736     if (is_store) {
2737       assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2738       assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2739       assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2740     } else {
2741       assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2742       assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2743     }
2744  }
2745 #endif // ASSERT
2746 
2747   assert(kind == Relaxed, "Only plain accesses for now");
2748   if (callee()->is_static()) {
2749     // caller must have the capability!
2750     return false;
2751   }
2752   C->set_has_unsafe_access(true);
2753 
2754   const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2755   if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2756     // parameter valueType is not a constant
2757     return false;
2758   }
2759   ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2760   if (!mirror_type->is_inlinetype()) {
2761     // Dead code
2762     return false;
2763   }
2764   ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2765 
2766   const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2767   if (layout_type == nullptr || !layout_type->is_con()) {
2768     // parameter layoutKind is not a constant
2769     return false;
2770   }
2771   assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2772          layout_type->get_con() <= static_cast<int>(LayoutKind::UNKNOWN),
2773          "invalid layoutKind %d", layout_type->get_con());
2774   LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2775   assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NULL_FREE_NON_ATOMIC_FLAT ||
2776          layout == LayoutKind::NULL_FREE_ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2777          "unexpected layoutKind %d", layout_type->get_con());
2778 
2779   null_check(argument(0));
2780   if (stopped()) {
2781     return true;
2782   }
2783 
2784   Node* base = must_be_not_null(argument(1), true);
2785   Node* offset = argument(2);
2786   const Type* base_type = _gvn.type(base);
2787 
2788   Node* ptr;
2789   bool immutable_memory = false;
2790   DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2791   if (base_type->isa_instptr()) {
2792     const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2793     if (offset_type == nullptr || !offset_type->is_con()) {
2794       // Offset into a non-array should be a constant
2795       decorators |= C2_MISMATCHED;
2796     } else {
2797       int offset_con = checked_cast<int>(offset_type->get_con());
2798       ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2799       ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2800       if (field == nullptr) {
2801         assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2802         decorators |= C2_MISMATCHED;
2803       } else {
2804         assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2805                offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2806         immutable_memory = field->is_strict() && field->is_final();
2807 
2808         if (base->is_InlineType()) {
2809           assert(!is_store, "Cannot store into a non-larval value object");
2810           set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2811           return true;
2812         }
2813       }
2814     }
2815 
2816     if (base->is_InlineType()) {
2817       assert(!is_store, "Cannot store into a non-larval value object");
2818       base = base->as_InlineType()->buffer(this, true);
2819     }
2820     ptr = basic_plus_adr(base, ConvL2X(offset));
2821   } else if (base_type->isa_aryptr()) {
2822     decorators |= IS_ARRAY;
2823     if (layout == LayoutKind::REFERENCE) {
2824       if (!base_type->is_aryptr()->is_not_flat()) {
2825         const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2826         Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2827         replace_in_map(base, new_base);
2828         base = new_base;
2829       }
2830       ptr = basic_plus_adr(base, ConvL2X(offset));
2831     } else {
2832       if (UseArrayFlattening) {
2833         // Flat array must have an exact type
2834         bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2835         bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2836         Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
2837         replace_in_map(base, new_base);
2838         base = new_base;
2839         ptr = basic_plus_adr(base, ConvL2X(offset));
2840         const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2841         if (ptr_type->field_offset().get() != 0) {
2842           ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2843         }
2844       } else {
2845         uncommon_trap(Deoptimization::Reason_intrinsic,
2846                       Deoptimization::Action_none);
2847         return true;
2848       }
2849     }
2850   } else {
2851     decorators |= C2_MISMATCHED;
2852     ptr = basic_plus_adr(base, ConvL2X(offset));
2853   }
2854 
2855   if (is_store) {
2856     Node* value = argument(6);
2857     const Type* value_type = _gvn.type(value);
2858     if (!value_type->is_inlinetypeptr()) {
2859       value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2860       Node* new_value = _gvn.transform(new CastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2861       new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2862       replace_in_map(value, new_value);
2863       value = new_value;
2864     }
2865 
2866     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());
2867     if (layout == LayoutKind::REFERENCE) {
2868       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2869       access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2870     } else {
2871       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2872       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2873       value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2874     }
2875 
2876     return true;
2877   } else {
2878     decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2879     InlineTypeNode* result;
2880     if (layout == LayoutKind::REFERENCE) {
2881       const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2882       Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2883       result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2884     } else {
2885       bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2886       bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2887       result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2888     }
2889 
2890     set_result(result);
2891     return true;
2892   }
2893 }
2894 
2895 //----------------------------inline_unsafe_load_store----------------------------
2896 // This method serves a couple of different customers (depending on LoadStoreKind):
2897 //
2898 // LS_cmp_swap:
2899 //
2900 //   boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2901 //   boolean compareAndSetInt(   Object o, long offset, int    expected, int    x);
2902 //   boolean compareAndSetLong(  Object o, long offset, long   expected, long   x);
2903 //
2904 // LS_cmp_swap_weak:
2905 //
2906 //   boolean weakCompareAndSetReference(       Object o, long offset, Object expected, Object x);
2907 //   boolean weakCompareAndSetReferencePlain(  Object o, long offset, Object expected, Object x);
2908 //   boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2909 //   boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2910 //
2911 //   boolean weakCompareAndSetInt(          Object o, long offset, int    expected, int    x);
2912 //   boolean weakCompareAndSetIntPlain(     Object o, long offset, int    expected, int    x);
2913 //   boolean weakCompareAndSetIntAcquire(   Object o, long offset, int    expected, int    x);
2914 //   boolean weakCompareAndSetIntRelease(   Object o, long offset, int    expected, int    x);
2915 //
2916 //   boolean weakCompareAndSetLong(         Object o, long offset, long   expected, long   x);
2917 //   boolean weakCompareAndSetLongPlain(    Object o, long offset, long   expected, long   x);
2918 //   boolean weakCompareAndSetLongAcquire(  Object o, long offset, long   expected, long   x);
2919 //   boolean weakCompareAndSetLongRelease(  Object o, long offset, long   expected, long   x);
2920 //
2921 // LS_cmp_exchange:
2922 //
2923 //   Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2924 //   Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2925 //   Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2926 //
2927 //   Object compareAndExchangeIntVolatile(   Object o, long offset, Object expected, Object x);
2928 //   Object compareAndExchangeIntAcquire(    Object o, long offset, Object expected, Object x);
2929 //   Object compareAndExchangeIntRelease(    Object o, long offset, Object expected, Object x);
2930 //
2931 //   Object compareAndExchangeLongVolatile(  Object o, long offset, Object expected, Object x);
2932 //   Object compareAndExchangeLongAcquire(   Object o, long offset, Object expected, Object x);
2933 //   Object compareAndExchangeLongRelease(   Object o, long offset, Object expected, Object x);
2934 //
2935 // LS_get_add:
2936 //
2937 //   int  getAndAddInt( Object o, long offset, int  delta)
2938 //   long getAndAddLong(Object o, long offset, long delta)
2939 //
2940 // LS_get_set:
2941 //
2942 //   int    getAndSet(Object o, long offset, int    newValue)
2943 //   long   getAndSet(Object o, long offset, long   newValue)
2944 //   Object getAndSet(Object o, long offset, Object newValue)
2945 //
2946 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2947   // This basic scheme here is the same as inline_unsafe_access, but
2948   // differs in enough details that combining them would make the code
2949   // overly confusing.  (This is a true fact! I originally combined
2950   // them, but even I was confused by it!) As much code/comments as
2951   // possible are retained from inline_unsafe_access though to make
2952   // the correspondences clearer. - dl
2953 
2954   if (callee()->is_static())  return false;  // caller must have the capability!
2955 
2956   DecoratorSet decorators = C2_UNSAFE_ACCESS;
2957   decorators |= mo_decorator_for_access_kind(access_kind);
2958 
2959 #ifndef PRODUCT
2960   BasicType rtype;
2961   {
2962     ResourceMark rm;
2963     // Check the signatures.
2964     ciSignature* sig = callee()->signature();
2965     rtype = sig->return_type()->basic_type();
2966     switch(kind) {
2967       case LS_get_add:
2968       case LS_get_set: {
2969       // Check the signatures.
2970 #ifdef ASSERT
2971       assert(rtype == type, "get and set must return the expected type");
2972       assert(sig->count() == 3, "get and set has 3 arguments");
2973       assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2974       assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2975       assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2976       assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
2977 #endif // ASSERT
2978         break;
2979       }
2980       case LS_cmp_swap:
2981       case LS_cmp_swap_weak: {
2982       // Check the signatures.
2983 #ifdef ASSERT
2984       assert(rtype == T_BOOLEAN, "CAS must return boolean");
2985       assert(sig->count() == 4, "CAS has 4 arguments");
2986       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2987       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2988 #endif // ASSERT
2989         break;
2990       }
2991       case LS_cmp_exchange: {
2992       // Check the signatures.
2993 #ifdef ASSERT
2994       assert(rtype == type, "CAS must return the expected type");
2995       assert(sig->count() == 4, "CAS has 4 arguments");
2996       assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2997       assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2998 #endif // ASSERT
2999         break;
3000       }
3001       default:
3002         ShouldNotReachHere();
3003     }
3004   }
3005 #endif //PRODUCT
3006 
3007   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
3008 
3009   // Get arguments:
3010   Node* receiver = nullptr;
3011   Node* base     = nullptr;
3012   Node* offset   = nullptr;
3013   Node* oldval   = nullptr;
3014   Node* newval   = nullptr;
3015   switch(kind) {
3016     case LS_cmp_swap:
3017     case LS_cmp_swap_weak:
3018     case LS_cmp_exchange: {
3019       const bool two_slot_type = type2size[type] == 2;
3020       receiver = argument(0);  // type: oop
3021       base     = argument(1);  // type: oop
3022       offset   = argument(2);  // type: long
3023       oldval   = argument(4);  // type: oop, int, or long
3024       newval   = argument(two_slot_type ? 6 : 5);  // type: oop, int, or long
3025       break;
3026     }
3027     case LS_get_add:
3028     case LS_get_set: {
3029       receiver = argument(0);  // type: oop
3030       base     = argument(1);  // type: oop
3031       offset   = argument(2);  // type: long
3032       oldval   = nullptr;
3033       newval   = argument(4);  // type: oop, int, or long
3034       break;
3035     }
3036     default:
3037       ShouldNotReachHere();
3038   }
3039 
3040   // Build field offset expression.
3041   // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
3042   // to be plain byte offsets, which are also the same as those accepted
3043   // by oopDesc::field_addr.
3044   assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
3045   // 32-bit machines ignore the high half of long offsets
3046   offset = ConvL2X(offset);
3047   // Save state and restore on bailout
3048   SavedState old_state(this);
3049   Node* adr = make_unsafe_address(base, offset,type, false);
3050   const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
3051 
3052   Compile::AliasType* alias_type = C->alias_type(adr_type);
3053   BasicType bt = alias_type->basic_type();
3054   if (bt != T_ILLEGAL &&
3055       (is_reference_type(bt) != (type == T_OBJECT))) {
3056     // Don't intrinsify mismatched object accesses.
3057     return false;
3058   }
3059 
3060   old_state.discard();
3061 
3062   // For CAS, unlike inline_unsafe_access, there seems no point in
3063   // trying to refine types. Just use the coarse types here.
3064   assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
3065   const Type *value_type = Type::get_const_basic_type(type);
3066 
3067   switch (kind) {
3068     case LS_get_set:
3069     case LS_cmp_exchange: {
3070       if (type == T_OBJECT) {
3071         const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
3072         if (tjp != nullptr) {
3073           value_type = tjp;
3074         }
3075       }
3076       break;
3077     }
3078     case LS_cmp_swap:
3079     case LS_cmp_swap_weak:
3080     case LS_get_add:
3081       break;
3082     default:
3083       ShouldNotReachHere();
3084   }
3085 
3086   // Null check receiver.
3087   receiver = null_check(receiver);
3088   if (stopped()) {
3089     return true;
3090   }
3091 
3092   int alias_idx = C->get_alias_index(adr_type);
3093 
3094   if (is_reference_type(type)) {
3095     decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3096 
3097     if (oldval != nullptr && oldval->is_InlineType()) {
3098       // Re-execute the unsafe access if allocation triggers deoptimization.
3099       PreserveReexecuteState preexecs(this);
3100       jvms()->set_should_reexecute(true);
3101       oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3102     }
3103     if (newval != nullptr && newval->is_InlineType()) {
3104       // Re-execute the unsafe access if allocation triggers deoptimization.
3105       PreserveReexecuteState preexecs(this);
3106       jvms()->set_should_reexecute(true);
3107       newval = newval->as_InlineType()->buffer(this)->get_oop();
3108     }
3109 
3110     // Transformation of a value which could be null pointer (CastPP #null)
3111     // could be delayed during Parse (for example, in adjust_map_after_if()).
3112     // Execute transformation here to avoid barrier generation in such case.
3113     if (_gvn.type(newval) == TypePtr::NULL_PTR)
3114       newval = _gvn.makecon(TypePtr::NULL_PTR);
3115 
3116     if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3117       // Refine the value to a null constant, when it is known to be null
3118       oldval = _gvn.makecon(TypePtr::NULL_PTR);
3119     }
3120   }
3121 
3122   Node* result = nullptr;
3123   switch (kind) {
3124     case LS_cmp_exchange: {
3125       result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3126                                             oldval, newval, value_type, type, decorators);
3127       break;
3128     }
3129     case LS_cmp_swap_weak:
3130       decorators |= C2_WEAK_CMPXCHG;
3131     case LS_cmp_swap: {
3132       result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3133                                              oldval, newval, value_type, type, decorators);
3134       break;
3135     }
3136     case LS_get_set: {
3137       result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3138                                      newval, value_type, type, decorators);
3139       break;
3140     }
3141     case LS_get_add: {
3142       result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3143                                     newval, value_type, type, decorators);
3144       break;
3145     }
3146     default:
3147       ShouldNotReachHere();
3148   }
3149 
3150   assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3151   set_result(result);
3152   return true;
3153 }
3154 
3155 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3156   // Regardless of form, don't allow previous ld/st to move down,
3157   // then issue acquire, release, or volatile mem_bar.
3158   insert_mem_bar(Op_MemBarCPUOrder);
3159   switch(id) {
3160     case vmIntrinsics::_loadFence:
3161       insert_mem_bar(Op_LoadFence);
3162       return true;
3163     case vmIntrinsics::_storeFence:
3164       insert_mem_bar(Op_StoreFence);
3165       return true;
3166     case vmIntrinsics::_storeStoreFence:
3167       insert_mem_bar(Op_StoreStoreFence);
3168       return true;
3169     case vmIntrinsics::_fullFence:
3170       insert_mem_bar(Op_MemBarVolatile);
3171       return true;
3172     default:
3173       fatal_unexpected_iid(id);
3174       return false;
3175   }
3176 }
3177 
3178 // private native int arrayInstanceBaseOffset0(Object[] array);
3179 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3180   Node* array = argument(1);
3181   Node* klass_node = load_object_klass(array);
3182 
3183   jint  layout_con = Klass::_lh_neutral_value;
3184   Node* layout_val = get_layout_helper(klass_node, layout_con);
3185   int   layout_is_con = (layout_val == nullptr);
3186 
3187   Node* header_size = nullptr;
3188   if (layout_is_con) {
3189     int hsize = Klass::layout_helper_header_size(layout_con);
3190     header_size = intcon(hsize);
3191   } else {
3192     Node* hss = intcon(Klass::_lh_header_size_shift);
3193     Node* hsm = intcon(Klass::_lh_header_size_mask);
3194     header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3195     header_size = _gvn.transform(new AndINode(header_size, hsm));
3196   }
3197   set_result(header_size);
3198   return true;
3199 }
3200 
3201 // private native int arrayInstanceIndexScale0(Object[] array);
3202 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3203   Node* array = argument(1);
3204   Node* klass_node = load_object_klass(array);
3205 
3206   jint  layout_con = Klass::_lh_neutral_value;
3207   Node* layout_val = get_layout_helper(klass_node, layout_con);
3208   int   layout_is_con = (layout_val == nullptr);
3209 
3210   Node* element_size = nullptr;
3211   if (layout_is_con) {
3212     int log_element_size  = Klass::layout_helper_log2_element_size(layout_con);
3213     int elem_size = 1 << log_element_size;
3214     element_size = intcon(elem_size);
3215   } else {
3216     Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3217     Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3218     Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3219     log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3220     element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3221   }
3222   set_result(element_size);
3223   return true;
3224 }
3225 
3226 // private native int arrayLayout0(Object[] array);
3227 bool LibraryCallKit::inline_arrayLayout() {
3228   RegionNode* region = new RegionNode(2);
3229   Node* phi = new PhiNode(region, TypeInt::POS);
3230 
3231   Node* array = argument(1);
3232   Node* klass_node = load_object_klass(array);
3233   generate_refArray_guard(klass_node, region);
3234   if (region->req() == 3) {
3235     phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3236   }
3237 
3238   int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3239   Node* layout_kind_addr = basic_plus_adr(klass_node, layout_kind_offset);
3240   Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3241 
3242   region->init_req(1, control());
3243   phi->init_req(1, layout_kind);
3244 
3245   set_control(_gvn.transform(region));
3246   set_result(_gvn.transform(phi));
3247   return true;
3248 }
3249 
3250 // private native int[] getFieldMap0(Class <?> c);
3251 //   int offset = c._klass._acmp_maps_offset;
3252 //   return (int[])c.obj_field(offset);
3253 bool LibraryCallKit::inline_getFieldMap() {
3254   Node* mirror = argument(1);
3255   Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
3256 
3257   int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
3258   Node* field_map_offset_addr = basic_plus_adr(klass, field_map_offset_offset);
3259   Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
3260   field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
3261 
3262   Node* map_addr = basic_plus_adr(mirror, field_map_offset);
3263   const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
3264   // TODO 8350865 Remove this
3265   val_type = val_type->cast_to_not_flat(true)->cast_to_not_null_free(true);
3266   Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
3267 
3268   set_result(map);
3269   return true;
3270 }
3271 
3272 bool LibraryCallKit::inline_onspinwait() {
3273   insert_mem_bar(Op_OnSpinWait);
3274   return true;
3275 }
3276 
3277 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3278   if (!kls->is_Con()) {
3279     return true;
3280   }
3281   const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3282   if (klsptr == nullptr) {
3283     return true;
3284   }
3285   ciInstanceKlass* ik = klsptr->instance_klass();
3286   // don't need a guard for a klass that is already initialized
3287   return !ik->is_initialized();
3288 }
3289 
3290 //----------------------------inline_unsafe_writeback0-------------------------
3291 // public native void Unsafe.writeback0(long address)
3292 bool LibraryCallKit::inline_unsafe_writeback0() {
3293   if (!Matcher::has_match_rule(Op_CacheWB)) {
3294     return false;
3295   }
3296 #ifndef PRODUCT
3297   assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3298   assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3299   ciSignature* sig = callee()->signature();
3300   assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3301 #endif
3302   null_check_receiver();  // null-check, then ignore
3303   Node *addr = argument(1);
3304   addr = new CastX2PNode(addr);
3305   addr = _gvn.transform(addr);
3306   Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3307   flush = _gvn.transform(flush);
3308   set_memory(flush, TypeRawPtr::BOTTOM);
3309   return true;
3310 }
3311 
3312 //----------------------------inline_unsafe_writeback0-------------------------
3313 // public native void Unsafe.writeback0(long address)
3314 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3315   if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3316     return false;
3317   }
3318   if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3319     return false;
3320   }
3321 #ifndef PRODUCT
3322   assert(Matcher::has_match_rule(Op_CacheWB),
3323          (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3324                 : "found match rule for CacheWBPostSync but not CacheWB"));
3325 
3326 #endif
3327   null_check_receiver();  // null-check, then ignore
3328   Node *sync;
3329   if (is_pre) {
3330     sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3331   } else {
3332     sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3333   }
3334   sync = _gvn.transform(sync);
3335   set_memory(sync, TypeRawPtr::BOTTOM);
3336   return true;
3337 }
3338 
3339 //----------------------------inline_unsafe_allocate---------------------------
3340 // public native Object Unsafe.allocateInstance(Class<?> cls);
3341 bool LibraryCallKit::inline_unsafe_allocate() {
3342 
3343 #if INCLUDE_JVMTI
3344   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3345     return false;
3346   }
3347 #endif //INCLUDE_JVMTI
3348 
3349   if (callee()->is_static())  return false;  // caller must have the capability!
3350 
3351   null_check_receiver();  // null-check, then ignore
3352   Node* cls = null_check(argument(1));
3353   if (stopped())  return true;
3354 
3355   Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3356   kls = null_check(kls);
3357   if (stopped())  return true;  // argument was like int.class
3358 
3359 #if INCLUDE_JVMTI
3360     // Don't try to access new allocated obj in the intrinsic.
3361     // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3362     // Deoptimize and allocate in interpreter instead.
3363     Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3364     Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3365     Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3366     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3367     {
3368       BuildCutout unless(this, tst, PROB_MAX);
3369       uncommon_trap(Deoptimization::Reason_intrinsic,
3370                     Deoptimization::Action_make_not_entrant);
3371     }
3372     if (stopped()) {
3373       return true;
3374     }
3375 #endif //INCLUDE_JVMTI
3376 
3377   Node* test = nullptr;
3378   if (LibraryCallKit::klass_needs_init_guard(kls)) {
3379     // Note:  The argument might still be an illegal value like
3380     // Serializable.class or Object[].class.   The runtime will handle it.
3381     // But we must make an explicit check for initialization.
3382     Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
3383     // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3384     // can generate code to load it as unsigned byte.
3385     Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3386     Node* bits = intcon(InstanceKlass::fully_initialized);
3387     test = _gvn.transform(new SubINode(inst, bits));
3388     // The 'test' is non-zero if we need to take a slow path.
3389   }
3390   Node* obj = nullptr;
3391   const TypeInstKlassPtr* tkls = _gvn.type(kls)->isa_instklassptr();
3392   if (tkls != nullptr && tkls->instance_klass()->is_inlinetype()) {
3393     obj = InlineTypeNode::make_all_zero(_gvn, tkls->instance_klass()->as_inline_klass())->buffer(this);
3394   } else {
3395     obj = new_instance(kls, test);
3396   }
3397   set_result(obj);
3398   return true;
3399 }
3400 
3401 //------------------------inline_native_time_funcs--------------
3402 // inline code for System.currentTimeMillis() and System.nanoTime()
3403 // these have the same type and signature
3404 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3405   const TypeFunc* tf = OptoRuntime::void_long_Type();
3406   const TypePtr* no_memory_effects = nullptr;
3407   Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3408   Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3409 #ifdef ASSERT
3410   Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3411   assert(value_top == top(), "second value must be top");
3412 #endif
3413   set_result(value);
3414   return true;
3415 }
3416 
3417 //--------------------inline_native_vthread_start_transition--------------------
3418 // inline void startTransition(boolean is_mount);
3419 // inline void startFinalTransition();
3420 // Pseudocode of implementation:
3421 //
3422 // java_lang_Thread::set_is_in_vthread_transition(vthread, true);
3423 // carrier->set_is_in_vthread_transition(true);
3424 // OrderAccess::storeload();
3425 // int disable_requests = java_lang_Thread::vthread_transition_disable_count(vthread)
3426 //                        + global_vthread_transition_disable_count();
3427 // if (disable_requests > 0) {
3428 //   slow path: runtime call
3429 // }
3430 bool LibraryCallKit::inline_native_vthread_start_transition(address funcAddr, const char* funcName, bool is_final_transition) {
3431   Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3432   IdealKit ideal(this);
3433 
3434   Node* thread = ideal.thread();
3435   Node* jt_addr = basic_plus_adr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3436   Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3437   access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3438   access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3439   insert_mem_bar(Op_MemBarVolatile);
3440   ideal.sync_kit(this);
3441 
3442   Node* global_disable_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::global_vthread_transition_disable_count_address()));
3443   Node* global_disable = ideal.load(ideal.ctrl(), global_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3444   Node* vt_disable_addr = basic_plus_adr(vt_oop, java_lang_Thread::vthread_transition_disable_count_offset());
3445   Node* vt_disable = ideal.load(ideal.ctrl(), vt_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3446   Node* disabled = _gvn.transform(new AddINode(global_disable, vt_disable));
3447 
3448   ideal.if_then(disabled, BoolTest::ne, ideal.ConI(0)); {
3449     sync_kit(ideal);
3450     Node* is_mount = is_final_transition ? ideal.ConI(0) : _gvn.transform(argument(1));
3451     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3452     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3453     ideal.sync_kit(this);
3454   }
3455   ideal.end_if();
3456 
3457   final_sync(ideal);
3458   return true;
3459 }
3460 
3461 bool LibraryCallKit::inline_native_vthread_end_transition(address funcAddr, const char* funcName, bool is_first_transition) {
3462   Node* vt_oop = _gvn.transform(must_be_not_null(argument(0), true)); // VirtualThread this argument
3463   IdealKit ideal(this);
3464 
3465   Node* _notify_jvmti_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::notify_jvmti_events_address()));
3466   Node* _notify_jvmti = ideal.load(ideal.ctrl(), _notify_jvmti_addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3467 
3468   ideal.if_then(_notify_jvmti, BoolTest::eq, ideal.ConI(1)); {
3469     sync_kit(ideal);
3470     Node* is_mount = is_first_transition ? ideal.ConI(1) : _gvn.transform(argument(1));
3471     const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3472     make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3473     ideal.sync_kit(this);
3474   } ideal.else_(); {
3475     Node* thread = ideal.thread();
3476     Node* jt_addr = basic_plus_adr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3477     Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3478 
3479     sync_kit(ideal);
3480     access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3481     access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3482     ideal.sync_kit(this);
3483   } ideal.end_if();
3484 
3485   final_sync(ideal);
3486   return true;
3487 }
3488 
3489 #if INCLUDE_JVMTI
3490 
3491 // Always update the is_disable_suspend bit.
3492 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3493   if (!DoJVMTIVirtualThreadTransitions) {
3494     return true;
3495   }
3496   IdealKit ideal(this);
3497 
3498   {
3499     // unconditionally update the is_disable_suspend bit in current JavaThread
3500     Node* thread = ideal.thread();
3501     Node* arg = _gvn.transform(argument(0)); // argument for notification
3502     Node* addr = basic_plus_adr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3503     const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3504 
3505     sync_kit(ideal);
3506     access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3507     ideal.sync_kit(this);
3508   }
3509   final_sync(ideal);
3510 
3511   return true;
3512 }
3513 
3514 #endif // INCLUDE_JVMTI
3515 
3516 #ifdef JFR_HAVE_INTRINSICS
3517 
3518 /**
3519  * if oop->klass != null
3520  *   // normal class
3521  *   epoch = _epoch_state ? 2 : 1
3522  *   if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3523  *     ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3524  *   }
3525  *   id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3526  * else
3527  *   // primitive class
3528  *   if oop->array_klass != null
3529  *     id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3530  *   else
3531  *     id = LAST_TYPE_ID + 1 // void class path
3532  *   if (!signaled)
3533  *     signaled = true
3534  */
3535 bool LibraryCallKit::inline_native_classID() {
3536   Node* cls = argument(0);
3537 
3538   IdealKit ideal(this);
3539 #define __ ideal.
3540   IdealVariable result(ideal); __ declarations_done();
3541   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3542                                                  basic_plus_adr(cls, java_lang_Class::klass_offset()),
3543                                                  TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3544 
3545 
3546   __ if_then(kls, BoolTest::ne, null()); {
3547     Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3548     Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3549 
3550     Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3551     Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3552     epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3553     Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3554     mask = _gvn.transform(new OrLNode(mask, epoch));
3555     Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3556 
3557     float unlikely  = PROB_UNLIKELY(0.999);
3558     __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3559       sync_kit(ideal);
3560       make_runtime_call(RC_LEAF,
3561                         OptoRuntime::class_id_load_barrier_Type(),
3562                         CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3563                         "class id load barrier",
3564                         TypePtr::BOTTOM,
3565                         kls);
3566       ideal.sync_kit(this);
3567     } __ end_if();
3568 
3569     ideal.set(result,  _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3570   } __ else_(); {
3571     Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3572                                                    basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3573                                                    TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3574     __ if_then(array_kls, BoolTest::ne, null()); {
3575       Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3576       Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3577       Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3578       ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3579     } __ else_(); {
3580       // void class case
3581       ideal.set(result, _gvn.transform(longcon(LAST_TYPE_ID + 1)));
3582     } __ end_if();
3583 
3584     Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3585     Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3586     __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3587       ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3588     } __ end_if();
3589   } __ end_if();
3590 
3591   final_sync(ideal);
3592   set_result(ideal.value(result));
3593 #undef __
3594   return true;
3595 }
3596 
3597 //------------------------inline_native_jvm_commit------------------
3598 bool LibraryCallKit::inline_native_jvm_commit() {
3599   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3600 
3601   // Save input memory and i_o state.
3602   Node* input_memory_state = reset_memory();
3603   set_all_memory(input_memory_state);
3604   Node* input_io_state = i_o();
3605 
3606   // TLS.
3607   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3608   // Jfr java buffer.
3609   Node* java_buffer_offset = _gvn.transform(new AddPNode(top(), tls_ptr, _gvn.transform(MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR)))));
3610   Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3611   Node* java_buffer_pos_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET)))));
3612 
3613   // Load the current value of the notified field in the JfrThreadLocal.
3614   Node* notified_offset = basic_plus_adr(top(), tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3615   Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3616 
3617   // Test for notification.
3618   Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3619   Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3620   IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3621 
3622   // True branch, is notified.
3623   Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3624   set_control(is_notified);
3625 
3626   // Reset notified state.
3627   store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3628   Node* notified_reset_memory = reset_memory();
3629 
3630   // 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.
3631   Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3632   // Convert the machine-word to a long.
3633   Node* current_pos = _gvn.transform(ConvX2L(current_pos_X));
3634 
3635   // False branch, not notified.
3636   Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3637   set_control(not_notified);
3638   set_all_memory(input_memory_state);
3639 
3640   // Arg is the next position as a long.
3641   Node* arg = argument(0);
3642   // Convert long to machine-word.
3643   Node* next_pos_X = _gvn.transform(ConvL2X(arg));
3644 
3645   // Store the next_position to the underlying jfr java buffer.
3646   store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3647 
3648   Node* commit_memory = reset_memory();
3649   set_all_memory(commit_memory);
3650 
3651   // 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.
3652   Node* java_buffer_flags_offset = _gvn.transform(new AddPNode(top(), java_buffer, _gvn.transform(MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET)))));
3653   Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3654   Node* lease_constant = _gvn.transform(_gvn.intcon(4));
3655 
3656   // And flags with lease constant.
3657   Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3658 
3659   // Branch on lease to conditionalize returning the leased java buffer.
3660   Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3661   Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3662   IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3663 
3664   // False branch, not a lease.
3665   Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3666 
3667   // True branch, is lease.
3668   Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3669   set_control(is_lease);
3670 
3671   // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3672   Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3673                                               OptoRuntime::void_void_Type(),
3674                                               SharedRuntime::jfr_return_lease(),
3675                                               "return_lease", TypePtr::BOTTOM);
3676   Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3677 
3678   RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3679   record_for_igvn(lease_compare_rgn);
3680   PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3681   record_for_igvn(lease_compare_mem);
3682   PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3683   record_for_igvn(lease_compare_io);
3684   PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3685   record_for_igvn(lease_result_value);
3686 
3687   // Update control and phi nodes.
3688   lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3689   lease_compare_rgn->init_req(_false_path, not_lease);
3690 
3691   lease_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3692   lease_compare_mem->init_req(_false_path, commit_memory);
3693 
3694   lease_compare_io->init_req(_true_path, i_o());
3695   lease_compare_io->init_req(_false_path, input_io_state);
3696 
3697   lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3698   lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3699 
3700   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3701   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3702   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3703   PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3704 
3705   // Update control and phi nodes.
3706   result_rgn->init_req(_true_path, is_notified);
3707   result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3708 
3709   result_mem->init_req(_true_path, notified_reset_memory);
3710   result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3711 
3712   result_io->init_req(_true_path, input_io_state);
3713   result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3714 
3715   result_value->init_req(_true_path, current_pos);
3716   result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3717 
3718   // Set output state.
3719   set_control(_gvn.transform(result_rgn));
3720   set_all_memory(_gvn.transform(result_mem));
3721   set_i_o(_gvn.transform(result_io));
3722   set_result(result_rgn, result_value);
3723   return true;
3724 }
3725 
3726 /*
3727  * The intrinsic is a model of this pseudo-code:
3728  *
3729  * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3730  * jobject h_event_writer = tl->java_event_writer();
3731  * if (h_event_writer == nullptr) {
3732  *   return nullptr;
3733  * }
3734  * oop threadObj = Thread::threadObj();
3735  * oop vthread = java_lang_Thread::vthread(threadObj);
3736  * traceid tid;
3737  * bool pinVirtualThread;
3738  * bool excluded;
3739  * if (vthread != threadObj) {  // i.e. current thread is virtual
3740  *   tid = java_lang_Thread::tid(vthread);
3741  *   u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3742  *   pinVirtualThread = VMContinuations;
3743  *   excluded = vthread_epoch_raw & excluded_mask;
3744  *   if (!excluded) {
3745  *     traceid current_epoch = JfrTraceIdEpoch::current_generation();
3746  *     u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3747  *     if (vthread_epoch != current_epoch) {
3748  *       write_checkpoint();
3749  *     }
3750  *   }
3751  * } else {
3752  *   tid = java_lang_Thread::tid(threadObj);
3753  *   u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3754  *   pinVirtualThread = false;
3755  *   excluded = thread_epoch_raw & excluded_mask;
3756  * }
3757  * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3758  * traceid tid_in_event_writer = getField(event_writer, "threadID");
3759  * if (tid_in_event_writer != tid) {
3760  *   setField(event_writer, "pinVirtualThread", pinVirtualThread);
3761  *   setField(event_writer, "excluded", excluded);
3762  *   setField(event_writer, "threadID", tid);
3763  * }
3764  * return event_writer
3765  */
3766 bool LibraryCallKit::inline_native_getEventWriter() {
3767   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3768 
3769   // Save input memory and i_o state.
3770   Node* input_memory_state = reset_memory();
3771   set_all_memory(input_memory_state);
3772   Node* input_io_state = i_o();
3773 
3774   // The most significant bit of the u2 is used to denote thread exclusion
3775   Node* excluded_shift = _gvn.intcon(15);
3776   Node* excluded_mask = _gvn.intcon(1 << 15);
3777   // The epoch generation is the range [1-32767]
3778   Node* epoch_mask = _gvn.intcon(32767);
3779 
3780   // TLS
3781   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3782 
3783   // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3784   Node* jobj_ptr = basic_plus_adr(top(), tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3785 
3786   // Load the eventwriter jobject handle.
3787   Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3788 
3789   // Null check the jobject handle.
3790   Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3791   Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3792   IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3793 
3794   // False path, jobj is null.
3795   Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3796 
3797   // True path, jobj is not null.
3798   Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3799 
3800   set_control(jobj_is_not_null);
3801 
3802   // Load the threadObj for the CarrierThread.
3803   Node* threadObj = generate_current_thread(tls_ptr);
3804 
3805   // Load the vthread.
3806   Node* vthread = generate_virtual_thread(tls_ptr);
3807 
3808   // If vthread != threadObj, this is a virtual thread.
3809   Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3810   Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3811   IfNode* iff_vthread_not_equal_threadObj =
3812     create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3813 
3814   // False branch, fallback to threadObj.
3815   Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3816   set_control(vthread_equal_threadObj);
3817 
3818   // Load the tid field from the vthread object.
3819   Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3820 
3821   // Load the raw epoch value from the threadObj.
3822   Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3823   Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3824                                              _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3825                                              TypeInt::CHAR, T_CHAR,
3826                                              IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3827 
3828   // Mask off the excluded information from the epoch.
3829   Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3830 
3831   // True branch, this is a virtual thread.
3832   Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3833   set_control(vthread_not_equal_threadObj);
3834 
3835   // Load the tid field from the vthread object.
3836   Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3837 
3838   // Continuation support determines if a virtual thread should be pinned.
3839   Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3840   Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3841 
3842   // Load the raw epoch value from the vthread.
3843   Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3844   Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3845                                            TypeInt::CHAR, T_CHAR,
3846                                            IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3847 
3848   // Mask off the excluded information from the epoch.
3849   Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(excluded_mask)));
3850 
3851   // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3852   Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, _gvn.transform(excluded_mask)));
3853   Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3854   IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3855 
3856   // False branch, vthread is excluded, no need to write epoch info.
3857   Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3858 
3859   // True branch, vthread is included, update epoch info.
3860   Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3861   set_control(included);
3862 
3863   // Get epoch value.
3864   Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, _gvn.transform(epoch_mask)));
3865 
3866   // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3867   Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3868   Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3869 
3870   // Compare the epoch in the vthread to the current epoch generation.
3871   Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3872   Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3873   IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3874 
3875   // False path, epoch is equal, checkpoint information is valid.
3876   Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3877 
3878   // True path, epoch is not equal, write a checkpoint for the vthread.
3879   Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3880 
3881   set_control(epoch_is_not_equal);
3882 
3883   // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3884   // The call also updates the native thread local thread id and the vthread with the current epoch.
3885   Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3886                                                   OptoRuntime::jfr_write_checkpoint_Type(),
3887                                                   SharedRuntime::jfr_write_checkpoint(),
3888                                                   "write_checkpoint", TypePtr::BOTTOM);
3889   Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3890 
3891   // vthread epoch != current epoch
3892   RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3893   record_for_igvn(epoch_compare_rgn);
3894   PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3895   record_for_igvn(epoch_compare_mem);
3896   PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3897   record_for_igvn(epoch_compare_io);
3898 
3899   // Update control and phi nodes.
3900   epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3901   epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3902   epoch_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
3903   epoch_compare_mem->init_req(_false_path, input_memory_state);
3904   epoch_compare_io->init_req(_true_path, i_o());
3905   epoch_compare_io->init_req(_false_path, input_io_state);
3906 
3907   // excluded != true
3908   RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3909   record_for_igvn(exclude_compare_rgn);
3910   PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3911   record_for_igvn(exclude_compare_mem);
3912   PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3913   record_for_igvn(exclude_compare_io);
3914 
3915   // Update control and phi nodes.
3916   exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3917   exclude_compare_rgn->init_req(_false_path, excluded);
3918   exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3919   exclude_compare_mem->init_req(_false_path, input_memory_state);
3920   exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3921   exclude_compare_io->init_req(_false_path, input_io_state);
3922 
3923   // vthread != threadObj
3924   RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3925   record_for_igvn(vthread_compare_rgn);
3926   PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3927   PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3928   record_for_igvn(vthread_compare_io);
3929   PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3930   record_for_igvn(tid);
3931   PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3932   record_for_igvn(exclusion);
3933   PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
3934   record_for_igvn(pinVirtualThread);
3935 
3936   // Update control and phi nodes.
3937   vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
3938   vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
3939   vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
3940   vthread_compare_mem->init_req(_false_path, input_memory_state);
3941   vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
3942   vthread_compare_io->init_req(_false_path, input_io_state);
3943   tid->init_req(_true_path, _gvn.transform(vthread_tid));
3944   tid->init_req(_false_path, _gvn.transform(thread_obj_tid));
3945   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
3946   exclusion->init_req(_false_path, _gvn.transform(threadObj_is_excluded));
3947   pinVirtualThread->init_req(_true_path, _gvn.transform(continuation_support));
3948   pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
3949 
3950   // Update branch state.
3951   set_control(_gvn.transform(vthread_compare_rgn));
3952   set_all_memory(_gvn.transform(vthread_compare_mem));
3953   set_i_o(_gvn.transform(vthread_compare_io));
3954 
3955   // Load the event writer oop by dereferencing the jobject handle.
3956   ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
3957   assert(klass_EventWriter->is_loaded(), "invariant");
3958   ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
3959   const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
3960   const TypeOopPtr* const xtype = aklass->as_instance_type();
3961   Node* jobj_untagged = _gvn.transform(new AddPNode(top(), jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
3962   Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3963 
3964   // Load the current thread id from the event writer object.
3965   Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
3966   // Get the field offset to, conditionally, store an updated tid value later.
3967   Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
3968   // Get the field offset to, conditionally, store an updated exclusion value later.
3969   Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
3970   // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
3971   Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
3972 
3973   RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
3974   record_for_igvn(event_writer_tid_compare_rgn);
3975   PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3976   record_for_igvn(event_writer_tid_compare_mem);
3977   PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
3978   record_for_igvn(event_writer_tid_compare_io);
3979 
3980   // Compare the current tid from the thread object to what is currently stored in the event writer object.
3981   Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
3982   Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
3983   IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3984 
3985   // False path, tids are the same.
3986   Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
3987 
3988   // True path, tid is not equal, need to update the tid in the event writer.
3989   Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
3990   record_for_igvn(tid_is_not_equal);
3991 
3992   // Store the pin state to the event writer.
3993   store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
3994 
3995   // Store the exclusion state to the event writer.
3996   Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
3997   store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
3998 
3999   // Store the tid to the event writer.
4000   store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
4001 
4002   // Update control and phi nodes.
4003   event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
4004   event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
4005   event_writer_tid_compare_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4006   event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
4007   event_writer_tid_compare_io->init_req(_true_path, _gvn.transform(i_o()));
4008   event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
4009 
4010   // Result of top level CFG, Memory, IO and Value.
4011   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4012   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4013   PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
4014   PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
4015 
4016   // Result control.
4017   result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
4018   result_rgn->init_req(_false_path, jobj_is_null);
4019 
4020   // Result memory.
4021   result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
4022   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4023 
4024   // Result IO.
4025   result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
4026   result_io->init_req(_false_path, _gvn.transform(input_io_state));
4027 
4028   // Result value.
4029   result_value->init_req(_true_path, _gvn.transform(event_writer)); // return event writer oop
4030   result_value->init_req(_false_path, null()); // return null
4031 
4032   // Set output state.
4033   set_control(_gvn.transform(result_rgn));
4034   set_all_memory(_gvn.transform(result_mem));
4035   set_i_o(_gvn.transform(result_io));
4036   set_result(result_rgn, result_value);
4037   return true;
4038 }
4039 
4040 /*
4041  * The intrinsic is a model of this pseudo-code:
4042  *
4043  * JfrThreadLocal* const tl = thread->jfr_thread_local();
4044  * if (carrierThread != thread) { // is virtual thread
4045  *   const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
4046  *   bool excluded = vthread_epoch_raw & excluded_mask;
4047  *   AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
4048  *   AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
4049  *   if (!excluded) {
4050  *     const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
4051  *     AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
4052  *   }
4053  *   AtomicAccess::release_store(&tl->_vthread, true);
4054  *   return;
4055  * }
4056  * AtomicAccess::release_store(&tl->_vthread, false);
4057  */
4058 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
4059   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4060 
4061   Node* input_memory_state = reset_memory();
4062   set_all_memory(input_memory_state);
4063 
4064   // The most significant bit of the u2 is used to denote thread exclusion
4065   Node* excluded_mask = _gvn.intcon(1 << 15);
4066   // The epoch generation is the range [1-32767]
4067   Node* epoch_mask = _gvn.intcon(32767);
4068 
4069   Node* const carrierThread = generate_current_thread(jt);
4070   // If thread != carrierThread, this is a virtual thread.
4071   Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
4072   Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
4073   IfNode* iff_thread_not_equal_carrierThread =
4074     create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
4075 
4076   Node* vthread_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
4077 
4078   // False branch, is carrierThread.
4079   Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
4080   // Store release
4081   Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
4082 
4083   set_all_memory(input_memory_state);
4084 
4085   // True branch, is virtual thread.
4086   Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
4087   set_control(thread_not_equal_carrierThread);
4088 
4089   // Load the raw epoch value from the vthread.
4090   Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
4091   Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
4092                                    IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
4093 
4094   // Mask off the excluded information from the epoch.
4095   Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(excluded_mask)));
4096 
4097   // Load the tid field from the thread.
4098   Node* tid = load_field_from_object(thread, "tid", "J");
4099 
4100   // Store the vthread tid to the jfr thread local.
4101   Node* thread_id_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
4102   Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
4103 
4104   // Branch is_excluded to conditionalize updating the epoch .
4105   Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, _gvn.transform(excluded_mask)));
4106   Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
4107   IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
4108 
4109   // True branch, vthread is excluded, no need to write epoch info.
4110   Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
4111   set_control(excluded);
4112   Node* vthread_is_excluded = _gvn.intcon(1);
4113 
4114   // False branch, vthread is included, update epoch info.
4115   Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
4116   set_control(included);
4117   Node* vthread_is_included = _gvn.intcon(0);
4118 
4119   // Get epoch value.
4120   Node* epoch = _gvn.transform(new AndINode(epoch_raw, _gvn.transform(epoch_mask)));
4121 
4122   // Store the vthread epoch to the jfr thread local.
4123   Node* vthread_epoch_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
4124   Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
4125 
4126   RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
4127   record_for_igvn(excluded_rgn);
4128   PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
4129   record_for_igvn(excluded_mem);
4130   PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
4131   record_for_igvn(exclusion);
4132 
4133   // Merge the excluded control and memory.
4134   excluded_rgn->init_req(_true_path, excluded);
4135   excluded_rgn->init_req(_false_path, included);
4136   excluded_mem->init_req(_true_path, tid_memory);
4137   excluded_mem->init_req(_false_path, included_memory);
4138   exclusion->init_req(_true_path, _gvn.transform(vthread_is_excluded));
4139   exclusion->init_req(_false_path, _gvn.transform(vthread_is_included));
4140 
4141   // Set intermediate state.
4142   set_control(_gvn.transform(excluded_rgn));
4143   set_all_memory(excluded_mem);
4144 
4145   // Store the vthread exclusion state to the jfr thread local.
4146   Node* thread_local_excluded_offset = basic_plus_adr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
4147   store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
4148 
4149   // Store release
4150   Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
4151 
4152   RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
4153   record_for_igvn(thread_compare_rgn);
4154   PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4155   record_for_igvn(thread_compare_mem);
4156   PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
4157   record_for_igvn(vthread);
4158 
4159   // Merge the thread_compare control and memory.
4160   thread_compare_rgn->init_req(_true_path, control());
4161   thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
4162   thread_compare_mem->init_req(_true_path, vthread_true_memory);
4163   thread_compare_mem->init_req(_false_path, vthread_false_memory);
4164 
4165   // Set output state.
4166   set_control(_gvn.transform(thread_compare_rgn));
4167   set_all_memory(_gvn.transform(thread_compare_mem));
4168 }
4169 
4170 #endif // JFR_HAVE_INTRINSICS
4171 
4172 //------------------------inline_native_currentCarrierThread------------------
4173 bool LibraryCallKit::inline_native_currentCarrierThread() {
4174   Node* junk = nullptr;
4175   set_result(generate_current_thread(junk));
4176   return true;
4177 }
4178 
4179 //------------------------inline_native_currentThread------------------
4180 bool LibraryCallKit::inline_native_currentThread() {
4181   Node* junk = nullptr;
4182   set_result(generate_virtual_thread(junk));
4183   return true;
4184 }
4185 
4186 //------------------------inline_native_setVthread------------------
4187 bool LibraryCallKit::inline_native_setCurrentThread() {
4188   assert(C->method()->changes_current_thread(),
4189          "method changes current Thread but is not annotated ChangesCurrentThread");
4190   Node* arr = argument(1);
4191   Node* thread = _gvn.transform(new ThreadLocalNode());
4192   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::vthread_offset()));
4193   Node* thread_obj_handle
4194     = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4195   thread_obj_handle = _gvn.transform(thread_obj_handle);
4196   const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4197   access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4198 
4199   // Change the _monitor_owner_id of the JavaThread
4200   Node* tid = load_field_from_object(arr, "tid", "J");
4201   Node* monitor_owner_id_offset = basic_plus_adr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4202   store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4203 
4204   JFR_ONLY(extend_setCurrentThread(thread, arr);)
4205   return true;
4206 }
4207 
4208 const Type* LibraryCallKit::scopedValueCache_type() {
4209   ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4210   const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4211   const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
4212 
4213   // Because we create the scopedValue cache lazily we have to make the
4214   // type of the result BotPTR.
4215   bool xk = etype->klass_is_exact();
4216   const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4217   return objects_type;
4218 }
4219 
4220 Node* LibraryCallKit::scopedValueCache_helper() {
4221   Node* thread = _gvn.transform(new ThreadLocalNode());
4222   Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::scopedValueCache_offset()));
4223   // We cannot use immutable_memory() because we might flip onto a
4224   // different carrier thread, at which point we'll need to use that
4225   // carrier thread's cache.
4226   // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4227   //       TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4228   return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4229 }
4230 
4231 //------------------------inline_native_scopedValueCache------------------
4232 bool LibraryCallKit::inline_native_scopedValueCache() {
4233   Node* cache_obj_handle = scopedValueCache_helper();
4234   const Type* objects_type = scopedValueCache_type();
4235   set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4236 
4237   return true;
4238 }
4239 
4240 //------------------------inline_native_setScopedValueCache------------------
4241 bool LibraryCallKit::inline_native_setScopedValueCache() {
4242   Node* arr = argument(0);
4243   Node* cache_obj_handle = scopedValueCache_helper();
4244   const Type* objects_type = scopedValueCache_type();
4245 
4246   const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4247   access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4248 
4249   return true;
4250 }
4251 
4252 //------------------------inline_native_Continuation_pin and unpin-----------
4253 
4254 // Shared implementation routine for both pin and unpin.
4255 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4256   enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4257 
4258   // Save input memory.
4259   Node* input_memory_state = reset_memory();
4260   set_all_memory(input_memory_state);
4261 
4262   // TLS
4263   Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4264   Node* last_continuation_offset = basic_plus_adr(top(), tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4265   Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4266 
4267   // Null check the last continuation object.
4268   Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4269   Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4270   IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4271 
4272   // False path, last continuation is null.
4273   Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4274 
4275   // True path, last continuation is not null.
4276   Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4277 
4278   set_control(continuation_is_not_null);
4279 
4280   // Load the pin count from the last continuation.
4281   Node* pin_count_offset = basic_plus_adr(top(), last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4282   Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4283 
4284   // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4285   Node* pin_count_rhs;
4286   if (unpin) {
4287     pin_count_rhs = _gvn.intcon(0);
4288   } else {
4289     pin_count_rhs = _gvn.intcon(UINT32_MAX);
4290   }
4291   Node* pin_count_cmp = _gvn.transform(new CmpUNode(_gvn.transform(pin_count), pin_count_rhs));
4292   Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4293   IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4294 
4295   // True branch, pin count over/underflow.
4296   Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4297   {
4298     // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4299     // which will throw IllegalStateException for pin count over/underflow.
4300     // No memory changed so far - we can use memory create by reset_memory()
4301     // at the beginning of this intrinsic. No need to call reset_memory() again.
4302     PreserveJVMState pjvms(this);
4303     set_control(pin_count_over_underflow);
4304     uncommon_trap(Deoptimization::Reason_intrinsic,
4305                   Deoptimization::Action_none);
4306     assert(stopped(), "invariant");
4307   }
4308 
4309   // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4310   Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4311   set_control(valid_pin_count);
4312 
4313   Node* next_pin_count;
4314   if (unpin) {
4315     next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4316   } else {
4317     next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4318   }
4319 
4320   store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4321 
4322   // Result of top level CFG and Memory.
4323   RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4324   record_for_igvn(result_rgn);
4325   PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4326   record_for_igvn(result_mem);
4327 
4328   result_rgn->init_req(_true_path, _gvn.transform(valid_pin_count));
4329   result_rgn->init_req(_false_path, _gvn.transform(continuation_is_null));
4330   result_mem->init_req(_true_path, _gvn.transform(reset_memory()));
4331   result_mem->init_req(_false_path, _gvn.transform(input_memory_state));
4332 
4333   // Set output state.
4334   set_control(_gvn.transform(result_rgn));
4335   set_all_memory(_gvn.transform(result_mem));
4336 
4337   return true;
4338 }
4339 
4340 //---------------------------load_mirror_from_klass----------------------------
4341 // Given a klass oop, load its java mirror (a java.lang.Class oop).
4342 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
4343   Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
4344   Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4345   // mirror = ((OopHandle)mirror)->resolve();
4346   return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4347 }
4348 
4349 //-----------------------load_klass_from_mirror_common-------------------------
4350 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4351 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4352 // and branch to the given path on the region.
4353 // If never_see_null, take an uncommon trap on null, so we can optimistically
4354 // compile for the non-null case.
4355 // If the region is null, force never_see_null = true.
4356 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4357                                                     bool never_see_null,
4358                                                     RegionNode* region,
4359                                                     int null_path,
4360                                                     int offset) {
4361   if (region == nullptr)  never_see_null = true;
4362   Node* p = basic_plus_adr(mirror, offset);
4363   const TypeKlassPtr*  kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4364   Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4365   Node* null_ctl = top();
4366   kls = null_check_oop(kls, &null_ctl, never_see_null);
4367   if (region != nullptr) {
4368     // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4369     region->init_req(null_path, null_ctl);
4370   } else {
4371     assert(null_ctl == top(), "no loose ends");
4372   }
4373   return kls;
4374 }
4375 
4376 //--------------------(inline_native_Class_query helpers)---------------------
4377 // Use this for JVM_ACC_INTERFACE.
4378 // Fall through if (mods & mask) == bits, take the guard otherwise.
4379 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4380                                                  ByteSize offset, const Type* type, BasicType bt) {
4381   // Branch around if the given klass has the given modifier bit set.
4382   // Like generate_guard, adds a new path onto the region.
4383   Node* modp = basic_plus_adr(kls, in_bytes(offset));
4384   Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4385   Node* mask = intcon(modifier_mask);
4386   Node* bits = intcon(modifier_bits);
4387   Node* mbit = _gvn.transform(new AndINode(mods, mask));
4388   Node* cmp  = _gvn.transform(new CmpINode(mbit, bits));
4389   Node* bol  = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4390   return generate_fair_guard(bol, region);
4391 }
4392 
4393 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4394   return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4395                                     InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4396 }
4397 
4398 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4399 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4400   return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4401                                     Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4402 }
4403 
4404 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4405   return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4406 }
4407 
4408 //-------------------------inline_native_Class_query-------------------
4409 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4410   const Type* return_type = TypeInt::BOOL;
4411   Node* prim_return_value = top();  // what happens if it's a primitive class?
4412   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4413   bool expect_prim = false;     // most of these guys expect to work on refs
4414 
4415   enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4416 
4417   Node* mirror = argument(0);
4418   Node* obj    = top();
4419 
4420   switch (id) {
4421   case vmIntrinsics::_isInstance:
4422     // nothing is an instance of a primitive type
4423     prim_return_value = intcon(0);
4424     obj = argument(1);
4425     break;
4426   case vmIntrinsics::_isHidden:
4427     prim_return_value = intcon(0);
4428     break;
4429   case vmIntrinsics::_getSuperclass:
4430     prim_return_value = null();
4431     return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4432     break;
4433   default:
4434     fatal_unexpected_iid(id);
4435     break;
4436   }
4437 
4438   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4439   if (mirror_con == nullptr)  return false;  // cannot happen?
4440 
4441 #ifndef PRODUCT
4442   if (C->print_intrinsics() || C->print_inlining()) {
4443     ciType* k = mirror_con->java_mirror_type();
4444     if (k) {
4445       tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4446       k->print_name();
4447       tty->cr();
4448     }
4449   }
4450 #endif
4451 
4452   // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4453   RegionNode* region = new RegionNode(PATH_LIMIT);
4454   record_for_igvn(region);
4455   PhiNode* phi = new PhiNode(region, return_type);
4456 
4457   // The mirror will never be null of Reflection.getClassAccessFlags, however
4458   // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4459   // if it is. See bug 4774291.
4460 
4461   // For Reflection.getClassAccessFlags(), the null check occurs in
4462   // the wrong place; see inline_unsafe_access(), above, for a similar
4463   // situation.
4464   mirror = null_check(mirror);
4465   // If mirror or obj is dead, only null-path is taken.
4466   if (stopped())  return true;
4467 
4468   if (expect_prim)  never_see_null = false;  // expect nulls (meaning prims)
4469 
4470   // Now load the mirror's klass metaobject, and null-check it.
4471   // Side-effects region with the control path if the klass is null.
4472   Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4473   // If kls is null, we have a primitive mirror.
4474   phi->init_req(_prim_path, prim_return_value);
4475   if (stopped()) { set_result(region, phi); return true; }
4476   bool safe_for_replace = (region->in(_prim_path) == top());
4477 
4478   Node* p;  // handy temp
4479   Node* null_ctl;
4480 
4481   // Now that we have the non-null klass, we can perform the real query.
4482   // For constant classes, the query will constant-fold in LoadNode::Value.
4483   Node* query_value = top();
4484   switch (id) {
4485   case vmIntrinsics::_isInstance:
4486     // nothing is an instance of a primitive type
4487     query_value = gen_instanceof(obj, kls, safe_for_replace);
4488     break;
4489 
4490   case vmIntrinsics::_isHidden:
4491     // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4492     if (generate_hidden_class_guard(kls, region) != nullptr)
4493       // A guard was added.  If the guard is taken, it was an hidden class.
4494       phi->add_req(intcon(1));
4495     // If we fall through, it's a plain class.
4496     query_value = intcon(0);
4497     break;
4498 
4499 
4500   case vmIntrinsics::_getSuperclass:
4501     // The rules here are somewhat unfortunate, but we can still do better
4502     // with random logic than with a JNI call.
4503     // Interfaces store null or Object as _super, but must report null.
4504     // Arrays store an intermediate super as _super, but must report Object.
4505     // Other types can report the actual _super.
4506     // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4507     if (generate_array_guard(kls, region) != nullptr) {
4508       // A guard was added.  If the guard is taken, it was an array.
4509       phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4510     }
4511     // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4512     // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4513     if (generate_interface_guard(kls, region) != nullptr) {
4514       // A guard was added.  If the guard is taken, it was an interface.
4515       phi->add_req(null());
4516     }
4517     // If we fall through, it's a plain class.  Get its _super.
4518     if (!stopped()) {
4519       p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
4520       kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4521       null_ctl = top();
4522       kls = null_check_oop(kls, &null_ctl);
4523       if (null_ctl != top()) {
4524         // If the guard is taken, Object.superClass is null (both klass and mirror).
4525         region->add_req(null_ctl);
4526         phi   ->add_req(null());
4527       }
4528       if (!stopped()) {
4529         query_value = load_mirror_from_klass(kls);
4530       }
4531     }
4532     break;
4533 
4534   default:
4535     fatal_unexpected_iid(id);
4536     break;
4537   }
4538 
4539   // Fall-through is the normal case of a query to a real class.
4540   phi->init_req(1, query_value);
4541   region->init_req(1, control());
4542 
4543   C->set_has_split_ifs(true); // Has chance for split-if optimization
4544   set_result(region, phi);
4545   return true;
4546 }
4547 
4548 
4549 //-------------------------inline_Class_cast-------------------
4550 bool LibraryCallKit::inline_Class_cast() {
4551   Node* mirror = argument(0); // Class
4552   Node* obj    = argument(1);
4553   const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4554   if (mirror_con == nullptr) {
4555     return false;  // dead path (mirror->is_top()).
4556   }
4557   if (obj == nullptr || obj->is_top()) {
4558     return false;  // dead path
4559   }
4560   const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4561 
4562   // First, see if Class.cast() can be folded statically.
4563   // java_mirror_type() returns non-null for compile-time Class constants.
4564   ciType* tm = mirror_con->java_mirror_type();
4565   if (tm != nullptr && tm->is_klass() &&
4566       tp != nullptr) {
4567     if (!tp->is_loaded()) {
4568       // Don't use intrinsic when class is not loaded.
4569       return false;
4570     } else {
4571       const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4572       int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4573       if (static_res == Compile::SSC_always_true) {
4574         // isInstance() is true - fold the code.
4575         set_result(obj);
4576         return true;
4577       } else if (static_res == Compile::SSC_always_false) {
4578         // Don't use intrinsic, have to throw ClassCastException.
4579         // If the reference is null, the non-intrinsic bytecode will
4580         // be optimized appropriately.
4581         return false;
4582       }
4583     }
4584   }
4585 
4586   // Bailout intrinsic and do normal inlining if exception path is frequent.
4587   if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4588     return false;
4589   }
4590 
4591   // Generate dynamic checks.
4592   // Class.cast() is java implementation of _checkcast bytecode.
4593   // Do checkcast (Parse::do_checkcast()) optimizations here.
4594 
4595   mirror = null_check(mirror);
4596   // If mirror is dead, only null-path is taken.
4597   if (stopped()) {
4598     return true;
4599   }
4600 
4601   // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4602   enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4603   RegionNode* region = new RegionNode(PATH_LIMIT);
4604   record_for_igvn(region);
4605 
4606   // Now load the mirror's klass metaobject, and null-check it.
4607   // If kls is null, we have a primitive mirror and
4608   // nothing is an instance of a primitive type.
4609   Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4610 
4611   Node* res = top();
4612   Node* io = i_o();
4613   Node* mem = merged_memory();
4614   if (!stopped()) {
4615 
4616     Node* bad_type_ctrl = top();
4617     // Do checkcast optimizations.
4618     res = gen_checkcast(obj, kls, &bad_type_ctrl);
4619     region->init_req(_bad_type_path, bad_type_ctrl);
4620   }
4621   if (region->in(_prim_path) != top() ||
4622       region->in(_bad_type_path) != top() ||
4623       region->in(_npe_path) != top()) {
4624     // Let Interpreter throw ClassCastException.
4625     PreserveJVMState pjvms(this);
4626     set_control(_gvn.transform(region));
4627     // Set IO and memory because gen_checkcast may override them when buffering inline types
4628     set_i_o(io);
4629     set_all_memory(mem);
4630     uncommon_trap(Deoptimization::Reason_intrinsic,
4631                   Deoptimization::Action_maybe_recompile);
4632   }
4633   if (!stopped()) {
4634     set_result(res);
4635   }
4636   return true;
4637 }
4638 
4639 
4640 //--------------------------inline_native_subtype_check------------------------
4641 // This intrinsic takes the JNI calls out of the heart of
4642 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4643 bool LibraryCallKit::inline_native_subtype_check() {
4644   // Pull both arguments off the stack.
4645   Node* args[2];                // two java.lang.Class mirrors: superc, subc
4646   args[0] = argument(0);
4647   args[1] = argument(1);
4648   Node* klasses[2];             // corresponding Klasses: superk, subk
4649   klasses[0] = klasses[1] = top();
4650 
4651   enum {
4652     // A full decision tree on {superc is prim, subc is prim}:
4653     _prim_0_path = 1,           // {P,N} => false
4654                                 // {P,P} & superc!=subc => false
4655     _prim_same_path,            // {P,P} & superc==subc => true
4656     _prim_1_path,               // {N,P} => false
4657     _ref_subtype_path,          // {N,N} & subtype check wins => true
4658     _both_ref_path,             // {N,N} & subtype check loses => false
4659     PATH_LIMIT
4660   };
4661 
4662   RegionNode* region = new RegionNode(PATH_LIMIT);
4663   RegionNode* prim_region = new RegionNode(2);
4664   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
4665   record_for_igvn(region);
4666   record_for_igvn(prim_region);
4667 
4668   const TypePtr* adr_type = TypeRawPtr::BOTTOM;   // memory type of loads
4669   const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4670   int class_klass_offset = java_lang_Class::klass_offset();
4671 
4672   // First null-check both mirrors and load each mirror's klass metaobject.
4673   int which_arg;
4674   for (which_arg = 0; which_arg <= 1; which_arg++) {
4675     Node* arg = args[which_arg];
4676     arg = null_check(arg);
4677     if (stopped())  break;
4678     args[which_arg] = arg;
4679 
4680     Node* p = basic_plus_adr(arg, class_klass_offset);
4681     Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4682     klasses[which_arg] = _gvn.transform(kls);
4683   }
4684 
4685   // Having loaded both klasses, test each for null.
4686   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4687   for (which_arg = 0; which_arg <= 1; which_arg++) {
4688     Node* kls = klasses[which_arg];
4689     Node* null_ctl = top();
4690     kls = null_check_oop(kls, &null_ctl, never_see_null);
4691     if (which_arg == 0) {
4692       prim_region->init_req(1, null_ctl);
4693     } else {
4694       region->init_req(_prim_1_path, null_ctl);
4695     }
4696     if (stopped())  break;
4697     klasses[which_arg] = kls;
4698   }
4699 
4700   if (!stopped()) {
4701     // now we have two reference types, in klasses[0..1]
4702     Node* subk   = klasses[1];  // the argument to isAssignableFrom
4703     Node* superk = klasses[0];  // the receiver
4704     region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4705     region->set_req(_ref_subtype_path, control());
4706   }
4707 
4708   // If both operands are primitive (both klasses null), then
4709   // we must return true when they are identical primitives.
4710   // It is convenient to test this after the first null klass check.
4711   // This path is also used if superc is a value mirror.
4712   set_control(_gvn.transform(prim_region));
4713   if (!stopped()) {
4714     // Since superc is primitive, make a guard for the superc==subc case.
4715     Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4716     Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4717     generate_fair_guard(bol_eq, region);
4718     if (region->req() == PATH_LIMIT+1) {
4719       // A guard was added.  If the added guard is taken, superc==subc.
4720       region->swap_edges(PATH_LIMIT, _prim_same_path);
4721       region->del_req(PATH_LIMIT);
4722     }
4723     region->set_req(_prim_0_path, control()); // Not equal after all.
4724   }
4725 
4726   // these are the only paths that produce 'true':
4727   phi->set_req(_prim_same_path,   intcon(1));
4728   phi->set_req(_ref_subtype_path, intcon(1));
4729 
4730   // pull together the cases:
4731   assert(region->req() == PATH_LIMIT, "sane region");
4732   for (uint i = 1; i < region->req(); i++) {
4733     Node* ctl = region->in(i);
4734     if (ctl == nullptr || ctl == top()) {
4735       region->set_req(i, top());
4736       phi   ->set_req(i, top());
4737     } else if (phi->in(i) == nullptr) {
4738       phi->set_req(i, intcon(0)); // all other paths produce 'false'
4739     }
4740   }
4741 
4742   set_control(_gvn.transform(region));
4743   set_result(_gvn.transform(phi));
4744   return true;
4745 }
4746 
4747 //---------------------generate_array_guard_common------------------------
4748 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4749 
4750   if (stopped()) {
4751     return nullptr;
4752   }
4753 
4754   // Like generate_guard, adds a new path onto the region.
4755   jint  layout_con = 0;
4756   Node* layout_val = get_layout_helper(kls, layout_con);
4757   if (layout_val == nullptr) {
4758     bool query = 0;
4759     switch(kind) {
4760       case RefArray:       query = Klass::layout_helper_is_refArray(layout_con); break;
4761       case NonRefArray:    query = !Klass::layout_helper_is_refArray(layout_con); break;
4762       case TypeArray:      query = Klass::layout_helper_is_typeArray(layout_con); break;
4763       case AnyArray:       query = Klass::layout_helper_is_array(layout_con); break;
4764       case NonArray:       query = !Klass::layout_helper_is_array(layout_con); break;
4765       default:
4766         ShouldNotReachHere();
4767     }
4768     if (!query) {
4769       return nullptr;                       // never a branch
4770     } else {                             // always a branch
4771       Node* always_branch = control();
4772       if (region != nullptr)
4773         region->add_req(always_branch);
4774       set_control(top());
4775       return always_branch;
4776     }
4777   }
4778   unsigned int value = 0;
4779   BoolTest::mask btest = BoolTest::illegal;
4780   switch(kind) {
4781     case RefArray:
4782     case NonRefArray: {
4783       value = Klass::_lh_array_tag_ref_value;
4784       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4785       btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4786       break;
4787     }
4788     case TypeArray: {
4789       value = Klass::_lh_array_tag_type_value;
4790       layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4791       btest = BoolTest::eq;
4792       break;
4793     }
4794     case AnyArray:    value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4795     case NonArray:    value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4796     default:
4797       ShouldNotReachHere();
4798   }
4799   // Now test the correct condition.
4800   jint nval = (jint)value;
4801   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4802   Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4803   Node* ctrl = generate_fair_guard(bol, region);
4804   Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4805   if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4806     // Keep track of the fact that 'obj' is an array to prevent
4807     // array specific accesses from floating above the guard.
4808     *obj = _gvn.transform(new CastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4809   }
4810   return ctrl;
4811 }
4812 
4813 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4814 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4815 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4816 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4817   assert(null_free || atomic, "nullable implies atomic");
4818   Node* componentType = argument(0);
4819   Node* length = argument(1);
4820   Node* init_val = null_free ? argument(2) : nullptr;
4821 
4822   const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4823   if (tp != nullptr) {
4824     ciInstanceKlass* ik = tp->instance_klass();
4825     if (ik == C->env()->Class_klass()) {
4826       ciType* t = tp->java_mirror_type();
4827       if (t != nullptr && t->is_inlinetype()) {
4828 
4829         ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4830         assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4831 
4832         // TOOD 8350865 ZGC needs card marks on initializing oop stores
4833         if (UseZGC && null_free && !array_klass->is_flat_array_klass()) {
4834           return false;
4835         }
4836 
4837         if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4838           const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4839           if (null_free) {
4840             if (init_val->is_InlineType()) {
4841               if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4842                 // Zeroing is enough because the init value is the all-zero value
4843                 init_val = nullptr;
4844               } else {
4845                 init_val = init_val->as_InlineType()->buffer(this);
4846               }
4847             }
4848             // TODO 8350865 Should we add a check of the init_val type (maybe in debug only + halt)?
4849             // If we insert a checkcast here, we can be sure that init_val is an InlineTypeNode, so
4850             // when we folded a field load from an allocation (e.g. during escape analysis), we can
4851             // remove the check init_val->is_InlineType().
4852           }
4853           Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4854           const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4855           assert(arytype->is_null_free() == null_free, "inconsistency");
4856           assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4857           set_result(obj);
4858           return true;
4859         }
4860       }
4861     }
4862   }
4863   return false;
4864 }
4865 
4866 // public static native boolean ValueClass::isFlatArray(Object array);
4867 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4868 // public static native boolean ValueClass::isAtomicArray(Object array);
4869 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4870   Node* array = argument(0);
4871 
4872   Node* bol;
4873   switch(check) {
4874     case IsFlat:
4875       // TODO 8350865 Use the object version here instead of loading the klass
4876       // 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
4877       bol = flat_array_test(load_object_klass(array));
4878       break;
4879     case IsNullRestricted:
4880       bol = null_free_array_test(array);
4881       break;
4882     case IsAtomic:
4883       // TODO 8350865 Implement this. It's a bit more complicated, see conditions in JVM_IsAtomicArray
4884       // Enable TestIntrinsics::test87/88 once this is implemented
4885       // bol = null_free_atomic_array_test
4886       return false;
4887     default:
4888       ShouldNotReachHere();
4889   }
4890 
4891   Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4892   set_result(res);
4893   return true;
4894 }
4895 
4896 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4897 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4898 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4899   RegionNode* region = new RegionNode(2);
4900   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4901 
4902   if (type_array_guard) {
4903     generate_typeArray_guard(klass_node, region);
4904     if (region->req() == 3) {
4905       phi->add_req(klass_node);
4906     }
4907   }
4908   Node* adr_refined_klass = basic_plus_adr(klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
4909   Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4910 
4911   // Can be null if not initialized yet, just deopt
4912   Node* null_ctl = top();
4913   refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
4914 
4915   region->init_req(1, control());
4916   phi->init_req(1, refined_klass);
4917 
4918   set_control(_gvn.transform(region));
4919   return _gvn.transform(phi);
4920 }
4921 
4922 // Load the non-refined array klass from an ObjArrayKlass.
4923 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
4924   const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
4925   if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
4926     return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
4927   }
4928 
4929   RegionNode* region = new RegionNode(2);
4930   Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
4931 
4932   generate_typeArray_guard(klass_node, region);
4933   if (region->req() == 3) {
4934     phi->add_req(klass_node);
4935   }
4936   Node* super_adr = basic_plus_adr(klass_node, in_bytes(Klass::super_offset()));
4937   Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
4938 
4939   region->init_req(1, control());
4940   phi->init_req(1, super_klass);
4941 
4942   set_control(_gvn.transform(region));
4943   return _gvn.transform(phi);
4944 }
4945 
4946 //-----------------------inline_native_newArray--------------------------
4947 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
4948 // private        native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4949 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4950   Node* mirror;
4951   Node* count_val;
4952   if (uninitialized) {
4953     null_check_receiver();
4954     mirror    = argument(1);
4955     count_val = argument(2);
4956   } else {
4957     mirror    = argument(0);
4958     count_val = argument(1);
4959   }
4960 
4961   mirror = null_check(mirror);
4962   // If mirror or obj is dead, only null-path is taken.
4963   if (stopped())  return true;
4964 
4965   enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4966   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4967   PhiNode*    result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4968   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
4969   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4970 
4971   bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4972   Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
4973                                                   result_reg, _slow_path);
4974   Node* normal_ctl   = control();
4975   Node* no_array_ctl = result_reg->in(_slow_path);
4976 
4977   // Generate code for the slow case.  We make a call to newArray().
4978   set_control(no_array_ctl);
4979   if (!stopped()) {
4980     // Either the input type is void.class, or else the
4981     // array klass has not yet been cached.  Either the
4982     // ensuing call will throw an exception, or else it
4983     // will cache the array klass for next time.
4984     PreserveJVMState pjvms(this);
4985     CallJavaNode* slow_call = nullptr;
4986     if (uninitialized) {
4987       // Generate optimized virtual call (holder class 'Unsafe' is final)
4988       slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4989     } else {
4990       slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4991     }
4992     Node* slow_result = set_results_for_java_call(slow_call);
4993     // this->control() comes from set_results_for_java_call
4994     result_reg->set_req(_slow_path, control());
4995     result_val->set_req(_slow_path, slow_result);
4996     result_io ->set_req(_slow_path, i_o());
4997     result_mem->set_req(_slow_path, reset_memory());
4998   }
4999 
5000   set_control(normal_ctl);
5001   if (!stopped()) {
5002     // Normal case:  The array type has been cached in the java.lang.Class.
5003     // The following call works fine even if the array type is polymorphic.
5004     // It could be a dynamic mix of int[], boolean[], Object[], etc.
5005 
5006     klass_node = load_default_refined_array_klass(klass_node);
5007 
5008     Node* obj = new_array(klass_node, count_val, 0);  // no arguments to push
5009     result_reg->init_req(_normal_path, control());
5010     result_val->init_req(_normal_path, obj);
5011     result_io ->init_req(_normal_path, i_o());
5012     result_mem->init_req(_normal_path, reset_memory());
5013 
5014     if (uninitialized) {
5015       // Mark the allocation so that zeroing is skipped
5016       AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
5017       alloc->maybe_set_complete(&_gvn);
5018     }
5019   }
5020 
5021   // Return the combined state.
5022   set_i_o(        _gvn.transform(result_io)  );
5023   set_all_memory( _gvn.transform(result_mem));
5024 
5025   C->set_has_split_ifs(true); // Has chance for split-if optimization
5026   set_result(result_reg, result_val);
5027   return true;
5028 }
5029 
5030 //----------------------inline_native_getLength--------------------------
5031 // public static native int java.lang.reflect.Array.getLength(Object array);
5032 bool LibraryCallKit::inline_native_getLength() {
5033   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5034 
5035   Node* array = null_check(argument(0));
5036   // If array is dead, only null-path is taken.
5037   if (stopped())  return true;
5038 
5039   // Deoptimize if it is a non-array.
5040   Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
5041 
5042   if (non_array != nullptr) {
5043     PreserveJVMState pjvms(this);
5044     set_control(non_array);
5045     uncommon_trap(Deoptimization::Reason_intrinsic,
5046                   Deoptimization::Action_maybe_recompile);
5047   }
5048 
5049   // If control is dead, only non-array-path is taken.
5050   if (stopped())  return true;
5051 
5052   // The works fine even if the array type is polymorphic.
5053   // It could be a dynamic mix of int[], boolean[], Object[], etc.
5054   Node* result = load_array_length(array);
5055 
5056   C->set_has_split_ifs(true);  // Has chance for split-if optimization
5057   set_result(result);
5058   return true;
5059 }
5060 
5061 //------------------------inline_array_copyOf----------------------------
5062 // public static <T,U> T[] java.util.Arrays.copyOf(     U[] original, int newLength,         Class<? extends T[]> newType);
5063 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from,      int to, Class<? extends T[]> newType);
5064 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
5065   if (too_many_traps(Deoptimization::Reason_intrinsic))  return false;
5066 
5067   // Get the arguments.
5068   Node* original          = argument(0);
5069   Node* start             = is_copyOfRange? argument(1): intcon(0);
5070   Node* end               = is_copyOfRange? argument(2): argument(1);
5071   Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
5072 
5073   Node* newcopy = nullptr;
5074 
5075   // Set the original stack and the reexecute bit for the interpreter to reexecute
5076   // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5077   { PreserveReexecuteState preexecs(this);
5078     jvms()->set_should_reexecute(true);
5079 
5080     array_type_mirror = null_check(array_type_mirror);
5081     original          = null_check(original);
5082 
5083     // Check if a null path was taken unconditionally.
5084     if (stopped())  return true;
5085 
5086     Node* orig_length = load_array_length(original);
5087 
5088     Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5089     klass_node = null_check(klass_node);
5090 
5091     RegionNode* bailout = new RegionNode(1);
5092     record_for_igvn(bailout);
5093 
5094     // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5095     // Bail out if that is so.
5096     // Inline type array may have object field that would require a
5097     // write barrier. Conservatively, go to slow path.
5098     // TODO 8251971: Optimize for the case when flat src/dst are later found
5099     // to not contain oops (i.e., move this check to the macro expansion phase).
5100     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5101     const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5102     const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5103     bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5104                         // Can src array be flat and contain oops?
5105                         (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5106                         // Can dest array be flat and contain oops?
5107                         tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5108     Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5109 
5110     Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5111 
5112     if (not_objArray != nullptr) {
5113       // Improve the klass node's type from the new optimistic assumption:
5114       ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5115       bool not_flat = !UseArrayFlattening;
5116       bool not_null_free = !Arguments::is_valhalla_enabled();
5117       const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5118       Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5119       refined_klass_node = _gvn.transform(cast);
5120     }
5121 
5122     // Bail out if either start or end is negative.
5123     generate_negative_guard(start, bailout, &start);
5124     generate_negative_guard(end,   bailout, &end);
5125 
5126     Node* length = end;
5127     if (_gvn.type(start) != TypeInt::ZERO) {
5128       length = _gvn.transform(new SubINode(end, start));
5129     }
5130 
5131     // Bail out if length is negative (i.e., if start > end).
5132     // Without this the new_array would throw
5133     // NegativeArraySizeException but IllegalArgumentException is what
5134     // should be thrown
5135     generate_negative_guard(length, bailout, &length);
5136 
5137     // Handle inline type arrays
5138     bool can_validate = !too_many_traps(Deoptimization::Reason_class_check);
5139     if (!stopped()) {
5140       // TODO 8251971
5141       if (!orig_t->is_null_free()) {
5142         // Not statically known to be null free, add a check
5143         generate_fair_guard(null_free_array_test(original), bailout);
5144       }
5145       orig_t = _gvn.type(original)->isa_aryptr();
5146       if (orig_t != nullptr && orig_t->is_flat()) {
5147         // Src is flat, check that dest is flat as well
5148         if (exclude_flat) {
5149           // Dest can't be flat, bail out
5150           bailout->add_req(control());
5151           set_control(top());
5152         } else {
5153           generate_fair_guard(flat_array_test(refined_klass_node, /* flat = */ false), bailout);
5154         }
5155         // TODO 8350865 This is not correct anymore. Write tests and fix logic similar to arraycopy.
5156       } else if (UseArrayFlattening && (orig_t == nullptr || !orig_t->is_not_flat()) &&
5157                  // If dest is flat, src must be flat as well (guaranteed by src <: dest check if validated).
5158                  ((!tklass->is_flat() && tklass->can_be_inline_array()) || !can_validate)) {
5159         // Src might be flat and dest might not be flat. Go to the slow path if src is flat.
5160         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat.
5161         generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5162         if (orig_t != nullptr) {
5163           orig_t = orig_t->cast_to_not_flat();
5164           original = _gvn.transform(new CheckCastPPNode(control(), original, orig_t));
5165         }
5166       }
5167       if (!can_validate) {
5168         // No validation. The subtype check emitted at macro expansion time will not go to the slow
5169         // path but call checkcast_arraycopy which can not handle flat/null-free inline type arrays.
5170         // TODO 8251971: Optimize for the case when src/dest are later found to be both flat/null-free.
5171         generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5172         generate_fair_guard(null_free_array_test(original), bailout);
5173       }
5174     }
5175 
5176     // Bail out if start is larger than the original length
5177     Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5178     generate_negative_guard(orig_tail, bailout, &orig_tail);
5179 
5180     if (bailout->req() > 1) {
5181       PreserveJVMState pjvms(this);
5182       set_control(_gvn.transform(bailout));
5183       uncommon_trap(Deoptimization::Reason_intrinsic,
5184                     Deoptimization::Action_maybe_recompile);
5185     }
5186 
5187     if (!stopped()) {
5188       // How many elements will we copy from the original?
5189       // The answer is MinI(orig_tail, length).
5190       Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5191 
5192       // Generate a direct call to the right arraycopy function(s).
5193       // We know the copy is disjoint but we might not know if the
5194       // oop stores need checking.
5195       // Extreme case:  Arrays.copyOf((Integer[])x, 10, String[].class).
5196       // This will fail a store-check if x contains any non-nulls.
5197 
5198       // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5199       // loads/stores but it is legal only if we're sure the
5200       // Arrays.copyOf would succeed. So we need all input arguments
5201       // to the copyOf to be validated, including that the copy to the
5202       // new array won't trigger an ArrayStoreException. That subtype
5203       // check can be optimized if we know something on the type of
5204       // the input array from type speculation.
5205       if (_gvn.type(klass_node)->singleton()) {
5206         const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5207         const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5208 
5209         int test = C->static_subtype_check(superk, subk);
5210         if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5211           const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5212           if (t_original->speculative_type() != nullptr) {
5213             original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5214           }
5215         }
5216       }
5217 
5218       bool validated = false;
5219       // Reason_class_check rather than Reason_intrinsic because we
5220       // want to intrinsify even if this traps.
5221       if (can_validate) {
5222         Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5223 
5224         if (not_subtype_ctrl != top()) {
5225           PreserveJVMState pjvms(this);
5226           set_control(not_subtype_ctrl);
5227           uncommon_trap(Deoptimization::Reason_class_check,
5228                         Deoptimization::Action_make_not_entrant);
5229           assert(stopped(), "Should be stopped");
5230         }
5231         validated = true;
5232       }
5233 
5234       if (!stopped()) {
5235         newcopy = new_array(refined_klass_node, length, 0);  // no arguments to push
5236 
5237         ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5238                                                 load_object_klass(original), klass_node);
5239         if (!is_copyOfRange) {
5240           ac->set_copyof(validated);
5241         } else {
5242           ac->set_copyofrange(validated);
5243         }
5244         Node* n = _gvn.transform(ac);
5245         if (n == ac) {
5246           ac->connect_outputs(this);
5247         } else {
5248           assert(validated, "shouldn't transform if all arguments not validated");
5249           set_all_memory(n);
5250         }
5251       }
5252     }
5253   } // original reexecute is set back here
5254 
5255   C->set_has_split_ifs(true); // Has chance for split-if optimization
5256   if (!stopped()) {
5257     set_result(newcopy);
5258   }
5259   return true;
5260 }
5261 
5262 
5263 //----------------------generate_virtual_guard---------------------------
5264 // Helper for hashCode and clone.  Peeks inside the vtable to avoid a call.
5265 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5266                                              RegionNode* slow_region) {
5267   ciMethod* method = callee();
5268   int vtable_index = method->vtable_index();
5269   assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5270          "bad index %d", vtable_index);
5271   // Get the Method* out of the appropriate vtable entry.
5272   int entry_offset  = in_bytes(Klass::vtable_start_offset()) +
5273                      vtable_index*vtableEntry::size_in_bytes() +
5274                      in_bytes(vtableEntry::method_offset());
5275   Node* entry_addr  = basic_plus_adr(obj_klass, entry_offset);
5276   Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5277 
5278   // Compare the target method with the expected method (e.g., Object.hashCode).
5279   const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5280 
5281   Node* native_call = makecon(native_call_addr);
5282   Node* chk_native  = _gvn.transform(new CmpPNode(target_call, native_call));
5283   Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5284 
5285   return generate_slow_guard(test_native, slow_region);
5286 }
5287 
5288 //-----------------------generate_method_call----------------------------
5289 // Use generate_method_call to make a slow-call to the real
5290 // method if the fast path fails.  An alternative would be to
5291 // use a stub like OptoRuntime::slow_arraycopy_Java.
5292 // This only works for expanding the current library call,
5293 // not another intrinsic.  (E.g., don't use this for making an
5294 // arraycopy call inside of the copyOf intrinsic.)
5295 CallJavaNode*
5296 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5297   // When compiling the intrinsic method itself, do not use this technique.
5298   guarantee(callee() != C->method(), "cannot make slow-call to self");
5299 
5300   ciMethod* method = callee();
5301   // ensure the JVMS we have will be correct for this call
5302   guarantee(method_id == method->intrinsic_id(), "must match");
5303 
5304   const TypeFunc* tf = TypeFunc::make(method);
5305   if (res_not_null) {
5306     assert(tf->return_type() == T_OBJECT, "");
5307     const TypeTuple* range = tf->range_cc();
5308     const Type** fields = TypeTuple::fields(range->cnt());
5309     fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5310     const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5311     tf = TypeFunc::make(tf->domain_cc(), new_range);
5312   }
5313   CallJavaNode* slow_call;
5314   if (is_static) {
5315     assert(!is_virtual, "");
5316     slow_call = new CallStaticJavaNode(C, tf,
5317                            SharedRuntime::get_resolve_static_call_stub(), method);
5318   } else if (is_virtual) {
5319     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5320     int vtable_index = Method::invalid_vtable_index;
5321     if (UseInlineCaches) {
5322       // Suppress the vtable call
5323     } else {
5324       // hashCode and clone are not a miranda methods,
5325       // so the vtable index is fixed.
5326       // No need to use the linkResolver to get it.
5327        vtable_index = method->vtable_index();
5328        assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5329               "bad index %d", vtable_index);
5330     }
5331     slow_call = new CallDynamicJavaNode(tf,
5332                           SharedRuntime::get_resolve_virtual_call_stub(),
5333                           method, vtable_index);
5334   } else {  // neither virtual nor static:  opt_virtual
5335     assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5336     slow_call = new CallStaticJavaNode(C, tf,
5337                                 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5338     slow_call->set_optimized_virtual(true);
5339   }
5340   if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5341     // To be able to issue a direct call (optimized virtual or virtual)
5342     // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5343     // about the method being invoked should be attached to the call site to
5344     // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5345     slow_call->set_override_symbolic_info(true);
5346   }
5347   set_arguments_for_java_call(slow_call);
5348   set_edges_for_java_call(slow_call);
5349   return slow_call;
5350 }
5351 
5352 
5353 /**
5354  * Build special case code for calls to hashCode on an object. This call may
5355  * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5356  * slightly different code.
5357  */
5358 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5359   assert(is_static == callee()->is_static(), "correct intrinsic selection");
5360   assert(!(is_virtual && is_static), "either virtual, special, or static");
5361 
5362   enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5363 
5364   RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5365   PhiNode*    result_val = new PhiNode(result_reg, TypeInt::INT);
5366   PhiNode*    result_io  = new PhiNode(result_reg, Type::ABIO);
5367   PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5368   Node* obj = argument(0);
5369 
5370   // Don't intrinsify hashcode on inline types for now.
5371   // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5372   if (gvn().type(obj)->is_inlinetypeptr()) {
5373     return false;
5374   }
5375 
5376   if (!is_static) {
5377     // Check for hashing null object
5378     obj = null_check_receiver();
5379     if (stopped())  return true;        // unconditionally null
5380     result_reg->init_req(_null_path, top());
5381     result_val->init_req(_null_path, top());
5382   } else {
5383     // Do a null check, and return zero if null.
5384     // System.identityHashCode(null) == 0
5385     Node* null_ctl = top();
5386     obj = null_check_oop(obj, &null_ctl);
5387     result_reg->init_req(_null_path, null_ctl);
5388     result_val->init_req(_null_path, _gvn.intcon(0));
5389   }
5390 
5391   // Unconditionally null?  Then return right away.
5392   if (stopped()) {
5393     set_control( result_reg->in(_null_path));
5394     if (!stopped())
5395       set_result(result_val->in(_null_path));
5396     return true;
5397   }
5398 
5399   // We only go to the fast case code if we pass a number of guards.  The
5400   // paths which do not pass are accumulated in the slow_region.
5401   RegionNode* slow_region = new RegionNode(1);
5402   record_for_igvn(slow_region);
5403 
5404   // If this is a virtual call, we generate a funny guard.  We pull out
5405   // the vtable entry corresponding to hashCode() from the target object.
5406   // If the target method which we are calling happens to be the native
5407   // Object hashCode() method, we pass the guard.  We do not need this
5408   // guard for non-virtual calls -- the caller is known to be the native
5409   // Object hashCode().
5410   if (is_virtual) {
5411     // After null check, get the object's klass.
5412     Node* obj_klass = load_object_klass(obj);
5413     generate_virtual_guard(obj_klass, slow_region);
5414   }
5415 
5416   // Get the header out of the object, use LoadMarkNode when available
5417   Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5418   // The control of the load must be null. Otherwise, the load can move before
5419   // the null check after castPP removal.
5420   Node* no_ctrl = nullptr;
5421   Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5422 
5423   if (!UseObjectMonitorTable) {
5424     // Test the header to see if it is safe to read w.r.t. locking.
5425     // We cannot use the inline type mask as this may check bits that are overriden
5426     // by an object monitor's pointer when inflating locking.
5427     Node *lock_mask      = _gvn.MakeConX(markWord::lock_mask_in_place);
5428     Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5429     Node *monitor_val   = _gvn.MakeConX(markWord::monitor_value);
5430     Node *chk_monitor   = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5431     Node *test_monitor  = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5432 
5433     generate_slow_guard(test_monitor, slow_region);
5434   }
5435 
5436   // Get the hash value and check to see that it has been properly assigned.
5437   // We depend on hash_mask being at most 32 bits and avoid the use of
5438   // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5439   // vm: see markWord.hpp.
5440   Node *hash_mask      = _gvn.intcon(markWord::hash_mask);
5441   Node *hash_shift     = _gvn.intcon(markWord::hash_shift);
5442   Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5443   // This hack lets the hash bits live anywhere in the mark object now, as long
5444   // as the shift drops the relevant bits into the low 32 bits.  Note that
5445   // Java spec says that HashCode is an int so there's no point in capturing
5446   // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5447   hshifted_header      = ConvX2I(hshifted_header);
5448   Node *hash_val       = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5449 
5450   Node *no_hash_val    = _gvn.intcon(markWord::no_hash);
5451   Node *chk_assigned   = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5452   Node *test_assigned  = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5453 
5454   generate_slow_guard(test_assigned, slow_region);
5455 
5456   Node* init_mem = reset_memory();
5457   // fill in the rest of the null path:
5458   result_io ->init_req(_null_path, i_o());
5459   result_mem->init_req(_null_path, init_mem);
5460 
5461   result_val->init_req(_fast_path, hash_val);
5462   result_reg->init_req(_fast_path, control());
5463   result_io ->init_req(_fast_path, i_o());
5464   result_mem->init_req(_fast_path, init_mem);
5465 
5466   // Generate code for the slow case.  We make a call to hashCode().
5467   set_control(_gvn.transform(slow_region));
5468   if (!stopped()) {
5469     // No need for PreserveJVMState, because we're using up the present state.
5470     set_all_memory(init_mem);
5471     vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5472     CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5473     Node* slow_result = set_results_for_java_call(slow_call);
5474     // this->control() comes from set_results_for_java_call
5475     result_reg->init_req(_slow_path, control());
5476     result_val->init_req(_slow_path, slow_result);
5477     result_io  ->set_req(_slow_path, i_o());
5478     result_mem ->set_req(_slow_path, reset_memory());
5479   }
5480 
5481   // Return the combined state.
5482   set_i_o(        _gvn.transform(result_io)  );
5483   set_all_memory( _gvn.transform(result_mem));
5484 
5485   set_result(result_reg, result_val);
5486   return true;
5487 }
5488 
5489 //---------------------------inline_native_getClass----------------------------
5490 // public final native Class<?> java.lang.Object.getClass();
5491 //
5492 // Build special case code for calls to getClass on an object.
5493 bool LibraryCallKit::inline_native_getClass() {
5494   Node* obj = argument(0);
5495   if (obj->is_InlineType()) {
5496     const Type* t = _gvn.type(obj);
5497     if (t->maybe_null()) {
5498       null_check(obj);
5499     }
5500     set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5501     return true;
5502   }
5503   obj = null_check_receiver();
5504   if (stopped())  return true;
5505   set_result(load_mirror_from_klass(load_object_klass(obj)));
5506   return true;
5507 }
5508 
5509 //-----------------inline_native_Reflection_getCallerClass---------------------
5510 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5511 //
5512 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5513 //
5514 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5515 // in that it must skip particular security frames and checks for
5516 // caller sensitive methods.
5517 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5518 #ifndef PRODUCT
5519   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5520     tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5521   }
5522 #endif
5523 
5524   if (!jvms()->has_method()) {
5525 #ifndef PRODUCT
5526     if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5527       tty->print_cr("  Bailing out because intrinsic was inlined at top level");
5528     }
5529 #endif
5530     return false;
5531   }
5532 
5533   // Walk back up the JVM state to find the caller at the required
5534   // depth.
5535   JVMState* caller_jvms = jvms();
5536 
5537   // Cf. JVM_GetCallerClass
5538   // NOTE: Start the loop at depth 1 because the current JVM state does
5539   // not include the Reflection.getCallerClass() frame.
5540   for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5541     ciMethod* m = caller_jvms->method();
5542     switch (n) {
5543     case 0:
5544       fatal("current JVM state does not include the Reflection.getCallerClass frame");
5545       break;
5546     case 1:
5547       // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5548       if (!m->caller_sensitive()) {
5549 #ifndef PRODUCT
5550         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5551           tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
5552         }
5553 #endif
5554         return false;  // bail-out; let JVM_GetCallerClass do the work
5555       }
5556       break;
5557     default:
5558       if (!m->is_ignored_by_security_stack_walk()) {
5559         // We have reached the desired frame; return the holder class.
5560         // Acquire method holder as java.lang.Class and push as constant.
5561         ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5562         ciInstance* caller_mirror = caller_klass->java_mirror();
5563         set_result(makecon(TypeInstPtr::make(caller_mirror)));
5564 
5565 #ifndef PRODUCT
5566         if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5567           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());
5568           tty->print_cr("  JVM state at this point:");
5569           for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5570             ciMethod* m = jvms()->of_depth(i)->method();
5571             tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5572           }
5573         }
5574 #endif
5575         return true;
5576       }
5577       break;
5578     }
5579   }
5580 
5581 #ifndef PRODUCT
5582   if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5583     tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5584     tty->print_cr("  JVM state at this point:");
5585     for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5586       ciMethod* m = jvms()->of_depth(i)->method();
5587       tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5588     }
5589   }
5590 #endif
5591 
5592   return false;  // bail-out; let JVM_GetCallerClass do the work
5593 }
5594 
5595 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5596   Node* arg = argument(0);
5597   Node* result = nullptr;
5598 
5599   switch (id) {
5600   case vmIntrinsics::_floatToRawIntBits:    result = new MoveF2INode(arg);  break;
5601   case vmIntrinsics::_intBitsToFloat:       result = new MoveI2FNode(arg);  break;
5602   case vmIntrinsics::_doubleToRawLongBits:  result = new MoveD2LNode(arg);  break;
5603   case vmIntrinsics::_longBitsToDouble:     result = new MoveL2DNode(arg);  break;
5604   case vmIntrinsics::_floatToFloat16:       result = new ConvF2HFNode(arg); break;
5605   case vmIntrinsics::_float16ToFloat:       result = new ConvHF2FNode(arg); break;
5606 
5607   case vmIntrinsics::_doubleToLongBits: {
5608     // two paths (plus control) merge in a wood
5609     RegionNode *r = new RegionNode(3);
5610     Node *phi = new PhiNode(r, TypeLong::LONG);
5611 
5612     Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5613     // Build the boolean node
5614     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5615 
5616     // Branch either way.
5617     // NaN case is less traveled, which makes all the difference.
5618     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5619     Node *opt_isnan = _gvn.transform(ifisnan);
5620     assert( opt_isnan->is_If(), "Expect an IfNode");
5621     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5622     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5623 
5624     set_control(iftrue);
5625 
5626     static const jlong nan_bits = CONST64(0x7ff8000000000000);
5627     Node *slow_result = longcon(nan_bits); // return NaN
5628     phi->init_req(1, _gvn.transform( slow_result ));
5629     r->init_req(1, iftrue);
5630 
5631     // Else fall through
5632     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5633     set_control(iffalse);
5634 
5635     phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5636     r->init_req(2, iffalse);
5637 
5638     // Post merge
5639     set_control(_gvn.transform(r));
5640     record_for_igvn(r);
5641 
5642     C->set_has_split_ifs(true); // Has chance for split-if optimization
5643     result = phi;
5644     assert(result->bottom_type()->isa_long(), "must be");
5645     break;
5646   }
5647 
5648   case vmIntrinsics::_floatToIntBits: {
5649     // two paths (plus control) merge in a wood
5650     RegionNode *r = new RegionNode(3);
5651     Node *phi = new PhiNode(r, TypeInt::INT);
5652 
5653     Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5654     // Build the boolean node
5655     Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5656 
5657     // Branch either way.
5658     // NaN case is less traveled, which makes all the difference.
5659     IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5660     Node *opt_isnan = _gvn.transform(ifisnan);
5661     assert( opt_isnan->is_If(), "Expect an IfNode");
5662     IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5663     Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5664 
5665     set_control(iftrue);
5666 
5667     static const jint nan_bits = 0x7fc00000;
5668     Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5669     phi->init_req(1, _gvn.transform( slow_result ));
5670     r->init_req(1, iftrue);
5671 
5672     // Else fall through
5673     Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5674     set_control(iffalse);
5675 
5676     phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5677     r->init_req(2, iffalse);
5678 
5679     // Post merge
5680     set_control(_gvn.transform(r));
5681     record_for_igvn(r);
5682 
5683     C->set_has_split_ifs(true); // Has chance for split-if optimization
5684     result = phi;
5685     assert(result->bottom_type()->isa_int(), "must be");
5686     break;
5687   }
5688 
5689   default:
5690     fatal_unexpected_iid(id);
5691     break;
5692   }
5693   set_result(_gvn.transform(result));
5694   return true;
5695 }
5696 
5697 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5698   Node* arg = argument(0);
5699   Node* result = nullptr;
5700 
5701   switch (id) {
5702   case vmIntrinsics::_floatIsInfinite:
5703     result = new IsInfiniteFNode(arg);
5704     break;
5705   case vmIntrinsics::_floatIsFinite:
5706     result = new IsFiniteFNode(arg);
5707     break;
5708   case vmIntrinsics::_doubleIsInfinite:
5709     result = new IsInfiniteDNode(arg);
5710     break;
5711   case vmIntrinsics::_doubleIsFinite:
5712     result = new IsFiniteDNode(arg);
5713     break;
5714   default:
5715     fatal_unexpected_iid(id);
5716     break;
5717   }
5718   set_result(_gvn.transform(result));
5719   return true;
5720 }
5721 
5722 //----------------------inline_unsafe_copyMemory-------------------------
5723 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5724 
5725 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5726   const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5727   const Type*       base_t = gvn.type(base);
5728 
5729   bool in_native = (base_t == TypePtr::NULL_PTR);
5730   bool in_heap   = !TypePtr::NULL_PTR->higher_equal(base_t);
5731   bool is_mixed  = !in_heap && !in_native;
5732 
5733   if (is_mixed) {
5734     return true; // mixed accesses can touch both on-heap and off-heap memory
5735   }
5736   if (in_heap) {
5737     bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5738     if (!is_prim_array) {
5739       // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5740       // there's not enough type information available to determine proper memory slice for it.
5741       return true;
5742     }
5743   }
5744   return false;
5745 }
5746 
5747 bool LibraryCallKit::inline_unsafe_copyMemory() {
5748   if (callee()->is_static())  return false;  // caller must have the capability!
5749   null_check_receiver();  // null-check receiver
5750   if (stopped())  return true;
5751 
5752   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5753 
5754   Node* src_base =         argument(1);  // type: oop
5755   Node* src_off  = ConvL2X(argument(2)); // type: long
5756   Node* dst_base =         argument(4);  // type: oop
5757   Node* dst_off  = ConvL2X(argument(5)); // type: long
5758   Node* size     = ConvL2X(argument(7)); // type: long
5759 
5760   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5761          "fieldOffset must be byte-scaled");
5762 
5763   Node* src_addr = make_unsafe_address(src_base, src_off);
5764   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5765 
5766   Node* thread = _gvn.transform(new ThreadLocalNode());
5767   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5768   BasicType doing_unsafe_access_bt = T_BYTE;
5769   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5770 
5771   // update volatile field
5772   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5773 
5774   int flags = RC_LEAF | RC_NO_FP;
5775 
5776   const TypePtr* dst_type = TypePtr::BOTTOM;
5777 
5778   // Adjust memory effects of the runtime call based on input values.
5779   if (!has_wide_mem(_gvn, src_addr, src_base) &&
5780       !has_wide_mem(_gvn, dst_addr, dst_base)) {
5781     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5782 
5783     const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5784     if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5785       flags |= RC_NARROW_MEM; // narrow in memory
5786     }
5787   }
5788 
5789   // Call it.  Note that the length argument is not scaled.
5790   make_runtime_call(flags,
5791                     OptoRuntime::fast_arraycopy_Type(),
5792                     StubRoutines::unsafe_arraycopy(),
5793                     "unsafe_arraycopy",
5794                     dst_type,
5795                     src_addr, dst_addr, size XTOP);
5796 
5797   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5798 
5799   return true;
5800 }
5801 
5802 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5803 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5804 bool LibraryCallKit::inline_unsafe_setMemory() {
5805   if (callee()->is_static())  return false;  // caller must have the capability!
5806   null_check_receiver();  // null-check receiver
5807   if (stopped())  return true;
5808 
5809   C->set_has_unsafe_access(true);  // Mark eventual nmethod as "unsafe".
5810 
5811   Node* dst_base =         argument(1);  // type: oop
5812   Node* dst_off  = ConvL2X(argument(2)); // type: long
5813   Node* size     = ConvL2X(argument(4)); // type: long
5814   Node* byte     =         argument(6);  // type: byte
5815 
5816   assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5817          "fieldOffset must be byte-scaled");
5818 
5819   Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5820 
5821   Node* thread = _gvn.transform(new ThreadLocalNode());
5822   Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5823   BasicType doing_unsafe_access_bt = T_BYTE;
5824   assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5825 
5826   // update volatile field
5827   store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5828 
5829   int flags = RC_LEAF | RC_NO_FP;
5830 
5831   const TypePtr* dst_type = TypePtr::BOTTOM;
5832 
5833   // Adjust memory effects of the runtime call based on input values.
5834   if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5835     dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5836 
5837     flags |= RC_NARROW_MEM; // narrow in memory
5838   }
5839 
5840   // Call it.  Note that the length argument is not scaled.
5841   make_runtime_call(flags,
5842                     OptoRuntime::unsafe_setmemory_Type(),
5843                     StubRoutines::unsafe_setmemory(),
5844                     "unsafe_setmemory",
5845                     dst_type,
5846                     dst_addr, size XTOP, byte);
5847 
5848   store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5849 
5850   return true;
5851 }
5852 
5853 #undef XTOP
5854 
5855 //------------------------clone_coping-----------------------------------
5856 // Helper function for inline_native_clone.
5857 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5858   assert(obj_size != nullptr, "");
5859   Node* raw_obj = alloc_obj->in(1);
5860   assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5861 
5862   AllocateNode* alloc = nullptr;
5863   if (ReduceBulkZeroing &&
5864       // If we are implementing an array clone without knowing its source type
5865       // (can happen when compiling the array-guarded branch of a reflective
5866       // Object.clone() invocation), initialize the array within the allocation.
5867       // This is needed because some GCs (e.g. ZGC) might fall back in this case
5868       // to a runtime clone call that assumes fully initialized source arrays.
5869       (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5870     // We will be completely responsible for initializing this object -
5871     // mark Initialize node as complete.
5872     alloc = AllocateNode::Ideal_allocation(alloc_obj);
5873     // The object was just allocated - there should be no any stores!
5874     guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5875     // Mark as complete_with_arraycopy so that on AllocateNode
5876     // expansion, we know this AllocateNode is initialized by an array
5877     // copy and a StoreStore barrier exists after the array copy.
5878     alloc->initialization()->set_complete_with_arraycopy();
5879   }
5880 
5881   Node* size = _gvn.transform(obj_size);
5882   access_clone(obj, alloc_obj, size, is_array);
5883 
5884   // Do not let reads from the cloned object float above the arraycopy.
5885   if (alloc != nullptr) {
5886     // Do not let stores that initialize this object be reordered with
5887     // a subsequent store that would make this object accessible by
5888     // other threads.
5889     // Record what AllocateNode this StoreStore protects so that
5890     // escape analysis can go from the MemBarStoreStoreNode to the
5891     // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5892     // based on the escape status of the AllocateNode.
5893     insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5894   } else {
5895     insert_mem_bar(Op_MemBarCPUOrder);
5896   }
5897 }
5898 
5899 //------------------------inline_native_clone----------------------------
5900 // protected native Object java.lang.Object.clone();
5901 //
5902 // Here are the simple edge cases:
5903 //  null receiver => normal trap
5904 //  virtual and clone was overridden => slow path to out-of-line clone
5905 //  not cloneable or finalizer => slow path to out-of-line Object.clone
5906 //
5907 // The general case has two steps, allocation and copying.
5908 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5909 //
5910 // Copying also has two cases, oop arrays and everything else.
5911 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5912 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5913 //
5914 // These steps fold up nicely if and when the cloned object's klass
5915 // can be sharply typed as an object array, a type array, or an instance.
5916 //
5917 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5918   PhiNode* result_val;
5919 
5920   // Set the reexecute bit for the interpreter to reexecute
5921   // the bytecode that invokes Object.clone if deoptimization happens.
5922   { PreserveReexecuteState preexecs(this);
5923     jvms()->set_should_reexecute(true);
5924 
5925     Node* obj = argument(0);
5926     obj = null_check_receiver();
5927     if (stopped())  return true;
5928 
5929     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5930     if (obj_type->is_inlinetypeptr()) {
5931       // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5932       // no identity.
5933       set_result(obj);
5934       return true;
5935     }
5936 
5937     // If we are going to clone an instance, we need its exact type to
5938     // know the number and types of fields to convert the clone to
5939     // loads/stores. Maybe a speculative type can help us.
5940     if (!obj_type->klass_is_exact() &&
5941         obj_type->speculative_type() != nullptr &&
5942         obj_type->speculative_type()->is_instance_klass() &&
5943         !obj_type->speculative_type()->is_inlinetype()) {
5944       ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5945       if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5946           !spec_ik->has_injected_fields()) {
5947         if (!obj_type->isa_instptr() ||
5948             obj_type->is_instptr()->instance_klass()->has_subklass()) {
5949           obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5950         }
5951       }
5952     }
5953 
5954     // Conservatively insert a memory barrier on all memory slices.
5955     // Do not let writes into the original float below the clone.
5956     insert_mem_bar(Op_MemBarCPUOrder);
5957 
5958     // paths into result_reg:
5959     enum {
5960       _slow_path = 1,     // out-of-line call to clone method (virtual or not)
5961       _objArray_path,     // plain array allocation, plus arrayof_oop_arraycopy
5962       _array_path,        // plain array allocation, plus arrayof_long_arraycopy
5963       _instance_path,     // plain instance allocation, plus arrayof_long_arraycopy
5964       PATH_LIMIT
5965     };
5966     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5967     result_val             = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5968     PhiNode*    result_i_o = new PhiNode(result_reg, Type::ABIO);
5969     PhiNode*    result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5970     record_for_igvn(result_reg);
5971 
5972     Node* obj_klass = load_object_klass(obj);
5973     // We only go to the fast case code if we pass a number of guards.
5974     // The paths which do not pass are accumulated in the slow_region.
5975     RegionNode* slow_region = new RegionNode(1);
5976     record_for_igvn(slow_region);
5977 
5978     Node* array_obj = obj;
5979     Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5980     if (array_ctl != nullptr) {
5981       // It's an array.
5982       PreserveJVMState pjvms(this);
5983       set_control(array_ctl);
5984 
5985       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5986       const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
5987       if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
5988           obj_type->can_be_inline_array() &&
5989           (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
5990         // Flat inline type array may have object field that would require a
5991         // write barrier. Conservatively, go to slow path.
5992         generate_fair_guard(flat_array_test(obj_klass), slow_region);
5993       }
5994 
5995       if (!stopped()) {
5996         Node* obj_length = load_array_length(array_obj);
5997         Node* array_size = nullptr; // Size of the array without object alignment padding.
5998         Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5999 
6000         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6001         if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
6002           // If it is an oop array, it requires very special treatment,
6003           // because gc barriers are required when accessing the array.
6004           Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
6005           if (is_obja != nullptr) {
6006             PreserveJVMState pjvms2(this);
6007             set_control(is_obja);
6008             // Generate a direct call to the right arraycopy function(s).
6009             // Clones are always tightly coupled.
6010             ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
6011             ac->set_clone_oop_array();
6012             Node* n = _gvn.transform(ac);
6013             assert(n == ac, "cannot disappear");
6014             ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
6015 
6016             result_reg->init_req(_objArray_path, control());
6017             result_val->init_req(_objArray_path, alloc_obj);
6018             result_i_o ->set_req(_objArray_path, i_o());
6019             result_mem ->set_req(_objArray_path, reset_memory());
6020           }
6021         }
6022         // Otherwise, there are no barriers to worry about.
6023         // (We can dispense with card marks if we know the allocation
6024         //  comes out of eden (TLAB)...  In fact, ReduceInitialCardMarks
6025         //  causes the non-eden paths to take compensating steps to
6026         //  simulate a fresh allocation, so that no further
6027         //  card marks are required in compiled code to initialize
6028         //  the object.)
6029 
6030         if (!stopped()) {
6031           copy_to_clone(obj, alloc_obj, array_size, true);
6032 
6033           // Present the results of the copy.
6034           result_reg->init_req(_array_path, control());
6035           result_val->init_req(_array_path, alloc_obj);
6036           result_i_o ->set_req(_array_path, i_o());
6037           result_mem ->set_req(_array_path, reset_memory());
6038         }
6039       }
6040     }
6041 
6042     if (!stopped()) {
6043       // It's an instance (we did array above).  Make the slow-path tests.
6044       // If this is a virtual call, we generate a funny guard.  We grab
6045       // the vtable entry corresponding to clone() from the target object.
6046       // If the target method which we are calling happens to be the
6047       // Object clone() method, we pass the guard.  We do not need this
6048       // guard for non-virtual calls; the caller is known to be the native
6049       // Object clone().
6050       if (is_virtual) {
6051         generate_virtual_guard(obj_klass, slow_region);
6052       }
6053 
6054       // The object must be easily cloneable and must not have a finalizer.
6055       // Both of these conditions may be checked in a single test.
6056       // We could optimize the test further, but we don't care.
6057       generate_misc_flags_guard(obj_klass,
6058                                 // Test both conditions:
6059                                 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6060                                 // Must be cloneable but not finalizer:
6061                                 KlassFlags::_misc_is_cloneable_fast,
6062                                 slow_region);
6063     }
6064 
6065     if (!stopped()) {
6066       // It's an instance, and it passed the slow-path tests.
6067       PreserveJVMState pjvms(this);
6068       Node* obj_size = nullptr; // Total object size, including object alignment padding.
6069       // Need to deoptimize on exception from allocation since Object.clone intrinsic
6070       // is reexecuted if deoptimization occurs and there could be problems when merging
6071       // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
6072       Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
6073 
6074       copy_to_clone(obj, alloc_obj, obj_size, false);
6075 
6076       // Present the results of the slow call.
6077       result_reg->init_req(_instance_path, control());
6078       result_val->init_req(_instance_path, alloc_obj);
6079       result_i_o ->set_req(_instance_path, i_o());
6080       result_mem ->set_req(_instance_path, reset_memory());
6081     }
6082 
6083     // Generate code for the slow case.  We make a call to clone().
6084     set_control(_gvn.transform(slow_region));
6085     if (!stopped()) {
6086       PreserveJVMState pjvms(this);
6087       CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
6088       // We need to deoptimize on exception (see comment above)
6089       Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
6090       // this->control() comes from set_results_for_java_call
6091       result_reg->init_req(_slow_path, control());
6092       result_val->init_req(_slow_path, slow_result);
6093       result_i_o ->set_req(_slow_path, i_o());
6094       result_mem ->set_req(_slow_path, reset_memory());
6095     }
6096 
6097     // Return the combined state.
6098     set_control(    _gvn.transform(result_reg));
6099     set_i_o(        _gvn.transform(result_i_o));
6100     set_all_memory( _gvn.transform(result_mem));
6101   } // original reexecute is set back here
6102 
6103   set_result(_gvn.transform(result_val));
6104   return true;
6105 }
6106 
6107 // If we have a tightly coupled allocation, the arraycopy may take care
6108 // of the array initialization. If one of the guards we insert between
6109 // the allocation and the arraycopy causes a deoptimization, an
6110 // uninitialized array will escape the compiled method. To prevent that
6111 // we set the JVM state for uncommon traps between the allocation and
6112 // the arraycopy to the state before the allocation so, in case of
6113 // deoptimization, we'll reexecute the allocation and the
6114 // initialization.
6115 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6116   if (alloc != nullptr) {
6117     ciMethod* trap_method = alloc->jvms()->method();
6118     int trap_bci = alloc->jvms()->bci();
6119 
6120     if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6121         !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6122       // Make sure there's no store between the allocation and the
6123       // arraycopy otherwise visible side effects could be rexecuted
6124       // in case of deoptimization and cause incorrect execution.
6125       bool no_interfering_store = true;
6126       Node* mem = alloc->in(TypeFunc::Memory);
6127       if (mem->is_MergeMem()) {
6128         for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6129           Node* n = mms.memory();
6130           if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6131             assert(n->is_Store(), "what else?");
6132             no_interfering_store = false;
6133             break;
6134           }
6135         }
6136       } else {
6137         for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6138           Node* n = mms.memory();
6139           if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6140             assert(n->is_Store(), "what else?");
6141             no_interfering_store = false;
6142             break;
6143           }
6144         }
6145       }
6146 
6147       if (no_interfering_store) {
6148         SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6149 
6150         JVMState* saved_jvms = jvms();
6151         saved_reexecute_sp = _reexecute_sp;
6152 
6153         set_jvms(sfpt->jvms());
6154         _reexecute_sp = jvms()->sp();
6155 
6156         return saved_jvms;
6157       }
6158     }
6159   }
6160   return nullptr;
6161 }
6162 
6163 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6164 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6165 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6166   JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6167   uint size = alloc->req();
6168   SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6169   old_jvms->set_map(sfpt);
6170   for (uint i = 0; i < size; i++) {
6171     sfpt->init_req(i, alloc->in(i));
6172   }
6173   int adjustment = 1;
6174   const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6175   if (ary_klass_ptr->is_null_free()) {
6176     // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6177     // also requires the componentType and initVal on stack for re-execution.
6178     // Re-create and push the componentType.
6179     ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6180     ciInstance* instance = klass->component_mirror_instance();
6181     const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6182     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6183     adjustment++;
6184   }
6185   // re-push array length for deoptimization
6186   sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6187   if (ary_klass_ptr->is_null_free()) {
6188     // Re-create and push the initVal.
6189     Node* init_val = alloc->in(AllocateNode::InitValue);
6190     if (init_val == nullptr) {
6191       init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6192     } else if (UseCompressedOops) {
6193       init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6194     }
6195     sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6196     adjustment++;
6197   }
6198   old_jvms->set_sp(old_jvms->sp() + adjustment);
6199   old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6200   old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6201   old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6202   old_jvms->set_should_reexecute(true);
6203 
6204   sfpt->set_i_o(map()->i_o());
6205   sfpt->set_memory(map()->memory());
6206   sfpt->set_control(map()->control());
6207   return sfpt;
6208 }
6209 
6210 // In case of a deoptimization, we restart execution at the
6211 // allocation, allocating a new array. We would leave an uninitialized
6212 // array in the heap that GCs wouldn't expect. Move the allocation
6213 // after the traps so we don't allocate the array if we
6214 // deoptimize. This is possible because tightly_coupled_allocation()
6215 // guarantees there's no observer of the allocated array at this point
6216 // and the control flow is simple enough.
6217 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6218                                                     int saved_reexecute_sp, uint new_idx) {
6219   if (saved_jvms_before_guards != nullptr && !stopped()) {
6220     replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6221 
6222     assert(alloc != nullptr, "only with a tightly coupled allocation");
6223     // restore JVM state to the state at the arraycopy
6224     saved_jvms_before_guards->map()->set_control(map()->control());
6225     assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6226     assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6227     // If we've improved the types of some nodes (null check) while
6228     // emitting the guards, propagate them to the current state
6229     map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6230     set_jvms(saved_jvms_before_guards);
6231     _reexecute_sp = saved_reexecute_sp;
6232 
6233     // Remove the allocation from above the guards
6234     CallProjections* callprojs = alloc->extract_projections(true);
6235     InitializeNode* init = alloc->initialization();
6236     Node* alloc_mem = alloc->in(TypeFunc::Memory);
6237     C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6238     init->replace_mem_projs_by(alloc_mem, C);
6239 
6240     // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6241     // the allocation (i.e. is only valid if the allocation succeeds):
6242     // 1) replace CastIINode with AllocateArrayNode's length here
6243     // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6244     //
6245     // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6246     // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6247     Node* init_control = init->proj_out(TypeFunc::Control);
6248     Node* alloc_length = alloc->Ideal_length();
6249 #ifdef ASSERT
6250     Node* prev_cast = nullptr;
6251 #endif
6252     for (uint i = 0; i < init_control->outcnt(); i++) {
6253       Node* init_out = init_control->raw_out(i);
6254       if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6255 #ifdef ASSERT
6256         if (prev_cast == nullptr) {
6257           prev_cast = init_out;
6258         } else {
6259           if (prev_cast->cmp(*init_out) == false) {
6260             prev_cast->dump();
6261             init_out->dump();
6262             assert(false, "not equal CastIINode");
6263           }
6264         }
6265 #endif
6266         C->gvn_replace_by(init_out, alloc_length);
6267       }
6268     }
6269     C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6270 
6271     // move the allocation here (after the guards)
6272     _gvn.hash_delete(alloc);
6273     alloc->set_req(TypeFunc::Control, control());
6274     alloc->set_req(TypeFunc::I_O, i_o());
6275     Node *mem = reset_memory();
6276     set_all_memory(mem);
6277     alloc->set_req(TypeFunc::Memory, mem);
6278     set_control(init->proj_out_or_null(TypeFunc::Control));
6279     set_i_o(callprojs->fallthrough_ioproj);
6280 
6281     // Update memory as done in GraphKit::set_output_for_allocation()
6282     const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6283     const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6284     if (ary_type->isa_aryptr() && length_type != nullptr) {
6285       ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6286     }
6287     const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6288     int            elemidx  = C->get_alias_index(telemref);
6289     // Need to properly move every memory projection for the Initialize
6290 #ifdef ASSERT
6291     int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6292     int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6293 #endif
6294     auto move_proj = [&](ProjNode* proj) {
6295       int alias_idx = C->get_alias_index(proj->adr_type());
6296       assert(alias_idx == Compile::AliasIdxRaw ||
6297              alias_idx == elemidx ||
6298              alias_idx == mark_idx ||
6299              alias_idx == klass_idx, "should be raw memory or array element type");
6300       set_memory(proj, alias_idx);
6301     };
6302     init->for_each_proj(move_proj, TypeFunc::Memory);
6303 
6304     Node* allocx = _gvn.transform(alloc);
6305     assert(allocx == alloc, "where has the allocation gone?");
6306     assert(dest->is_CheckCastPP(), "not an allocation result?");
6307 
6308     _gvn.hash_delete(dest);
6309     dest->set_req(0, control());
6310     Node* destx = _gvn.transform(dest);
6311     assert(destx == dest, "where has the allocation result gone?");
6312 
6313     array_ideal_length(alloc, ary_type, true);
6314   }
6315 }
6316 
6317 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6318 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6319 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6320 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6321 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6322 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6323 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6324                                                                        JVMState* saved_jvms_before_guards) {
6325   if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6326     // There is at least one unrelated uncommon trap which needs to be replaced.
6327     SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6328 
6329     JVMState* saved_jvms = jvms();
6330     const int saved_reexecute_sp = _reexecute_sp;
6331     set_jvms(sfpt->jvms());
6332     _reexecute_sp = jvms()->sp();
6333 
6334     replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6335 
6336     // Restore state
6337     set_jvms(saved_jvms);
6338     _reexecute_sp = saved_reexecute_sp;
6339   }
6340 }
6341 
6342 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6343 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6344 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6345   Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6346   while (if_proj->is_IfProj()) {
6347     CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6348     if (uncommon_trap != nullptr) {
6349       create_new_uncommon_trap(uncommon_trap);
6350     }
6351     assert(if_proj->in(0)->is_If(), "must be If");
6352     if_proj = if_proj->in(0)->in(0);
6353   }
6354   assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6355          "must have reached control projection of init node");
6356 }
6357 
6358 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6359   const int trap_request = uncommon_trap_call->uncommon_trap_request();
6360   assert(trap_request != 0, "no valid UCT trap request");
6361   PreserveJVMState pjvms(this);
6362   set_control(uncommon_trap_call->in(0));
6363   uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6364                 Deoptimization::trap_request_action(trap_request));
6365   assert(stopped(), "Should be stopped");
6366   _gvn.hash_delete(uncommon_trap_call);
6367   uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6368 }
6369 
6370 // Common checks for array sorting intrinsics arguments.
6371 // Returns `true` if checks passed.
6372 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6373   // check address of the class
6374   if (elementType == nullptr || elementType->is_top()) {
6375     return false;  // dead path
6376   }
6377   const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6378   if (elem_klass == nullptr) {
6379     return false;  // dead path
6380   }
6381   // java_mirror_type() returns non-null for compile-time Class constants only
6382   ciType* elem_type = elem_klass->java_mirror_type();
6383   if (elem_type == nullptr) {
6384     return false;
6385   }
6386   bt = elem_type->basic_type();
6387   // Disable the intrinsic if the CPU does not support SIMD sort
6388   if (!Matcher::supports_simd_sort(bt)) {
6389     return false;
6390   }
6391   // check address of the array
6392   if (obj == nullptr || obj->is_top()) {
6393     return false;  // dead path
6394   }
6395   const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6396   if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6397     return false; // failed input validation
6398   }
6399   return true;
6400 }
6401 
6402 //------------------------------inline_array_partition-----------------------
6403 bool LibraryCallKit::inline_array_partition() {
6404   address stubAddr = StubRoutines::select_array_partition_function();
6405   if (stubAddr == nullptr) {
6406     return false; // Intrinsic's stub is not implemented on this platform
6407   }
6408   assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6409 
6410   // no receiver because it is a static method
6411   Node* elementType     = argument(0);
6412   Node* obj             = argument(1);
6413   Node* offset          = argument(2); // long
6414   Node* fromIndex       = argument(4);
6415   Node* toIndex         = argument(5);
6416   Node* indexPivot1     = argument(6);
6417   Node* indexPivot2     = argument(7);
6418   // PartitionOperation:  argument(8) is ignored
6419 
6420   Node* pivotIndices = nullptr;
6421   BasicType bt = T_ILLEGAL;
6422 
6423   if (!check_array_sort_arguments(elementType, obj, bt)) {
6424     return false;
6425   }
6426   null_check(obj);
6427   // If obj is dead, only null-path is taken.
6428   if (stopped()) {
6429     return true;
6430   }
6431   // Set the original stack and the reexecute bit for the interpreter to reexecute
6432   // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6433   { PreserveReexecuteState preexecs(this);
6434     jvms()->set_should_reexecute(true);
6435 
6436     Node* obj_adr = make_unsafe_address(obj, offset);
6437 
6438     // create the pivotIndices array of type int and size = 2
6439     Node* size = intcon(2);
6440     Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6441     pivotIndices = new_array(klass_node, size, 0);  // no arguments to push
6442     AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6443     guarantee(alloc != nullptr, "created above");
6444     Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6445 
6446     // pass the basic type enum to the stub
6447     Node* elemType = intcon(bt);
6448 
6449     // Call the stub
6450     const char *stubName = "array_partition_stub";
6451     make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6452                       stubAddr, stubName, TypePtr::BOTTOM,
6453                       obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6454                       indexPivot1, indexPivot2);
6455 
6456   } // original reexecute is set back here
6457 
6458   if (!stopped()) {
6459     set_result(pivotIndices);
6460   }
6461 
6462   return true;
6463 }
6464 
6465 
6466 //------------------------------inline_array_sort-----------------------
6467 bool LibraryCallKit::inline_array_sort() {
6468   address stubAddr = StubRoutines::select_arraysort_function();
6469   if (stubAddr == nullptr) {
6470     return false; // Intrinsic's stub is not implemented on this platform
6471   }
6472   assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6473 
6474   // no receiver because it is a static method
6475   Node* elementType     = argument(0);
6476   Node* obj             = argument(1);
6477   Node* offset          = argument(2); // long
6478   Node* fromIndex       = argument(4);
6479   Node* toIndex         = argument(5);
6480   // SortOperation:       argument(6) is ignored
6481 
6482   BasicType bt = T_ILLEGAL;
6483 
6484   if (!check_array_sort_arguments(elementType, obj, bt)) {
6485     return false;
6486   }
6487   null_check(obj);
6488   // If obj is dead, only null-path is taken.
6489   if (stopped()) {
6490     return true;
6491   }
6492   Node* obj_adr = make_unsafe_address(obj, offset);
6493 
6494   // pass the basic type enum to the stub
6495   Node* elemType = intcon(bt);
6496 
6497   // Call the stub.
6498   const char *stubName = "arraysort_stub";
6499   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6500                     stubAddr, stubName, TypePtr::BOTTOM,
6501                     obj_adr, elemType, fromIndex, toIndex);
6502 
6503   return true;
6504 }
6505 
6506 
6507 //------------------------------inline_arraycopy-----------------------
6508 // public static native void java.lang.System.arraycopy(Object src,  int  srcPos,
6509 //                                                      Object dest, int destPos,
6510 //                                                      int length);
6511 bool LibraryCallKit::inline_arraycopy() {
6512   // Get the arguments.
6513   Node* src         = argument(0);  // type: oop
6514   Node* src_offset  = argument(1);  // type: int
6515   Node* dest        = argument(2);  // type: oop
6516   Node* dest_offset = argument(3);  // type: int
6517   Node* length      = argument(4);  // type: int
6518 
6519   uint new_idx = C->unique();
6520 
6521   // Check for allocation before we add nodes that would confuse
6522   // tightly_coupled_allocation()
6523   AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6524 
6525   int saved_reexecute_sp = -1;
6526   JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6527   // See arraycopy_restore_alloc_state() comment
6528   // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6529   // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6530   // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6531   bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6532 
6533   // The following tests must be performed
6534   // (1) src and dest are arrays.
6535   // (2) src and dest arrays must have elements of the same BasicType
6536   // (3) src and dest must not be null.
6537   // (4) src_offset must not be negative.
6538   // (5) dest_offset must not be negative.
6539   // (6) length must not be negative.
6540   // (7) src_offset + length must not exceed length of src.
6541   // (8) dest_offset + length must not exceed length of dest.
6542   // (9) each element of an oop array must be assignable
6543 
6544   // (3) src and dest must not be null.
6545   // always do this here because we need the JVM state for uncommon traps
6546   Node* null_ctl = top();
6547   src  = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6548   assert(null_ctl->is_top(), "no null control here");
6549   dest = null_check(dest, T_ARRAY);
6550 
6551   if (!can_emit_guards) {
6552     // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6553     // guards but the arraycopy node could still take advantage of a
6554     // tightly allocated allocation. tightly_coupled_allocation() is
6555     // called again to make sure it takes the null check above into
6556     // account: the null check is mandatory and if it caused an
6557     // uncommon trap to be emitted then the allocation can't be
6558     // considered tightly coupled in this context.
6559     alloc = tightly_coupled_allocation(dest);
6560   }
6561 
6562   bool validated = false;
6563 
6564   const Type* src_type  = _gvn.type(src);
6565   const Type* dest_type = _gvn.type(dest);
6566   const TypeAryPtr* top_src  = src_type->isa_aryptr();
6567   const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6568 
6569   // Do we have the type of src?
6570   bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6571   // Do we have the type of dest?
6572   bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6573   // Is the type for src from speculation?
6574   bool src_spec = false;
6575   // Is the type for dest from speculation?
6576   bool dest_spec = false;
6577 
6578   if ((!has_src || !has_dest) && can_emit_guards) {
6579     // We don't have sufficient type information, let's see if
6580     // speculative types can help. We need to have types for both src
6581     // and dest so that it pays off.
6582 
6583     // Do we already have or could we have type information for src
6584     bool could_have_src = has_src;
6585     // Do we already have or could we have type information for dest
6586     bool could_have_dest = has_dest;
6587 
6588     ciKlass* src_k = nullptr;
6589     if (!has_src) {
6590       src_k = src_type->speculative_type_not_null();
6591       if (src_k != nullptr && src_k->is_array_klass()) {
6592         could_have_src = true;
6593       }
6594     }
6595 
6596     ciKlass* dest_k = nullptr;
6597     if (!has_dest) {
6598       dest_k = dest_type->speculative_type_not_null();
6599       if (dest_k != nullptr && dest_k->is_array_klass()) {
6600         could_have_dest = true;
6601       }
6602     }
6603 
6604     if (could_have_src && could_have_dest) {
6605       // This is going to pay off so emit the required guards
6606       if (!has_src) {
6607         src = maybe_cast_profiled_obj(src, src_k, true);
6608         src_type  = _gvn.type(src);
6609         top_src  = src_type->isa_aryptr();
6610         has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6611         src_spec = true;
6612       }
6613       if (!has_dest) {
6614         dest = maybe_cast_profiled_obj(dest, dest_k, true);
6615         dest_type  = _gvn.type(dest);
6616         top_dest  = dest_type->isa_aryptr();
6617         has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6618         dest_spec = true;
6619       }
6620     }
6621   }
6622 
6623   if (has_src && has_dest && can_emit_guards) {
6624     BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6625     BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6626     if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6627     if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6628 
6629     if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6630       // If both arrays are object arrays then having the exact types
6631       // for both will remove the need for a subtype check at runtime
6632       // before the call and may make it possible to pick a faster copy
6633       // routine (without a subtype check on every element)
6634       // Do we have the exact type of src?
6635       bool could_have_src = src_spec;
6636       // Do we have the exact type of dest?
6637       bool could_have_dest = dest_spec;
6638       ciKlass* src_k = nullptr;
6639       ciKlass* dest_k = nullptr;
6640       if (!src_spec) {
6641         src_k = src_type->speculative_type_not_null();
6642         if (src_k != nullptr && src_k->is_array_klass()) {
6643           could_have_src = true;
6644         }
6645       }
6646       if (!dest_spec) {
6647         dest_k = dest_type->speculative_type_not_null();
6648         if (dest_k != nullptr && dest_k->is_array_klass()) {
6649           could_have_dest = true;
6650         }
6651       }
6652       if (could_have_src && could_have_dest) {
6653         // If we can have both exact types, emit the missing guards
6654         if (could_have_src && !src_spec) {
6655           src = maybe_cast_profiled_obj(src, src_k, true);
6656           src_type = _gvn.type(src);
6657           top_src = src_type->isa_aryptr();
6658         }
6659         if (could_have_dest && !dest_spec) {
6660           dest = maybe_cast_profiled_obj(dest, dest_k, true);
6661           dest_type = _gvn.type(dest);
6662           top_dest = dest_type->isa_aryptr();
6663         }
6664       }
6665     }
6666   }
6667 
6668   ciMethod* trap_method = method();
6669   int trap_bci = bci();
6670   if (saved_jvms_before_guards != nullptr) {
6671     trap_method = alloc->jvms()->method();
6672     trap_bci = alloc->jvms()->bci();
6673   }
6674 
6675   bool negative_length_guard_generated = false;
6676 
6677   if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6678       can_emit_guards && !src->is_top() && !dest->is_top()) {
6679     // validate arguments: enables transformation the ArrayCopyNode
6680     validated = true;
6681 
6682     RegionNode* slow_region = new RegionNode(1);
6683     record_for_igvn(slow_region);
6684 
6685     // (1) src and dest are arrays.
6686     generate_non_array_guard(load_object_klass(src), slow_region, &src);
6687     generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6688 
6689     // (2) src and dest arrays must have elements of the same BasicType
6690     // done at macro expansion or at Ideal transformation time
6691 
6692     // (4) src_offset must not be negative.
6693     generate_negative_guard(src_offset, slow_region);
6694 
6695     // (5) dest_offset must not be negative.
6696     generate_negative_guard(dest_offset, slow_region);
6697 
6698     // (7) src_offset + length must not exceed length of src.
6699     generate_limit_guard(src_offset, length,
6700                          load_array_length(src),
6701                          slow_region);
6702 
6703     // (8) dest_offset + length must not exceed length of dest.
6704     generate_limit_guard(dest_offset, length,
6705                          load_array_length(dest),
6706                          slow_region);
6707 
6708     // (6) length must not be negative.
6709     // This is also checked in generate_arraycopy() during macro expansion, but
6710     // we also have to check it here for the case where the ArrayCopyNode will
6711     // be eliminated by Escape Analysis.
6712     if (EliminateAllocations) {
6713       generate_negative_guard(length, slow_region);
6714       negative_length_guard_generated = true;
6715     }
6716 
6717     // (9) each element of an oop array must be assignable
6718     Node* dest_klass = load_object_klass(dest);
6719     Node* refined_dest_klass = dest_klass;
6720     if (src != dest) {
6721       dest_klass = load_non_refined_array_klass(refined_dest_klass);
6722       Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6723       slow_region->add_req(not_subtype_ctrl);
6724     }
6725 
6726     // TODO 8350865 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6727     // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6728     Node* src_klass = load_object_klass(src);
6729     Node* adr_prop_src = basic_plus_adr(src_klass, in_bytes(ArrayKlass::properties_offset()));
6730     Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6731     Node* adr_prop_dest = basic_plus_adr(refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6732     Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest, TypeRawPtr::BOTTOM, TypeInt::INT, T_INT, MemNode::unordered));
6733 
6734     prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6735     prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6736     prop_src = _gvn.transform(new AndINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6737 
6738     Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(ArrayKlass::ArrayProperties::NULL_RESTRICTED)));
6739     Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6740     generate_fair_guard(tst, slow_region);
6741 
6742     // TODO 8350865 This is too strong
6743     generate_fair_guard(flat_array_test(src), slow_region);
6744     generate_fair_guard(flat_array_test(dest), slow_region);
6745 
6746     {
6747       PreserveJVMState pjvms(this);
6748       set_control(_gvn.transform(slow_region));
6749       uncommon_trap(Deoptimization::Reason_intrinsic,
6750                     Deoptimization::Action_make_not_entrant);
6751       assert(stopped(), "Should be stopped");
6752     }
6753 
6754     const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6755     if (dest_klass_t == nullptr) {
6756       // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6757       // are in a dead path.
6758       uncommon_trap(Deoptimization::Reason_intrinsic,
6759                     Deoptimization::Action_make_not_entrant);
6760       return true;
6761     }
6762 
6763     const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6764     src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6765     arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6766   }
6767 
6768   if (stopped()) {
6769     return true;
6770   }
6771 
6772   Node* dest_klass = load_object_klass(dest);
6773   dest_klass = load_non_refined_array_klass(dest_klass);
6774 
6775   ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6776                                           // Create LoadRange and LoadKlass nodes for use during macro expansion here
6777                                           // so the compiler has a chance to eliminate them: during macro expansion,
6778                                           // we have to set their control (CastPP nodes are eliminated).
6779                                           load_object_klass(src), dest_klass,
6780                                           load_array_length(src), load_array_length(dest));
6781 
6782   ac->set_arraycopy(validated);
6783 
6784   Node* n = _gvn.transform(ac);
6785   if (n == ac) {
6786     ac->connect_outputs(this);
6787   } else {
6788     assert(validated, "shouldn't transform if all arguments not validated");
6789     set_all_memory(n);
6790   }
6791   clear_upper_avx();
6792 
6793 
6794   return true;
6795 }
6796 
6797 
6798 // Helper function which determines if an arraycopy immediately follows
6799 // an allocation, with no intervening tests or other escapes for the object.
6800 AllocateArrayNode*
6801 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6802   if (stopped())             return nullptr;  // no fast path
6803   if (!C->do_aliasing())     return nullptr;  // no MergeMems around
6804 
6805   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6806   if (alloc == nullptr)  return nullptr;
6807 
6808   Node* rawmem = memory(Compile::AliasIdxRaw);
6809   // Is the allocation's memory state untouched?
6810   if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6811     // Bail out if there have been raw-memory effects since the allocation.
6812     // (Example:  There might have been a call or safepoint.)
6813     return nullptr;
6814   }
6815   rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6816   if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6817     return nullptr;
6818   }
6819 
6820   // There must be no unexpected observers of this allocation.
6821   for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6822     Node* obs = ptr->fast_out(i);
6823     if (obs != this->map()) {
6824       return nullptr;
6825     }
6826   }
6827 
6828   // This arraycopy must unconditionally follow the allocation of the ptr.
6829   Node* alloc_ctl = ptr->in(0);
6830   Node* ctl = control();
6831   while (ctl != alloc_ctl) {
6832     // There may be guards which feed into the slow_region.
6833     // Any other control flow means that we might not get a chance
6834     // to finish initializing the allocated object.
6835     // Various low-level checks bottom out in uncommon traps. These
6836     // are considered safe since we've already checked above that
6837     // there is no unexpected observer of this allocation.
6838     if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6839       assert(ctl->in(0)->is_If(), "must be If");
6840       ctl = ctl->in(0)->in(0);
6841     } else {
6842       return nullptr;
6843     }
6844   }
6845 
6846   // If we get this far, we have an allocation which immediately
6847   // precedes the arraycopy, and we can take over zeroing the new object.
6848   // The arraycopy will finish the initialization, and provide
6849   // a new control state to which we will anchor the destination pointer.
6850 
6851   return alloc;
6852 }
6853 
6854 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6855   if (node->is_IfProj()) {
6856     IfProjNode* other_proj = node->as_IfProj()->other_if_proj();
6857     for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6858       Node* obs = other_proj->fast_out(j);
6859       if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6860           (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6861         return obs->as_CallStaticJava();
6862       }
6863     }
6864   }
6865   return nullptr;
6866 }
6867 
6868 //-------------inline_encodeISOArray-----------------------------------
6869 // encode char[] to byte[] in ISO_8859_1 or ASCII
6870 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6871   assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6872   // no receiver since it is static method
6873   Node *src         = argument(0);
6874   Node *src_offset  = argument(1);
6875   Node *dst         = argument(2);
6876   Node *dst_offset  = argument(3);
6877   Node *length      = argument(4);
6878 
6879   src = must_be_not_null(src, true);
6880   dst = must_be_not_null(dst, true);
6881 
6882   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6883   const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6884   if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6885       dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6886     // failed array check
6887     return false;
6888   }
6889 
6890   // Figure out the size and type of the elements we will be copying.
6891   BasicType src_elem = src_type->elem()->array_element_basic_type();
6892   BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6893   if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6894     return false;
6895   }
6896 
6897   Node* src_start = array_element_address(src, src_offset, T_CHAR);
6898   Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6899   // 'src_start' points to src array + scaled offset
6900   // 'dst_start' points to dst array + scaled offset
6901 
6902   const TypeAryPtr* mtype = TypeAryPtr::BYTES;
6903   Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length, ascii);
6904   enc = _gvn.transform(enc);
6905   Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6906   set_memory(res_mem, mtype);
6907   set_result(enc);
6908   clear_upper_avx();
6909 
6910   return true;
6911 }
6912 
6913 //-------------inline_multiplyToLen-----------------------------------
6914 bool LibraryCallKit::inline_multiplyToLen() {
6915   assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
6916 
6917   address stubAddr = StubRoutines::multiplyToLen();
6918   if (stubAddr == nullptr) {
6919     return false; // Intrinsic's stub is not implemented on this platform
6920   }
6921   const char* stubName = "multiplyToLen";
6922 
6923   assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
6924 
6925   // no receiver because it is a static method
6926   Node* x    = argument(0);
6927   Node* xlen = argument(1);
6928   Node* y    = argument(2);
6929   Node* ylen = argument(3);
6930   Node* z    = argument(4);
6931 
6932   x = must_be_not_null(x, true);
6933   y = must_be_not_null(y, true);
6934 
6935   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6936   const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
6937   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6938       y_type == nullptr || y_type->elem() == Type::BOTTOM) {
6939     // failed array check
6940     return false;
6941   }
6942 
6943   BasicType x_elem = x_type->elem()->array_element_basic_type();
6944   BasicType y_elem = y_type->elem()->array_element_basic_type();
6945   if (x_elem != T_INT || y_elem != T_INT) {
6946     return false;
6947   }
6948 
6949   Node* x_start = array_element_address(x, intcon(0), x_elem);
6950   Node* y_start = array_element_address(y, intcon(0), y_elem);
6951   // 'x_start' points to x array + scaled xlen
6952   // 'y_start' points to y array + scaled ylen
6953 
6954   Node* z_start = array_element_address(z, intcon(0), T_INT);
6955 
6956   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6957                                  OptoRuntime::multiplyToLen_Type(),
6958                                  stubAddr, stubName, TypePtr::BOTTOM,
6959                                  x_start, xlen, y_start, ylen, z_start);
6960 
6961   C->set_has_split_ifs(true); // Has chance for split-if optimization
6962   set_result(z);
6963   return true;
6964 }
6965 
6966 //-------------inline_squareToLen------------------------------------
6967 bool LibraryCallKit::inline_squareToLen() {
6968   assert(UseSquareToLenIntrinsic, "not implemented on this platform");
6969 
6970   address stubAddr = StubRoutines::squareToLen();
6971   if (stubAddr == nullptr) {
6972     return false; // Intrinsic's stub is not implemented on this platform
6973   }
6974   const char* stubName = "squareToLen";
6975 
6976   assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
6977 
6978   Node* x    = argument(0);
6979   Node* len  = argument(1);
6980   Node* z    = argument(2);
6981   Node* zlen = argument(3);
6982 
6983   x = must_be_not_null(x, true);
6984   z = must_be_not_null(z, true);
6985 
6986   const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6987   const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
6988   if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6989       z_type == nullptr || z_type->elem() == Type::BOTTOM) {
6990     // failed array check
6991     return false;
6992   }
6993 
6994   BasicType x_elem = x_type->elem()->array_element_basic_type();
6995   BasicType z_elem = z_type->elem()->array_element_basic_type();
6996   if (x_elem != T_INT || z_elem != T_INT) {
6997     return false;
6998   }
6999 
7000 
7001   Node* x_start = array_element_address(x, intcon(0), x_elem);
7002   Node* z_start = array_element_address(z, intcon(0), z_elem);
7003 
7004   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7005                                   OptoRuntime::squareToLen_Type(),
7006                                   stubAddr, stubName, TypePtr::BOTTOM,
7007                                   x_start, len, z_start, zlen);
7008 
7009   set_result(z);
7010   return true;
7011 }
7012 
7013 //-------------inline_mulAdd------------------------------------------
7014 bool LibraryCallKit::inline_mulAdd() {
7015   assert(UseMulAddIntrinsic, "not implemented on this platform");
7016 
7017   address stubAddr = StubRoutines::mulAdd();
7018   if (stubAddr == nullptr) {
7019     return false; // Intrinsic's stub is not implemented on this platform
7020   }
7021   const char* stubName = "mulAdd";
7022 
7023   assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
7024 
7025   Node* out      = argument(0);
7026   Node* in       = argument(1);
7027   Node* offset   = argument(2);
7028   Node* len      = argument(3);
7029   Node* k        = argument(4);
7030 
7031   in = must_be_not_null(in, true);
7032   out = must_be_not_null(out, true);
7033 
7034   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
7035   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
7036   if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
7037        in_type == nullptr ||  in_type->elem() == Type::BOTTOM) {
7038     // failed array check
7039     return false;
7040   }
7041 
7042   BasicType out_elem = out_type->elem()->array_element_basic_type();
7043   BasicType in_elem = in_type->elem()->array_element_basic_type();
7044   if (out_elem != T_INT || in_elem != T_INT) {
7045     return false;
7046   }
7047 
7048   Node* outlen = load_array_length(out);
7049   Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
7050   Node* out_start = array_element_address(out, intcon(0), out_elem);
7051   Node* in_start = array_element_address(in, intcon(0), in_elem);
7052 
7053   Node*  call = make_runtime_call(RC_LEAF|RC_NO_FP,
7054                                   OptoRuntime::mulAdd_Type(),
7055                                   stubAddr, stubName, TypePtr::BOTTOM,
7056                                   out_start,in_start, new_offset, len, k);
7057   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7058   set_result(result);
7059   return true;
7060 }
7061 
7062 //-------------inline_montgomeryMultiply-----------------------------------
7063 bool LibraryCallKit::inline_montgomeryMultiply() {
7064   address stubAddr = StubRoutines::montgomeryMultiply();
7065   if (stubAddr == nullptr) {
7066     return false; // Intrinsic's stub is not implemented on this platform
7067   }
7068 
7069   assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
7070   const char* stubName = "montgomery_multiply";
7071 
7072   assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
7073 
7074   Node* a    = argument(0);
7075   Node* b    = argument(1);
7076   Node* n    = argument(2);
7077   Node* len  = argument(3);
7078   Node* inv  = argument(4);
7079   Node* m    = argument(6);
7080 
7081   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7082   const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
7083   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7084   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7085   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7086       b_type == nullptr || b_type->elem() == Type::BOTTOM ||
7087       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7088       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7089     // failed array check
7090     return false;
7091   }
7092 
7093   BasicType a_elem = a_type->elem()->array_element_basic_type();
7094   BasicType b_elem = b_type->elem()->array_element_basic_type();
7095   BasicType n_elem = n_type->elem()->array_element_basic_type();
7096   BasicType m_elem = m_type->elem()->array_element_basic_type();
7097   if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7098     return false;
7099   }
7100 
7101   // Make the call
7102   {
7103     Node* a_start = array_element_address(a, intcon(0), a_elem);
7104     Node* b_start = array_element_address(b, intcon(0), b_elem);
7105     Node* n_start = array_element_address(n, intcon(0), n_elem);
7106     Node* m_start = array_element_address(m, intcon(0), m_elem);
7107 
7108     Node* call = make_runtime_call(RC_LEAF,
7109                                    OptoRuntime::montgomeryMultiply_Type(),
7110                                    stubAddr, stubName, TypePtr::BOTTOM,
7111                                    a_start, b_start, n_start, len, inv, top(),
7112                                    m_start);
7113     set_result(m);
7114   }
7115 
7116   return true;
7117 }
7118 
7119 bool LibraryCallKit::inline_montgomerySquare() {
7120   address stubAddr = StubRoutines::montgomerySquare();
7121   if (stubAddr == nullptr) {
7122     return false; // Intrinsic's stub is not implemented on this platform
7123   }
7124 
7125   assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7126   const char* stubName = "montgomery_square";
7127 
7128   assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7129 
7130   Node* a    = argument(0);
7131   Node* n    = argument(1);
7132   Node* len  = argument(2);
7133   Node* inv  = argument(3);
7134   Node* m    = argument(5);
7135 
7136   const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7137   const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7138   const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7139   if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7140       n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7141       m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7142     // failed array check
7143     return false;
7144   }
7145 
7146   BasicType a_elem = a_type->elem()->array_element_basic_type();
7147   BasicType n_elem = n_type->elem()->array_element_basic_type();
7148   BasicType m_elem = m_type->elem()->array_element_basic_type();
7149   if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7150     return false;
7151   }
7152 
7153   // Make the call
7154   {
7155     Node* a_start = array_element_address(a, intcon(0), a_elem);
7156     Node* n_start = array_element_address(n, intcon(0), n_elem);
7157     Node* m_start = array_element_address(m, intcon(0), m_elem);
7158 
7159     Node* call = make_runtime_call(RC_LEAF,
7160                                    OptoRuntime::montgomerySquare_Type(),
7161                                    stubAddr, stubName, TypePtr::BOTTOM,
7162                                    a_start, n_start, len, inv, top(),
7163                                    m_start);
7164     set_result(m);
7165   }
7166 
7167   return true;
7168 }
7169 
7170 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7171   address stubAddr = nullptr;
7172   const char* stubName = nullptr;
7173 
7174   stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7175   if (stubAddr == nullptr) {
7176     return false; // Intrinsic's stub is not implemented on this platform
7177   }
7178 
7179   stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7180 
7181   assert(callee()->signature()->size() == 5, "expected 5 arguments");
7182 
7183   Node* newArr = argument(0);
7184   Node* oldArr = argument(1);
7185   Node* newIdx = argument(2);
7186   Node* shiftCount = argument(3);
7187   Node* numIter = argument(4);
7188 
7189   const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7190   const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7191   if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7192       oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7193     return false;
7194   }
7195 
7196   BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7197   BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7198   if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7199     return false;
7200   }
7201 
7202   // Make the call
7203   {
7204     Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7205     Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7206 
7207     Node* call = make_runtime_call(RC_LEAF,
7208                                    OptoRuntime::bigIntegerShift_Type(),
7209                                    stubAddr,
7210                                    stubName,
7211                                    TypePtr::BOTTOM,
7212                                    newArr_start,
7213                                    oldArr_start,
7214                                    newIdx,
7215                                    shiftCount,
7216                                    numIter);
7217   }
7218 
7219   return true;
7220 }
7221 
7222 //-------------inline_vectorizedMismatch------------------------------
7223 bool LibraryCallKit::inline_vectorizedMismatch() {
7224   assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7225 
7226   assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7227   Node* obja    = argument(0); // Object
7228   Node* aoffset = argument(1); // long
7229   Node* objb    = argument(3); // Object
7230   Node* boffset = argument(4); // long
7231   Node* length  = argument(6); // int
7232   Node* scale   = argument(7); // int
7233 
7234   const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7235   const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7236   if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7237       objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7238       scale == top()) {
7239     return false; // failed input validation
7240   }
7241 
7242   Node* obja_adr = make_unsafe_address(obja, aoffset);
7243   Node* objb_adr = make_unsafe_address(objb, boffset);
7244 
7245   // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7246   //
7247   //    inline_limit = ArrayOperationPartialInlineSize / element_size;
7248   //    if (length <= inline_limit) {
7249   //      inline_path:
7250   //        vmask   = VectorMaskGen length
7251   //        vload1  = LoadVectorMasked obja, vmask
7252   //        vload2  = LoadVectorMasked objb, vmask
7253   //        result1 = VectorCmpMasked vload1, vload2, vmask
7254   //    } else {
7255   //      call_stub_path:
7256   //        result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7257   //    }
7258   //    exit_block:
7259   //      return Phi(result1, result2);
7260   //
7261   enum { inline_path = 1,  // input is small enough to process it all at once
7262          stub_path   = 2,  // input is too large; call into the VM
7263          PATH_LIMIT  = 3
7264   };
7265 
7266   Node* exit_block = new RegionNode(PATH_LIMIT);
7267   Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7268   Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7269 
7270   Node* call_stub_path = control();
7271 
7272   BasicType elem_bt = T_ILLEGAL;
7273 
7274   const TypeInt* scale_t = _gvn.type(scale)->is_int();
7275   if (scale_t->is_con()) {
7276     switch (scale_t->get_con()) {
7277       case 0: elem_bt = T_BYTE;  break;
7278       case 1: elem_bt = T_SHORT; break;
7279       case 2: elem_bt = T_INT;   break;
7280       case 3: elem_bt = T_LONG;  break;
7281 
7282       default: elem_bt = T_ILLEGAL; break; // not supported
7283     }
7284   }
7285 
7286   int inline_limit = 0;
7287   bool do_partial_inline = false;
7288 
7289   if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7290     inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7291     do_partial_inline = inline_limit >= 16;
7292   }
7293 
7294   if (do_partial_inline) {
7295     assert(elem_bt != T_ILLEGAL, "sanity");
7296 
7297     if (Matcher::match_rule_supported_vector(Op_VectorMaskGen,    inline_limit, elem_bt) &&
7298         Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7299         Matcher::match_rule_supported_vector(Op_VectorCmpMasked,  inline_limit, elem_bt)) {
7300 
7301       const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7302       Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7303       Node* bol_gt     = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7304 
7305       call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7306 
7307       if (!stopped()) {
7308         Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7309 
7310         const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7311         const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7312         Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7313         Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7314 
7315         Node* vmask      = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7316         Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7317         Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7318         Node* result     = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7319 
7320         exit_block->init_req(inline_path, control());
7321         memory_phi->init_req(inline_path, map()->memory());
7322         result_phi->init_req(inline_path, result);
7323 
7324         C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7325         clear_upper_avx();
7326       }
7327     }
7328   }
7329 
7330   if (call_stub_path != nullptr) {
7331     set_control(call_stub_path);
7332 
7333     Node* call = make_runtime_call(RC_LEAF,
7334                                    OptoRuntime::vectorizedMismatch_Type(),
7335                                    StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7336                                    obja_adr, objb_adr, length, scale);
7337 
7338     exit_block->init_req(stub_path, control());
7339     memory_phi->init_req(stub_path, map()->memory());
7340     result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7341   }
7342 
7343   exit_block = _gvn.transform(exit_block);
7344   memory_phi = _gvn.transform(memory_phi);
7345   result_phi = _gvn.transform(result_phi);
7346 
7347   record_for_igvn(exit_block);
7348   record_for_igvn(memory_phi);
7349   record_for_igvn(result_phi);
7350 
7351   set_control(exit_block);
7352   set_all_memory(memory_phi);
7353   set_result(result_phi);
7354 
7355   return true;
7356 }
7357 
7358 //------------------------------inline_vectorizedHashcode----------------------------
7359 bool LibraryCallKit::inline_vectorizedHashCode() {
7360   assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7361 
7362   assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7363   Node* array          = argument(0);
7364   Node* offset         = argument(1);
7365   Node* length         = argument(2);
7366   Node* initialValue   = argument(3);
7367   Node* basic_type     = argument(4);
7368 
7369   if (basic_type == top()) {
7370     return false; // failed input validation
7371   }
7372 
7373   const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7374   if (!basic_type_t->is_con()) {
7375     return false; // Only intrinsify if mode argument is constant
7376   }
7377 
7378   array = must_be_not_null(array, true);
7379 
7380   BasicType bt = (BasicType)basic_type_t->get_con();
7381 
7382   // Resolve address of first element
7383   Node* array_start = array_element_address(array, offset, bt);
7384 
7385   set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(TypeAryPtr::get_array_body_type(bt)),
7386     array_start, length, initialValue, basic_type)));
7387   clear_upper_avx();
7388 
7389   return true;
7390 }
7391 
7392 /**
7393  * Calculate CRC32 for byte.
7394  * int java.util.zip.CRC32.update(int crc, int b)
7395  */
7396 bool LibraryCallKit::inline_updateCRC32() {
7397   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7398   assert(callee()->signature()->size() == 2, "update has 2 parameters");
7399   // no receiver since it is static method
7400   Node* crc  = argument(0); // type: int
7401   Node* b    = argument(1); // type: int
7402 
7403   /*
7404    *    int c = ~ crc;
7405    *    b = timesXtoThe32[(b ^ c) & 0xFF];
7406    *    b = b ^ (c >>> 8);
7407    *    crc = ~b;
7408    */
7409 
7410   Node* M1 = intcon(-1);
7411   crc = _gvn.transform(new XorINode(crc, M1));
7412   Node* result = _gvn.transform(new XorINode(crc, b));
7413   result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7414 
7415   Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7416   Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7417   Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
7418   result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7419 
7420   crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7421   result = _gvn.transform(new XorINode(crc, result));
7422   result = _gvn.transform(new XorINode(result, M1));
7423   set_result(result);
7424   return true;
7425 }
7426 
7427 /**
7428  * Calculate CRC32 for byte[] array.
7429  * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7430  */
7431 bool LibraryCallKit::inline_updateBytesCRC32() {
7432   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7433   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7434   // no receiver since it is static method
7435   Node* crc     = argument(0); // type: int
7436   Node* src     = argument(1); // type: oop
7437   Node* offset  = argument(2); // type: int
7438   Node* length  = argument(3); // type: int
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   // We assume that range check is done by caller.
7457   // TODO: generate range check (offset+length < src.length) in debug VM.
7458 
7459   // Call the stub.
7460   address stubAddr = StubRoutines::updateBytesCRC32();
7461   const char *stubName = "updateBytesCRC32";
7462 
7463   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7464                                  stubAddr, stubName, TypePtr::BOTTOM,
7465                                  crc, src_start, length);
7466   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7467   set_result(result);
7468   return true;
7469 }
7470 
7471 /**
7472  * Calculate CRC32 for ByteBuffer.
7473  * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7474  */
7475 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7476   assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7477   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7478   // no receiver since it is static method
7479   Node* crc     = argument(0); // type: int
7480   Node* src     = argument(1); // type: long
7481   Node* offset  = argument(3); // type: int
7482   Node* length  = argument(4); // type: int
7483 
7484   src = ConvL2X(src);  // adjust Java long to machine word
7485   Node* base = _gvn.transform(new CastX2PNode(src));
7486   offset = ConvI2X(offset);
7487 
7488   // 'src_start' points to src array + scaled offset
7489   Node* src_start = basic_plus_adr(top(), base, offset);
7490 
7491   // Call the stub.
7492   address stubAddr = StubRoutines::updateBytesCRC32();
7493   const char *stubName = "updateBytesCRC32";
7494 
7495   Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7496                                  stubAddr, stubName, TypePtr::BOTTOM,
7497                                  crc, src_start, length);
7498   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7499   set_result(result);
7500   return true;
7501 }
7502 
7503 //------------------------------get_table_from_crc32c_class-----------------------
7504 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7505   Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7506   assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7507 
7508   return table;
7509 }
7510 
7511 //------------------------------inline_updateBytesCRC32C-----------------------
7512 //
7513 // Calculate CRC32C for byte[] array.
7514 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7515 //
7516 bool LibraryCallKit::inline_updateBytesCRC32C() {
7517   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7518   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7519   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7520   // no receiver since it is a static method
7521   Node* crc     = argument(0); // type: int
7522   Node* src     = argument(1); // type: oop
7523   Node* offset  = argument(2); // type: int
7524   Node* end     = argument(3); // type: int
7525 
7526   Node* length = _gvn.transform(new SubINode(end, offset));
7527 
7528   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7529   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7530     // failed array check
7531     return false;
7532   }
7533 
7534   // Figure out the size and type of the elements we will be copying.
7535   BasicType src_elem = src_type->elem()->array_element_basic_type();
7536   if (src_elem != T_BYTE) {
7537     return false;
7538   }
7539 
7540   // 'src_start' points to src array + scaled offset
7541   src = must_be_not_null(src, true);
7542   Node* src_start = array_element_address(src, offset, src_elem);
7543 
7544   // static final int[] byteTable in class CRC32C
7545   Node* table = get_table_from_crc32c_class(callee()->holder());
7546   table = must_be_not_null(table, true);
7547   Node* table_start = array_element_address(table, intcon(0), T_INT);
7548 
7549   // We assume that range check is done by caller.
7550   // TODO: generate range check (offset+length < src.length) in debug VM.
7551 
7552   // Call the stub.
7553   address stubAddr = StubRoutines::updateBytesCRC32C();
7554   const char *stubName = "updateBytesCRC32C";
7555 
7556   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7557                                  stubAddr, stubName, TypePtr::BOTTOM,
7558                                  crc, src_start, length, table_start);
7559   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7560   set_result(result);
7561   return true;
7562 }
7563 
7564 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7565 //
7566 // Calculate CRC32C for DirectByteBuffer.
7567 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7568 //
7569 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7570   assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7571   assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7572   assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7573   // no receiver since it is a static method
7574   Node* crc     = argument(0); // type: int
7575   Node* src     = argument(1); // type: long
7576   Node* offset  = argument(3); // type: int
7577   Node* end     = argument(4); // type: int
7578 
7579   Node* length = _gvn.transform(new SubINode(end, offset));
7580 
7581   src = ConvL2X(src);  // adjust Java long to machine word
7582   Node* base = _gvn.transform(new CastX2PNode(src));
7583   offset = ConvI2X(offset);
7584 
7585   // 'src_start' points to src array + scaled offset
7586   Node* src_start = basic_plus_adr(top(), base, offset);
7587 
7588   // static final int[] byteTable in class CRC32C
7589   Node* table = get_table_from_crc32c_class(callee()->holder());
7590   table = must_be_not_null(table, true);
7591   Node* table_start = array_element_address(table, intcon(0), T_INT);
7592 
7593   // Call the stub.
7594   address stubAddr = StubRoutines::updateBytesCRC32C();
7595   const char *stubName = "updateBytesCRC32C";
7596 
7597   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7598                                  stubAddr, stubName, TypePtr::BOTTOM,
7599                                  crc, src_start, length, table_start);
7600   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7601   set_result(result);
7602   return true;
7603 }
7604 
7605 //------------------------------inline_updateBytesAdler32----------------------
7606 //
7607 // Calculate Adler32 checksum for byte[] array.
7608 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7609 //
7610 bool LibraryCallKit::inline_updateBytesAdler32() {
7611   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7612   assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7613   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7614   // no receiver since it is static method
7615   Node* crc     = argument(0); // type: int
7616   Node* src     = argument(1); // type: oop
7617   Node* offset  = argument(2); // type: int
7618   Node* length  = argument(3); // type: int
7619 
7620   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7621   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7622     // failed array check
7623     return false;
7624   }
7625 
7626   // Figure out the size and type of the elements we will be copying.
7627   BasicType src_elem = src_type->elem()->array_element_basic_type();
7628   if (src_elem != T_BYTE) {
7629     return false;
7630   }
7631 
7632   // 'src_start' points to src array + scaled offset
7633   Node* src_start = array_element_address(src, offset, src_elem);
7634 
7635   // We assume that range check is done by caller.
7636   // TODO: generate range check (offset+length < src.length) in debug VM.
7637 
7638   // Call the stub.
7639   address stubAddr = StubRoutines::updateBytesAdler32();
7640   const char *stubName = "updateBytesAdler32";
7641 
7642   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7643                                  stubAddr, stubName, TypePtr::BOTTOM,
7644                                  crc, src_start, length);
7645   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7646   set_result(result);
7647   return true;
7648 }
7649 
7650 //------------------------------inline_updateByteBufferAdler32---------------
7651 //
7652 // Calculate Adler32 checksum for DirectByteBuffer.
7653 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7654 //
7655 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7656   assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7657   assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7658   assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7659   // no receiver since it is static method
7660   Node* crc     = argument(0); // type: int
7661   Node* src     = argument(1); // type: long
7662   Node* offset  = argument(3); // type: int
7663   Node* length  = argument(4); // type: int
7664 
7665   src = ConvL2X(src);  // adjust Java long to machine word
7666   Node* base = _gvn.transform(new CastX2PNode(src));
7667   offset = ConvI2X(offset);
7668 
7669   // 'src_start' points to src array + scaled offset
7670   Node* src_start = basic_plus_adr(top(), base, offset);
7671 
7672   // Call the stub.
7673   address stubAddr = StubRoutines::updateBytesAdler32();
7674   const char *stubName = "updateBytesAdler32";
7675 
7676   Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7677                                  stubAddr, stubName, TypePtr::BOTTOM,
7678                                  crc, src_start, length);
7679 
7680   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7681   set_result(result);
7682   return true;
7683 }
7684 
7685 //----------------------------inline_reference_get0----------------------------
7686 // public T java.lang.ref.Reference.get();
7687 bool LibraryCallKit::inline_reference_get0() {
7688   const int referent_offset = java_lang_ref_Reference::referent_offset();
7689 
7690   // Get the argument:
7691   Node* reference_obj = null_check_receiver();
7692   if (stopped()) return true;
7693 
7694   DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7695   Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7696                                         decorators, /*is_static*/ false, nullptr);
7697   if (result == nullptr) return false;
7698 
7699   // Add memory barrier to prevent commoning reads from this field
7700   // across safepoint since GC can change its value.
7701   insert_mem_bar(Op_MemBarCPUOrder);
7702 
7703   set_result(result);
7704   return true;
7705 }
7706 
7707 //----------------------------inline_reference_refersTo0----------------------------
7708 // bool java.lang.ref.Reference.refersTo0();
7709 // bool java.lang.ref.PhantomReference.refersTo0();
7710 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7711   // Get arguments:
7712   Node* reference_obj = null_check_receiver();
7713   Node* other_obj = argument(1);
7714   if (stopped()) return true;
7715 
7716   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7717   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7718   Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7719                                           decorators, /*is_static*/ false, nullptr);
7720   if (referent == nullptr) return false;
7721 
7722   // Add memory barrier to prevent commoning reads from this field
7723   // across safepoint since GC can change its value.
7724   insert_mem_bar(Op_MemBarCPUOrder);
7725 
7726   Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7727   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7728   IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7729 
7730   RegionNode* region = new RegionNode(3);
7731   PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7732 
7733   Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7734   region->init_req(1, if_true);
7735   phi->init_req(1, intcon(1));
7736 
7737   Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7738   region->init_req(2, if_false);
7739   phi->init_req(2, intcon(0));
7740 
7741   set_control(_gvn.transform(region));
7742   record_for_igvn(region);
7743   set_result(_gvn.transform(phi));
7744   return true;
7745 }
7746 
7747 //----------------------------inline_reference_clear0----------------------------
7748 // void java.lang.ref.Reference.clear0();
7749 // void java.lang.ref.PhantomReference.clear0();
7750 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7751   // This matches the implementation in JVM_ReferenceClear, see the comments there.
7752 
7753   // Get arguments
7754   Node* reference_obj = null_check_receiver();
7755   if (stopped()) return true;
7756 
7757   // Common access parameters
7758   DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7759   decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7760   Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7761   const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7762   const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7763 
7764   Node* referent = access_load_at(reference_obj,
7765                                   referent_field_addr,
7766                                   referent_field_addr_type,
7767                                   val_type,
7768                                   T_OBJECT,
7769                                   decorators);
7770 
7771   IdealKit ideal(this);
7772 #define __ ideal.
7773   __ if_then(referent, BoolTest::ne, null());
7774     sync_kit(ideal);
7775     access_store_at(reference_obj,
7776                     referent_field_addr,
7777                     referent_field_addr_type,
7778                     null(),
7779                     val_type,
7780                     T_OBJECT,
7781                     decorators);
7782     __ sync_kit(this);
7783   __ end_if();
7784   final_sync(ideal);
7785 #undef __
7786 
7787   return true;
7788 }
7789 
7790 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7791                                              DecoratorSet decorators, bool is_static,
7792                                              ciInstanceKlass* fromKls) {
7793   if (fromKls == nullptr) {
7794     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7795     assert(tinst != nullptr, "obj is null");
7796     assert(tinst->is_loaded(), "obj is not loaded");
7797     fromKls = tinst->instance_klass();
7798   } else {
7799     assert(is_static, "only for static field access");
7800   }
7801   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7802                                               ciSymbol::make(fieldTypeString),
7803                                               is_static);
7804 
7805   assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7806   if (field == nullptr) return (Node *) nullptr;
7807 
7808   if (is_static) {
7809     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7810     fromObj = makecon(tip);
7811   }
7812 
7813   // Next code  copied from Parse::do_get_xxx():
7814 
7815   // Compute address and memory type.
7816   int offset  = field->offset_in_bytes();
7817   bool is_vol = field->is_volatile();
7818   ciType* field_klass = field->type();
7819   assert(field_klass->is_loaded(), "should be loaded");
7820   const TypePtr* adr_type = C->alias_type(field)->adr_type();
7821   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7822   assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7823     "slice of address and input slice don't match");
7824   BasicType bt = field->layout_type();
7825 
7826   // Build the resultant type of the load
7827   const Type *type;
7828   if (bt == T_OBJECT) {
7829     type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7830   } else {
7831     type = Type::get_const_basic_type(bt);
7832   }
7833 
7834   if (is_vol) {
7835     decorators |= MO_SEQ_CST;
7836   }
7837 
7838   return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7839 }
7840 
7841 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7842                                                  bool is_exact /* true */, bool is_static /* false */,
7843                                                  ciInstanceKlass * fromKls /* nullptr */) {
7844   if (fromKls == nullptr) {
7845     const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7846     assert(tinst != nullptr, "obj is null");
7847     assert(tinst->is_loaded(), "obj is not loaded");
7848     assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7849     fromKls = tinst->instance_klass();
7850   }
7851   else {
7852     assert(is_static, "only for static field access");
7853   }
7854   ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7855     ciSymbol::make(fieldTypeString),
7856     is_static);
7857 
7858   assert(field != nullptr, "undefined field");
7859   assert(!field->is_volatile(), "not defined for volatile fields");
7860 
7861   if (is_static) {
7862     const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7863     fromObj = makecon(tip);
7864   }
7865 
7866   // Next code  copied from Parse::do_get_xxx():
7867 
7868   // Compute address and memory type.
7869   int offset = field->offset_in_bytes();
7870   Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7871 
7872   return adr;
7873 }
7874 
7875 //------------------------------inline_aescrypt_Block-----------------------
7876 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7877   address stubAddr = nullptr;
7878   const char *stubName;
7879   bool is_decrypt = false;
7880   assert(UseAES, "need AES instruction support");
7881 
7882   switch(id) {
7883   case vmIntrinsics::_aescrypt_encryptBlock:
7884     stubAddr = StubRoutines::aescrypt_encryptBlock();
7885     stubName = "aescrypt_encryptBlock";
7886     break;
7887   case vmIntrinsics::_aescrypt_decryptBlock:
7888     stubAddr = StubRoutines::aescrypt_decryptBlock();
7889     stubName = "aescrypt_decryptBlock";
7890     is_decrypt = true;
7891     break;
7892   default:
7893     break;
7894   }
7895   if (stubAddr == nullptr) return false;
7896 
7897   Node* aescrypt_object = argument(0);
7898   Node* src             = argument(1);
7899   Node* src_offset      = argument(2);
7900   Node* dest            = argument(3);
7901   Node* dest_offset     = argument(4);
7902 
7903   src = must_be_not_null(src, true);
7904   dest = must_be_not_null(dest, true);
7905 
7906   // (1) src and dest are arrays.
7907   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7908   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7909   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7910          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7911 
7912   // for the quick and dirty code we will skip all the checks.
7913   // we are just trying to get the call to be generated.
7914   Node* src_start  = src;
7915   Node* dest_start = dest;
7916   if (src_offset != nullptr || dest_offset != nullptr) {
7917     assert(src_offset != nullptr && dest_offset != nullptr, "");
7918     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7919     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7920   }
7921 
7922   // now need to get the start of its expanded key array
7923   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7924   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7925   if (k_start == nullptr) return false;
7926 
7927   // Call the stub.
7928   make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
7929                     stubAddr, stubName, TypePtr::BOTTOM,
7930                     src_start, dest_start, k_start);
7931 
7932   return true;
7933 }
7934 
7935 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
7936 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
7937   address stubAddr = nullptr;
7938   const char *stubName = nullptr;
7939   bool is_decrypt = false;
7940   assert(UseAES, "need AES instruction support");
7941 
7942   switch(id) {
7943   case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
7944     stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
7945     stubName = "cipherBlockChaining_encryptAESCrypt";
7946     break;
7947   case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
7948     stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
7949     stubName = "cipherBlockChaining_decryptAESCrypt";
7950     is_decrypt = true;
7951     break;
7952   default:
7953     break;
7954   }
7955   if (stubAddr == nullptr) return false;
7956 
7957   Node* cipherBlockChaining_object = argument(0);
7958   Node* src                        = argument(1);
7959   Node* src_offset                 = argument(2);
7960   Node* len                        = argument(3);
7961   Node* dest                       = argument(4);
7962   Node* dest_offset                = argument(5);
7963 
7964   src = must_be_not_null(src, false);
7965   dest = must_be_not_null(dest, false);
7966 
7967   // (1) src and dest are arrays.
7968   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7969   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7970   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
7971          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7972 
7973   // checks are the responsibility of the caller
7974   Node* src_start  = src;
7975   Node* dest_start = dest;
7976   if (src_offset != nullptr || dest_offset != nullptr) {
7977     assert(src_offset != nullptr && dest_offset != nullptr, "");
7978     src_start  = array_element_address(src,  src_offset,  T_BYTE);
7979     dest_start = array_element_address(dest, dest_offset, T_BYTE);
7980   }
7981 
7982   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7983   // (because of the predicated logic executed earlier).
7984   // so we cast it here safely.
7985   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7986 
7987   Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7988   if (embeddedCipherObj == nullptr) return false;
7989 
7990   // cast it to what we know it will be at runtime
7991   const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
7992   assert(tinst != nullptr, "CBC obj is null");
7993   assert(tinst->is_loaded(), "CBC obj is not loaded");
7994   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7995   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7996 
7997   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7998   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7999   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8000   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8001   aescrypt_object = _gvn.transform(aescrypt_object);
8002 
8003   // we need to get the start of the aescrypt_object's expanded key array
8004   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8005   if (k_start == nullptr) return false;
8006 
8007   // similarly, get the start address of the r vector
8008   Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
8009   if (objRvec == nullptr) return false;
8010   Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
8011 
8012   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8013   Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8014                                      OptoRuntime::cipherBlockChaining_aescrypt_Type(),
8015                                      stubAddr, stubName, TypePtr::BOTTOM,
8016                                      src_start, dest_start, k_start, r_start, len);
8017 
8018   // return cipher length (int)
8019   Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
8020   set_result(retvalue);
8021   return true;
8022 }
8023 
8024 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
8025 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
8026   address stubAddr = nullptr;
8027   const char *stubName = nullptr;
8028   bool is_decrypt = false;
8029   assert(UseAES, "need AES instruction support");
8030 
8031   switch (id) {
8032   case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
8033     stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
8034     stubName = "electronicCodeBook_encryptAESCrypt";
8035     break;
8036   case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
8037     stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
8038     stubName = "electronicCodeBook_decryptAESCrypt";
8039     is_decrypt = true;
8040     break;
8041   default:
8042     break;
8043   }
8044 
8045   if (stubAddr == nullptr) return false;
8046 
8047   Node* electronicCodeBook_object = argument(0);
8048   Node* src                       = argument(1);
8049   Node* src_offset                = argument(2);
8050   Node* len                       = argument(3);
8051   Node* dest                      = argument(4);
8052   Node* dest_offset               = argument(5);
8053 
8054   // (1) src and dest are arrays.
8055   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8056   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8057   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8058          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8059 
8060   // checks are the responsibility of the caller
8061   Node* src_start = src;
8062   Node* dest_start = dest;
8063   if (src_offset != nullptr || dest_offset != nullptr) {
8064     assert(src_offset != nullptr && dest_offset != nullptr, "");
8065     src_start = array_element_address(src, src_offset, T_BYTE);
8066     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8067   }
8068 
8069   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8070   // (because of the predicated logic executed earlier).
8071   // so we cast it here safely.
8072   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8073 
8074   Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8075   if (embeddedCipherObj == nullptr) return false;
8076 
8077   // cast it to what we know it will be at runtime
8078   const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
8079   assert(tinst != nullptr, "ECB obj is null");
8080   assert(tinst->is_loaded(), "ECB obj is not loaded");
8081   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8082   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8083 
8084   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8085   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8086   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8087   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8088   aescrypt_object = _gvn.transform(aescrypt_object);
8089 
8090   // we need to get the start of the aescrypt_object's expanded key array
8091   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8092   if (k_start == nullptr) return false;
8093 
8094   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8095   Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8096                                      OptoRuntime::electronicCodeBook_aescrypt_Type(),
8097                                      stubAddr, stubName, TypePtr::BOTTOM,
8098                                      src_start, dest_start, k_start, len);
8099 
8100   // return cipher length (int)
8101   Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8102   set_result(retvalue);
8103   return true;
8104 }
8105 
8106 //------------------------------inline_counterMode_AESCrypt-----------------------
8107 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8108   assert(UseAES, "need AES instruction support");
8109   if (!UseAESCTRIntrinsics) return false;
8110 
8111   address stubAddr = nullptr;
8112   const char *stubName = nullptr;
8113   if (id == vmIntrinsics::_counterMode_AESCrypt) {
8114     stubAddr = StubRoutines::counterMode_AESCrypt();
8115     stubName = "counterMode_AESCrypt";
8116   }
8117   if (stubAddr == nullptr) return false;
8118 
8119   Node* counterMode_object = argument(0);
8120   Node* src = argument(1);
8121   Node* src_offset = argument(2);
8122   Node* len = argument(3);
8123   Node* dest = argument(4);
8124   Node* dest_offset = argument(5);
8125 
8126   // (1) src and dest are arrays.
8127   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8128   const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8129   assert( src_type != nullptr &&  src_type->elem() != Type::BOTTOM &&
8130          dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8131 
8132   // checks are the responsibility of the caller
8133   Node* src_start = src;
8134   Node* dest_start = dest;
8135   if (src_offset != nullptr || dest_offset != nullptr) {
8136     assert(src_offset != nullptr && dest_offset != nullptr, "");
8137     src_start = array_element_address(src, src_offset, T_BYTE);
8138     dest_start = array_element_address(dest, dest_offset, T_BYTE);
8139   }
8140 
8141   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8142   // (because of the predicated logic executed earlier).
8143   // so we cast it here safely.
8144   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8145   Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8146   if (embeddedCipherObj == nullptr) return false;
8147   // cast it to what we know it will be at runtime
8148   const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8149   assert(tinst != nullptr, "CTR obj is null");
8150   assert(tinst->is_loaded(), "CTR obj is not loaded");
8151   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8152   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8153   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8154   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8155   const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8156   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8157   aescrypt_object = _gvn.transform(aescrypt_object);
8158   // we need to get the start of the aescrypt_object's expanded key array
8159   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
8160   if (k_start == nullptr) return false;
8161   // similarly, get the start address of the r vector
8162   Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8163   if (obj_counter == nullptr) return false;
8164   Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8165 
8166   Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8167   if (saved_encCounter == nullptr) return false;
8168   Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8169   Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8170 
8171   // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8172   Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8173                                      OptoRuntime::counterMode_aescrypt_Type(),
8174                                      stubAddr, stubName, TypePtr::BOTTOM,
8175                                      src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8176 
8177   // return cipher length (int)
8178   Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8179   set_result(retvalue);
8180   return true;
8181 }
8182 
8183 //------------------------------get_key_start_from_aescrypt_object-----------------------
8184 Node* LibraryCallKit::get_key_start_from_aescrypt_object(Node* aescrypt_object, bool is_decrypt) {
8185   // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8186   // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8187   // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8188   // The following platform specific stubs of encryption and decryption use the same round keys.
8189 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8190   bool use_decryption_key = false;
8191 #else
8192   bool use_decryption_key = is_decrypt;
8193 #endif
8194   Node* objAESCryptKey = load_field_from_object(aescrypt_object, use_decryption_key ? "sessionKd" : "sessionKe", "[I");
8195   assert(objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8196   if (objAESCryptKey == nullptr) return (Node *) nullptr;
8197 
8198   // now have the array, need to get the start address of the selected key array
8199   Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8200   return k_start;
8201 }
8202 
8203 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8204 // Return node representing slow path of predicate check.
8205 // the pseudo code we want to emulate with this predicate is:
8206 // for encryption:
8207 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8208 // for decryption:
8209 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8210 //    note cipher==plain is more conservative than the original java code but that's OK
8211 //
8212 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8213   // The receiver was checked for null already.
8214   Node* objCBC = argument(0);
8215 
8216   Node* src = argument(1);
8217   Node* dest = argument(4);
8218 
8219   // Load embeddedCipher field of CipherBlockChaining object.
8220   Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8221 
8222   // get AESCrypt klass for instanceOf check
8223   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8224   // will have same classloader as CipherBlockChaining object
8225   const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8226   assert(tinst != nullptr, "CBCobj is null");
8227   assert(tinst->is_loaded(), "CBCobj is not loaded");
8228 
8229   // we want to do an instanceof comparison against the AESCrypt class
8230   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8231   if (!klass_AESCrypt->is_loaded()) {
8232     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8233     Node* ctrl = control();
8234     set_control(top()); // no regular fast path
8235     return ctrl;
8236   }
8237 
8238   src = must_be_not_null(src, true);
8239   dest = must_be_not_null(dest, true);
8240 
8241   // Resolve oops to stable for CmpP below.
8242   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8243 
8244   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8245   Node* cmp_instof  = _gvn.transform(new CmpINode(instof, intcon(1)));
8246   Node* bool_instof  = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8247 
8248   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8249 
8250   // for encryption, we are done
8251   if (!decrypting)
8252     return instof_false;  // even if it is null
8253 
8254   // for decryption, we need to add a further check to avoid
8255   // taking the intrinsic path when cipher and plain are the same
8256   // see the original java code for why.
8257   RegionNode* region = new RegionNode(3);
8258   region->init_req(1, instof_false);
8259 
8260   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8261   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8262   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8263   region->init_req(2, src_dest_conjoint);
8264 
8265   record_for_igvn(region);
8266   return _gvn.transform(region);
8267 }
8268 
8269 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8270 // Return node representing slow path of predicate check.
8271 // the pseudo code we want to emulate with this predicate is:
8272 // for encryption:
8273 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8274 // for decryption:
8275 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8276 //    note cipher==plain is more conservative than the original java code but that's OK
8277 //
8278 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8279   // The receiver was checked for null already.
8280   Node* objECB = argument(0);
8281 
8282   // Load embeddedCipher field of ElectronicCodeBook object.
8283   Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8284 
8285   // get AESCrypt klass for instanceOf check
8286   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8287   // will have same classloader as ElectronicCodeBook object
8288   const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8289   assert(tinst != nullptr, "ECBobj is null");
8290   assert(tinst->is_loaded(), "ECBobj is not loaded");
8291 
8292   // we want to do an instanceof comparison against the AESCrypt class
8293   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8294   if (!klass_AESCrypt->is_loaded()) {
8295     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8296     Node* ctrl = control();
8297     set_control(top()); // no regular fast path
8298     return ctrl;
8299   }
8300   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8301 
8302   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8303   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8304   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8305 
8306   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8307 
8308   // for encryption, we are done
8309   if (!decrypting)
8310     return instof_false;  // even if it is null
8311 
8312   // for decryption, we need to add a further check to avoid
8313   // taking the intrinsic path when cipher and plain are the same
8314   // see the original java code for why.
8315   RegionNode* region = new RegionNode(3);
8316   region->init_req(1, instof_false);
8317   Node* src = argument(1);
8318   Node* dest = argument(4);
8319   Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8320   Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8321   Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8322   region->init_req(2, src_dest_conjoint);
8323 
8324   record_for_igvn(region);
8325   return _gvn.transform(region);
8326 }
8327 
8328 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8329 // Return node representing slow path of predicate check.
8330 // the pseudo code we want to emulate with this predicate is:
8331 // for encryption:
8332 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8333 // for decryption:
8334 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8335 //    note cipher==plain is more conservative than the original java code but that's OK
8336 //
8337 
8338 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8339   // The receiver was checked for null already.
8340   Node* objCTR = argument(0);
8341 
8342   // Load embeddedCipher field of CipherBlockChaining object.
8343   Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8344 
8345   // get AESCrypt klass for instanceOf check
8346   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8347   // will have same classloader as CipherBlockChaining object
8348   const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8349   assert(tinst != nullptr, "CTRobj is null");
8350   assert(tinst->is_loaded(), "CTRobj is not loaded");
8351 
8352   // we want to do an instanceof comparison against the AESCrypt class
8353   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8354   if (!klass_AESCrypt->is_loaded()) {
8355     // if AESCrypt is not even loaded, we never take the intrinsic fast path
8356     Node* ctrl = control();
8357     set_control(top()); // no regular fast path
8358     return ctrl;
8359   }
8360 
8361   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8362   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8363   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8364   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8365   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8366 
8367   return instof_false; // even if it is null
8368 }
8369 
8370 //------------------------------inline_ghash_processBlocks
8371 bool LibraryCallKit::inline_ghash_processBlocks() {
8372   address stubAddr;
8373   const char *stubName;
8374   assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8375 
8376   stubAddr = StubRoutines::ghash_processBlocks();
8377   stubName = "ghash_processBlocks";
8378 
8379   Node* data           = argument(0);
8380   Node* offset         = argument(1);
8381   Node* len            = argument(2);
8382   Node* state          = argument(3);
8383   Node* subkeyH        = argument(4);
8384 
8385   state = must_be_not_null(state, true);
8386   subkeyH = must_be_not_null(subkeyH, true);
8387   data = must_be_not_null(data, true);
8388 
8389   Node* state_start  = array_element_address(state, intcon(0), T_LONG);
8390   assert(state_start, "state is null");
8391   Node* subkeyH_start  = array_element_address(subkeyH, intcon(0), T_LONG);
8392   assert(subkeyH_start, "subkeyH is null");
8393   Node* data_start  = array_element_address(data, offset, T_BYTE);
8394   assert(data_start, "data is null");
8395 
8396   Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8397                                   OptoRuntime::ghash_processBlocks_Type(),
8398                                   stubAddr, stubName, TypePtr::BOTTOM,
8399                                   state_start, subkeyH_start, data_start, len);
8400   return true;
8401 }
8402 
8403 //------------------------------inline_chacha20Block
8404 bool LibraryCallKit::inline_chacha20Block() {
8405   address stubAddr;
8406   const char *stubName;
8407   assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8408 
8409   stubAddr = StubRoutines::chacha20Block();
8410   stubName = "chacha20Block";
8411 
8412   Node* state          = argument(0);
8413   Node* result         = argument(1);
8414 
8415   state = must_be_not_null(state, true);
8416   result = must_be_not_null(result, true);
8417 
8418   Node* state_start  = array_element_address(state, intcon(0), T_INT);
8419   assert(state_start, "state is null");
8420   Node* result_start  = array_element_address(result, intcon(0), T_BYTE);
8421   assert(result_start, "result is null");
8422 
8423   Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8424                                   OptoRuntime::chacha20Block_Type(),
8425                                   stubAddr, stubName, TypePtr::BOTTOM,
8426                                   state_start, result_start);
8427   // return key stream length (int)
8428   Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8429   set_result(retvalue);
8430   return true;
8431 }
8432 
8433 //------------------------------inline_kyberNtt
8434 bool LibraryCallKit::inline_kyberNtt() {
8435   address stubAddr;
8436   const char *stubName;
8437   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8438   assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8439 
8440   stubAddr = StubRoutines::kyberNtt();
8441   stubName = "kyberNtt";
8442   if (!stubAddr) return false;
8443 
8444   Node* coeffs          = argument(0);
8445   Node* ntt_zetas        = argument(1);
8446 
8447   coeffs = must_be_not_null(coeffs, true);
8448   ntt_zetas = must_be_not_null(ntt_zetas, true);
8449 
8450   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8451   assert(coeffs_start, "coeffs is null");
8452   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8453   assert(ntt_zetas_start, "ntt_zetas is null");
8454   Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8455                                   OptoRuntime::kyberNtt_Type(),
8456                                   stubAddr, stubName, TypePtr::BOTTOM,
8457                                   coeffs_start, ntt_zetas_start);
8458   // return an int
8459   Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8460   set_result(retvalue);
8461   return true;
8462 }
8463 
8464 //------------------------------inline_kyberInverseNtt
8465 bool LibraryCallKit::inline_kyberInverseNtt() {
8466   address stubAddr;
8467   const char *stubName;
8468   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8469   assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8470 
8471   stubAddr = StubRoutines::kyberInverseNtt();
8472   stubName = "kyberInverseNtt";
8473   if (!stubAddr) return false;
8474 
8475   Node* coeffs          = argument(0);
8476   Node* zetas           = argument(1);
8477 
8478   coeffs = must_be_not_null(coeffs, true);
8479   zetas = must_be_not_null(zetas, true);
8480 
8481   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8482   assert(coeffs_start, "coeffs is null");
8483   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8484   assert(zetas_start, "inverseNtt_zetas is null");
8485   Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8486                                   OptoRuntime::kyberInverseNtt_Type(),
8487                                   stubAddr, stubName, TypePtr::BOTTOM,
8488                                   coeffs_start, zetas_start);
8489 
8490   // return an int
8491   Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8492   set_result(retvalue);
8493   return true;
8494 }
8495 
8496 //------------------------------inline_kyberNttMult
8497 bool LibraryCallKit::inline_kyberNttMult() {
8498   address stubAddr;
8499   const char *stubName;
8500   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8501   assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8502 
8503   stubAddr = StubRoutines::kyberNttMult();
8504   stubName = "kyberNttMult";
8505   if (!stubAddr) return false;
8506 
8507   Node* result          = argument(0);
8508   Node* ntta            = argument(1);
8509   Node* nttb            = argument(2);
8510   Node* zetas           = argument(3);
8511 
8512   result = must_be_not_null(result, true);
8513   ntta = must_be_not_null(ntta, true);
8514   nttb = must_be_not_null(nttb, true);
8515   zetas = must_be_not_null(zetas, true);
8516 
8517   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8518   assert(result_start, "result is null");
8519   Node* ntta_start  = array_element_address(ntta, intcon(0), T_SHORT);
8520   assert(ntta_start, "ntta is null");
8521   Node* nttb_start  = array_element_address(nttb, intcon(0), T_SHORT);
8522   assert(nttb_start, "nttb is null");
8523   Node* zetas_start  = array_element_address(zetas, intcon(0), T_SHORT);
8524   assert(zetas_start, "nttMult_zetas is null");
8525   Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8526                                   OptoRuntime::kyberNttMult_Type(),
8527                                   stubAddr, stubName, TypePtr::BOTTOM,
8528                                   result_start, ntta_start, nttb_start,
8529                                   zetas_start);
8530 
8531   // return an int
8532   Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8533   set_result(retvalue);
8534 
8535   return true;
8536 }
8537 
8538 //------------------------------inline_kyberAddPoly_2
8539 bool LibraryCallKit::inline_kyberAddPoly_2() {
8540   address stubAddr;
8541   const char *stubName;
8542   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8543   assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8544 
8545   stubAddr = StubRoutines::kyberAddPoly_2();
8546   stubName = "kyberAddPoly_2";
8547   if (!stubAddr) return false;
8548 
8549   Node* result          = argument(0);
8550   Node* a               = argument(1);
8551   Node* b               = argument(2);
8552 
8553   result = must_be_not_null(result, true);
8554   a = must_be_not_null(a, true);
8555   b = must_be_not_null(b, true);
8556 
8557   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8558   assert(result_start, "result is null");
8559   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8560   assert(a_start, "a is null");
8561   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8562   assert(b_start, "b is null");
8563   Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8564                                   OptoRuntime::kyberAddPoly_2_Type(),
8565                                   stubAddr, stubName, TypePtr::BOTTOM,
8566                                   result_start, a_start, b_start);
8567   // return an int
8568   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8569   set_result(retvalue);
8570   return true;
8571 }
8572 
8573 //------------------------------inline_kyberAddPoly_3
8574 bool LibraryCallKit::inline_kyberAddPoly_3() {
8575   address stubAddr;
8576   const char *stubName;
8577   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8578   assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8579 
8580   stubAddr = StubRoutines::kyberAddPoly_3();
8581   stubName = "kyberAddPoly_3";
8582   if (!stubAddr) return false;
8583 
8584   Node* result          = argument(0);
8585   Node* a               = argument(1);
8586   Node* b               = argument(2);
8587   Node* c               = argument(3);
8588 
8589   result = must_be_not_null(result, true);
8590   a = must_be_not_null(a, true);
8591   b = must_be_not_null(b, true);
8592   c = must_be_not_null(c, true);
8593 
8594   Node* result_start  = array_element_address(result, intcon(0), T_SHORT);
8595   assert(result_start, "result is null");
8596   Node* a_start  = array_element_address(a, intcon(0), T_SHORT);
8597   assert(a_start, "a is null");
8598   Node* b_start  = array_element_address(b, intcon(0), T_SHORT);
8599   assert(b_start, "b is null");
8600   Node* c_start  = array_element_address(c, intcon(0), T_SHORT);
8601   assert(c_start, "c is null");
8602   Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8603                                   OptoRuntime::kyberAddPoly_3_Type(),
8604                                   stubAddr, stubName, TypePtr::BOTTOM,
8605                                   result_start, a_start, b_start, c_start);
8606   // return an int
8607   Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8608   set_result(retvalue);
8609   return true;
8610 }
8611 
8612 //------------------------------inline_kyber12To16
8613 bool LibraryCallKit::inline_kyber12To16() {
8614   address stubAddr;
8615   const char *stubName;
8616   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8617   assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8618 
8619   stubAddr = StubRoutines::kyber12To16();
8620   stubName = "kyber12To16";
8621   if (!stubAddr) return false;
8622 
8623   Node* condensed       = argument(0);
8624   Node* condensedOffs   = argument(1);
8625   Node* parsed          = argument(2);
8626   Node* parsedLength    = argument(3);
8627 
8628   condensed = must_be_not_null(condensed, true);
8629   parsed = must_be_not_null(parsed, true);
8630 
8631   Node* condensed_start  = array_element_address(condensed, intcon(0), T_BYTE);
8632   assert(condensed_start, "condensed is null");
8633   Node* parsed_start  = array_element_address(parsed, intcon(0), T_SHORT);
8634   assert(parsed_start, "parsed is null");
8635   Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8636                                   OptoRuntime::kyber12To16_Type(),
8637                                   stubAddr, stubName, TypePtr::BOTTOM,
8638                                   condensed_start, condensedOffs, parsed_start, parsedLength);
8639   // return an int
8640   Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8641   set_result(retvalue);
8642   return true;
8643 
8644 }
8645 
8646 //------------------------------inline_kyberBarrettReduce
8647 bool LibraryCallKit::inline_kyberBarrettReduce() {
8648   address stubAddr;
8649   const char *stubName;
8650   assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8651   assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8652 
8653   stubAddr = StubRoutines::kyberBarrettReduce();
8654   stubName = "kyberBarrettReduce";
8655   if (!stubAddr) return false;
8656 
8657   Node* coeffs          = argument(0);
8658 
8659   coeffs = must_be_not_null(coeffs, true);
8660 
8661   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_SHORT);
8662   assert(coeffs_start, "coeffs is null");
8663   Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8664                                   OptoRuntime::kyberBarrettReduce_Type(),
8665                                   stubAddr, stubName, TypePtr::BOTTOM,
8666                                   coeffs_start);
8667   // return an int
8668   Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8669   set_result(retvalue);
8670   return true;
8671 }
8672 
8673 //------------------------------inline_dilithiumAlmostNtt
8674 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8675   address stubAddr;
8676   const char *stubName;
8677   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8678   assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8679 
8680   stubAddr = StubRoutines::dilithiumAlmostNtt();
8681   stubName = "dilithiumAlmostNtt";
8682   if (!stubAddr) return false;
8683 
8684   Node* coeffs          = argument(0);
8685   Node* ntt_zetas        = argument(1);
8686 
8687   coeffs = must_be_not_null(coeffs, true);
8688   ntt_zetas = must_be_not_null(ntt_zetas, true);
8689 
8690   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8691   assert(coeffs_start, "coeffs is null");
8692   Node* ntt_zetas_start  = array_element_address(ntt_zetas, intcon(0), T_INT);
8693   assert(ntt_zetas_start, "ntt_zetas is null");
8694   Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8695                                   OptoRuntime::dilithiumAlmostNtt_Type(),
8696                                   stubAddr, stubName, TypePtr::BOTTOM,
8697                                   coeffs_start, ntt_zetas_start);
8698   // return an int
8699   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8700   set_result(retvalue);
8701   return true;
8702 }
8703 
8704 //------------------------------inline_dilithiumAlmostInverseNtt
8705 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8706   address stubAddr;
8707   const char *stubName;
8708   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8709   assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8710 
8711   stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8712   stubName = "dilithiumAlmostInverseNtt";
8713   if (!stubAddr) return false;
8714 
8715   Node* coeffs          = argument(0);
8716   Node* zetas           = argument(1);
8717 
8718   coeffs = must_be_not_null(coeffs, true);
8719   zetas = must_be_not_null(zetas, true);
8720 
8721   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8722   assert(coeffs_start, "coeffs is null");
8723   Node* zetas_start  = array_element_address(zetas, intcon(0), T_INT);
8724   assert(zetas_start, "inverseNtt_zetas is null");
8725   Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8726                                   OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8727                                   stubAddr, stubName, TypePtr::BOTTOM,
8728                                   coeffs_start, zetas_start);
8729   // return an int
8730   Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8731   set_result(retvalue);
8732   return true;
8733 }
8734 
8735 //------------------------------inline_dilithiumNttMult
8736 bool LibraryCallKit::inline_dilithiumNttMult() {
8737   address stubAddr;
8738   const char *stubName;
8739   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8740   assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8741 
8742   stubAddr = StubRoutines::dilithiumNttMult();
8743   stubName = "dilithiumNttMult";
8744   if (!stubAddr) return false;
8745 
8746   Node* result          = argument(0);
8747   Node* ntta            = argument(1);
8748   Node* nttb            = argument(2);
8749   Node* zetas           = argument(3);
8750 
8751   result = must_be_not_null(result, true);
8752   ntta = must_be_not_null(ntta, true);
8753   nttb = must_be_not_null(nttb, true);
8754   zetas = must_be_not_null(zetas, true);
8755 
8756   Node* result_start  = array_element_address(result, intcon(0), T_INT);
8757   assert(result_start, "result is null");
8758   Node* ntta_start  = array_element_address(ntta, intcon(0), T_INT);
8759   assert(ntta_start, "ntta is null");
8760   Node* nttb_start  = array_element_address(nttb, intcon(0), T_INT);
8761   assert(nttb_start, "nttb is null");
8762   Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8763                                   OptoRuntime::dilithiumNttMult_Type(),
8764                                   stubAddr, stubName, TypePtr::BOTTOM,
8765                                   result_start, ntta_start, nttb_start);
8766 
8767   // return an int
8768   Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8769   set_result(retvalue);
8770 
8771   return true;
8772 }
8773 
8774 //------------------------------inline_dilithiumMontMulByConstant
8775 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8776   address stubAddr;
8777   const char *stubName;
8778   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8779   assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8780 
8781   stubAddr = StubRoutines::dilithiumMontMulByConstant();
8782   stubName = "dilithiumMontMulByConstant";
8783   if (!stubAddr) return false;
8784 
8785   Node* coeffs          = argument(0);
8786   Node* constant        = argument(1);
8787 
8788   coeffs = must_be_not_null(coeffs, true);
8789 
8790   Node* coeffs_start  = array_element_address(coeffs, intcon(0), T_INT);
8791   assert(coeffs_start, "coeffs is null");
8792   Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8793                                   OptoRuntime::dilithiumMontMulByConstant_Type(),
8794                                   stubAddr, stubName, TypePtr::BOTTOM,
8795                                   coeffs_start, constant);
8796 
8797   // return an int
8798   Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8799   set_result(retvalue);
8800   return true;
8801 }
8802 
8803 
8804 //------------------------------inline_dilithiumDecomposePoly
8805 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8806   address stubAddr;
8807   const char *stubName;
8808   assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8809   assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8810 
8811   stubAddr = StubRoutines::dilithiumDecomposePoly();
8812   stubName = "dilithiumDecomposePoly";
8813   if (!stubAddr) return false;
8814 
8815   Node* input          = argument(0);
8816   Node* lowPart        = argument(1);
8817   Node* highPart       = argument(2);
8818   Node* twoGamma2      = argument(3);
8819   Node* multiplier     = argument(4);
8820 
8821   input = must_be_not_null(input, true);
8822   lowPart = must_be_not_null(lowPart, true);
8823   highPart = must_be_not_null(highPart, true);
8824 
8825   Node* input_start  = array_element_address(input, intcon(0), T_INT);
8826   assert(input_start, "input is null");
8827   Node* lowPart_start  = array_element_address(lowPart, intcon(0), T_INT);
8828   assert(lowPart_start, "lowPart is null");
8829   Node* highPart_start  = array_element_address(highPart, intcon(0), T_INT);
8830   assert(highPart_start, "highPart is null");
8831 
8832   Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8833                                   OptoRuntime::dilithiumDecomposePoly_Type(),
8834                                   stubAddr, stubName, TypePtr::BOTTOM,
8835                                   input_start, lowPart_start, highPart_start,
8836                                   twoGamma2, multiplier);
8837 
8838   // return an int
8839   Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8840   set_result(retvalue);
8841   return true;
8842 }
8843 
8844 bool LibraryCallKit::inline_base64_encodeBlock() {
8845   address stubAddr;
8846   const char *stubName;
8847   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8848   assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8849   stubAddr = StubRoutines::base64_encodeBlock();
8850   stubName = "encodeBlock";
8851 
8852   if (!stubAddr) return false;
8853   Node* base64obj = argument(0);
8854   Node* src = argument(1);
8855   Node* offset = argument(2);
8856   Node* len = argument(3);
8857   Node* dest = argument(4);
8858   Node* dp = argument(5);
8859   Node* isURL = argument(6);
8860 
8861   src = must_be_not_null(src, true);
8862   dest = must_be_not_null(dest, true);
8863 
8864   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8865   assert(src_start, "source array is null");
8866   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8867   assert(dest_start, "destination array is null");
8868 
8869   Node* base64 = make_runtime_call(RC_LEAF,
8870                                    OptoRuntime::base64_encodeBlock_Type(),
8871                                    stubAddr, stubName, TypePtr::BOTTOM,
8872                                    src_start, offset, len, dest_start, dp, isURL);
8873   return true;
8874 }
8875 
8876 bool LibraryCallKit::inline_base64_decodeBlock() {
8877   address stubAddr;
8878   const char *stubName;
8879   assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8880   assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8881   stubAddr = StubRoutines::base64_decodeBlock();
8882   stubName = "decodeBlock";
8883 
8884   if (!stubAddr) return false;
8885   Node* base64obj = argument(0);
8886   Node* src = argument(1);
8887   Node* src_offset = argument(2);
8888   Node* len = argument(3);
8889   Node* dest = argument(4);
8890   Node* dest_offset = argument(5);
8891   Node* isURL = argument(6);
8892   Node* isMIME = argument(7);
8893 
8894   src = must_be_not_null(src, true);
8895   dest = must_be_not_null(dest, true);
8896 
8897   Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8898   assert(src_start, "source array is null");
8899   Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8900   assert(dest_start, "destination array is null");
8901 
8902   Node* call = make_runtime_call(RC_LEAF,
8903                                  OptoRuntime::base64_decodeBlock_Type(),
8904                                  stubAddr, stubName, TypePtr::BOTTOM,
8905                                  src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
8906   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8907   set_result(result);
8908   return true;
8909 }
8910 
8911 bool LibraryCallKit::inline_poly1305_processBlocks() {
8912   address stubAddr;
8913   const char *stubName;
8914   assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
8915   assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
8916   stubAddr = StubRoutines::poly1305_processBlocks();
8917   stubName = "poly1305_processBlocks";
8918 
8919   if (!stubAddr) return false;
8920   null_check_receiver();  // null-check receiver
8921   if (stopped())  return true;
8922 
8923   Node* input = argument(1);
8924   Node* input_offset = argument(2);
8925   Node* len = argument(3);
8926   Node* alimbs = argument(4);
8927   Node* rlimbs = argument(5);
8928 
8929   input = must_be_not_null(input, true);
8930   alimbs = must_be_not_null(alimbs, true);
8931   rlimbs = must_be_not_null(rlimbs, true);
8932 
8933   Node* input_start = array_element_address(input, input_offset, T_BYTE);
8934   assert(input_start, "input array is null");
8935   Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
8936   assert(acc_start, "acc array is null");
8937   Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
8938   assert(r_start, "r array is null");
8939 
8940   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8941                                  OptoRuntime::poly1305_processBlocks_Type(),
8942                                  stubAddr, stubName, TypePtr::BOTTOM,
8943                                  input_start, len, acc_start, r_start);
8944   return true;
8945 }
8946 
8947 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
8948   address stubAddr;
8949   const char *stubName;
8950   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8951   assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
8952   stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
8953   stubName = "intpoly_montgomeryMult_P256";
8954 
8955   if (!stubAddr) return false;
8956   null_check_receiver();  // null-check receiver
8957   if (stopped())  return true;
8958 
8959   Node* a = argument(1);
8960   Node* b = argument(2);
8961   Node* r = argument(3);
8962 
8963   a = must_be_not_null(a, true);
8964   b = must_be_not_null(b, true);
8965   r = must_be_not_null(r, true);
8966 
8967   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8968   assert(a_start, "a array is null");
8969   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8970   assert(b_start, "b array is null");
8971   Node* r_start = array_element_address(r, intcon(0), T_LONG);
8972   assert(r_start, "r array is null");
8973 
8974   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8975                                  OptoRuntime::intpoly_montgomeryMult_P256_Type(),
8976                                  stubAddr, stubName, TypePtr::BOTTOM,
8977                                  a_start, b_start, r_start);
8978   return true;
8979 }
8980 
8981 bool LibraryCallKit::inline_intpoly_assign() {
8982   assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8983   assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
8984   const char *stubName = "intpoly_assign";
8985   address stubAddr = StubRoutines::intpoly_assign();
8986   if (!stubAddr) return false;
8987 
8988   Node* set = argument(0);
8989   Node* a = argument(1);
8990   Node* b = argument(2);
8991   Node* arr_length = load_array_length(a);
8992 
8993   a = must_be_not_null(a, true);
8994   b = must_be_not_null(b, true);
8995 
8996   Node* a_start = array_element_address(a, intcon(0), T_LONG);
8997   assert(a_start, "a array is null");
8998   Node* b_start = array_element_address(b, intcon(0), T_LONG);
8999   assert(b_start, "b array is null");
9000 
9001   Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9002                                  OptoRuntime::intpoly_assign_Type(),
9003                                  stubAddr, stubName, TypePtr::BOTTOM,
9004                                  set, a_start, b_start, arr_length);
9005   return true;
9006 }
9007 
9008 //------------------------------inline_digestBase_implCompress-----------------------
9009 //
9010 // Calculate MD5 for single-block byte[] array.
9011 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
9012 //
9013 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
9014 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
9015 //
9016 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
9017 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
9018 //
9019 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
9020 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
9021 //
9022 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
9023 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
9024 //
9025 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
9026   assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
9027 
9028   Node* digestBase_obj = argument(0);
9029   Node* src            = argument(1); // type oop
9030   Node* ofs            = argument(2); // type int
9031 
9032   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9033   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9034     // failed array check
9035     return false;
9036   }
9037   // Figure out the size and type of the elements we will be copying.
9038   BasicType src_elem = src_type->elem()->array_element_basic_type();
9039   if (src_elem != T_BYTE) {
9040     return false;
9041   }
9042   // 'src_start' points to src array + offset
9043   src = must_be_not_null(src, true);
9044   Node* src_start = array_element_address(src, ofs, src_elem);
9045   Node* state = nullptr;
9046   Node* block_size = nullptr;
9047   address stubAddr;
9048   const char *stubName;
9049 
9050   switch(id) {
9051   case vmIntrinsics::_md5_implCompress:
9052     assert(UseMD5Intrinsics, "need MD5 instruction support");
9053     state = get_state_from_digest_object(digestBase_obj, T_INT);
9054     stubAddr = StubRoutines::md5_implCompress();
9055     stubName = "md5_implCompress";
9056     break;
9057   case vmIntrinsics::_sha_implCompress:
9058     assert(UseSHA1Intrinsics, "need SHA1 instruction support");
9059     state = get_state_from_digest_object(digestBase_obj, T_INT);
9060     stubAddr = StubRoutines::sha1_implCompress();
9061     stubName = "sha1_implCompress";
9062     break;
9063   case vmIntrinsics::_sha2_implCompress:
9064     assert(UseSHA256Intrinsics, "need SHA256 instruction support");
9065     state = get_state_from_digest_object(digestBase_obj, T_INT);
9066     stubAddr = StubRoutines::sha256_implCompress();
9067     stubName = "sha256_implCompress";
9068     break;
9069   case vmIntrinsics::_sha5_implCompress:
9070     assert(UseSHA512Intrinsics, "need SHA512 instruction support");
9071     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9072     stubAddr = StubRoutines::sha512_implCompress();
9073     stubName = "sha512_implCompress";
9074     break;
9075   case vmIntrinsics::_sha3_implCompress:
9076     assert(UseSHA3Intrinsics, "need SHA3 instruction support");
9077     state = get_state_from_digest_object(digestBase_obj, T_LONG);
9078     stubAddr = StubRoutines::sha3_implCompress();
9079     stubName = "sha3_implCompress";
9080     block_size = get_block_size_from_digest_object(digestBase_obj);
9081     if (block_size == nullptr) return false;
9082     break;
9083   default:
9084     fatal_unexpected_iid(id);
9085     return false;
9086   }
9087   if (state == nullptr) return false;
9088 
9089   assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9090   if (stubAddr == nullptr) return false;
9091 
9092   // Call the stub.
9093   Node* call;
9094   if (block_size == nullptr) {
9095     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9096                              stubAddr, stubName, TypePtr::BOTTOM,
9097                              src_start, state);
9098   } else {
9099     call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9100                              stubAddr, stubName, TypePtr::BOTTOM,
9101                              src_start, state, block_size);
9102   }
9103 
9104   return true;
9105 }
9106 
9107 //------------------------------inline_double_keccak
9108 bool LibraryCallKit::inline_double_keccak() {
9109   address stubAddr;
9110   const char *stubName;
9111   assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9112   assert(callee()->signature()->size() == 2, "double_keccak has 2 parameters");
9113 
9114   stubAddr = StubRoutines::double_keccak();
9115   stubName = "double_keccak";
9116   if (!stubAddr) return false;
9117 
9118   Node* status0        = argument(0);
9119   Node* status1        = argument(1);
9120 
9121   status0 = must_be_not_null(status0, true);
9122   status1 = must_be_not_null(status1, true);
9123 
9124   Node* status0_start  = array_element_address(status0, intcon(0), T_LONG);
9125   assert(status0_start, "status0 is null");
9126   Node* status1_start  = array_element_address(status1, intcon(0), T_LONG);
9127   assert(status1_start, "status1 is null");
9128   Node* double_keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9129                                   OptoRuntime::double_keccak_Type(),
9130                                   stubAddr, stubName, TypePtr::BOTTOM,
9131                                   status0_start, status1_start);
9132   // return an int
9133   Node* retvalue = _gvn.transform(new ProjNode(double_keccak, TypeFunc::Parms));
9134   set_result(retvalue);
9135   return true;
9136 }
9137 
9138 
9139 //------------------------------inline_digestBase_implCompressMB-----------------------
9140 //
9141 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9142 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9143 //
9144 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9145   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9146          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9147   assert((uint)predicate < 5, "sanity");
9148   assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9149 
9150   Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9151   Node* src            = argument(1); // byte[] array
9152   Node* ofs            = argument(2); // type int
9153   Node* limit          = argument(3); // type int
9154 
9155   const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9156   if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9157     // failed array check
9158     return false;
9159   }
9160   // Figure out the size and type of the elements we will be copying.
9161   BasicType src_elem = src_type->elem()->array_element_basic_type();
9162   if (src_elem != T_BYTE) {
9163     return false;
9164   }
9165   // 'src_start' points to src array + offset
9166   src = must_be_not_null(src, false);
9167   Node* src_start = array_element_address(src, ofs, src_elem);
9168 
9169   const char* klass_digestBase_name = nullptr;
9170   const char* stub_name = nullptr;
9171   address     stub_addr = nullptr;
9172   BasicType elem_type = T_INT;
9173 
9174   switch (predicate) {
9175   case 0:
9176     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9177       klass_digestBase_name = "sun/security/provider/MD5";
9178       stub_name = "md5_implCompressMB";
9179       stub_addr = StubRoutines::md5_implCompressMB();
9180     }
9181     break;
9182   case 1:
9183     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9184       klass_digestBase_name = "sun/security/provider/SHA";
9185       stub_name = "sha1_implCompressMB";
9186       stub_addr = StubRoutines::sha1_implCompressMB();
9187     }
9188     break;
9189   case 2:
9190     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9191       klass_digestBase_name = "sun/security/provider/SHA2";
9192       stub_name = "sha256_implCompressMB";
9193       stub_addr = StubRoutines::sha256_implCompressMB();
9194     }
9195     break;
9196   case 3:
9197     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9198       klass_digestBase_name = "sun/security/provider/SHA5";
9199       stub_name = "sha512_implCompressMB";
9200       stub_addr = StubRoutines::sha512_implCompressMB();
9201       elem_type = T_LONG;
9202     }
9203     break;
9204   case 4:
9205     if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9206       klass_digestBase_name = "sun/security/provider/SHA3";
9207       stub_name = "sha3_implCompressMB";
9208       stub_addr = StubRoutines::sha3_implCompressMB();
9209       elem_type = T_LONG;
9210     }
9211     break;
9212   default:
9213     fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9214   }
9215   if (klass_digestBase_name != nullptr) {
9216     assert(stub_addr != nullptr, "Stub is generated");
9217     if (stub_addr == nullptr) return false;
9218 
9219     // get DigestBase klass to lookup for SHA klass
9220     const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9221     assert(tinst != nullptr, "digestBase_obj is not instance???");
9222     assert(tinst->is_loaded(), "DigestBase is not loaded");
9223 
9224     ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9225     assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9226     ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9227     return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9228   }
9229   return false;
9230 }
9231 
9232 //------------------------------inline_digestBase_implCompressMB-----------------------
9233 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9234                                                       BasicType elem_type, address stubAddr, const char *stubName,
9235                                                       Node* src_start, Node* ofs, Node* limit) {
9236   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9237   const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9238   Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9239   digest_obj = _gvn.transform(digest_obj);
9240 
9241   Node* state = get_state_from_digest_object(digest_obj, elem_type);
9242   if (state == nullptr) return false;
9243 
9244   Node* block_size = nullptr;
9245   if (strcmp("sha3_implCompressMB", stubName) == 0) {
9246     block_size = get_block_size_from_digest_object(digest_obj);
9247     if (block_size == nullptr) return false;
9248   }
9249 
9250   // Call the stub.
9251   Node* call;
9252   if (block_size == nullptr) {
9253     call = make_runtime_call(RC_LEAF|RC_NO_FP,
9254                              OptoRuntime::digestBase_implCompressMB_Type(false),
9255                              stubAddr, stubName, TypePtr::BOTTOM,
9256                              src_start, state, ofs, limit);
9257   } else {
9258      call = make_runtime_call(RC_LEAF|RC_NO_FP,
9259                              OptoRuntime::digestBase_implCompressMB_Type(true),
9260                              stubAddr, stubName, TypePtr::BOTTOM,
9261                              src_start, state, block_size, ofs, limit);
9262   }
9263 
9264   // return ofs (int)
9265   Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9266   set_result(result);
9267 
9268   return true;
9269 }
9270 
9271 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9272 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9273   assert(UseAES, "need AES instruction support");
9274   address stubAddr = nullptr;
9275   const char *stubName = nullptr;
9276   stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9277   stubName = "galoisCounterMode_AESCrypt";
9278 
9279   if (stubAddr == nullptr) return false;
9280 
9281   Node* in      = argument(0);
9282   Node* inOfs   = argument(1);
9283   Node* len     = argument(2);
9284   Node* ct      = argument(3);
9285   Node* ctOfs   = argument(4);
9286   Node* out     = argument(5);
9287   Node* outOfs  = argument(6);
9288   Node* gctr_object = argument(7);
9289   Node* ghash_object = argument(8);
9290 
9291   // (1) in, ct and out are arrays.
9292   const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9293   const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9294   const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9295   assert( in_type != nullptr &&  in_type->elem() != Type::BOTTOM &&
9296           ct_type != nullptr &&  ct_type->elem() != Type::BOTTOM &&
9297          out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9298 
9299   // checks are the responsibility of the caller
9300   Node* in_start = in;
9301   Node* ct_start = ct;
9302   Node* out_start = out;
9303   if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9304     assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9305     in_start = array_element_address(in, inOfs, T_BYTE);
9306     ct_start = array_element_address(ct, ctOfs, T_BYTE);
9307     out_start = array_element_address(out, outOfs, T_BYTE);
9308   }
9309 
9310   // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9311   // (because of the predicated logic executed earlier).
9312   // so we cast it here safely.
9313   // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9314   Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9315   Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9316   Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9317   Node* state = load_field_from_object(ghash_object, "state", "[J");
9318 
9319   if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9320     return false;
9321   }
9322   // cast it to what we know it will be at runtime
9323   const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9324   assert(tinst != nullptr, "GCTR obj is null");
9325   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9326   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9327   assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9328   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9329   const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9330   const TypeOopPtr* xtype = aklass->as_instance_type();
9331   Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9332   aescrypt_object = _gvn.transform(aescrypt_object);
9333   // we need to get the start of the aescrypt_object's expanded key array
9334   Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
9335   if (k_start == nullptr) return false;
9336   // similarly, get the start address of the r vector
9337   Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9338   Node* state_start = array_element_address(state, intcon(0), T_LONG);
9339   Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9340 
9341 
9342   // Call the stub, passing params
9343   Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9344                                OptoRuntime::galoisCounterMode_aescrypt_Type(),
9345                                stubAddr, stubName, TypePtr::BOTTOM,
9346                                in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9347 
9348   // return cipher length (int)
9349   Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9350   set_result(retvalue);
9351 
9352   return true;
9353 }
9354 
9355 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9356 // Return node representing slow path of predicate check.
9357 // the pseudo code we want to emulate with this predicate is:
9358 // for encryption:
9359 //    if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9360 // for decryption:
9361 //    if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9362 //    note cipher==plain is more conservative than the original java code but that's OK
9363 //
9364 
9365 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9366   // The receiver was checked for null already.
9367   Node* objGCTR = argument(7);
9368   // Load embeddedCipher field of GCTR object.
9369   Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9370   assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9371 
9372   // get AESCrypt klass for instanceOf check
9373   // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9374   // will have same classloader as CipherBlockChaining object
9375   const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9376   assert(tinst != nullptr, "GCTR obj is null");
9377   assert(tinst->is_loaded(), "GCTR obj is not loaded");
9378 
9379   // we want to do an instanceof comparison against the AESCrypt class
9380   ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9381   if (!klass_AESCrypt->is_loaded()) {
9382     // if AESCrypt is not even loaded, we never take the intrinsic fast path
9383     Node* ctrl = control();
9384     set_control(top()); // no regular fast path
9385     return ctrl;
9386   }
9387 
9388   ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9389   Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9390   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9391   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9392   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9393 
9394   return instof_false; // even if it is null
9395 }
9396 
9397 //------------------------------get_state_from_digest_object-----------------------
9398 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9399   const char* state_type;
9400   switch (elem_type) {
9401     case T_BYTE: state_type = "[B"; break;
9402     case T_INT:  state_type = "[I"; break;
9403     case T_LONG: state_type = "[J"; break;
9404     default: ShouldNotReachHere();
9405   }
9406   Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9407   assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9408   if (digest_state == nullptr) return (Node *) nullptr;
9409 
9410   // now have the array, need to get the start address of the state array
9411   Node* state = array_element_address(digest_state, intcon(0), elem_type);
9412   return state;
9413 }
9414 
9415 //------------------------------get_block_size_from_sha3_object----------------------------------
9416 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9417   Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9418   assert (block_size != nullptr, "sanity");
9419   return block_size;
9420 }
9421 
9422 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9423 // Return node representing slow path of predicate check.
9424 // the pseudo code we want to emulate with this predicate is:
9425 //    if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9426 //
9427 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9428   assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9429          "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9430   assert((uint)predicate < 5, "sanity");
9431 
9432   // The receiver was checked for null already.
9433   Node* digestBaseObj = argument(0);
9434 
9435   // get DigestBase klass for instanceOf check
9436   const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9437   assert(tinst != nullptr, "digestBaseObj is null");
9438   assert(tinst->is_loaded(), "DigestBase is not loaded");
9439 
9440   const char* klass_name = nullptr;
9441   switch (predicate) {
9442   case 0:
9443     if (UseMD5Intrinsics) {
9444       // we want to do an instanceof comparison against the MD5 class
9445       klass_name = "sun/security/provider/MD5";
9446     }
9447     break;
9448   case 1:
9449     if (UseSHA1Intrinsics) {
9450       // we want to do an instanceof comparison against the SHA class
9451       klass_name = "sun/security/provider/SHA";
9452     }
9453     break;
9454   case 2:
9455     if (UseSHA256Intrinsics) {
9456       // we want to do an instanceof comparison against the SHA2 class
9457       klass_name = "sun/security/provider/SHA2";
9458     }
9459     break;
9460   case 3:
9461     if (UseSHA512Intrinsics) {
9462       // we want to do an instanceof comparison against the SHA5 class
9463       klass_name = "sun/security/provider/SHA5";
9464     }
9465     break;
9466   case 4:
9467     if (UseSHA3Intrinsics) {
9468       // we want to do an instanceof comparison against the SHA3 class
9469       klass_name = "sun/security/provider/SHA3";
9470     }
9471     break;
9472   default:
9473     fatal("unknown SHA intrinsic predicate: %d", predicate);
9474   }
9475 
9476   ciKlass* klass = nullptr;
9477   if (klass_name != nullptr) {
9478     klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9479   }
9480   if ((klass == nullptr) || !klass->is_loaded()) {
9481     // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9482     Node* ctrl = control();
9483     set_control(top()); // no intrinsic path
9484     return ctrl;
9485   }
9486   ciInstanceKlass* instklass = klass->as_instance_klass();
9487 
9488   Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9489   Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9490   Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9491   Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9492 
9493   return instof_false;  // even if it is null
9494 }
9495 
9496 //-------------inline_fma-----------------------------------
9497 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9498   Node *a = nullptr;
9499   Node *b = nullptr;
9500   Node *c = nullptr;
9501   Node* result = nullptr;
9502   switch (id) {
9503   case vmIntrinsics::_fmaD:
9504     assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9505     // no receiver since it is static method
9506     a = argument(0);
9507     b = argument(2);
9508     c = argument(4);
9509     result = _gvn.transform(new FmaDNode(a, b, c));
9510     break;
9511   case vmIntrinsics::_fmaF:
9512     assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9513     a = argument(0);
9514     b = argument(1);
9515     c = argument(2);
9516     result = _gvn.transform(new FmaFNode(a, b, c));
9517     break;
9518   default:
9519     fatal_unexpected_iid(id);  break;
9520   }
9521   set_result(result);
9522   return true;
9523 }
9524 
9525 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9526   // argument(0) is receiver
9527   Node* codePoint = argument(1);
9528   Node* n = nullptr;
9529 
9530   switch (id) {
9531     case vmIntrinsics::_isDigit :
9532       n = new DigitNode(control(), codePoint);
9533       break;
9534     case vmIntrinsics::_isLowerCase :
9535       n = new LowerCaseNode(control(), codePoint);
9536       break;
9537     case vmIntrinsics::_isUpperCase :
9538       n = new UpperCaseNode(control(), codePoint);
9539       break;
9540     case vmIntrinsics::_isWhitespace :
9541       n = new WhitespaceNode(control(), codePoint);
9542       break;
9543     default:
9544       fatal_unexpected_iid(id);
9545   }
9546 
9547   set_result(_gvn.transform(n));
9548   return true;
9549 }
9550 
9551 bool LibraryCallKit::inline_profileBoolean() {
9552   Node* counts = argument(1);
9553   const TypeAryPtr* ary = nullptr;
9554   ciArray* aobj = nullptr;
9555   if (counts->is_Con()
9556       && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9557       && (aobj = ary->const_oop()->as_array()) != nullptr
9558       && (aobj->length() == 2)) {
9559     // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9560     jint false_cnt = aobj->element_value(0).as_int();
9561     jint  true_cnt = aobj->element_value(1).as_int();
9562 
9563     if (C->log() != nullptr) {
9564       C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9565                      false_cnt, true_cnt);
9566     }
9567 
9568     if (false_cnt + true_cnt == 0) {
9569       // According to profile, never executed.
9570       uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9571                           Deoptimization::Action_reinterpret);
9572       return true;
9573     }
9574 
9575     // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9576     // is a number of each value occurrences.
9577     Node* result = argument(0);
9578     if (false_cnt == 0 || true_cnt == 0) {
9579       // According to profile, one value has been never seen.
9580       int expected_val = (false_cnt == 0) ? 1 : 0;
9581 
9582       Node* cmp  = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9583       Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9584 
9585       IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9586       Node* fast_path = _gvn.transform(new IfTrueNode(check));
9587       Node* slow_path = _gvn.transform(new IfFalseNode(check));
9588 
9589       { // Slow path: uncommon trap for never seen value and then reexecute
9590         // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9591         // the value has been seen at least once.
9592         PreserveJVMState pjvms(this);
9593         PreserveReexecuteState preexecs(this);
9594         jvms()->set_should_reexecute(true);
9595 
9596         set_control(slow_path);
9597         set_i_o(i_o());
9598 
9599         uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9600                             Deoptimization::Action_reinterpret);
9601       }
9602       // The guard for never seen value enables sharpening of the result and
9603       // returning a constant. It allows to eliminate branches on the same value
9604       // later on.
9605       set_control(fast_path);
9606       result = intcon(expected_val);
9607     }
9608     // Stop profiling.
9609     // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9610     // By replacing method body with profile data (represented as ProfileBooleanNode
9611     // on IR level) we effectively disable profiling.
9612     // It enables full speed execution once optimized code is generated.
9613     Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9614     C->record_for_igvn(profile);
9615     set_result(profile);
9616     return true;
9617   } else {
9618     // Continue profiling.
9619     // Profile data isn't available at the moment. So, execute method's bytecode version.
9620     // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9621     // is compiled and counters aren't available since corresponding MethodHandle
9622     // isn't a compile-time constant.
9623     return false;
9624   }
9625 }
9626 
9627 bool LibraryCallKit::inline_isCompileConstant() {
9628   Node* n = argument(0);
9629   set_result(n->is_Con() ? intcon(1) : intcon(0));
9630   return true;
9631 }
9632 
9633 //------------------------------- inline_getObjectSize --------------------------------------
9634 //
9635 // Calculate the runtime size of the object/array.
9636 //   native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9637 //
9638 bool LibraryCallKit::inline_getObjectSize() {
9639   Node* obj = argument(3);
9640   Node* klass_node = load_object_klass(obj);
9641 
9642   jint  layout_con = Klass::_lh_neutral_value;
9643   Node* layout_val = get_layout_helper(klass_node, layout_con);
9644   int   layout_is_con = (layout_val == nullptr);
9645 
9646   if (layout_is_con) {
9647     // Layout helper is constant, can figure out things at compile time.
9648 
9649     if (Klass::layout_helper_is_instance(layout_con)) {
9650       // Instance case:  layout_con contains the size itself.
9651       Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9652       set_result(size);
9653     } else {
9654       // Array case: size is round(header + element_size*arraylength).
9655       // Since arraylength is different for every array instance, we have to
9656       // compute the whole thing at runtime.
9657 
9658       Node* arr_length = load_array_length(obj);
9659 
9660       int round_mask = MinObjAlignmentInBytes - 1;
9661       int hsize  = Klass::layout_helper_header_size(layout_con);
9662       int eshift = Klass::layout_helper_log2_element_size(layout_con);
9663 
9664       if ((round_mask & ~right_n_bits(eshift)) == 0) {
9665         round_mask = 0;  // strength-reduce it if it goes away completely
9666       }
9667       assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9668       Node* header_size = intcon(hsize + round_mask);
9669 
9670       Node* lengthx = ConvI2X(arr_length);
9671       Node* headerx = ConvI2X(header_size);
9672 
9673       Node* abody = lengthx;
9674       if (eshift != 0) {
9675         abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9676       }
9677       Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9678       if (round_mask != 0) {
9679         size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9680       }
9681       size = ConvX2L(size);
9682       set_result(size);
9683     }
9684   } else {
9685     // Layout helper is not constant, need to test for array-ness at runtime.
9686 
9687     enum { _instance_path = 1, _array_path, PATH_LIMIT };
9688     RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9689     PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9690     record_for_igvn(result_reg);
9691 
9692     Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9693     if (array_ctl != nullptr) {
9694       // Array case: size is round(header + element_size*arraylength).
9695       // Since arraylength is different for every array instance, we have to
9696       // compute the whole thing at runtime.
9697 
9698       PreserveJVMState pjvms(this);
9699       set_control(array_ctl);
9700       Node* arr_length = load_array_length(obj);
9701 
9702       int round_mask = MinObjAlignmentInBytes - 1;
9703       Node* mask = intcon(round_mask);
9704 
9705       Node* hss = intcon(Klass::_lh_header_size_shift);
9706       Node* hsm = intcon(Klass::_lh_header_size_mask);
9707       Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9708       header_size = _gvn.transform(new AndINode(header_size, hsm));
9709       header_size = _gvn.transform(new AddINode(header_size, mask));
9710 
9711       // There is no need to mask or shift this value.
9712       // The semantics of LShiftINode include an implicit mask to 0x1F.
9713       assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9714       Node* elem_shift = layout_val;
9715 
9716       Node* lengthx = ConvI2X(arr_length);
9717       Node* headerx = ConvI2X(header_size);
9718 
9719       Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9720       Node* size = _gvn.transform(new AddXNode(headerx, abody));
9721       if (round_mask != 0) {
9722         size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9723       }
9724       size = ConvX2L(size);
9725 
9726       result_reg->init_req(_array_path, control());
9727       result_val->init_req(_array_path, size);
9728     }
9729 
9730     if (!stopped()) {
9731       // Instance case: the layout helper gives us instance size almost directly,
9732       // but we need to mask out the _lh_instance_slow_path_bit.
9733       Node* size = ConvI2X(layout_val);
9734       assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9735       Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9736       size = _gvn.transform(new AndXNode(size, mask));
9737       size = ConvX2L(size);
9738 
9739       result_reg->init_req(_instance_path, control());
9740       result_val->init_req(_instance_path, size);
9741     }
9742 
9743     set_result(result_reg, result_val);
9744   }
9745 
9746   return true;
9747 }
9748 
9749 //------------------------------- inline_blackhole --------------------------------------
9750 //
9751 // Make sure all arguments to this node are alive.
9752 // This matches methods that were requested to be blackholed through compile commands.
9753 //
9754 bool LibraryCallKit::inline_blackhole() {
9755   assert(callee()->is_static(), "Should have been checked before: only static methods here");
9756   assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9757   assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9758 
9759   // Blackhole node pinches only the control, not memory. This allows
9760   // the blackhole to be pinned in the loop that computes blackholed
9761   // values, but have no other side effects, like breaking the optimizations
9762   // across the blackhole.
9763 
9764   Node* bh = _gvn.transform(new BlackholeNode(control()));
9765   set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9766 
9767   // Bind call arguments as blackhole arguments to keep them alive
9768   uint nargs = callee()->arg_size();
9769   for (uint i = 0; i < nargs; i++) {
9770     bh->add_req(argument(i));
9771   }
9772 
9773   return true;
9774 }
9775 
9776 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9777   const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9778   if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9779     return nullptr; // box klass is not Float16
9780   }
9781 
9782   // Null check; get notnull casted pointer
9783   Node* null_ctl = top();
9784   Node* not_null_box = null_check_oop(box, &null_ctl, true);
9785   // If not_null_box is dead, only null-path is taken
9786   if (stopped()) {
9787     set_control(null_ctl);
9788     return nullptr;
9789   }
9790   assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9791   const TypePtr* adr_type = C->alias_type(field)->adr_type();
9792   Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9793   return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9794 }
9795 
9796 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9797   PreserveReexecuteState preexecs(this);
9798   jvms()->set_should_reexecute(true);
9799 
9800   const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9801   Node* klass_node = makecon(klass_type);
9802   Node* box = new_instance(klass_node);
9803 
9804   Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9805   const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9806 
9807   Node* field_store = _gvn.transform(access_store_at(box,
9808                                                      value_field,
9809                                                      value_adr_type,
9810                                                      value,
9811                                                      TypeInt::SHORT,
9812                                                      T_SHORT,
9813                                                      IN_HEAP));
9814   set_memory(field_store, value_adr_type);
9815   return box;
9816 }
9817 
9818 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9819   if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9820       !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9821     return false;
9822   }
9823 
9824   const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9825   if (box_type == nullptr || box_type->const_oop() == nullptr) {
9826     return false;
9827   }
9828 
9829   ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9830   const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9831   ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9832                                                     ciSymbols::short_signature(),
9833                                                     false);
9834   assert(field != nullptr, "");
9835 
9836   // Transformed nodes
9837   Node* fld1 = nullptr;
9838   Node* fld2 = nullptr;
9839   Node* fld3 = nullptr;
9840   switch(num_args) {
9841     case 3:
9842       fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9843       if (fld3 == nullptr) {
9844         return false;
9845       }
9846       fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9847     // fall-through
9848     case 2:
9849       fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9850       if (fld2 == nullptr) {
9851         return false;
9852       }
9853       fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9854     // fall-through
9855     case 1:
9856       fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9857       if (fld1 == nullptr) {
9858         return false;
9859       }
9860       fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9861       break;
9862     default: fatal("Unsupported number of arguments %d", num_args);
9863   }
9864 
9865   Node* result = nullptr;
9866   switch (id) {
9867     // Unary operations
9868     case vmIntrinsics::_sqrt_float16:
9869       result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9870       break;
9871     // Ternary operations
9872     case vmIntrinsics::_fma_float16:
9873       result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9874       break;
9875     default:
9876       fatal_unexpected_iid(id);
9877       break;
9878   }
9879   result = _gvn.transform(new ReinterpretHF2SNode(result));
9880   set_result(box_fp16_value(float16_box_type, field, result));
9881   return true;
9882 }
9883